问:
slim inception_v4 retrain ValueError: All shapes must be fully defined
I got the following error

```<code>ValueError: All shapes must be fully defined: [TensorShape([Dimension(299), Dimension(299), Dimension(3)]), TensorShape([Dimension(None)])]
</code>```

when training the inception_v4 with slim.

Full traceback

```<code>Traceback (most recent call last):
  File "../models/slim/train_vienna_classifier.py", line 575, in <module>
    tf.app.run()
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "../models/slim/train_vienna_classifier.py", line 441, in main
    capacity=5 * FLAGS.batch_size)
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 872, in batch
    name=name)
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 658, in _batch
    capacity=capacity, dtypes=types, shapes=shapes, shared_name=shared_name)
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.py", line 685, in __init__
    shapes = _as_shape_list(shapes, dtypes)
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.py", line 77, in _as_shape_list
    raise ValueError("All shapes must be fully defined: %s" % shapes)
ValueError: All shapes must be fully defined: [TensorShape([Dimension(299), Dimension(299), Dimension(3)]), TensorShape([Dimension(None)])]
</code>```

The code

```<code>with tf.device(deploy_config.inputs_device()):
  provider = slim.dataset_data_provider.DatasetDataProvider(
      dataset,
      num_readers=FLAGS.num_readers,
      common_queue_capacity=20 * FLAGS.batch_size,
      common_queue_min=10 * FLAGS.batch_size)
  [image, label] = provider.get(['image', 'label'])
  label -= FLAGS.labels_offset

  train_image_size = FLAGS.train_image_size or network_fn.default_image_size

  image = image_preprocessing_fn(image, train_image_size, train_image_size)
  images, labels = tf.train.batch(
      [image, label],
      batch_size=FLAGS.batch_size,
      num_threads=FLAGS.num_preprocessing_threads,
      capacity=5 * FLAGS.batch_size)
  labels = slim.one_hot_encoding(
      labels, dataset.num_classes - FLAGS.labels_offset)
  batch_queue = slim.prefetch_queue.prefetch_queue(
      [images, labels], capacity=2 * deploy_config.num_clones)
</code>```

Although the sizes of images in the dataset are different, I am using the given preprocessing function for resizing them, therefore it should not return the error. Am I correct?

答:
The issue is not with the images but the labels as its shape is not defined:  [TensorShape([Dimension(299), Dimension(299), Dimension(3)]), TensorShape([Dimension(None)])]. The second tensor dimension is shown as None. So setting the labels to the correct shape should fix this issue.

Use the tf.reshape() function to set the shape of the labels.

Body:
I got the following error

ValueError: All shapes must be fully defined: [TensorShape([Dimension(299), Dimension(299), Dimension(3)]), TensorShape([Dimension(None)])]

when training the inception_v4 with slim.

Full traceback

Traceback (most recent call last):
  File "../models/slim/train_vienna_classifier.py", line 575, in <module>
    tf.app.run()
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "../models/slim/train_vienna_classifier.py", line 441, in main
    capacity=5 * FLAGS.batch_size)
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 872, in batch
    name=name)
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 658, in _batch
    capacity=capacity, dtypes=types, shapes=shapes, shared_name=shared_name)
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.py", line 685, in __init__
    shapes = _as_shape_list(shapes, dtypes)
  File "/home/osman/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.py", line 77, in _as_shape_list
    raise ValueError("All shapes must be fully defined: %s" % shapes)
ValueError: All shapes must be fully defined: [TensorShape([Dimension(299), Dimension(299), Dimension(3)]), TensorShape([Dimension(None)])]

The code

with tf.device(deploy_config.inputs_device()):
  provider = slim.dataset_data_provider.DatasetDataProvider(
      dataset,
      num_readers=FLAGS.num_readers,
      common_queue_capacity=20 * FLAGS.batch_size,
      common_queue_min=10 * FLAGS.batch_size)
  [image, label] = provider.get(['image', 'label'])
  label -= FLAGS.labels_offset

  train_image_size = FLAGS.train_image_size or network_fn.default_image_size

  image = image_preprocessing_fn(image, train_image_size, train_image_size)
  images, labels = tf.train.batch(
      [image, label],
      batch_size=FLAGS.batch_size,
      num_threads=FLAGS.num_preprocessing_threads,
      capacity=5 * FLAGS.batch_size)
  labels = slim.one_hot_encoding(
      labels, dataset.num_classes - FLAGS.labels_offset)
  batch_queue = slim.prefetch_queue.prefetch_queue(
      [images, labels], capacity=2 * deploy_config.num_clones)

Although the sizes of images in the dataset are different, I am using the given preprocessing function for resizing them, therefore it should not return the error. Am I correct?


来源: stackexchange

问:
Why doesn't my negative margin work in IE7?
I have two stacked divs, where I want the content from the top div to flow over onto the bottom div.  Using a negative bottom margin on the content wrapper, I was able to achieve this in all browsers except IE 7, where instead of flowing over the bottom div, the content gets cut-off/overlapped by it.

I'm looking for an explanation of what exactly is happening here, and potential fixes.

Complete HTML example:

```<code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Negative Margin Test</title>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssreset/reset-min.css">

<style type="text/css">

.container {
 width: 800px;
 background: none;
 position:relative;
}
.container-mid{
 background:#F00;/**/
 border:dashed thick #090;
 width:100%;
}
.container-bottom{
 background:#FF0;/**/
 border:dashed thick #090;
 width:100%;
 height: 200px;
}
.container-inner{
 width:100%;
 margin:0 auto;
 margin-bottom:-200px;/**/

}

</style>

</head>

<body>

<div class="container">

    <div class="container-mid">

        <div class="container-inner">

            <div class="content">

                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>
                <br />
                <br />
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>
                <br />
                <br />
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>

            </div><!-- end .content -->

        </div><!-- end .container-inner -->

    </div><!-- end .container-mid -->

    <div class="container-bottom"></div>

  <!-- end .container --></div>

</body>
</html>
</code>```

In IE8: (Results same with Chrome/FFox/etc...)

In IE 7: (Tested with IE8->Developer Tools->IE7 Mode)

As you can see, overflowing content gets overlapped by the yellow div.

See my live example

答:
Try setting position:relative; on .container-inner so it explicitly has a higher stacking order, which should place it above.

```<code>.container-inner { position:relative; }
</code>```

I documented this bug here.

ContentLicense: CC BY-SA 2.5

Body:
I have two stacked divs, where I want the content from the top div to flow over onto the bottom div.  Using a negative bottom margin on the content wrapper, I was able to achieve this in all browsers except IE 7, where instead of flowing over the bottom div, the content gets cut-off/overlapped by it.

I'm looking for an explanation of what exactly is happening here, and potential fixes.

Complete HTML example:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Negative Margin Test</title>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssreset/reset-min.css">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

In IE8: (Results same with Chrome/FFox/etc...)

In IE 7: (Tested with IE8->Developer Tools->IE7 Mode)

As you can see, overflowing content gets overlapped by the yellow div.

See my live example

Body:
Try setting position:relative; on .container-inner so it explicitly has a higher stacking order, which should place it above.

.container-inner { position:relative; }

I documented this bug here.


问:
Express Router GET request console.log shows undefined request parameters
I've looked on SO for an identical questions, since I feel this is a pretty simple error on my part, but the closest thing I've found is this link. I'm learning Node.JS, and am writing a relatively simple endpoint to receive get requests for a certain artist:

```<code>router.get("/:artistID", (req, res) => {
  console.log(req.params);
  console.log(req.params.artistId);
  res.send(req.params);
})
</code>```

What I expect to see is 1), a JSON object with { artistID: "whatIsent"}, 2) a "whatIsent", and then 3) the same JSON object as a response when I use an API testing utility such as Postman.

Results 1) and 3) occur as expected, but here's what I see in my console:

```<code>{ artistID: 'whatIsent' }
undefined
</code>```

Here is the GET request I send:
http://localhost:8080/artists/whatIsent.

What exactly is going on? Is Express translating artistId into some intermediate object that is not a string?

Edit: I used typeof req.params.artistId, and it also returns undefined...

答:
You have a typo in your code.

It should be artistID instead of artistId.

ContentLicense: CC BY-SA 3.0

Body:
I've looked on SO for an identical questions, since I feel this is a pretty simple error on my part, but the closest thing I've found is this link. I'm learning Node.JS, and am writing a relatively simple endpoint to receive get requests for a certain artist:

router.get("/:artistID", (req, res) => {
  console.log(req.params);
  console.log(req.params.artistId);
  res.send(req.params);
})

What I expect to see is 1), a JSON object with { artistID: "whatIsent"}, 2) a "whatIsent", and then 3) the same JSON object as a response when I use an API testing utility such as Postman.

Results 1) and 3) occur as expected, but here's what I see in my console:

{ artistID: 'whatIsent' }
undefined

Here is the GET request I send:
http://localhost:8080/artists/whatIsent.

What exactly is going on? Is Express translating artistId into some intermediate object that is not a string?

Edit: I used typeof req.params.artistId, and it also returns undefined...


问:
iOS app freezes after dismiss view in swift
My issue is this I have two viewControllers connected with a modal segue like normal A--->B, A has the controls like textFields, switches, buttons and a mapView where I get the userLocation. B hast only a button, and a mapView at the moment, but when I tap the exit button it does successfully dismisses viewController B and shows A only controls are frozen, can't tap anything anymore, I don't know why. Any help?

B code

```<code>import UIKit
import MapKit
import Parse
import CoreLocation

class MapaMososViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapMozosFollow: MKMapView!

    var totlaAutomozo: String!
    var fechaRegistro: String!

    override func viewDidLoad() {
        super.viewDidLoad()

        mapMozosFollow.delegate = self

        mapMozosFollow.showsUserLocation = true
        mapMozosFollow.showsTraffic = false
        mapMozosFollow.showsScale = false
        print(mapMozosFollow.userLocation.location)

    }

    override func viewDidAppear(_ animated: Bool) {

        self.displayError(error: "Exito", message: "Tu pago ha sido procesado, en unos momentos atenderemos tu orden. Total es de $\(totlaAutomozo!) la fecha registrada \(fechaRegistro!)")

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewWillDisappear(_ animated: Bool) {

    }
    @IBAction func salirTapped(_ sender: UIButton) {

            self.dismiss(animated: true, completion: {

                print("here dismissing")
            })

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        print(locations.last!.coordinate)
        centerMapOnLocation(locations.last!)
    }
    let regionRadius: CLLocationDistance = 2000

    func centerMapOnLocation(_ location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
                                                                  regionRadius * 2.0, regionRadius * 2.0)
        mapMozosFollow.setRegion(coordinateRegion, animated: true)
    }

}
</code>```

EDIT 1: A ViewController code.

```import UIKit
import Parse
import MapKit
import BraintreeDropIn
import Braintree

class ViewController: UIViewController, PayPalPaymentDelegate, PayPalFuturePaymentDelegate, PayPalProfileSharingDelegate, CLLocationManagerDelegate, UITextFieldDelegate, MKMapViewDelegate, BTDropInViewControllerDelegate {

    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var mapaLugar: MKMapView!
    @IBOutlet weak var numeroExteriorTextField: UITextField!
    @IBOutlet weak var telefonoTextField: UITextField!

    @IBOutlet weak var lavadoSwitch: UISwitch!
    @IBOutlet weak var lavadoYAspiradSwitch: UISwitch!

    @IBOutlet weak var numeroCarrosTextField: UITextField!
    @IBOutlet weak var numeroMinivanTextField: UITextField!
    @IBOutlet weak var numeroPickUpsTextField: UITextField!
    @IBOutlet weak var numeroVansTextField: UITextField!

    @IBOutlet weak var numeroAspiradoCarrosTextField: UITextField!
    @IBOutlet weak var numeroAspiradoMinivanTextField: UITextField!
    @IBOutlet weak var numeroAspiradoPickUpsTextField: UITextField!
    @IBOutlet weak var numeroAspiradoVansTextField: UITextField!

    @IBOutlet weak var botonRealizarPedido: UIButton!
    @IBOutlet weak var botonInstrucciones: UIButton!

    @IBOutlet weak var totalLabel: UILabel!

    var showAlertFirstTime: Bool = true

    var locationManager: CLLocationManager = CLLocationManager()
    var ubicacion: CLLocationCoordinate2D!

    var environment:String = PayPalEnvironmentSandbox {
        willSet(newEnvironment) {
            if (newEnvironment != environment) {
                PayPalMobile.preconnect(withEnvironment: newEnvironment)
            }
        }
    }

    var braintreeClient: BTAPIClient?

    let defaults = UserDefaults.standard

    var resultText = "" // empty
    var payPalConfig = PayPalConfiguration() // default

    var total: NSDecimalNumber!

    var vistaDeMozos: Bool = false

    var fechaRegistro: String!
    var totalToSend: String!

    @IBOutlet weak var constrainSizeMap: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        botonInstrucciones.backgroundColor = UIColor(colorLiteralRed: (200.0/255.0), green: 0.0, blue: 0.0, alpha: 1.0)
        botonInstrucciones.layer.cornerRadius = 3
        botonInstrucciones.layer.borderWidth = 2
        botonInstrucciones.layer.borderColor = UIColor.clear.cgColor
        botonInstrucciones.layer.shadowColor = UIColor(colorLiteralRed: (100.0/255.0), green: 0.0, blue: 0.0, alpha: 1.0).cgColor
        botonInstrucciones.layer.shadowOpacity = 1.0
        botonInstrucciones.layer.shadowRadius = 1.0
        botonInstrucciones.layer.shadowOffset = CGSize(width: 0, height: 3)

        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.requestAlwaysAuthorization()

        self.locationManager.startUpdatingLocation()

        NotificationCenter.default.post(name: Notification.Name(rawValue: "keyPressed"), object: nil)

        numeroCarrosTextField.delegate = self
        numeroMinivanTextField.delegate = self
        numeroPickUpsTextField.delegate = self
        numeroVansTextField.delegate = self

        numeroAspiradoCarrosTextField.delegate = self
        numeroAspiradoMinivanTextField.delegate = self
        numeroAspiradoPickUpsTextField.delegate = self
        numeroAspiradoVansTextField.delegate = self

        do {

            if defaults.object(forKey: "clientId") == nil || clientId == "000" {

                let idTest = try PFCloud.callFunction("newCutomer", withParameters: nil)
                print(idTest)
                clientId = idTest as! String
                defaults.set(clientId, forKey: "clientId")

            } else {

                print(self.clientId)
            }

        } catch let error {

            print(error)
        }

        if defaults.object(forKey: "clientId") == nil {

        } else {

            clientId = defaults.string(forKey: "clientId")!
            print(clientId)
        }

       fetchClientToken()

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ViewController.keyboardWillShow(notification:)),
            name: NSNotification.Name.UIKeyboardWillShow,
            object: nil
        )
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ViewController.keyboardWillHide(notification:)),
            name: NSNotification.Name.UIKeyboardWillHide,
            object: nil
        )

        scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.interactive

        let touch = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTapGestureCaptured(gesture:)))
        scrollView.addGestureRecognizer(touch)

    }

    func singleTapGestureCaptured(gesture: UITapGestureRecognizer){
        self.view.endEditing(true)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        if showAlertFirstTime {

            showAlertFirstTime = false
        } else {

        }
      }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        PayPalMobile.preconnect(withEnvironment: environment)

        print("stop test")

    }
    @IBAction func realizarPedidoTapped(_ sender: UIButton) {

        let numeroExterior = numeroExteriorTextField.text!
        let numeroMotosLavado = numeroCarrosTextField.text!
        let numeroDeportivosLavado = numeroMinivanTextField.text!
        let numeroCarroLavado = numeroPickUpsTextField.text!
        let numeroCamionLavado = numeroVansTextField.text!
        let numeroMotoLavadoAspirado = numeroAspiradoCarrosTextField.text!
        let numeroDeportivoLavadoAspirado = numeroAspiradoMinivanTextField.text!
        let numeroCarroLavadoAspirado = numeroAspiradoPickUpsTextField.text!
        let numeroCamionLavadoAspirado = numeroAspiradoVansTextField.text!
        let numeroTelefono = telefonoTextField.text!

        if numeroExterior == "" || numeroTelefono == "" {

            displayError("Error", message: "Te falto llenar tu numero exterior y/o telefono")

        } else {

            //Braintree init
            self.braintreeClient = BTAPIClient(authorization: clientToken)

        let items = [item1]
        let subtotal = PayPalItem.totalPrice(forItems: items)

        //var subtotal = PayPalItem.totalPrice(forItems: items)
        let shipping = NSDecimalNumber(string: "0.00")
        let tax = NSDecimalNumber(string: "0.00")

        //details ???

        let paymentDetails = PayPalPaymentDetails(subtotal: subtotal, withShipping: shipping, withTax: tax)

        self.total = subtotal.adding(shipping).adding(tax)

        let payment = PayPalPayment(amount: total, currencyCode: "MXN", shortDescription: "Automozo inc", intent: .sale)

        payment.items = items
        payment.paymentDetails = paymentDetails

        print("\(payment.localizedAmountForDisplay)")

        self.showDropIn(clientTokenOrTokenizationKey: clientToken)

        if (payment.processable) {

            let paymentViewController = PayPalPaymentViewController(payment: payment, configuration: payPalConfig, delegate: self)

        }
        else {

            print("Payment not processalbe: \(payment.description)")
            print("payment not processable \(payment)")

            displayError("Error", message: "Hubo un error al procesar tu pago, por favor intenta de nuevo.")

            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        super.prepare(for: segue, sender: sender)
        if segue.identifier == "MapaMozosSegue" {

            let mapaMozosVC = segue.destination as! MapaMososViewController
            mapaMozosVC.totlaAutomozo = totalToSend!
            mapaMozosVC.fechaRegistro = fechaRegistro
            locationManager.stopUpdatingLocation()
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField) {

        textField.resignFirstResponder()
        print("test text field ended")

        if textField.text == "" {

            textField.text = "0"
        }

        var numeroCarrosLavadoVar = numeroCarrosTextField.text!
        var numeroMinivansLavadoVar = numeroMinivanTextField.text!
        var numeroPickUpsLavadoVar = numeroPickUpsTextField.text!
        var numeroVansLavadoVar = numeroVansTextField.text!

        var numeroCarrosLavadoAspiradoVar = numeroAspiradoCarrosTextField.text!
        var numeroMinivansLavadoAspiradoVar = numeroAspiradoMinivanTextField.text!
        var numeroPickUpsLavadoAspiradoVar = numeroAspiradoPickUpsTextField.text!
        var numeroVansLavadoAspiradoVar = numeroAspiradoVansTextField.text!

        if numeroCarrosLavadoVar == "" {
            numeroCarrosLavadoVar = "0"
            numeroCarrosTextField.text = "0"
        }
        if numeroMinivansLavadoVar == "" {
            numeroMinivansLavadoVar = "0"
            numeroMinivanTextField.text = "0"

        }
        if numeroPickUpsLavadoVar == "" {
            numeroPickUpsLavadoVar = "0"
            numeroPickUpsTextField.text = "0"
        }
        if numeroVansLavadoVar == "" {
            numeroVansLavadoVar = "0"
            numeroVansTextField.text = "0"

        }
        if numeroCarrosLavadoAspiradoVar == "" {
            numeroCarrosLavadoAspiradoVar = "0"
            numeroAspiradoCarrosTextField.text = "0"
        }
        if numeroMinivansLavadoAspiradoVar == "" {
            numeroMinivansLavadoAspiradoVar = "0"
            numeroMinivanTextField.text = "0"

        }
        if numeroPickUpsLavadoAspiradoVar == "" {
            numeroPickUpsLavadoAspiradoVar = "0"
            numeroAspiradoPickUpsTextField.text = "0"
        }
        if numeroVansLavadoAspiradoVar == "" {
            numeroVansLavadoAspiradoVar = "0"
            numeroVansTextField.text = "0"

        }

        let priceOfLavadoCarro = Int(numeroCarrosLavadoVar)! * pricesLavado["LavadoCarro"]!
        let priceOfLavadoMinivan = Int(numeroMinivansLavadoVar)! * pricesLavado["LavadoMinivan"]!
        let priceOfLavadoPickUp = Int(numeroPickUpsLavadoVar)! * pricesLavado["LavadoPickUp"]!
        let priceOfLavadoVan = Int(numeroVansLavadoVar)! * pricesLavado["LavadoVan"]!

        //Lavado y Aspirado

        let priceOfLavadoYAspiradoCarro = Int(numeroCarrosLavadoAspiradoVar)! * pricesLavadoYAspirado["LavadoYAspiradoCarro"]!
        let priceOfLavadoYAspiradoMinivan = Int(numeroMinivansLavadoAspiradoVar)! * pricesLavadoYAspirado["LavadoYAspiradoMinivan"]!
        let priceOfLavadoYAspiradoPickUp = Int(numeroPickUpsLavadoAspiradoVar)! * pricesLavadoYAspirado["LavadoYAspiradoPickUp"]!
        let priceOfLavadoYAspiradoVan = Int(numeroVansLavadoAspiradoVar)! * pricesLavadoYAspirado["LavadoYAspiradoVan"]!

        let totalAutomozo = priceOfLavadoCarro + priceOfLavadoMinivan + priceOfLavadoPickUp + priceOfLavadoVan + priceOfLavadoYAspiradoCarro + priceOfLavadoYAspiradoMinivan + priceOfLavadoYAspiradoPickUp + priceOfLavadoYAspiradoVan

        print(totalAutomozo)

        totalLabel.text = "\(totalAutomozo).00"

        textField.resignFirstResponder()
    }

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {

        if (textField.text?.characters.count)! == 1 {

            print("text quota meet")
            textField.resignFirstResponder()
            self.view.endEditing(true)

            return true

        } else {

            textField.text = "0"
        }

        return true
    }

    let regionRadius: CLLocationDistance = 100

    func centerMapOnLocation(_ location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
                                                                  regionRadius * 2.0, regionRadius * 2.0)
        mapaLugar.setRegion(coordinateRegion, animated: true)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        centerMapOnLocation(locations.last!)
        ubicacion = locations.last!.coordinate

   }
    // Mark - Braintree methods

    func showDropIn(clientTokenOrTokenizationKey: String) {

        var value: Bool = false
        var totlaAutomozo = self.totalLabel.text

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM dd YYYY HH:mm"
        dateFormatter.timeZone = NSTimeZone.local

        fechaRegistro = dateFormatter.string(from: Date())

        let request =  BTDropInRequest()
        request.amount = "\(total)"
        request.currencyCode = "MXN"
        print(request.description)
        BTUIKAppearance.darkTheme()
        BTUIKAppearance.sharedInstance().activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
//            request.
        let dropIn = BTDropInController(authorization: clientTokenOrTokenizationKey, request: request)
        { (controller, result, error) in
            if (error != nil) {
                print("ERROR")
            } else if (result?.isCancelled == true) {
                print("CANCELLED")
            } else if let result = result {
                // Use the BTDropInResult properties to update your UI

                print(result.paymentOptionType)
                print("payment method: \(result.paymentMethod?.nonce)")
                print("ppayment desc \(result.paymentDescription)")
                print(result.paymentIcon.description)

                value = self.postNonceToServer(paymentMethodNonce: (result.paymentMethod?.nonce)!)

                }
                controller.dismiss(animated: true, completion: nil)

                if value {

                    self.locationManager.stopUpdatingLocation()

                    self.performSegue(withIdentifier: "MapaMozosSegue", sender: self)

                    self.vistaDeMozos = true

                } else {

                    self.displayError("Alerta", message: "El pedido ha sido cancelado exitosamente.")

                    //top row
                    self.numeroCarrosTextField.text = "0"
                    self.numeroMinivanTextField.text = "0"
                    self.numeroPickUpsTextField.text = "0"
                    self.numeroVansTextField.text = "0"

                    //bottom row
                    self.numeroAspiradoCarrosTextField.text = "0"
                    self.numeroAspiradoMinivanTextField.text = "0"
                    self.numeroAspiradoPickUpsTextField.text = "0"
                    self.numeroAspiradoVansTextField.text = "0"

                    //data
                    self.telefonoTextField.text = ""
                    self.telefonoTextField.text = ""
                }
            }
            self.present(dropIn!, animated: true, completion: nil)

    }

    func userDidCancelPayment() {
        self.dismiss(animated: true, completion: nil)
    }

    func postNonceToServer(paymentMethodNonce: String) -> Bool {

        var val = true

        do {
            var response = try PFCloud.callFunction("checkout", withParameters: ["payment_method_nonce":paymentMethodNonce, "amount":"\(total!).00", "customerId": clientId])
            print(response)

        } catch let error {

            print(error.localizedDescription)
        }

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM. dd, YYYY HH:mm"
        dateFormatter.timeZone = NSTimeZone.local

        fechaRegistro = dateFormatter.string(from: Date())

        let usuarioPagado: PFObject = PFObject(className: "Ordenes")
        let location: PFGeoPoint = PFGeoPoint(latitude: ubicacion.latitude, longitude: ubicacion.longitude)
        usuarioPagado["Ubicacion"] = location
        usuarioPagado["NumeroExterior"] = numeroExteriorTextField.text!
        usuarioPagado["NumeroDeTelefono"] = telefonoTextField.text!
        usuarioPagado["LavadoCarro"] = numeroCarrosTextField.text!
        usuarioPagado["LavadoMiniVan"] = numeroMinivanTextField.text!
        usuarioPagado["LavadoPickUp"] = numeroPickUpsTextField.text!
        usuarioPagado["LavadoDeVan"] = numeroVansTextField.text!
        usuarioPagado["LavadoAspiradoCarro"] = numeroAspiradoCarrosTextField.text!
        usuarioPagado["LavadoAspiradoMiniVan"] = numeroAspiradoMinivanTextField.text!
        usuarioPagado["LavadoAspiradoPickUp"] = numeroAspiradoPickUpsTextField.text!
        usuarioPagado["LavadoAspiradoDeVan"] = numeroAspiradoVansTextField.text!
        usuarioPagado["Monto"] = totalLabel.text!
        usuarioPagado["NumeroDeTelefono"] = telefonoTextField.text!
        usuarioPagado["TipoDeCelular"] = "iPhone"
        usuarioPagado["FechaDeOrden"] = fechaRegistro

        self.totalToSend = self.totalLabel.text!

                usuarioPagado.saveInBackground() {
                    (success: Bool, error: Error?) -> Void in

                    if error == nil {

                        //done
                        print("saved object")
                        val = false

                    } else {

                        //not done
                        print("not saved because \(error?.localizedDescription)")

                    }
                }

        numeroCarrosTextField.text = "0"
        numeroMinivanTextField.text = "0"
        numeroPickUpsTextField.text = "0"
        numeroVansTextField.text = "0"

        numeroAspiradoCarrosTextField.text = "0"
        numeroAspiradoMinivanTextField.text = "0"
        numeroAspiradoPickUpsTextField.text = "0"
        numeroAspiradoVansTextField.text = "0"
        totalLabel.text = "00.00"
        self.lavadoSwitch.isOn = false
        self.lavadoYAspiradSwitch.isOn = false

        self.numeroExteriorTextField.text = ""
        self.telefonoTextField.text = ""

        self.numeroCarrosTextField.isHidden = true
        self.numeroMinivanTextField.isHidden = true
        self.numeroPickUpsTextField.isHidden = true
        self.numeroVansTextField.isHidden = true

        self.numeroAspiradoCarrosTextField.isHidden = true
        self.numeroAspiradoMinivanTextField.isHidden = true
        self.numeroAspiradoPickUpsTextField.isHidden = true
        self.numeroAspiradoVansTextField.isHidden = true
    return val

    }

    func drop(inViewControllerDidLoad viewController: BTDropInViewController) {

        print("did load view drop")

    }

    func drop(inViewControllerDidCancel viewController: BTDropInViewController) {

        print("did cancel drop payment")

    }

    func drop(inViewControllerWillComplete viewController: BTDropInViewController) {

        print("drop will complete payment")

    }

    func drop(_ viewController: BTDropInViewController, didSucceedWithTokenization paymentMethodNonce: BTPaymentMethodNonce) {

        var totlaAutomozo = totalLabel.text

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM dd YYYY HH:mm"
        dateFormatter.timeZone = NSTimeZone.local

        fechaRegistro = dateFormatter.string(from: Date())

        print("did succeeded with tokenization")
        print(" \(paymentMethodNonce.nonce)")

        var value = postNonceToServer(paymentMethodNonce: paymentMethodNonce.nonce)

        self.dismiss(animated: true, completion: nil)

        if value {

            displayError("Exito", message: "Tu pago ha sido procesado, en unos momentos atenderemos tu orden. Total es de $\(totlaAutomozo ?? "00.00") la fecha registrada \(fechaRegistro)")

        } else {

            self.displayError("Error", message: "Hubo un error al guardar tu informacion, ponte en contacto con nosotros.")
        }

    }

    func fetchClientToken() {

        do {

            let response = try PFCloud.callFunction("generateToken", withParameters: ["clientId": clientId])
           self.clientToken = response as! String

        } catch let error {

            print(error)
        }
    }

    func keyboardWillShow(notification:NSNotification){

        var userInfo = notification.userInfo!
        var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        keyboardFrame = self.view.convert(keyboardFrame, from: nil)

        var contentInset:UIEdgeInsets = self.scrollView.contentInset
        contentInset.bottom = keyboardFrame.size.height
        self.scrollView.contentInset = contentInset
    }

    func keyboardWillHide(notification:NSNotification){

        let contentInset:UIEdgeInsets = UIEdgeInsets.zero
        self.scrollView.contentInset = contentInset
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)

    }

    func showFullMap() {

        if vistaDeMozos {

            self.telefonoTextField.isHidden = true
            self.botonRealizarPedido.isHidden = true
            self.lavadoSwitch.isHidden = true
            self.lavadoYAspiradSwitch.isHidden = true
            self.botonRealizarPedido.isHidden = true

            self.numeroExteriorTextField.isHidden = true

            self.numeroCarrosTextField.isHidden = true
            self.numeroMinivanTextField.isHidden = true
            self.numeroPickUpsTextField.isHidden = true
            self.numeroVansTextField.isHidden = true

            self.numeroAspiradoCarrosTextField.isHidden = true
            self.numeroAspiradoMinivanTextField.isHidden = true
            self.numeroAspiradoPickUpsTextField.isHidden = true
            self.numeroAspiradoVansTextField.isHidden = true

            self.view.layoutSubviews()
        } else {

        }
    }
}
```

答:
Make sure to check if any NSDelayedPerforming methods are blocking the main thread (Foundation > NSRunloop). i.e.  performSelector afterDelay...

In my case (Objective-C) I had to use cancelPreviousPerformRequestsWithTarget in the viewDidDisappear instance method of the ViewController.

```<code>[NSObject cancelPreviousPerformRequestsWithTarget:self];
</code>```

I think the same applies when using NSTimer.scheduledTimerWithTimeInterval (Swift) without invalidating the timer in the proper life cycle method.

Body:
My issue is this I have two viewControllers connected with a modal segue like normal A--->B, A has the controls like textFields, switches, buttons and a mapView where I get the userLocation. B hast only a button, and a mapView at the moment, but when I tap the exit button it does successfully dismisses viewController B and shows A only controls are frozen, can't tap anything anymore, I don't know why. Any help?

B code

import UIKit
import MapKit
import Parse
import CoreLocation

class MapaMososViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapMozosFollow: MKMapView!

    var totlaAutomozo: String!
    var fechaRegistro: String!

    override func viewDidLoad() {
        super.viewDidLoad()

        mapMozosFollow.delegate = self

        mapMozosFollow.showsUserLocation = true
        mapMozosFollow.showsTraffic = false
        mapMozosFollow.showsScale = false
        print(mapMozosFollow.userLocation.location)

    }

    override func viewDidAppear(_ animated: Bool) {

        self.displayError(error: "Exito", message: "Tu pago ha sido procesado, en unos momentos atenderemos tu orden. Total es de $\(totlaAutomozo!) la fecha registrada \(fechaRegistro!)")

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewWillDisappear(_ animated: Bool) {

    }
    @IBAction func salirTapped(_ sender: UIButton) {

            self.dismiss(animated: true, completion: {

                print("here dismissing")
            })

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        print(locations.last!.coordinate)
        centerMapOnLocation(locations.last!)
    }
    let regionRadius: CLLocationDistance = 2000

    func centerMapOnLocation(_ location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
                                                                  regionRadius * 2.0, regionRadius * 2.0)
        mapMozosFollow.setRegion(coordinateRegion, animated: true)
    }

}

EDIT 1: A ViewController code.

import UIKit
import Parse
import MapKit
import BraintreeDropIn
import Braintree

class ViewController: UIViewController, PayPalPaymentDelegate, PayPalFuturePaymentDelegate, PayPalProfileSharingDelegate, CLLocationManagerDelegate, UITextFieldDelegate, MKMapViewDelegate, BTDropInViewControllerDelegate {

    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var mapaLugar: MKMapView!
    @IBOutlet weak var numeroExteriorTextField: UITextField!
    @IBOutlet weak var telefonoTextField: UITextField!

    @IBOutlet weak var lavadoSwitch: UISwitch!
    @IBOutlet weak var lavadoYAspiradSwitch: UISwitch!

    @IBOutlet weak var numeroCarrosTextField: UITextField!
    @IBOutlet weak var numeroMinivanTextField: UITextField!
    @IBOutlet weak var numeroPickUpsTextField: UITextField!
    @IBOutlet weak var numeroVansTextField: UITextField!

    @IBOutlet weak var numeroAspiradoCarrosTextField: UITextField!
    @IBOutlet weak var numeroAspiradoMinivanTextField: UITextField!
    @IBOutlet weak var numeroAspiradoPickUpsTextField: UITextField!
    @IBOutlet weak var numeroAspiradoVansTextField: UITextField!

    @IBOutlet weak var botonRealizarPedido: UIButton!
    @IBOutlet weak var botonInstrucciones: UIButton!

    @IBOutlet weak var totalLabel: UILabel!

    var showAlertFirstTime: Bool = true

    var locationManager: CLLocationManager = CLLocationManager()
    var ubicacion: CLLocationCoordinate2D!

    var environment:String = PayPalEnvironmentSandbox {
        willSet(newEnvironment) {
            if (newEnvironment != environment) {
                PayPalMobile.preconnect(withEnvironment: newEnvironment)
            }
        }
    }

    var braintreeClient: BTAPIClient?

    let defaults = UserDefaults.standard

    var resultText = "" // empty
    var payPalConfig = PayPalConfiguration() // default

    var total: NSDecimalNumber!

    var vistaDeMozos: Bool = false

    var fechaRegistro: String!
    var totalToSend: String!

    @IBOutlet weak var constrainSizeMap: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        botonInstrucciones.backgroundColor = UIColor(colorLiteralRed: (200.0/255.0), green: 0.0, blue: 0.0, alpha: 1.0)
        botonInstrucciones.layer.cornerRadius = 3
        botonInstrucciones.layer.borderWidth = 2
        botonInstrucciones.layer.borderColor = UIColor.clear.cgColor
        botonInstrucciones.layer.shadowColor = UIColor(colorLiteralRed: (100.0/255.0), green: 0.0, blue: 0.0, alpha: 1.0).cgColor
        botonInstrucciones.layer.shadowOpacity = 1.0
        botonInstrucciones.layer.shadowRadius = 1.0
        botonInstrucciones.layer.shadowOffset = CGSize(width: 0, height: 3)

        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.requestAlwaysAuthorization()

        self.locationManager.startUpdatingLocation()

        NotificationCenter.default.post(name: Notification.Name(rawValue: "keyPressed"), object: nil)

        numeroCarrosTextField.delegate = self
        numeroMinivanTextField.delegate = self
        numeroPickUpsTextField.delegate = self
        numeroVansTextField.delegate = self

        numeroAspiradoCarrosTextField.delegate = self
        numeroAspiradoMinivanTextField.delegate = self
        numeroAspiradoPickUpsTextField.delegate = self
        numeroAspiradoVansTextField.delegate = self

        do {

            if defaults.object(forKey: "clientId") == nil || clientId == "000" {

                let idTest = try PFCloud.callFunction("newCutomer", withParameters: nil)
                print(idTest)
                clientId = idTest as! String
                defaults.set(clientId, forKey: "clientId")

            } else {

                print(self.clientId)
            }

        } catch let error {

            print(error)
        }

        if defaults.object(forKey: "clientId") == nil {

        } else {

            clientId = defaults.string(forKey: "clientId")!
            print(clientId)
        }

       fetchClientToken()

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ViewController.keyboardWillShow(notification:)),
            name: NSNotification.Name.UIKeyboardWillShow,
            object: nil
        )
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ViewController.keyboardWillHide(notification:)),
            name: NSNotification.Name.UIKeyboardWillHide,
            object: nil
        )

        scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.interactive

        let touch = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTapGestureCaptured(gesture:)))
        scrollView.addGestureRecognizer(touch)

    }

    func singleTapGestureCaptured(gesture: UITapGestureRecognizer){
        self.view.endEditing(true)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        if showAlertFirstTime {

            showAlertFirstTime = false
        } else {

        }
      }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        PayPalMobile.preconnect(withEnvironment: environment)

        print("stop test")

    }
    @IBAction func realizarPedidoTapped(_ sender: UIButton) {

        let numeroExterior = numeroExteriorTextField.text!
        let numeroMotosLavado = numeroCarrosTextField.text!
        let numeroDeportivosLavado = numeroMinivanTextField.text!
        let numeroCarroLavado = numeroPickUpsTextField.text!
        let numeroCamionLavado = numeroVansTextField.text!
        let numeroMotoLavadoAspirado = numeroAspiradoCarrosTextField.text!
        let numeroDeportivoLavadoAspirado = numeroAspiradoMinivanTextField.text!
        let numeroCarroLavadoAspirado = numeroAspiradoPickUpsTextField.text!
        let numeroCamionLavadoAspirado = numeroAspiradoVansTextField.text!
        let numeroTelefono = telefonoTextField.text!

        if numeroExterior == "" || numeroTelefono == "" {

            displayError("Error", message: "Te falto llenar tu numero exterior y/o telefono")

        } else {

            //Braintree init
            self.braintreeClient = BTAPIClient(authorization: clientToken)

        let items = [item1]
        let subtotal = PayPalItem.totalPrice(forItems: items)

        //var subtotal = PayPalItem.totalPrice(forItems: items)
        let shipping = NSDecimalNumber(string: "0.00")
        let tax = NSDecimalNumber(string: "0.00")

        //details ???

        let paymentDetails = PayPalPaymentDetails(subtotal: subtotal, withShipping: shipping, withTax: tax)

        self.total = subtotal.adding(shipping).adding(tax)

        let payment = PayPalPayment(amount: total, currencyCode: "MXN", shortDescription: "Automozo inc", intent: .sale)

        payment.items = items
        payment.paymentDetails = paymentDetails

        print("\(payment.localizedAmountForDisplay)")

        self.showDropIn(clientTokenOrTokenizationKey: clientToken)

        if (payment.processable) {

            let paymentViewController = PayPalPaymentViewController(payment: payment, configuration: payPalConfig, delegate: self)

        }
        else {

            print("Payment not processalbe: \(payment.description)")
            print("payment not processable \(payment)")

            displayError("Error", message: "Hubo un error al procesar tu pago, por favor intenta de nuevo.")

            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        super.prepare(for: segue, sender: sender)
        if segue.identifier == "MapaMozosSegue" {

            let mapaMozosVC = segue.destination as! MapaMososViewController
            mapaMozosVC.totlaAutomozo = totalToSend!
            mapaMozosVC.fechaRegistro = fechaRegistro
            locationManager.stopUpdatingLocation()
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField) {

        textField.resignFirstResponder()
        print("test text field ended")

        if textField.text == "" {

            textField.text = "0"
        }

        var numeroCarrosLavadoVar = numeroCarrosTextField.text!
        var numeroMinivansLavadoVar = numeroMinivanTextField.text!
        var numeroPickUpsLavadoVar = numeroPickUpsTextField.text!
        var numeroVansLavadoVar = numeroVansTextField.text!

        var numeroCarrosLavadoAspiradoVar = numeroAspiradoCarrosTextField.text!
        var numeroMinivansLavadoAspiradoVar = numeroAspiradoMinivanTextField.text!
        var numeroPickUpsLavadoAspiradoVar = numeroAspiradoPickUpsTextField.text!
        var numeroVansLavadoAspiradoVar = numeroAspiradoVansTextField.text!

        if numeroCarrosLavadoVar == "" {
            numeroCarrosLavadoVar = "0"
            numeroCarrosTextField.text = "0"
        }
        if numeroMinivansLavadoVar == "" {
            numeroMinivansLavadoVar = "0"
            numeroMinivanTextField.text = "0"

        }
        if numeroPickUpsLavadoVar == "" {
            numeroPickUpsLavadoVar = "0"
            numeroPickUpsTextField.text = "0"
        }
        if numeroVansLavadoVar == "" {
            numeroVansLavadoVar = "0"
            numeroVansTextField.text = "0"

        }
        if numeroCarrosLavadoAspiradoVar == "" {
            numeroCarrosLavadoAspiradoVar = "0"
            numeroAspiradoCarrosTextField.text = "0"
        }
        if numeroMinivansLavadoAspiradoVar == "" {
            numeroMinivansLavadoAspiradoVar = "0"
            numeroMinivanTextField.text = "0"

        }
        if numeroPickUpsLavadoAspiradoVar == "" {
            numeroPickUpsLavadoAspiradoVar = "0"
            numeroAspiradoPickUpsTextField.text = "0"
        }
        if numeroVansLavadoAspiradoVar == "" {
            numeroVansLavadoAspiradoVar = "0"
            numeroVansTextField.text = "0"

        }

        let priceOfLavadoCarro = Int(numeroCarrosLavadoVar)! * pricesLavado["LavadoCarro"]!
        let priceOfLavadoMinivan = Int(numeroMinivansLavadoVar)! * pricesLavado["LavadoMinivan"]!
        let priceOfLavadoPickUp = Int(numeroPickUpsLavadoVar)! * pricesLavado["LavadoPickUp"]!
        let priceOfLavadoVan = Int(numeroVansLavadoVar)! * pricesLavado["LavadoVan"]!

        //Lavado y Aspirado

        let priceOfLavadoYAspiradoCarro = Int(numeroCarrosLavadoAspiradoVar)! * pricesLavadoYAspirado["LavadoYAspiradoCarro"]!
        let priceOfLavadoYAspiradoMinivan = Int(numeroMinivansLavadoAspiradoVar)! * pricesLavadoYAspirado["LavadoYAspiradoMinivan"]!
        let priceOfLavadoYAspiradoPickUp = Int(numeroPickUpsLavadoAspiradoVar)! * pricesLavadoYAspirado["LavadoYAspiradoPickUp"]!
        let priceOfLavadoYAspiradoVan = Int(numeroVansLavadoAspiradoVar)! * pricesLavadoYAspirado["LavadoYAspiradoVan"]!

        let totalAutomozo = priceOfLavadoCarro + priceOfLavadoMinivan + priceOfLavadoPickUp + priceOfLavadoVan + priceOfLavadoYAspiradoCarro + priceOfLavadoYAspiradoMinivan + priceOfLavadoYAspiradoPickUp + priceOfLavadoYAspiradoVan

        print(totalAutomozo)

        totalLabel.text = "\(totalAutomozo).00"

        textField.resignFirstResponder()
    }

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {

        if (textField.text?.characters.count)! == 1 {

            print("text quota meet")
            textField.resignFirstResponder()
            self.view.endEditing(true)

            return true

        } else {

            textField.text = "0"
        }

        return true
    }

    let regionRadius: CLLocationDistance = 100

    func centerMapOnLocation(_ location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
                                                                  regionRadius * 2.0, regionRadius * 2.0)
        mapaLugar.setRegion(coordinateRegion, animated: true)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        centerMapOnLocation(locations.last!)
        ubicacion = locations.last!.coordinate

   }
    // Mark - Braintree methods

    func showDropIn(clientTokenOrTokenizationKey: String) {

        var value: Bool = false
        var totlaAutomozo = self.totalLabel.text

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM dd YYYY HH:mm"
        dateFormatter.timeZone = NSTimeZone.local

        fechaRegistro = dateFormatter.string(from: Date())

        let request =  BTDropInRequest()
        request.amount = "\(total)"
        request.currencyCode = "MXN"
        print(request.description)
        BTUIKAppearance.darkTheme()
        BTUIKAppearance.sharedInstance().activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
//            request.
        let dropIn = BTDropInController(authorization: clientTokenOrTokenizationKey, request: request)
        { (controller, result, error) in
            if (error != nil) {
                print("ERROR")
            } else if (result?.isCancelled == true) {
                print("CANCELLED")
            } else if let result = result {
                // Use the BTDropInResult properties to update your UI

                print(result.paymentOptionType)
                print("payment method: \(result.paymentMethod?.nonce)")
                print("ppayment desc \(result.paymentDescription)")
                print(result.paymentIcon.description)

                value = self.postNonceToServer(paymentMethodNonce: (result.paymentMethod?.nonce)!)

                }
                controller.dismiss(animated: true, completion: nil)

                if value {

                    self.locationManager.stopUpdatingLocation()

                    self.performSegue(withIdentifier: "MapaMozosSegue", sender: self)

                    self.vistaDeMozos = true

                } else {

                    self.displayError("Alerta", message: "El pedido ha sido cancelado exitosamente.")

                    //top row
                    self.numeroCarrosTextField.text = "0"
                    self.numeroMinivanTextField.text = "0"
                    self.numeroPickUpsTextField.text = "0"
                    self.numeroVansTextField.text = "0"

                    //bottom row
                    self.numeroAspiradoCarrosTextField.text = "0"
                    self.numeroAspiradoMinivanTextField.text = "0"
                    self.numeroAspiradoPickUpsTextField.text = "0"
                    self.numeroAspiradoVansTextField.text = "0"

                    //data
                    self.telefonoTextField.text = ""
                    self.telefonoTextField.text = ""
                }
            }
            self.present(dropIn!, animated: true, completion: nil)

    }

    func userDidCancelPayment() {
        self.dismiss(animated: true, completion: nil)
    }

    func postNonceToServer(paymentMethodNonce: String) -> Bool {

        var val = true

        do {
            var response = try PFCloud.callFunction("checkout", withParameters: ["payment_method_nonce":paymentMethodNonce, "amount":"\(total!).00", "customerId": clientId])
            print(response)

        } catch let error {

            print(error.localizedDescription)
        }

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM. dd, YYYY HH:mm"
        dateFormatter.timeZone = NSTimeZone.local

        fechaRegistro = dateFormatter.string(from: Date())

        let usuarioPagado: PFObject = PFObject(className: "Ordenes")
        let location: PFGeoPoint = PFGeoPoint(latitude: ubicacion.latitude, longitude: ubicacion.longitude)
        usuarioPagado["Ubicacion"] = location
        usuarioPagado["NumeroExterior"] = numeroExteriorTextField.text!
        usuarioPagado["NumeroDeTelefono"] = telefonoTextField.text!
        usuarioPagado["LavadoCarro"] = numeroCarrosTextField.text!
        usuarioPagado["LavadoMiniVan"] = numeroMinivanTextField.text!
        usuarioPagado["LavadoPickUp"] = numeroPickUpsTextField.text!
        usuarioPagado["LavadoDeVan"] = numeroVansTextField.text!
        usuarioPagado["LavadoAspiradoCarro"] = numeroAspiradoCarrosTextField.text!
        usuarioPagado["LavadoAspiradoMiniVan"] = numeroAspiradoMinivanTextField.text!
        usuarioPagado["LavadoAspiradoPickUp"] = numeroAspiradoPickUpsTextField.text!
        usuarioPagado["LavadoAspiradoDeVan"] = numeroAspiradoVansTextField.text!
        usuarioPagado["Monto"] = totalLabel.text!
        usuarioPagado["NumeroDeTelefono"] = telefonoTextField.text!
        usuarioPagado["TipoDeCelular"] = "iPhone"
        usuarioPagado["FechaDeOrden"] = fechaRegistro

        self.totalToSend = self.totalLabel.text!

                usuarioPagado.saveInBackground() {
                    (success: Bool, error: Error?) -> Void in

                    if error == nil {

                        //done
                        print("saved object")
                        val = false

                    } else {

                        //not done
                        print("not saved because \(error?.localizedDescription)")

                    }
                }

        numeroCarrosTextField.text = "0"
        numeroMinivanTextField.text = "0"
        numeroPickUpsTextField.text = "0"
        numeroVansTextField.text = "0"

        numeroAspiradoCarrosTextField.text = "0"
        numeroAspiradoMinivanTextField.text = "0"
        numeroAspiradoPickUpsTextField.text = "0"
        numeroAspiradoVansTextField.text = "0"
        totalLabel.text = "00.00"
        self.lavadoSwitch.isOn = false
        self.lavadoYAspiradSwitch.isOn = false

        self.numeroExteriorTextField.text = ""
        self.telefonoTextField.text = ""

        self.numeroCarrosTextField.isHidden = true
        self.numeroMinivanTextField.isHidden = true
        self.numeroPickUpsTextField.isHidden = true
        self.numeroVansTextField.isHidden = true

        self.numeroAspiradoCarrosTextField.isHidden = true
        self.numeroAspiradoMinivanTextField.isHidden = true
        self.numeroAspiradoPickUpsTextField.isHidden = true
        self.numeroAspiradoVansTextField.isHidden = true
    return val

    }

    func drop(inViewControllerDidLoad viewController: BTDropInViewController) {

        print("did load view drop")

    }

    func drop(inViewControllerDidCancel viewController: BTDropInViewController) {

        print("did cancel drop payment")

    }

    func drop(inViewControllerWillComplete viewController: BTDropInViewController) {

        print("drop will complete payment")

    }

    func drop(_ viewController: BTDropInViewController, didSucceedWithTokenization paymentMethodNonce: BTPaymentMethodNonce) {

        var totlaAutomozo = totalLabel.text

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM dd YYYY HH:mm"
        dateFormatter.timeZone = NSTimeZone.local

        fechaRegistro = dateFormatter.string(from: Date())

        print("did succeeded with tokenization")
        print(" \(paymentMethodNonce.nonce)")

        var value = postNonceToServer(paymentMethodNonce: paymentMethodNonce.nonce)

        self.dismiss(animated: true, completion: nil)

        if value {

            displayError("Exito", message: "Tu pago ha sido procesado, en unos momentos atenderemos tu orden. Total es de $\(totlaAutomozo ?? "00.00") la fecha registrada \(fechaRegistro)")

        } else {

            self.displayError("Error", message: "Hubo un error al guardar tu informacion, ponte en contacto con nosotros.")
        }

    }

    func fetchClientToken() {

        do {

            let response = try PFCloud.callFunction("generateToken", withParameters: ["clientId": clientId])
           self.clientToken = response as! String

        } catch let error {

            print(error)
        }
    }

    func keyboardWillShow(notification:NSNotification){

        var userInfo = notification.userInfo!
        var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        keyboardFrame = self.view.convert(keyboardFrame, from: nil)

        var contentInset:UIEdgeInsets = self.scrollView.contentInset
        contentInset.bottom = keyboardFrame.size.height
        self.scrollView.contentInset = contentInset
    }

    func keyboardWillHide(notification:NSNotification){

        let contentInset:UIEdgeInsets = UIEdgeInsets.zero
        self.scrollView.contentInset = contentInset
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)

    }

    func showFullMap() {

        if vistaDeMozos {

            self.telefonoTextField.isHidden = true
            self.botonRealizarPedido.isHidden = true
            self.lavadoSwitch.isHidden = true
            self.lavadoYAspiradSwitch.isHidden = true
            self.botonRealizarPedido.isHidden = true

            self.numeroExteriorTextField.isHidden = true

            self.numeroCarrosTextField.isHidden = true
            self.numeroMinivanTextField.isHidden = true
            self.numeroPickUpsTextField.isHidden = true
            self.numeroVansTextField.isHidden = true

            self.numeroAspiradoCarrosTextField.isHidden = true
            self.numeroAspiradoMinivanTextField.isHidden = true
            self.numeroAspiradoPickUpsTextField.isHidden = true
            self.numeroAspiradoVansTextField.isHidden = true

            self.view.layoutSubviews()
        } else {

        }
    }
}

Body:
Make sure to check if any NSDelayedPerforming methods are blocking the main thread (Foundation > NSRunloop). i.e.  performSelector afterDelay...

In my case (Objective-C) I had to use cancelPreviousPerformRequestsWithTarget in the viewDidDisappear instance method of the ViewController.

[NSObject cancelPreviousPerformRequestsWithTarget:self];

I think the same applies when using NSTimer.scheduledTimerWithTimeInterval (Swift) without invalidating the timer in the proper life cycle method.


问:
Get the Link in a string using regex
I need to check if a string contains a link and print it. So far this is my code

```<code>string strRegex = @"(http://\w+\.\w+\.\w+)";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"An http://w.facebook.me  http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd ahttp vhttp b... ../ .. extraordinary day dawns with each new day.";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    Console.WriteLine(myMatch.Value);
  }
}
</code>```

Output:

```<code>http://w.facebook.me
http://www.w3.org
</code>```

The output should be

```<code>http://w.facebook.me
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd
</code>```

In my regex i don't want to add another \w+ because i didn't know how many slash and how long words are there will be in a link .

So how can i do this better? how can i get the link without knowing how long the link will be?

Thank you

答:
Change the regex to

```<code>"(http://\w+\.\w+\.\w+(\/\w+)*)"
</code>```

If you want to match links like http://w.facebook.me/ i.e. with an extra slash at the end just change it to

```<code>"(http://\w+\.\w+\.\w+(\/\w+)*\/?)"
</code>```

Title: Get the Link in a string using regex

Body:
I need to check if a string contains a link and print it. So far this is my code

string strRegex = @"(http://\w+\.\w+\.\w+)";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"An http://w.facebook.me  http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd ahttp vhttp b... ../ .. extraordinary day dawns with each new day.";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    Console.WriteLine(myMatch.Value);
  }
}

Output:

http://w.facebook.me
http://www.w3.org

The output should be

http://w.facebook.me
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd

In my regex i don't want to add another \w+ because i didn't know how many slash and how long words are there will be in a link .

So how can i do this better? how can i get the link without knowing how long the link will be?

Thank you

Body:
Change the regex to

"(http://\w+\.\w+\.\w+(\/\w+)*)"

If you want to match links like http://w.facebook.me/ i.e. with an extra slash at the end just change it to

"(http://\w+\.\w+\.\w+(\/\w+)*\/?)"


问:
Calling a function inside a class to set the element of list
I'm trying to implement my first class, partly as a way to break up the modeling and solving of a math problem I'm having trouble with. I don't think my problem relates to the class, but...?

The error keeps telling me that: "NameError: global name 'corner2' is not defined"

I tried moving the function call, but it still doesn't recognize it, so I put it back into the list declaration in my init function.

Here is my code:

```<code>class RotatedRectangle(object):

def corner1(a,b):
    a/=2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner2(a,b):
    a/=-2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner3(a,b):
    a/=-2
    b/=-2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner4(a,b):
    a/=2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def __init__(self, a, b,):
        """Return a Rotated rectangle object whose name is a function of a and b."""
        self.name = str(a) + "," + str(b) + "-rectangle"
        self.corners = [corner1(a,b), corner2(a,b), corner3(a,b), corner4(a,b)]

"""A rectangle with sides equal to even integers a and b is drawn on the          Cartesian plane.Its center (the intersection point of its diagonals) coincides with the point (0, 0),but the sides of the rectangle are not parallel to the axes; instead, they are forming 45 degree angles with the axes.

How many points with integer coordinates are located inside the given   rectangle (including on its sides)? """
</code>```

答:
You have a few identation errors, and you forget to add the self parameter, it should be:

```<code>import math

class RotatedRectangle(object):
  def __init__(self, a, b,):
        """Return a Rotated rectangle object whose name is a function of a and b."""
        self.name = str(a) + "," + str(b) + "-rectangle"
        self.corners = [self.corner1(a,b), self.corner2(a,b), self.corner3(a,b), self.corner4(a,b)]

  def corner1(self,a,b):
      a/=2
      b/=2
      x=(a-b)*math.sin(math.pi/4)
      y=(a+b)*math.sin(math.pi/4)
      return (x,y)

  def corner2(self,a,b):
      a/=-2
      b/=2
      x=(a-b)*math.sin(math.pi/4)
      y=(a+b)*math.sin(math.pi/4)
      return (x,y)

  def corner3(self,a,b):
      a/=-2
      b/=-2
      x=(a-b)*math.sin(math.pi/4)
      y=(a+b)*math.sin(math.pi/4)
      return (x,y)

  def corner4(self,a,b):
      a/=2
      b/=2
      x=(a-b)*math.sin(math.pi/4)
      y=(a+b)*math.sin(math.pi/4)
      return (x,y)
</code>```

I strongly recommend to you to read this question and all the answers What is the purpose of self?

Body:
I'm trying to implement my first class, partly as a way to break up the modeling and solving of a math problem I'm having trouble with. I don't think my problem relates to the class, but...?

The error keeps telling me that: "NameError: global name 'corner2' is not defined"

I tried moving the function call, but it still doesn't recognize it, so I put it back into the list declaration in my init function.

Here is my code:

class RotatedRectangle(object):

def corner1(a,b):
    a/=2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner2(a,b):
    a/=-2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner3(a,b):
    a/=-2
    b/=-2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner4(a,b):
    a/=2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def __init__(self, a, b,):
        """Return a Rotated rectangle object whose name is a function of a and b."""
        self.name = str(a) + "," + str(b) + "-rectangle"
        self.corners = [corner1(a,b), corner2(a,b), corner3(a,b), corner4(a,b)]

"""A rectangle with sides equal to even integers a and b is drawn on the          Cartesian plane.Its center (the intersection point of its diagonals) coincides with the point (0, 0),but the sides of the rectangle are not parallel to the axes; instead, they are forming 45 degree angles with the axes.

How many points with integer coordinates are located inside the given   rectangle (including on its sides)? """

Body:
You have a few identation errors, and you forget to add the self parameter, it should be:

import math

class RotatedRectangle(object):
  def __init__(self, a, b,):
        """Return a Rotated rectangle object whose name is a function of a and b."""
        self.name = str(a) + "," + str(b) + "-rectangle"
        self.corners = [self.corner1(a,b), self.corner2(a,b), self.corner3(a,b), self.corner4(a,b)]

  def corner1(self,a,b):
      a/=2
      b/=2
      x=(a-b)*math.sin(math.pi/4)
      y=(a+b)*math.sin(math.pi/4)
      return (x,y)

  def corner2(self,a,b):
      a/=-2
      b/=2
      x=(a-b)*math.sin(math.pi/4)
      y=(a+b)*math.sin(math.pi/4)
      return (x,y)

  def corner3(self,a,b):
      a/=-2
      b/=-2
      x=(a-b)*math.sin(math.pi/4)
      y=(a+b)*math.sin(math.pi/4)
      return (x,y)

  def corner4(self,a,b):
      a/=2
      b/=2
      x=(a-b)*math.sin(math.pi/4)
      y=(a+b)*math.sin(math.pi/4)
      return (x,y)

I strongly recommend to you to read this question and all the answers What is the purpose of self?


问:
Electron, expose changing global variable to external modules
I have developed an Electron app with cytoscape.js for graph analysis. Currently, I am in the process of refactoring the code base and moving functions to external modules. Currently I am battling with the variable scope.

I have a number of variables that change when a user interacts with a graph.

I load different UIs (buttons) depending on the type of analysis.

Issue: I cannot pass the recent value of a variable to a module in a way that will simplify the code.

The following code shows the core issue.

```<code>// app.js

// require the module
const printValue = require('./printValue.js')

// global variable that I want to access
let selectedNode = ''

// called when a user clicks on node on the graph
cytoscape.on('tap', 'node', selection => {
  // stores the node's data
  selectedNode = selection.target[0]

  // I wan't to avoid that, since I load different configurations
  printValue(selectedNode) // prints the most recent value
})

// loads the different buttons
if (configuration === '1') {
  // I want to transfer it to an external module
  const button = document.getElementById('button-id')
  button.addEventListener('click', () => {
   console.log(selectedNode) // prints the most recent value
  })

  // I want to make this part work
  printValue(selectedNode) // prints '', the initial value of the variable
} else if (configuration === '2') {
  // loads different buttons with different functions
}
</code>```

The module has the following code

```<code>  // module.js

  module.exports = function printValue (value) {
    const button = document.getElementById('button-id')
    button.addEventListener('click', () => {
      console.log(value)
    })
  }
</code>```

What I want to do, is to move the button declarations and related functions of each configuration in modules. Then call those modules based on the app configuration the user has selected.

答:
Credit goes to Royalbingbong for his helpful comment and reference to pass-by-value.

This was very helpful link where the topic is explained in detail.

Here is the updated (working) code sample.

selectedNode was declared as a string (primitive type), so it couldn't pass the updated value to the module. selectedNode was changed to an object and the variable value is stored with the output key. The selected value is passed to the printValue function, where we print the value of the output key.

```<code>// app.js

// require the module
const printValue = require('./printValue.js')

// global variable that I want to access
let selectedNode = {}

// called when a user clicks on node on the graph
cytoscape.on('tap', 'node', selection => {
  // stores the node's data
  selectedNode.output = selection.target[0] // this is the important bit
})

if (configuration === '1') {
  // now works
  printValue(selectedNode) // prints the updated variable
} else if (configuration === '2') {
  // loads different buttons with different functions
}
</code>```

The module was changed to

```<code>// module.js

module.exports = function printValue (selectedNode) {
  const button = document.getElementById('button-id')
  button.addEventListener('click', () => {
   console.log(selectedNode.output) // the other important bit
  })
}
</code>```

Body:
I have developed an Electron app with cytoscape.js for graph analysis. Currently, I am in the process of refactoring the code base and moving functions to external modules. Currently I am battling with the variable scope.

I have a number of variables that change when a user interacts with a graph.

I load different UIs (buttons) depending on the type of analysis.

Issue: I cannot pass the recent value of a variable to a module in a way that will simplify the code.

The following code shows the core issue.

// app.js

// require the module
const printValue = require('./printValue.js')

// global variable that I want to access
let selectedNode = ''

// called when a user clicks on node on the graph
cytoscape.on('tap', 'node', selection => {
  // stores the node's data
  selectedNode = selection.target[0]

  // I wan't to avoid that, since I load different configurations
  printValue(selectedNode) // prints the most recent value
})

// loads the different buttons
if (configuration === '1') {
  // I want to transfer it to an external module
  const button = document.getElementById('button-id')
  button.addEventListener('click', () => {
   console.log(selectedNode) // prints the most recent value
  })

  // I want to make this part work
  printValue(selectedNode) // prints '', the initial value of the variable
} else if (configuration === '2') {
  // loads different buttons with different functions
}

The module has the following code

  // module.js

  module.exports = function printValue (value) {
    const button = document.getElementById('button-id')
    button.addEventListener('click', () => {
      console.log(value)
    })
  }

What I want to do, is to move the button declarations and related functions of each configuration in modules. Then call those modules based on the app configuration the user has selected.

Body:
Credit goes to Royalbingbong for his helpful comment and reference to pass-by-value.

This was very helpful link where the topic is explained in detail.

Here is the updated (working) code sample.

selectedNode was declared as a string (primitive type), so it couldn't pass the updated value to the module. selectedNode was changed to an object and the variable value is stored with the output key. The selected value is passed to the printValue function, where we print the value of the output key.

// app.js

// require the module
const printValue = require('./printValue.js')

// global variable that I want to access
let selectedNode = {}

// called when a user clicks on node on the graph
cytoscape.on('tap', 'node', selection => {
  // stores the node's data
  selectedNode.output = selection.target[0] // this is the important bit
})

if (configuration === '1') {
  // now works
  printValue(selectedNode) // prints the updated variable
} else if (configuration === '2') {
  // loads different buttons with different functions
}

The module was changed to

// module.js

module.exports = function printValue (selectedNode) {
  const button = document.getElementById('button-id')
  button.addEventListener('click', () => {
   console.log(selectedNode.output) // the other important bit
  })
}


问:
How to use SQL server from a different network
I have a SQL server running in my home, and everything in the same network works fine.

I would like for my computer at home to be running the SQL Server, and with a VB.NET application connect to it from school.

Is there any way? Thank you.

答:
The only way is to publish you home comp to the Internet real IP. so you need real IP address from your provider with port map 1433 to your home computer. don't forget to create strong password for sa account.
also you need access from school to internet with SQL proto. In many cases in public networks only http/https is enabled.</p>


问:
How to display XML RSS feed by PHP
I have an assignment to display my XML RSS via PHP on a website, so far I have tried multiple things and all have failed. And I was unable to find the answer since most people do RSS feed by PHP from MySQL database to get a live feed of posts.

XML RSS

```<code><?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<channel>
  <title>Treehouse front page</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  <item>
    <title>Code Academy</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  </item>
</channel>

</rss>
</code>```

How can I display this file via PHP?

答:
Thank you very much for leading me onto the right track!

But that code would work for DOM file while mine was simplexml.
I used the following code to solve the problem

```<code>    <?php
$rss = simplexml_load_file('rss.xml');

echo '<h4>'. $rss->channel->title . '</h4>';

foreach ($rss->channel->item as $item) {
   echo '<h4><a href="'. $item->link .'">' . $item->title . "</a></h4>";
   echo "<p>" . $item->title . "</p>";
   echo "<p>" . $item->description . "</p>";
}
?>
</code>```

Title: How to display XML RSS feed by PHP

Body:
I have an assignment to display my XML RSS via PHP on a website, so far I have tried multiple things and all have failed. And I was unable to find the answer since most people do RSS feed by PHP from MySQL database to get a live feed of posts.

XML RSS

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<channel>
  <title>Treehouse front page</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  <item>
    <title>Code Academy</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  </item>
</channel>

</rss>

How can I display this file via PHP?

Body:
Thank you very much for leading me onto the right track!

But that code would work for DOM file while mine was simplexml.
I used the following code to solve the problem

    <?php
$rss = simplexml_load_file('rss.xml');

echo '<h4>'. $rss->channel->title . '</h4>';

foreach ($rss->channel->item as $item) {
   echo '<h4><a href="'. $item->link .'">' . $item->title . "</a></h4>";
   echo "<p>" . $item->title . "</p>";
   echo "<p>" . $item->description . "</p>";
}
?>


问:
C non-blocking keyboard input
I'm trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn't require a keypress to continue each loop.

Is there a simple way to do this? I figure I could possibly do it with select() but that seems like a lot of work.

Alternatively, is there a way to catch a ctrl-c keypress to do cleanup before the program closes instead of non-blocking io?

答:
select() is a bit too low-level for convenience.  I suggest you use the ncurses library to put the terminal in cbreak mode and delay mode, then call getch(), which will return ERR if no character is ready:

```<code>WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);
</code>```

At that point you can call getch without blocking.

OwnerDisplayName: Zxaos

Title: C non-blocking keyboard input

LastEditorDisplayName: Zxaos

Body:
select() is a bit too low-level for convenience.  I suggest you use the ncurses library to put the terminal in cbreak mode and delay mode, then call getch(), which will return ERR if no character is ready:

WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);

At that point you can call getch without blocking.

OwnerDisplayName: Norman Ramsey


问:
JQuery tooltip that supports new line
I'm looking for a lightweight jquery plugin for displaying tooltips when the user hovers over an element. I would like the plugin to get the content from the title attribute and also it's important that I can make new lines.

Any help is appreciated!

答:
I usually use tipsy.

You can add any html element in tipsy, so
 works.

You just need to pass the html option as such :

```<code>$('#example-html').tipsy({html: true });
</code>```

If you don't want to use the title attribute to display html (it won't validate in this case), you can use the fallback option.

```<code>$('#example-fallback').tipsy({fallback: "Where's my tooltip yo'? <br/> yay !" });
</code>```

More options and examples on the tipsy webpage.

Title: JQuery tooltip that supports new line

Body:
I usually use tipsy.

You can add any html element in tipsy, so <br/> works.

You just need to pass the html option as such :

$('#example-html').tipsy({html: true });

If you don't want to use the title attribute to display html (it won't validate in this case), you can use the fallback option.

$('#example-fallback').tipsy({fallback: "Where's my tooltip yo'? <br/> yay !" });

More options and examples on the tipsy webpage.


问:
Gluon Mobile - fxml file "Location is not set"
I want to implement javafx app both on desktop and android. When I try load fxml file:

FXMLLoader loader = new FXMLLoader(getClass().getResource("ProjectSetup.fxml"));
Parent root = loader.load();

I am getting an error:
java.lang.IllegalStateException: Location is not set.

I tried putting it in Resources(Main), Resources(Desktop),Source Packages(Java).

Example

None of it worked.

Where should I put "ProjecSetup.fxml" to get it working?

答: The appropriate location for fxml files is src/main/resources/yourpackage. If the class which is calling getResource() is not located in the same package as the referenced fxml.file, i.e. src/main/yourpackage, you have to use an aboslute path: fxmlLoader(getClass().getResource("/yourpackage/ProjectSetup.fxml"). Pay attention to the leading slash


答:
When defining methods for a class in Python, the first argument is usually set to "self". Then, when calling that method, prefix it with self.

Here is the working code:

```<code>import math

class RotatedRectangle(object):

    def corner1(self,a,b):
        a/=2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner2(self,a,b):
        a/=-2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner3(self,a,b):
        a/=-2
        b/=-2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner4(self,a,b):
        a/=2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def __init__(self, a, b,):
            """Return a Rotated rectangle object whose name is a function of a and b."""
            self.name = str(a) + "," + str(b) + "-rectangle"
            self.corners = [self.corner1(a,b), self.corner2(a,b), self.corner3(a,b), self.corner4(a,b)]
</code>```

Title: Calling a function inside a class to set the element of list

Body:
When defining methods for a class in Python, the first argument is usually set to "self". Then, when calling that method, prefix it with self.

Here is the working code:

import math

class RotatedRectangle(object):

    def corner1(self,a,b):
        a/=2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner2(self,a,b):
        a/=-2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner3(self,a,b):
        a/=-2
        b/=-2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner4(self,a,b):
        a/=2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def __init__(self, a, b,):
            """Return a Rotated rectangle object whose name is a function of a and b."""
            self.name = str(a) + "," + str(b) + "-rectangle"
            self.corners = [self.corner1(a,b), self.corner2(a,b), self.corner3(a,b), self.corner4(a,b)]


问:
Angular 2 shared service to pass data to component-to-component
I am trying to pass the string value of this.title from my LandingPage.component to my ResultPage.component.

I retrieve the list.show value, and send it to my TitleService in like so in my:

landingpage.component.html

```<code><ol>
  <li (click)="selectShow(list.show)" [routerLink]="['/details', list.id]" *ngFor="let list of shows">{{list.show}}
  </li>
</ol>
</code>```

landingpage.component.ts

```<code>import { TitleService } from '../../services/title.service';

constructor(private TitleService: TitleService) {}

selectShow(show) {
  this.TitleService.fetchTitle(show)
}
</code>```

The above sends the list.show value to my:

title.service.ts

```<code>// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
  fetchTitle(title) {
    console.log("title is " + title); // this outputs correctly
    return title;
  }
}
</code>```

And here is how I manage the routing in my:

app-routing.module.ts

```<code>import { TitleService } from './services/title.service';

const routes: Routes = [
  { path: '', component: LandingPage },
  {
    path: 'details/:id', component: ResultPage
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [TitleService]
})
</code>```

My question

Once I receive the title.show value in my service component, I'm unsure how to then send it to my receiving component (resultpage.component)

How can I send my title value from my service to my ResultPage.component?

答:
Separation of concerns...  Your landing page is used to select the list item and navigate to the result page.  Let it do just that and only that.  Let the ResultPage.component do the rest.   Note:  Other answers recommend storing the value of the last title in the TitleService.  It's not a good idea to store state in a service.  Then TitleService cannot be used as a generic way to get any title separate from your current navigation, without side effects.

Remove (click) event.  Add 'show' as a QueryParam.

landingpage.component.html

```<code><li [routerLink]="['/details', list.id]"
    [queryParams]="{show: list.show}"
     *ngFor="let list of shows">
     {{list.show}}
</li>
</code>```

Subscribe to router params and queryparams to get the id and show.

resultpage.component.ts

```<code>import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService } from '../../services/title.service';

@Component({
  ...
})
export class ResultPageComponent implements OnInit, OnDestroy {

 itemId: string;
 show: string;
 subParams: any;       // infinite Observable to be unsubscribed
 subQueryParams: any;  // infinite Observable to be unsubscribed

 constructor(
          ...
          private TitleService: TitleService,
          protected route: ActivatedRoute,
          protected router: Router,
          ...
 ) {}

 ngOnInit() {
   this.subParams = this.route.params.subscribe(this.onParams);
   this.subQueryParams = this.route.queryParams(this.onQueryParams);
 }

 ngOnDestroy() {
   // Delete active subscribes on destroy
   this.subParams.unsubscribe();
   this.subQueryParams.unsubscribe();
 }

 onParams = (params: any) => {
   this.itemId = params['id'];
 }

 onQueryParams = (data: any) => {
  this.show = data.show;
  if(this.show) {
    this.TitleService.fetchTitle(this.show)
  }
 }
</code>```

Body:
I am trying to pass the string value of this.title from my LandingPage.component to my ResultPage.component.

I retrieve the list.show value, and send it to my TitleService in like so in my:

landingpage.component.html

{{list.show}}

landingpage.component.ts

import { TitleService } from '../../services/title.service';

constructor(private TitleService: TitleService) {}

selectShow(show) {
  this.TitleService.fetchTitle(show)
}

The above sends the list.show value to my:

title.service.ts

// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
  fetchTitle(title) {
    console.log("title is " + title); // this outputs correctly
    return title;
  }
}

And here is how I manage the routing in my:

app-routing.module.ts

import { TitleService } from './services/title.service';

const routes: Routes = [
  { path: '', component: LandingPage },
  {
    path: 'details/:id', component: ResultPage
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [TitleService]
})

My question

Once I receive the title.show value in my service component, I'm unsure how to then send it to my receiving component (resultpage.component)

How can I send my title value from my service to my ResultPage.component?

Body:
Separation of concerns...  Your landing page is used to select the list item and navigate to the result page.  Let it do just that and only that.  Let the ResultPage.component do the rest.   Note:  Other answers recommend storing the value of the last title in the TitleService.  It's not a good idea to store state in a service.  Then TitleService cannot be used as a generic way to get any title separate from your current navigation, without side effects.

Remove (click) event.  Add 'show' as a QueryParam.

landingpage.component.html

<li [routerLink]="['/details', list.id]"
    [queryParams]="{show: list.show}"
     *ngFor="let list of shows">
     {{list.show}}
</li>

Subscribe to router params and queryparams to get the id and show.

resultpage.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService } from '../../services/title.service';

@Component({
  ...
})
export class ResultPageComponent implements OnInit, OnDestroy {

 itemId: string;
 show: string;
 subParams: any;       // infinite Observable to be unsubscribed
 subQueryParams: any;  // infinite Observable to be unsubscribed

 constructor(
          ...
          private TitleService: TitleService,
          protected route: ActivatedRoute,
          protected router: Router,
          ...
 ) {}

 ngOnInit() {
   this.subParams = this.route.params.subscribe(this.onParams);
   this.subQueryParams = this.route.queryParams(this.onQueryParams);
 }

 ngOnDestroy() {
   // Delete active subscribes on destroy
   this.subParams.unsubscribe();
   this.subQueryParams.unsubscribe();
 }

 onParams = (params: any) => {
   this.itemId = params['id'];
 }

 onQueryParams = (data: any) => {
  this.show = data.show;
  if(this.show) {
    this.TitleService.fetchTitle(this.show)
  }
 }


问:
ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests
I have a default ASP.NET Core website created within Visual Studio 2017.  I have chosen to authenticate using an Azure Active Directory.
I run the site and can successfully login using an account in the Active Directory.

I can retrieve Claim information provided by Active Directory, e.g. by calling the following line I get the 'name'.

```<code>User.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
</code>```

I want to add a custom claim - CompanyId = 123456 for the logged in user.
I'm able to add a custom claim however it is only available on the page where the claim is set.

```<code>Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
((ClaimsIdentity)User.Identity).AddClaim(claim);
</code>```

My understanding is that I somehow need to update the token that has been issued by Active Directory or set the claim before the token is issued.  I'm unsure how to do this.

I suspect this needs to be done in the AccountController at SignIn()

```<code>// GET: /Account/SignIn
[HttpGet]
public IActionResult SignIn()
{
    return Challenge(
            new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
}
</code>```

I've read numerous articles and samples about this scenario (including https://github.com/ahelland/AADGuide-CodeSamples/tree/master/ClaimsWebApp) however have not managed to solve how to persist the Claim across requests.

I have successfully managed to persist custom Claims using ASP.NET Identity as the Authentication Provider, but this appears to be because the custom Claim is saved to the database..

答:
For those who would like more detail, the code provided is placed in Startup.cs

In the Configure method add/edit:

```<code>app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["Authentication:AzureAd:ClientId"],
    Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
    CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
    Events = new OpenIdConnectEvents
    {
        OnTokenValidated = TokenValidated
    }
});
</code>```

The private Task TokenValidated method is in the body of Startup.cs

The following sample is a good reference.
https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore-v2/blob/master/WebApp-OpenIDConnect-DotNet/Startup.cs

Body:
I have a default ASP.NET Core website created within Visual Studio 2017.  I have chosen to authenticate using an Azure Active Directory.
I run the site and can successfully login using an account in the Active Directory.

I can retrieve Claim information provided by Active Directory, e.g. by calling the following line I get the 'name'.

User.Claims.FirstOrDefault(c => c.Type == "name")?.Value;

I want to add a custom claim - CompanyId = 123456 for the logged in user.
I'm able to add a custom claim however it is only available on the page where the claim is set.

Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
((ClaimsIdentity)User.Identity).AddClaim(claim);

My understanding is that I somehow need to update the token that has been issued by Active Directory or set the claim before the token is issued.  I'm unsure how to do this.

I suspect this needs to be done in the AccountController at SignIn()

// GET: /Account/SignIn
[HttpGet]
public IActionResult SignIn()
{
    return Challenge(
            new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
}

I've read numerous articles and samples about this scenario (including https://github.com/ahelland/AADGuide-CodeSamples/tree/master/ClaimsWebApp) however have not managed to solve how to persist the Claim across requests.

I have successfully managed to persist custom Claims using ASP.NET Identity as the Authentication Provider, but this appears to be because the custom Claim is saved to the database..

Body:
For those who would like more detail, the code provided is placed in Startup.cs

In the Configure method add/edit:

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["Authentication:AzureAd:ClientId"],
    Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
    CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
    Events = new OpenIdConnectEvents
    {
        OnTokenValidated = TokenValidated
    }
});

The private Task TokenValidated method is in the body of Startup.cs

The following sample is a good reference.
https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore-v2/blob/master/WebApp-OpenIDConnect-DotNet/Startup.cs