问:
How to update an app already on the app store to contain in app purchases
Right now I have an app on the app store. I knew that I would late update it but I just wanted to make sure I put it up before I did that. So now I want to implement in-app purchases. However, for some reason it is not working:

This is in the ViewDidLoad()

```<code>    let productIdentifiers: Set<String> = ["1000Coins"]

    let productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)

    productsRequest.delegate = self

    productsRequest.start()
</code>```

And this is the other function. For some reason it is not printing this

```<code>print("Product: \(product.productIdentifier), \(product.localizedTitle),\(product.price.floatValue)")

func productsRequest(_ request: SKProductsRequest, didReceive
response: SKProductsResponse) {

    print("Loaded Products")

    for product in response.products {

        print("Product: \(product.productIdentifier), \(product.localizedTitle),\(product.price.floatValue)")

    }

}
</code>```

I created the in app purchase with iTunes connect but for some reason it is not working. Any suggestions?? Thanks!

答:
Don't clutter your ViewDidLoad unnecessarily. Create an in-app-purchase helper to handle all the functions associated with IAPs e.g get product identifiers, verify receipt, restore etc.

A good helper written by Ron Buencamino is this:

```<code>import StoreKit
protocol IAPManagerDelegate {
func managerDidRestorePurchases()
}

class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver, SKRequestDelegate {

static let sharedInstance = IAPManager()

var request:SKProductsRequest!
var products:NSArray!

var delegate:IAPManagerDelegate?

//Load product identifiers for store usage
func setupInAppPurchases(){
    self.validateProductIdentifiers(self.getProductIdentifiersFromMainBundle())

    SKPaymentQueue.default().add(self)
}

//Get product identifiers
func getProductIdentifiersFromMainBundle() -> NSArray {
    var identifiers = NSArray()
    if let url = Bundle.main.url(forResource: "iap_products", withExtension: "plist"){
        identifiers = NSArray(contentsOf: url)!
    }

    return identifiers
}

//Retrieve product information
func validateProductIdentifiers(_ identifiers:NSArray) {
    let productIdentifiers = NSSet(array: identifiers as [AnyObject])
    let productRequest = SKProductsRequest(productIdentifiers: productIdentifiers as! Set<String>)
    self.request = productRequest
    productRequest.delegate = self
    productRequest.start()

}

func createPaymentRequestForProduct(_ product:SKProduct){

    let payment = SKMutablePayment(product: product)
    payment.quantity = 1

    SKPaymentQueue.default().add(payment)

}

func verifyReceipt(_ transaction:SKPaymentTransaction?){
    let receiptURL = Bundle.main.appStoreReceiptURL!
    if let receipt = try? Data(contentsOf: receiptURL){
        //Receipt exists
        let requestContents = ["receipt-data" : receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))]

        //Perform request
        do {
            let requestData = try JSONSerialization.data(withJSONObject: requestContents, options: JSONSerialization.WritingOptions(rawValue: 0))

            //Build URL Request

            //change the storeURL before you submit to the app store
            let storeURL = URL(string: "https:/sandbox.itunes.apple.com/verifyReceipt")
            var request = URLRequest(url: storeURL!)
            request.httpMethod = "Post"
            request.httpBody = requestData

            let session = URLSession.shared
            let task = session.dataTask(with: request , completionHandler: { (responseData, response , error) -> Void in

                do {
                    let json = try JSONSerialization.jsonObject(with: responseData! as Data, options: .mutableLeaves) as! NSDictionary

                    print(json)

                    if (json.object(forKey: "status") as! NSNumber) == 0 {
                        //
                        let receipt_dict = json["receipt"] as! NSDictionary

                        if let purchases = receipt_dict["in_app"] as? NSArray  {
                            self.validatePurchaseArray(purchases)
                        }

                        // you can add more statements to check different parts of the receipt

                        if transaction != nil {
                            SKPaymentQueue.default().finishTransaction(transaction!)
                        }
                        DispatchQueue.main.sync(execute: { () -> Void in self.delegate?.managerDidRestorePurchases() } )                       }
                    else {
                        //Debug the receipt
                        print(json.object(forKey: "status") as! NSNumber)
                    }

                }
                catch {
                    print(error)
                }
            } )

            task.resume()

        }
        catch {
            print(error)
        }

    }
    else {
        //Receipt does not exist
        print("No Receipt")
    }
}
func validatePurchaseArray(_ purchases:NSArray){

    for purchase in purchases as! [NSDictionary]{

        self.unlockPurchasedFunctionalityForProductIdentifier(purchase["product_id"] as! String)

    }
}

func unlockPurchasedFunctionalityForProductIdentifier(_ productIdentifier:String){

    ///here you put the functionality that you want to unlock for the user
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
}

func isDateExpired(_ expires_date:Double) -> Bool{
    var isExpired:Bool = false
    let currentDate = (Date().timeIntervalSince1970 * 1000) as TimeInterval

    if currentDate > expires_date{
        isExpired = true
    }

    return isExpired
}

//MARK: SKProductsRequestDelegate
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    //
    self.products = response.products as NSArray!
    print(self.products)

}

//MARK: SKPaymentTransactionObserver Delegate Protocol
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    //
    for transaction in transactions as [SKPaymentTransaction]{
        switch transaction.transactionState{
        case .purchasing:
            print("Purchasing")
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
        case .deferred:
            print("Deferrred")
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        case .failed:
            print("Failed")
            print(transaction.error?.localizedDescription)
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            SKPaymentQueue.default().finishTransaction(transaction)
        case.purchased:
            print("Purchased")
            //
            self.verifyReceipt(transaction)
        case .restored:
            print("Restored")

        }
    }
}

func restorePurchases(){
    let request = SKReceiptRefreshRequest()
    request.delegate = self
    request.start()
}

func requestDidFinish(_ request: SKRequest) {
    self.verifyReceipt(nil)
}

}
</code>```

add a plist file named iap_products.plist to your Xcode and include the product ids. In said file include:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"     "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
 <array>
<string>product1Id</string>
<string>product2Id</string>
    so on....
</array>
</plist>
</code>```

Body:
Right now I have an app on the app store. I knew that I would late update it but I just wanted to make sure I put it up before I did that. So now I want to implement in-app purchases. However, for some reason it is not working:

This is in the ViewDidLoad()

    let productIdentifiers: Set<String> = ["1000Coins"]

    let productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)

    productsRequest.delegate = self

    productsRequest.start()

And this is the other function. For some reason it is not printing this

print("Product: \(product.productIdentifier), \(product.localizedTitle),\(product.price.floatValue)")

func productsRequest(_ request: SKProductsRequest, didReceive
response: SKProductsResponse) {

    print("Loaded Products")

    for product in response.products {

        print("Product: \(product.productIdentifier), \(product.localizedTitle),\(product.price.floatValue)")

    }

}

I created the in app purchase with iTunes connect but for some reason it is not working. Any suggestions?? Thanks!

Body:
Don't clutter your ViewDidLoad unnecessarily. Create an in-app-purchase helper to handle all the functions associated with IAPs e.g get product identifiers, verify receipt, restore etc.

A good helper written by Ron Buencamino is this:

import StoreKit
protocol IAPManagerDelegate {
func managerDidRestorePurchases()
}

class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver, SKRequestDelegate {

static let sharedInstance = IAPManager()

var request:SKProductsRequest!
var products:NSArray!

var delegate:IAPManagerDelegate?

//Load product identifiers for store usage
func setupInAppPurchases(){
    self.validateProductIdentifiers(self.getProductIdentifiersFromMainBundle())

    SKPaymentQueue.default().add(self)
}

//Get product identifiers
func getProductIdentifiersFromMainBundle() -> NSArray {
    var identifiers = NSArray()
    if let url = Bundle.main.url(forResource: "iap_products", withExtension: "plist"){
        identifiers = NSArray(contentsOf: url)!
    }

    return identifiers
}

//Retrieve product information
func validateProductIdentifiers(_ identifiers:NSArray) {
    let productIdentifiers = NSSet(array: identifiers as [AnyObject])
    let productRequest = SKProductsRequest(productIdentifiers: productIdentifiers as! Set<String>)
    self.request = productRequest
    productRequest.delegate = self
    productRequest.start()

}

func createPaymentRequestForProduct(_ product:SKProduct){

    let payment = SKMutablePayment(product: product)
    payment.quantity = 1

    SKPaymentQueue.default().add(payment)

}

func verifyReceipt(_ transaction:SKPaymentTransaction?){
    let receiptURL = Bundle.main.appStoreReceiptURL!
    if let receipt = try? Data(contentsOf: receiptURL){
        //Receipt exists
        let requestContents = ["receipt-data" : receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))]

        //Perform request
        do {
            let requestData = try JSONSerialization.data(withJSONObject: requestContents, options: JSONSerialization.WritingOptions(rawValue: 0))

            //Build URL Request

            //change the storeURL before you submit to the app store
            let storeURL = URL(string: "https:/sandbox.itunes.apple.com/verifyReceipt")
            var request = URLRequest(url: storeURL!)
            request.httpMethod = "Post"
            request.httpBody = requestData

            let session = URLSession.shared
            let task = session.dataTask(with: request , completionHandler: { (responseData, response , error) -> Void in

                do {
                    let json = try JSONSerialization.jsonObject(with: responseData! as Data, options: .mutableLeaves) as! NSDictionary

                    print(json)

                    if (json.object(forKey: "status") as! NSNumber) == 0 {
                        //
                        let receipt_dict = json["receipt"] as! NSDictionary

                        if let purchases = receipt_dict["in_app"] as? NSArray  {
                            self.validatePurchaseArray(purchases)
                        }

                        // you can add more statements to check different parts of the receipt

                        if transaction != nil {
                            SKPaymentQueue.default().finishTransaction(transaction!)
                        }
                        DispatchQueue.main.sync(execute: { () -> Void in self.delegate?.managerDidRestorePurchases() } )                       }
                    else {
                        //Debug the receipt
                        print(json.object(forKey: "status") as! NSNumber)
                    }

                }
                catch {
                    print(error)
                }
            } )

            task.resume()

        }
        catch {
            print(error)
        }

    }
    else {
        //Receipt does not exist
        print("No Receipt")
    }
}
func validatePurchaseArray(_ purchases:NSArray){

    for purchase in purchases as! [NSDictionary]{

        self.unlockPurchasedFunctionalityForProductIdentifier(purchase["product_id"] as! String)

    }
}

func unlockPurchasedFunctionalityForProductIdentifier(_ productIdentifier:String){

    ///here you put the functionality that you want to unlock for the user
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
}

func isDateExpired(_ expires_date:Double) -> Bool{
    var isExpired:Bool = false
    let currentDate = (Date().timeIntervalSince1970 * 1000) as TimeInterval

    if currentDate > expires_date{
        isExpired = true
    }

    return isExpired
}

//MARK: SKProductsRequestDelegate
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    //
    self.products = response.products as NSArray!
    print(self.products)

}

//MARK: SKPaymentTransactionObserver Delegate Protocol
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    //
    for transaction in transactions as [SKPaymentTransaction]{
        switch transaction.transactionState{
        case .purchasing:
            print("Purchasing")
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
        case .deferred:
            print("Deferrred")
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        case .failed:
            print("Failed")
            print(transaction.error?.localizedDescription)
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            SKPaymentQueue.default().finishTransaction(transaction)
        case.purchased:
            print("Purchased")
            //
            self.verifyReceipt(transaction)
        case .restored:
            print("Restored")

        }
    }
}

func restorePurchases(){
    let request = SKReceiptRefreshRequest()
    request.delegate = self
    request.start()
}

func requestDidFinish(_ request: SKRequest) {
    self.verifyReceipt(nil)
}

}

add a plist file named iap_products.plist to your Xcode and include the product ids. In said file include:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"     "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
 <array>
<string>product1Id</string>
<string>product2Id</string>
    so on....
</array>
</plist>


来源: stackexchange

问:
How to display a certain view depending on random number generation in swift?
I am following a tutorial, this is the repo on git

I have 7 views, that represent the die. And 6 labels, that show the random number each time I press the dieButtonTapped() button. When I press the button, first label appears with the random number generated, which is good, but I can't get the appropriate view to show up. So, if the random number is 5, label shows up with the number 5 in it, and 5 views out of 7 should show up, representing the die.
What it is doing now is that it shows random views that do not match the random number showed on the label.

Please help me correct func rearrangeDie() function to match what func updateScore(roll: Int) is returning.

Thank you !
Here is my code:

```<code>class ViewController: UIViewController {

    @IBOutlet weak var view1: UIView!
    @IBOutlet weak var view2: UIView!
    @IBOutlet weak var view3: UIView!
    @IBOutlet weak var view4: UIView!
    @IBOutlet weak var view5: UIView!
    @IBOutlet weak var view6: UIView!
    @IBOutlet weak var view7: UIView!

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!
    @IBOutlet weak var label5: UILabel!
    @IBOutlet weak var label6: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        view1.isHidden = true
        view2.isHidden = true
        view3.isHidden = true
        view4.isHidden = true
        view5.isHidden = true
        view6.isHidden = true
        view7.isHidden = true

        label1.isHidden = true
        label2.isHidden = true
        label3.isHidden = true
        label4.isHidden = true
        label5.isHidden = true
        label6.isHidden = true

    }

    @IBAction func dieButtonTapped(_ sender: AnyObject) {

        rearrangeDie()
        updateScore(roll: randomDiceRoll())
    }

    // Returns back a random Int (1, 2, 3, 4, 5, or 6)
    func randomDiceRoll() -> Int {
        return Int(arc4random_uniform(6) + 1)

    }

    func rearrangeDie() {

        if randomDiceRoll() == 1 {
            view7.isHidden = false
        }
        else if randomDiceRoll() == 2 {
            view2.isHidden = false
            view5.isHidden = false
        }
        else if randomDiceRoll() == 3 {
            view2.isHidden = false
            view7.isHidden = false
            view5.isHidden = false
        }
        else if randomDiceRoll() == 4 {
            view1.isHidden = false
            view2.isHidden = false
            view5.isHidden = false
            view6.isHidden = false
        }
        else if randomDiceRoll() == 5 {
            view1.isHidden = false
            view2.isHidden = false
            view5.isHidden = false
            view6.isHidden = false
            view7.isHidden = false
        }
        else if randomDiceRoll() == 6 {
            view1.isHidden = false
            view2.isHidden = false
            view3.isHidden = false
            view4.isHidden = false
            view5.isHidden = false
            view6.isHidden = false
        }

    }

    func updateScore(roll: Int) {

        let diceScore = String(roll)

        if label1.isHidden {
            label1.text = diceScore
            label1.isHidden = false

        }
        else if label2.isHidden {
            label2.text = diceScore
            label2.isHidden = false

        }
        else if label3.isHidden {
            label3.text = diceScore
            label3.isHidden = false

        }
        else if label4.isHidden {
            label4.text = diceScore
            label4.isHidden = false

        }
        else if label5.isHidden {
            label5.text = diceScore
            label5.isHidden = false

        }
        else if label6.isHidden {
            label6.text = diceScore
            label6.isHidden = false

        }
        else {
            viewDidLoad()
        }
    }
}
</code>```

答:
@the4Kman is correct in stating that calling the randomDiceRoll() will generate a new random number every time which leads to the problem you are facing. What you need instead, is to merge your rearrangeDie() and updateScore() methods into one. Also, as @nanothread59 suggested, you should use IBOutletCollections.

You should declare your collections like this

```<code>//Notice that you cannot make them "weak" properties
@IBOutlet var views: Array<UIView>!
@IBOutlet var labels: Array<UILabel>!
</code>```

Then give each of your view and label a tag from 1-7 in storyboard and connect them to their respective outletCollections. Once it is setup, you can merge your methods into one like this

```<code>func update() {
    //Hide all Views and Labels
    for item in views {
        item.isHidden = true
    }
    for item in labels {
        item.isHidden = true
    }

    //Get Random Value
    let random = randomDiceRoll()

    //UPDATE YOUR VIEWS' AND LABELS' HIDDEN PROPERTY AND VALUES HERE BASED ON THE RANDOM VALUE

    //To access a particular view or label, you'll do something like this
    for item in views {
        if item.tag == {whatever} {
            //DO SOMETHING
        }
    }
    //Repeat the above loop for labels as well
}
</code>```

P.S. With IBOutletCollections, your viewDidLoad will also change like this

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    //Hide all Views and Labels
    for item in views {
        item.isHidden = true
    }
    for item in labels {
        item.isHidden = true
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am following a tutorial, this is the repo on git

I have 7 views, that represent the die. And 6 labels, that show the random number each time I press the dieButtonTapped() button. When I press the button, first label appears with the random number generated, which is good, but I can't get the appropriate view to show up. So, if the random number is 5, label shows up with the number 5 in it, and 5 views out of 7 should show up, representing the die.
What it is doing now is that it shows random views that do not match the random number showed on the label.

Please help me correct func rearrangeDie() function to match what func updateScore(roll: Int) is returning.

Thank you !
Here is my code:

class ViewController: UIViewController {

    @IBOutlet weak var view1: UIView!
    @IBOutlet weak var view2: UIView!
    @IBOutlet weak var view3: UIView!
    @IBOutlet weak var view4: UIView!
    @IBOutlet weak var view5: UIView!
    @IBOutlet weak var view6: UIView!
    @IBOutlet weak var view7: UIView!

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!
    @IBOutlet weak var label5: UILabel!
    @IBOutlet weak var label6: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        view1.isHidden = true
        view2.isHidden = true
        view3.isHidden = true
        view4.isHidden = true
        view5.isHidden = true
        view6.isHidden = true
        view7.isHidden = true

        label1.isHidden = true
        label2.isHidden = true
        label3.isHidden = true
        label4.isHidden = true
        label5.isHidden = true
        label6.isHidden = true

    }

    @IBAction func dieButtonTapped(_ sender: AnyObject) {

        rearrangeDie()
        updateScore(roll: randomDiceRoll())
    }

    // Returns back a random Int (1, 2, 3, 4, 5, or 6)
    func randomDiceRoll() -> Int {
        return Int(arc4random_uniform(6) + 1)

    }

    func rearrangeDie() {

        if randomDiceRoll() == 1 {
            view7.isHidden = false
        }
        else if randomDiceRoll() == 2 {
            view2.isHidden = false
            view5.isHidden = false
        }
        else if randomDiceRoll() == 3 {
            view2.isHidden = false
            view7.isHidden = false
            view5.isHidden = false
        }
        else if randomDiceRoll() == 4 {
            view1.isHidden = false
            view2.isHidden = false
            view5.isHidden = false
            view6.isHidden = false
        }
        else if randomDiceRoll() == 5 {
            view1.isHidden = false
            view2.isHidden = false
            view5.isHidden = false
            view6.isHidden = false
            view7.isHidden = false
        }
        else if randomDiceRoll() == 6 {
            view1.isHidden = false
            view2.isHidden = false
            view3.isHidden = false
            view4.isHidden = false
            view5.isHidden = false
            view6.isHidden = false
        }

    }

    func updateScore(roll: Int) {

        let diceScore = String(roll)

        if label1.isHidden {
            label1.text = diceScore
            label1.isHidden = false

        }
        else if label2.isHidden {
            label2.text = diceScore
            label2.isHidden = false

        }
        else if label3.isHidden {
            label3.text = diceScore
            label3.isHidden = false

        }
        else if label4.isHidden {
            label4.text = diceScore
            label4.isHidden = false

        }
        else if label5.isHidden {
            label5.text = diceScore
            label5.isHidden = false

        }
        else if label6.isHidden {
            label6.text = diceScore
            label6.isHidden = false

        }
        else {
            viewDidLoad()
        }
    }
}

Body:
@the4Kman is correct in stating that calling the randomDiceRoll() will generate a new random number every time which leads to the problem you are facing. What you need instead, is to merge your rearrangeDie() and updateScore() methods into one. Also, as @nanothread59 suggested, you should use IBOutletCollections.

You should declare your collections like this

//Notice that you cannot make them "weak" properties
@IBOutlet var views: Array<UIView>!
@IBOutlet var labels: Array<UILabel>!

Then give each of your view and label a tag from 1-7 in storyboard and connect them to their respective outletCollections. Once it is setup, you can merge your methods into one like this

func update() {
    //Hide all Views and Labels
    for item in views {
        item.isHidden = true
    }
    for item in labels {
        item.isHidden = true
    }

    //Get Random Value
    let random = randomDiceRoll()

    //UPDATE YOUR VIEWS' AND LABELS' HIDDEN PROPERTY AND VALUES HERE BASED ON THE RANDOM VALUE

    //To access a particular view or label, you'll do something like this
    for item in views {
        if item.tag == {whatever} {
            //DO SOMETHING
        }
    }
    //Repeat the above loop for labels as well
}

P.S. With IBOutletCollections, your viewDidLoad will also change like this

override func viewDidLoad() {
    super.viewDidLoad()
    //Hide all Views and Labels
    for item in views {
        item.isHidden = true
    }
    for item in labels {
        item.isHidden = true
    }
}


问:
How to check if the cell inside the CSV file has a comma using C#
I'd like to know on how I can check if the cell inside my CSV file has a comma, so that I can then replace it with white space. Below is the image of my CSV file:
My CSV file

Here is my C# code:

```<code>if (System.IO.File.Exists(fName))
{
    System.IO.StreamReader objReader = new System.IO.StreamReader(fName);
    do
    {
        textLine = objReader.ReadLine();
        if (textLine != "")
        {
            splitLine = textLine.Split(',');
            if (splitLine[0] != "" || splitLine[1] != "")
            {
                dataGridView1.Rows.Add(splitLine);
            }
        }
    } while (objReader.Peek() != -1);
}
return true;
</code>```

Below is the result of the above code.
Result

Instead of Blk 32, Lot 3, the Lot 3 got separated due to the comma after the Blk 32. I want them to become one as Blk 32, Lot 3.

答:
I think for your case, it's better to add quotation marks around your columns when exporting to csv in Excel. You then can use regex to get those matching column data.

http://www.lenashore.com/2012/04/how-to-add-quotes-to-your-cells-in-excel-automatically/

ContentLicense: CC BY-SA 4.0

Body:
I'd like to know on how I can check if the cell inside my CSV file has a comma, so that I can then replace it with white space. Below is the image of my CSV file:
My CSV file

Here is my C# code:

if (System.IO.File.Exists(fName))
{
    System.IO.StreamReader objReader = new System.IO.StreamReader(fName);
    do
    {
        textLine = objReader.ReadLine();
        if (textLine != "")
        {
            splitLine = textLine.Split(',');
            if (splitLine[0] != "" || splitLine[1] != "")
            {
                dataGridView1.Rows.Add(splitLine);
            }
        }
    } while (objReader.Peek() != -1);
}
return true;

Below is the result of the above code.
Result

Instead of Blk 32, Lot 3, the Lot 3 got separated due to the comma after the Blk 32. I want them to become one as Blk 32, Lot 3.


问:
Set default cell in a UICollectionView (SWIFT)?
I'm a Swift beginner trying to implement a way to set a default cell in a CollectionView when the app first launches. I have overriden my 'isSelected' method to graphically show on the screen the selected cell eg; borderColor, etc...

My approach (rightly or not) so far is to call the 'didSelectItemAt' method inside my 'viewDidAppear' method.

I understand that the 'didSelectItemAt' method expects a CollectionView as its first argument, but not matter what I put as the first argument when I call the method inside my 'viewDidAppear' nothing seems to work.

any ideas?

```<code>extension DrinkMenuViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DrinkTypeImageCollectionViewCell", for: indexPath) as! DrinkTypeImageCollectionViewCell

        cell.imgDrinkType.image = imageArray[indexPath.row]
        cell.lbDrinkType.text = drinkTypeArray[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DrinkTypeImageCollectionViewCell", for: indexPath) as! DrinkTypeImageCollectionViewCell

        cell.isSelected = true

        print("selected cell: ", indexPath)
    }

    override func viewDidAppear(_ animated: Bool) {
        let indexPathForFirstRow = IndexPath(row: 0, section: 0)

        collectionView(<#T##collectionView: UICollectionView##UICollectionView#>, didSelectItemAt: indexPathForFirstRow)

        print (indexPathForFirstRow)
    }
}
</code>```

答:
You are not the one to explicitly call the delegate methods of any API.

func collectionView(_:didSelectItemAt:) is the delegate method of UICollectionView. The api itself handles when to call this method. So you must not call this method from anywhere in your code.

Again your implementation of func collectionView(_:didSelectItemAt:) doesn't make any sense. This method will automatically be called when you tap on any of your cell. You don't have to deque your cell again here.

Body:
I'm a Swift beginner trying to implement a way to set a default cell in a CollectionView when the app first launches. I have overriden my 'isSelected' method to graphically show on the screen the selected cell eg; borderColor, etc...

My approach (rightly or not) so far is to call the 'didSelectItemAt' method inside my 'viewDidAppear' method.

I understand that the 'didSelectItemAt' method expects a CollectionView as its first argument, but not matter what I put as the first argument when I call the method inside my 'viewDidAppear' nothing seems to work.

any ideas?

extension DrinkMenuViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DrinkTypeImageCollectionViewCell", for: indexPath) as! DrinkTypeImageCollectionViewCell

        cell.imgDrinkType.image = imageArray[indexPath.row]
        cell.lbDrinkType.text = drinkTypeArray[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DrinkTypeImageCollectionViewCell", for: indexPath) as! DrinkTypeImageCollectionViewCell

        cell.isSelected = true

        print("selected cell: ", indexPath)
    }

    override func viewDidAppear(_ animated: Bool) {
        let indexPathForFirstRow = IndexPath(row: 0, section: 0)

        collectionView(<#T##collectionView: UICollectionView##UICollectionView#>, didSelectItemAt: indexPathForFirstRow)

        print (indexPathForFirstRow)
    }
}


问:
Traefik https redirect (via kubernetes deployment)
I'm running traefik on AWS via kubernetes. It all works, except for my http=>https redirect configuration.

I have the following .toml file

```<code>defaultEntryPoints = ["http", "https"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      entryPoint = "https"
</code>```

With the Kubernetes Deployment + Service configurations below.

https requests work file, but http requests return:

```<code>> curl http://www.myserver.com
curl: (52) Empty reply from server
</code>```

Kubernetes config files:

```<code>kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: traefik-proxy
  labels:
    app: traefik-proxy
    tier: proxy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: traefik-proxy
      tier: proxy
  template:
    metadata:
      labels:
        app: traefik-proxy
        tier: proxy
    spec:
      terminationGracePeriodSeconds: 60

      # kubectl create configmap traefik-conf --from-file=./conf/k8s/traefik.toml
      volumes:
      - name: config
        configMap:
          name: traefik-conf

      containers:
      - image: traefik:v1.2.0-rc1-alpine
        name: traefik-proxy
        resources:
          limits:
            cpu: "200m"
            memory: "30Mi"
          requests:
            cpu: "100m"
            memory: "20Mi"
        volumeMounts:
        - mountPath: "/conf"
          name: config
        ports:
        - containerPort: 80
          hostPort: 80
          name: traefik-proxy
        - containerPort: 8080
          name: traefik-ui
        args:
        - --configFile=/conf/traefik.toml
        - --kubernetes
        - --web
---
apiVersion: v1
kind: Service
metadata:
  name: traefik-proxy
  annotations:
    # SSL certificate.
    # https://console.aws.amazon.com/acm (alienlabs.io)
    service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:us-east-1:861694698401:certificate/28204a9f-69ec-424d-8f56-ac085b7bdad8"
    service.beta.kubernetes.io/aws-load-balancer-backend-protocol: "http"
spec:
  type: LoadBalancer
  selector:
    app: traefik-proxy
    tier: proxy
  ports:
  - port: 80
    targetPort: 80
    name: http
  - port: 443
    targetPort: 80
    name: https
</code>```

答:
My traefik.toml config is similar to Corey's but is a little simpler. It works well for a catch-all redirect of http to https.

```<code>defaultEntryPoints = ["http","https"]
[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      entryPoint = "https"
  [entryPoints.https]
  address = ":443"
</code>```

Body:
I'm running traefik on AWS via kubernetes. It all works, except for my http=>https redirect configuration.

I have the following .toml file

defaultEntryPoints = ["http", "https"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      entryPoint = "https"

With the Kubernetes Deployment + Service configurations below.

https requests work file, but http requests return:

> curl http://www.myserver.com
curl: (52) Empty reply from server

Kubernetes config files:

kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: traefik-proxy
  labels:
    app: traefik-proxy
    tier: proxy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: traefik-proxy
      tier: proxy
  template:
    metadata:
      labels:
        app: traefik-proxy
        tier: proxy
    spec:
      terminationGracePeriodSeconds: 60

      # kubectl create configmap traefik-conf --from-file=./conf/k8s/traefik.toml
      volumes:
      - name: config
        configMap:
          name: traefik-conf

      containers:
      - image: traefik:v1.2.0-rc1-alpine
        name: traefik-proxy
        resources:
          limits:
            cpu: "200m"
            memory: "30Mi"
          requests:
            cpu: "100m"
            memory: "20Mi"
        volumeMounts:
        - mountPath: "/conf"
          name: config
        ports:
        - containerPort: 80
          hostPort: 80
          name: traefik-proxy
        - containerPort: 8080
          name: traefik-ui
        args:
        - --configFile=/conf/traefik.toml
        - --kubernetes
        - --web
---
apiVersion: v1
kind: Service
metadata:
  name: traefik-proxy
  annotations:
    # SSL certificate.
    # https://console.aws.amazon.com/acm (alienlabs.io)
    service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:us-east-1:861694698401:certificate/28204a9f-69ec-424d-8f56-ac085b7bdad8"
    service.beta.kubernetes.io/aws-load-balancer-backend-protocol: "http"
spec:
  type: LoadBalancer
  selector:
    app: traefik-proxy
    tier: proxy
  ports:
  - port: 80
    targetPort: 80
    name: http
  - port: 443
    targetPort: 80
    name: https

Body:
My traefik.toml config is similar to Corey's but is a little simpler. It works well for a catch-all redirect of http to https.

defaultEntryPoints = ["http","https"]
[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      entryPoint = "https"
  [entryPoints.https]
  address = ":443"


问:
An ASP.NET MVC validator to make sure at least one checkbox is checked
I have an ASP.NET MVC 2 project in which I've created a data transfer object to receive data from a web page form. The form has two groups of checkboxes on it. I want to validate the object to make sure that at least one of the checkboxes in each group is checked.

I'm doing the validation on the server side so that a user won't be able to hack around any client-side validation. (I will add client-side validation with jQuery later; that's easy.)

My understanding is that I have to create my own custom ValidationAttribute for my data transfer object class, but I don't understand how to create and use one that can accept an arbitrary list of checkbox properties to make sure that at least one of them is true. I am guessing I will have to call the attributes like this:

```<code>[AtLeastOneCheckbox("set1check1", "set1check2", "set1check3",
    ErrorMessage = "You must check at least one checkbox in set 1.")]
[AtLeastOneCheckbox("set2check1", "set2check2", "set2check3", "set2check4", "set2check5",
    ErrorMessage = "You must check at least one checkbox in set 2.")]
public class MyFormDTO
{
    ...
}
</code>```

What would the implementation of AtLeastOneCheckboxAttribute look like?

Or is there a different way that I should do this kind of validation?

答:
Your DTO, which is I'm guessing your ViewModel can ihert IDataErrorInfo.
Then you can do your validation like this (note I didn't compile this)</p>

```<code>//I'm guessing you have a list of checkboxes
IEnumerable<bool> checkBoxes1;
IEnumerable<bool> checkBoxes2;

public class MyFormDTO : IDataErrorInfo
{
    public string this[string prop]
    {
        get
        {
            if(prop == "checkBoxes1")
            {
                if(checkBoxes1.Any(x => x == true))
                {
                    return "Error: You need to select atleast one checkbox from set1";
                }
            }
            else if(prop == "checkBoxes2")
            {
                if(checkBoxes2.Any(x => x == true))
                {
                    return "Error: You need to select atleast one checkbox from set2";
                }
            }
            return null;
        }
    }
    public string Error { get { return null; } }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an ASP.NET MVC 2 project in which I've created a data transfer object to receive data from a web page form. The form has two groups of checkboxes on it. I want to validate the object to make sure that at least one of the checkboxes in each group is checked.

I'm doing the validation on the server side so that a user won't be able to hack around any client-side validation. (I will add client-side validation with jQuery later; that's easy.)

My understanding is that I have to create my own custom ValidationAttribute for my data transfer object class, but I don't understand how to create and use one that can accept an arbitrary list of checkbox properties to make sure that at least one of them is true. I am guessing I will have to call the attributes like this:

[AtLeastOneCheckbox("set1check1", "set1check2", "set1check3",
    ErrorMessage = "You must check at least one checkbox in set 1.")]
[AtLeastOneCheckbox("set2check1", "set2check2", "set2check3", "set2check4", "set2check5",
    ErrorMessage = "You must check at least one checkbox in set 2.")]
public class MyFormDTO
{
    ...
}

What would the implementation of AtLeastOneCheckboxAttribute look like?

Or is there a different way that I should do this kind of validation?

Body:
Your DTO, which is I'm guessing your ViewModel can ihert IDataErrorInfo.
Then you can do your validation like this (note I didn't compile this)

//I'm guessing you have a list of checkboxes
IEnumerable<bool> checkBoxes1;
IEnumerable<bool> checkBoxes2;

public class MyFormDTO : IDataErrorInfo
{
    public string this[string prop]
    {
        get
        {
            if(prop == "checkBoxes1")
            {
                if(checkBoxes1.Any(x => x == true))
                {
                    return "Error: You need to select atleast one checkbox from set1";
                }
            }
            else if(prop == "checkBoxes2")
            {
                if(checkBoxes2.Any(x => x == true))
                {
                    return "Error: You need to select atleast one checkbox from set2";
                }
            }
            return null;
        }
    }
    public string Error { get { return null; } }
}


问:
Find the names contained in each sentence (not the other way around)
My question is an extension of this one: How to extract sentences containing specific person names using R

I'll write the relevant part here (slightly edited for the sake of this question):

```<code>> sentences
[1] "Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin"
[2] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[3] " He studied the Scripture, especially of Paul, and Evangelical doctrine"
[4] " He was present at the disputation of Leipzig (1519) as a spectator, but participated by his comments."
[5] " Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium"

toMatch <- c("Martin Luther", "Paul", "Melanchthon")
</code>```

The answer provided gives the sentences that match each name:

```<code>foo<-function(Match){c(Match,sentences[grep(Match,sentences)])}
> lapply(toMatch,foo)
[[1]]
[1] "Martin Luther"
[2] "Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin"
[3] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"

[[2]]
[1] "Paul"
[2] " He studied the Scripture, especially of Paul, and Evangelical doctrine"

[[3]]
[1] "Melanchthon"
[2] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[3] " Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium"
</code>```

lapply(toMatch,foo) gives a list of toMatch elements and apply each one to the function foo, which search for matches in the sentences with grep (returning the position of the sentences vector that match): sentences[grep(Match,sentences)].

My question is, instead of returning every sentence that match the elements of the toMatch vector, how could we have a vector with every sentence and then look for the names that match each one (i.e: the other way around, I know it's a bit confusing, the output would be this):

```<code>[1] "Martin Luther"
[2] "Melanchthon","Martin Luther"
[3] "Paul"
[4] NA                   #Or maybe this row doesn't exists, it's the same for me
[5] "Melanchthon"
</code>```

Could this be done altering the result already provided or maybe this would be easier using a different function and lapply(sentences,FUNCTION)?

答:
One option would be str_extract

```<code>library(stringr)
lst <- str_extract_all(sentences, paste(toMatch, collapse="|"))
lst[lengths(lst)==0] <- NA
lst
#[[1]]
#[1] "Martin Luther"

#[[2]]
#[1] "Melanchthon"   "Martin Luther"

#[[3]]
#[1] "Paul"

#[[4]]
#[1] NA

#[[5]]
#[1] "Melanchthon"
</code>```

Or we can use regmatches/gregexpr from base R

```<code>lst <- regmatches(sentences, gregexpr(paste(toMatch, collapse="|"), sentences))
</code>```

and replace the list elements having 0 length as NA (as before)

Body:
My question is an extension of this one: How to extract sentences containing specific person names using R

I'll write the relevant part here (slightly edited for the sake of this question):

> sentences
[1] "Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin"
[2] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[3] " He studied the Scripture, especially of Paul, and Evangelical doctrine"
[4] " He was present at the disputation of Leipzig (1519) as a spectator, but participated by his comments."
[5] " Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium"

toMatch <- c("Martin Luther", "Paul", "Melanchthon")

The answer provided gives the sentences that match each name:

foo<-function(Match){c(Match,sentences[grep(Match,sentences)])}
> lapply(toMatch,foo)
[[1]]
[1] "Martin Luther"
[2] "Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin"
[3] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"

[[2]]
[1] "Paul"
[2] " He studied the Scripture, especially of Paul, and Evangelical doctrine"

[[3]]
[1] "Melanchthon"
[2] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[3] " Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium"

lapply(toMatch,foo) gives a list of toMatch elements and apply each one to the function foo, which search for matches in the sentences with grep (returning the position of the sentences vector that match): sentences[grep(Match,sentences)].

My question is, instead of returning every sentence that match the elements of the toMatch vector, how could we have a vector with every sentence and then look for the names that match each one (i.e: the other way around, I know it's a bit confusing, the output would be this):

[1] "Martin Luther"
[2] "Melanchthon","Martin Luther"
[3] "Paul"
[4] NA                   #Or maybe this row doesn't exists, it's the same for me
[5] "Melanchthon"

Could this be done altering the result already provided or maybe this would be easier using a different function and lapply(sentences,FUNCTION)?

Body:
One option would be str_extract

library(stringr)
lst <- str_extract_all(sentences, paste(toMatch, collapse="|"))
lst[lengths(lst)==0] <- NA
lst
#[[1]]
#[1] "Martin Luther"

#[[2]]
#[1] "Melanchthon"   "Martin Luther"

#[[3]]
#[1] "Paul"

#[[4]]
#[1] NA

#[[5]]
#[1] "Melanchthon"

Or we can use regmatches/gregexpr from base R

lst <- regmatches(sentences, gregexpr(paste(toMatch, collapse="|"), sentences))

and replace the list elements having 0 length as NA (as before)


问:
How Exactly Does the int() function work?
This is python 3. I have come upon some strange error where it says:
'can't assign to operator'. Please help with this and any other errors you may find. Thanks</p>

```<code>Answer = 0
def Game():
    print('Hello! Enter in a number to multiply!')
    Input1 = input
    print('Ok, now enter another number to multiply!')
    Input2 = input
    print('Now let me think about that.....')
    int(Input1) * int(Input2) = Answer
    print('The answer to that is' + Answer + '!')

playAgain = 'yes'
while playAgain == 'yes':
    Game()
    print('Do you want to play again? (Yes or No?)')
    playAgain = input()
</code>```

答:
```<code>Answer = 0
def Game():
    print('Hello! Enter in a number to multiply!')
    Input1 = input()
    print('Ok, now enter another number to multiply!')
    Input2 = input()
    print('Now let me think about that.....')
    Answer = int(Input1) * int(Input2)
    print('The answer to that is' + Answer + '!')

playAgain = 'yes'
while playAgain == 'yes':
    Game()
    print('Do you want to play again? (Yes or No?)')
    playAgain = input()
</code>```

Body:
This is python 3. I have come upon some strange error where it says:
'can't assign to operator'. Please help with this and any other errors you may find. Thanks

Answer = 0
def Game():
    print('Hello! Enter in a number to multiply!')
    Input1 = input
    print('Ok, now enter another number to multiply!')
    Input2 = input
    print('Now let me think about that.....')
    int(Input1) * int(Input2) = Answer
    print('The answer to that is' + Answer + '!')

playAgain = 'yes'
while playAgain == 'yes':
    Game()
    print('Do you want to play again? (Yes or No?)')
    playAgain = input()


问:
cannot view the output with echo

Array
(
    [id] => 9794ea5d-9dc1-4b15-a798-fd0fa4ff6f4c
    [timestamp] => 2017-07-05T03:47:00.764Z
    [lang] => en
    [result] => Array
        (
            [source] => agent
            [resolvedQuery] => what is annual leave
            [speech] =>
            [action] => test
            [actionIncomplete] =>
            [parameters] => Array
                (
                    [allowance_type] => Array
                        (
                        )

                    [bonus_type] => Array
                        (
                        )

                    [salary_type] => Array
                        (
                        )

                    [leave_type] => Array
                        (
                            [0] => annual leave
                        )

                )

            [contexts] => Array
                (
                    [0] => Array
                        (
                            [name] => to-apply
                            [parameters] => Array
                                (
                                    [allowance_type] => Array
                                        (
                                        )

                                    [leave_type] => Array
                                        (
                                            [0] => annual leave
                                        )

                                    [bonus_type.original] =>
                                    [bonus_type] => Array
                                        (
                                        )

                                    [leave_type.original] => annual leave
                                    [allowance_type.original] =>
                                    [salary_type] => Array
                                        (
                                        )

                                    [salary_type.original] =>
                                )

                            [lifespan] => 5
                        )

                )

            [metadata] => Array
                (
                    [intentId] => e2bda510-2f4d-41b8-a80b-e11f148c804b
                    [webhookUsed] => true
                    [webhookForSlotFillingUsed] => false
                    [intentName] => description-definition-what
                )

            [fulfillment] => Array
                (
                    [speech] =>
                    [messages] => Array
                        (
                            [0] => Array
                                (
                                    [type] => 0
                                    [speech] =>
                                )

                        )

                )

            [score] => 1
        )

    [status] => Array
        (
            [code] => 200
            [errorType] => success
        )

    [sessionId] => 07a5acce-9587-4f06-b715-1c9106732109
)```
</div>
</div>
</p>

<p>Hi so i have this code where im trying to create a webhook to call the json file from API.AI. It gets the data and saves in a new file call JSON.php but im trying to echo out the data it is not happening. Is because the page is not auto refresh or?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><?php

$data = json_decode(file_get_contents("php://input"), true);
file_put_contents("JSON.php", print_r($data, true));

echo $data['intentName'];

?></code>```

答: So it should be $data['result']['metadata']['intentName']; instead of $data['intentName']

Title: cannot view the output with echo

Body:
Array
(
    [id] => 9794ea5d-9dc1-4b15-a798-fd0fa4ff6f4c
    [timestamp] => 2017-07-05T03:47:00.764Z
    [lang] => en
    [result] => Array
        (
            [source] => agent
            [resolvedQuery] => what is annual leave
            [speech] =>
            [action] => test
            [actionIncomplete] =>
            [parameters] => Array
                (
                    [allowance_type] => Array
                        (
                        )

                    [bonus_type] => Array
                        (
                        )

                    [salary_type] => Array
                        (
                        )

                    [leave_type] => Array
                        (
                            [0] => annual leave
                        )

                )

            [contexts] => Array
                (
                    [0] => Array
                        (
                            [name] => to-apply
                            [parameters] => Array
                                (
                                    [allowance_type] => Array
                                        (
                                        )

                                    [leave_type] => Array
                                        (
                                            [0] => annual leave
                                        )

                                    [bonus_type.original] =>
                                    [bonus_type] => Array
                                        (
                                        )

                                    [leave_type.original] => annual leave
                                    [allowance_type.original] =>
                                    [salary_type] => Array
                                        (
                                        )

                                    [salary_type.original] =>
                                )

                            [lifespan] => 5
                        )

                )

            [metadata] => Array
                (
                    [intentId] => e2bda510-2f4d-41b8-a80b-e11f148c804b
                    [webhookUsed] => true
                    [webhookForSlotFillingUsed] => false
                    [intentName] => description-definition-what
                )

            [fulfillment] => Array
                (
                    [speech] =>
                    [messages] => Array
                        (
                            [0] => Array
                                (
                                    [type] => 0
                                    [speech] =>
                                )

                        )

                )

            [score] => 1
        )

    [status] => Array
        (
            [code] => 200
            [errorType] => success
        )

    [sessionId] => 07a5acce-9587-4f06-b715-1c9106732109
)

Hi so i have this code where im trying to create a webhook to call the json file from API.AI. It gets the data and saves in a new file call JSON.php but im trying to echo out the data it is not happening. Is because the page is not auto refresh or?

<?php

$data = json_decode(file_get_contents("php://input"), true);
file_put_contents("JSON.php", print_r($data, true));

echo $data['intentName'];

?>


问:
Export excel file using PHPExcel，take about 2 minutes，lead to 504
environment:php+nginx;
I use PHPExcel for export and import excel file,and this operation would take about two minutes for a big data size,which leading to 504 gateway timeout.
And the nginx factcgi_connect/read/send_timeout is 30s;
Do not change nginx settings,how can I do?</p>

答:
Run the file generation process in "offline" batch mode. PayPal does this for some reports - you request the report, get immediate notification that it is in process and when it is done (typically a few seconds but could be much longer) the status page is updated and you get a notification email. Basic steps:

Create a new table of reports to be processed.

When a user requests a report, add it with a "new" status

Add a new process running as a cronjob (e.g., every 5 minutes) that changes the status to "processing", creates the report and then changes the status to "completed" and stores the report in an accessible location (e.g., filename based on the report table record id)

Add a status page to show users the status of their reports including a download link if "completed".

This is a bit of work, but PHP makes it easy because you can run identical code from the command line and as a web process.


问:
How to place a button next to a text?
Hey guys I need to place these two buttons next to a name. How can I do that? They always appear below the word.

<ion-list>
    <ion-item *ngFor="let service of services">

{{service.name}}

        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list>```

答:
Try using this in CSS.

        h2 {
        margin: 0;
        display: inline-block;
        }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>         <ion-list>
            <ion-item *ngFor="let service of services">
                <h2>{{service.name}}</h2>
                <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon>  </button>
                <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
            </ion-item>
        </ion-list>
    </code>```

Title: How to place a button next to a text?

Body:
Try using this in CSS.

        h2 {
        margin: 0;
        display: inline-block;
        }

         <ion-list>
            <ion-item *ngFor="let service of services">
                <h2>{{service.name}}</h2>
                <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon>  </button>
                <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
            </ion-item>
        </ion-list>


问:
checkmate w/ NA elements
I'd like to use the checkmate package in R to determine if all elements in a character vector either (a) are NA or (b) conform to the regex pattern.  (In this specific case, an element may contain only digits.)

The call below returns "Assertion on 'x' failed: Must comply to pattern '^\d{2,3}$'", even with the any.missing parameter set to TRUE.  Is there a natural & concise way to test this w/ checkmate?  Is the any.missing parameter essentially ignored if a regex pattern is used?

```<code>x <- c("11", "22", "333", NA_character_)
pattern <- "^\\d{2,3}$"

checkmate::assert_character(x,  pattern=pattern, any.missing=TRUE)
</code>```

For reference, a similar expression using testit is

```<code>testit::assert(
  "Any existing elements must be missing or only digits",
  all(is.na(x) | grepl(pattern, x)
)
</code>```

答: Following https://github.com/mllg/checkmate/issues/106, the any.missing parameter is no longer ignored when a regex pattern is supplied.

Title: checkmate w/ NA elements

Body:
I'd like to use the checkmate package in R to determine if all elements in a character vector either (a) are NA or (b) conform to the regex pattern.  (In this specific case, an element may contain only digits.)

The call below returns "Assertion on 'x' failed: Must comply to pattern '^\d{2,3}$'", even with the any.missing parameter set to TRUE.  Is there a natural & concise way to test this w/ checkmate?  Is the any.missing parameter essentially ignored if a regex pattern is used?

x <- c("11", "22", "333", NA_character_)
pattern <- "^\\d{2,3}$"

checkmate::assert_character(x,  pattern=pattern, any.missing=TRUE)

For reference, a similar expression using testit is

testit::assert(
  "Any existing elements must be missing or only digits",
  all(is.na(x) | grepl(pattern, x)
)


问:
Securing a RESTful API
For my current side project, which is a modular web management system (which could contain modules for database management, cms, project management, resource management, time tracking, etc…), I want to expose the entire system as a RESTful API as I think that will make the system as more usable.  The system itself is going to be coded in ASP.MET MVC3 however if I make all the data/actions available through a RESTful API, that should make the system very easy to use with PHP, Ruby, Python, etc… (they could even make there own interface to manage certain data if they wanted).

However, the one thing that seems hard to do easily (from the user's using the RESTful API point of view) with a RESTful API is security with ajax functionality.  If I wanted something that was complex to setup and use, I would just create SOAP services but the whole drive for using a RESTful API is that it is very easy.  The most common way of securing a RESTful API with with a key that is associated with a user.  This works fine when all the calls are done on the server side however once you start doing ajax functionality, that changes.  I would want the RESTful API to be able to be called directly from javascript however anyone who are firebug would easily be able to access the key the user is using allow that person access to the system.  Is there a better way the secure a RESTful API where it does not make the user of the RESTful API do complex things just to set it up?

答:
For one thing, you can't prevent the user of your API to not expose his key.

But, if you are writing a client for your API, I would suggest using your server side to do any requests to the API, while your HTML pages provide the data from the user. If you absolutely must use Javascript to make calls to the API and you still have a server side that populates the page in question, then you can obscure the actual key via a one-way digest algorithm in a timestamp-dependant way, while generating the page, and make it that your api checks that digest in a time-dependant way too.

Also, I'd suggest that you take a look into OAuth Nonces and timestamps a bit more deeply. Twitter and other API providers obviously have this problem too, so they must be doing something with the Nonce values.

Title: Securing a RESTful API


答:
It seems like you're confused about how assignments work. When you want to assign to a variable, the variable always goes on the left. So to set Answer, it should be:

```<code>Answer = ...
</code>```

not

```<code>... = Answer
</code>```

You shouldn't think of this as just a statement that two things are conceptually equal, assignment is an action and the order matters: the value of the expression on the right is assigned to the variable on the left. So it should be:

```<code>Answer = int(Input1) * int(Input2)
</code>```

The lefthand side of an assignment can't be a function call.

Title: How Exactly Does the int() function work?

Body:
It seems like you're confused about how assignments work. When you want to assign to a variable, the variable always goes on the left. So to set Answer, it should be:

Answer = ...

not

... = Answer

You shouldn't think of this as just a statement that two things are conceptually equal, assignment is an action and the order matters: the value of the expression on the right is assigned to the variable on the left. So it should be:

Answer = int(Input1) * int(Input2)

The lefthand side of an assignment can't be a function call.


问:
Graphical bug NSVisualEffectView when app in background
My application has a NSTableView configured as a SourceList.
Under the NSTableView are two NSButton two add/remove items in the table.
The table and the buttons are embedded in a NSVisualEffectView (.behindWindow mode).

The result is great and I can see the background through the table and the buttons, BUT, when the app is in background (I give the focus to another app), the tableview and the buttons become black, and the view is not redrawn, as shown in the picture below (taken with an iPhone, because a screenshot does not show the bug!):

And here is the IB structure of the views:

The container view (CustomView) is layer-backed.

Any lead to solve this problem? Thanks in advance !

答:
Are any of your views opaque and implement drawRect:?

I've seen issues like this when a view implements drawRect: but doesn't completely fill the passed-in rect (or all of the rects returned from getRectsBeingDrawn:count:).


问:
unfortunately app is getting stopped while checking for network
I am using the following code to check for the internet connection through out my app.

```<code>public class ConnectionChangeReceiver extends BroadcastReceiver
{
  @Override
  public void onReceive( Context context, Intent intent )
  {
    ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService( Context.CONNECTIVITY_SERVICE );
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE );

    if (activeNetInfo != null)
    {
        Toast.makeText( context, "Active Network Type : " +
                       activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
    if(mobNetInfo != null)
    {
        Toast.makeText( context, "Mobile Network Type : " +
                          mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
  }
}
</code>```

And I have defined required permission in the manifest file.

Whenever I try to disconnect / connect the network using F8 key I will receive "UNFORTUNATELY APP HAS STOPPED", and I am not getting any print in logcat.

Can I know what is the mistake I am doing?

答:
Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

https://developer.android.google.cn/reference/android/net/ConnectivityManager.html?hl=zh-cn#CONNECTIVITY_ACTION

Body:
I am using the following code to check for the internet connection through out my app.

public class ConnectionChangeReceiver extends BroadcastReceiver
{
  @Override
  public void onReceive( Context context, Intent intent )
  {
    ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService( Context.CONNECTIVITY_SERVICE );
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE );

    if (activeNetInfo != null)
    {
        Toast.makeText( context, "Active Network Type : " +
                       activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
    if(mobNetInfo != null)
    {
        Toast.makeText( context, "Mobile Network Type : " +
                          mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
  }
}

And I have defined required permission in the manifest file.

Whenever I try to disconnect / connect the network using F8 key I will receive "UNFORTUNATELY APP HAS STOPPED", and I am not getting any print in logcat.

Can I know what is the mistake I am doing?


问:
ERROR SparkContext: Error initializing SparkContext. java.net.BindException: Cannot assign requested address: Service 'sparkDriver' failed
I have install below setup with version:
Hadoop version 1.0.3
java version "1.7.0_67"
Scala version 2.11.7
Spark version 2.1.1.

getting below error, can any one help me this.

```<code>root@sparkmaster:/home/user# spark-shell
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/07/05 01:07:35 WARN SparkContext: Support for Java 7 is deprecated as of Spark 2.0.0
17/07/05 01:07:36 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/07/05 01:07:37 WARN Utils: Service 'sparkDriver' could not bind on port 0. Attempting port 1.

17/07/05 01:07:37 ERROR SparkContext: Error initializing SparkContext.
java.net.BindException: Cannot assign requested address: Service 'sparkDriver' failed after 16 retries (starting from 0)! Consider explicitly setting the appropriate port for the service 'sparkDriver' (for example spark.ui.port for SparkUI) to an available port or increasing

<console>:14: error: not found: value spark
       import spark.implicits._

<console>:14: error: not found: value spark
       import spark.sql

Using Scala version 2.11.8 (Java HotSpot(TM) Client VM, Java 1.7.0_67)
Type in expressions to have them evaluated.
Type :help for more information.

scala>
</code>```

答:
There are a few different solutions

Get your hostname

```<code>$ hostname
</code>```

then try to assign your host name

```<code>$ sudo hostname -s 127.0.0.1
</code>```

Start spark-shell.

Add your hostname to your /etc/hosts file (if not present)

```<code>127.0.0.1      your_hostname
</code>```

Add env variable

```<code>export SPARK_LOCAL_IP="127.0.0.1"

load-spark-env.sh
</code>```

Above steps solved my problem but you can also try to add

```<code>export SPARK_LOCAL_IP=127.0.0.1
</code>```

under the comment for local IP on template file spark-env.sh.template (/usr/local/Cellar/apache-spark/2.1.0/libexec/conf/)

and then

```<code>cp spark-env.sh.template spark-env.sh
spark-shell
</code>```

If none of the above fixes, check your firewall and enable it, if not already enabled

Body:
I have install below setup with version:
Hadoop version 1.0.3
java version "1.7.0_67"
Scala version 2.11.7
Spark version 2.1.1.

getting below error, can any one help me this.

root@sparkmaster:/home/user# spark-shell
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/07/05 01:07:35 WARN SparkContext: Support for Java 7 is deprecated as of Spark 2.0.0
17/07/05 01:07:36 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/07/05 01:07:37 WARN Utils: Service 'sparkDriver' could not bind on port 0. Attempting port 1.

17/07/05 01:07:37 ERROR SparkContext: Error initializing SparkContext.
java.net.BindException: Cannot assign requested address: Service 'sparkDriver' failed after 16 retries (starting from 0)! Consider explicitly setting the appropriate port for the service 'sparkDriver' (for example spark.ui.port for SparkUI) to an available port or increasing

<console>:14: error: not found: value spark
       import spark.implicits._

<console>:14: error: not found: value spark
       import spark.sql

Using Scala version 2.11.8 (Java HotSpot(TM) Client VM, Java 1.7.0_67)
Type in expressions to have them evaluated.
Type :help for more information.

scala>

Body:
There are a few different solutions

Get your hostname

$ hostname

then try to assign your host name

$ sudo hostname -s 127.0.0.1

Start spark-shell.

Add your hostname to your /etc/hosts file (if not present)

127.0.0.1      your_hostname

Add env variable

export SPARK_LOCAL_IP="127.0.0.1"

load-spark-env.sh

Above steps solved my problem but you can also try to add

export SPARK_LOCAL_IP=127.0.0.1

under the comment for local IP on template file spark-env.sh.template (/usr/local/Cellar/apache-spark/2.1.0/libexec/conf/)

and then

cp spark-env.sh.template spark-env.sh
spark-shell

If none of the above fixes, check your firewall and enable it, if not already enabled


问:
Update using ajax in asp.net mvc
Hi can someone tell me the problem with this please, and how to fix it.

I'm trying to update part of the page using ajax, I'm using the basic code that comes with a new mvc project.

The logon page has this:

```<code> <span id="error"/>
@using (Ajax.BeginForm("LogOn", "Account", new AjaxOptions { UpdateTargetId="error"})) {
    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.UserName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
            </div>

            <div class="editor-label">
                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
            </div>

            <p>
                    <input type="submit" value="Log On" />
            </p>
        </fieldset>
    </div>
}
</code>```

and the controller like so:

```<code>        [HttpPost]
        public string LogOn(LogOnModel model, string returnUrl)
        {

            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                         Redirect(returnUrl);
                    }
                    else
                    {
                         RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return "The user name or password provided is incorrect.";
        }
</code>```

Basically what I have done is embeded the login form into a modal popup.
if the entered user credentials fail I want the error to be displayed inside the modal popup, not go off to another page.

The above code is just creating a blank page with the text "The user name or password provided is incorrect."...I need it to be displayed in the modal dialog (jQuery).

答: Well, the most obvious question is, do you have the scripts added to the page you're trying to do this in?  Second, if you're posting to HTTPS (you are, right?), your scripts also have to be HTTPS or you'll get a security error.</p>

Title: Update using ajax in asp.net mvc

Body:
Hi can someone tell me the problem with this please, and how to fix it.

I'm trying to update part of the page using ajax, I'm using the basic code that comes with a new mvc project.

The logon page has this:

@using (Ajax.BeginForm("LogOn", "Account", new AjaxOptions { UpdateTargetId="error"})) {

        <fieldset>
            <legend>Account Information</legend>

                @Html.LabelFor(m => m.UserName)

                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)

                @Html.LabelFor(m => m.Password)

                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)

                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)

                    <input type="submit" value="Log On" />

        </fieldset>

}

and the controller like so:

        [HttpPost]
        public string LogOn(LogOnModel model, string returnUrl)
        {

            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                         Redirect(returnUrl);
                    }
                    else
                    {
                         RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return "The user name or password provided is incorrect.";
        }

Basically what I have done is embeded the login form into a modal popup.
if the entered user credentials fail I want the error to be displayed inside the modal popup, not go off to another page.

The above code is just creating a blank page with the text "The user name or password provided is incorrect."...I need it to be displayed in the modal dialog (jQuery).


问:
How to popup a message box when receive a notification on foreground?
Using swift3 with xcode 8.3 and this is a webview app.

Below is my function in ViewController.swift to handle url received from push notification

```<code>func redirectTo(url: String) {
    let request = URLRequest(url: URL(string: url)!)
    MyApp.loadRequest(request)
}
</code>```

Below is my function in AppDelegate.swift to handle didReceiveRemoteNotification

```<code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if let pushUrl = userInfo[AnyHashable("url")] as? String {
        viewController?.redirectTo(url: pushUrl)
    }
}
</code>```

When my app running on background, it will redirect my app to url received from notification when I click on it.

However, when my app running on foreground, it will directly redirect my webview to url without doing nothing.

I know this is because every time I received a notification , it will call redirectTo function and then loadRequest.

My question is , how can I add a message box with two button, when my app running on forefround and receive a notification it will ask user to redirect or cancel ?

答:
You can create an alert to get confirmation from users. Something like this

```<code>    let alert = UIAlertController(title: "YOUR_TITLE", message: "YOUR_MESSAGE", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "Ok", style: .default) { _ in
        // Handle your ok action
    }
    alert.addAction(okAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
        // Handle your cancel action
    }
    alert.addAction(cancelAction)

    DispatchQueue.main.async {
        self.present(alert, animated: true, completion: nil)
    }
</code>```

As the URLRequest may be expensive, you might want to implement that in background.

```<code>DispatchQueue.global().async {
    let request = URLRequest(url: URL(string: url)!)
    MyApp.loadRequest(request)
}
</code>```

Body:
Using swift3 with xcode 8.3 and this is a webview app.

Below is my function in ViewController.swift to handle url received from push notification

func redirectTo(url: String) {
    let request = URLRequest(url: URL(string: url)!)
    MyApp.loadRequest(request)
}

Below is my function in AppDelegate.swift to handle didReceiveRemoteNotification

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if let pushUrl = userInfo[AnyHashable("url")] as? String {
        viewController?.redirectTo(url: pushUrl)
    }
}

When my app running on background, it will redirect my app to url received from notification when I click on it.

However, when my app running on foreground, it will directly redirect my webview to url without doing nothing.

I know this is because every time I received a notification , it will call redirectTo function and then loadRequest.

My question is , how can I add a message box with two button, when my app running on forefround and receive a notification it will ask user to redirect or cancel ?

Body:
You can create an alert to get confirmation from users. Something like this

    let alert = UIAlertController(title: "YOUR_TITLE", message: "YOUR_MESSAGE", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "Ok", style: .default) { _ in
        // Handle your ok action
    }
    alert.addAction(okAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
        // Handle your cancel action
    }
    alert.addAction(cancelAction)

    DispatchQueue.main.async {
        self.present(alert, animated: true, completion: nil)
    }

As the URLRequest may be expensive, you might want to implement that in background.

DispatchQueue.global().async {
    let request = URLRequest(url: URL(string: url)!)
    MyApp.loadRequest(request)
}


问:
How to disable TypeScript Object.defineProperty(exports, "__esModule", { value: true })?
The ts compiler emit this line in every file:

```<code>Object.defineProperty(exports, "__esModule", { value: true });
</code>```

But my code is running on Nodejs, I am not writing a libaray so I think this line is unnecessary for me. How can I disable it?
My compiler option is:

```<code>{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "allowJs": true,
        "sourceMap": true,
        "outDir": "build",
        "moduleResolution": "Node",
        "lib": ["es6"]
    }
}
</code>```

For example, compile this ts file:

```<code>function add(a: number, b: number): number {
    return a + b
}

export { add }
</code>```

I got:

```<code>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function add(a, b) {
    return a + b;
}
exports.add = add;
//# sourceMappingURL=App.js.map
</code>```

How can I remove the second line?

答:
But my code is running on Nodejs, I am not writing a libaray so I think this line is unnecessary for me. How can I disable it

It works fine. So don't remove it. Think of it like "use strict". It's not neccessary but its good to have.

It exists to allow interop between transpilers (typescript / babel / other future ones).

Body:
The ts compiler emit this line in every file:

Object.defineProperty(exports, "__esModule", { value: true });

But my code is running on Nodejs, I am not writing a libaray so I think this line is unnecessary for me. How can I disable it?
My compiler option is:

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "allowJs": true,
        "sourceMap": true,
        "outDir": "build",
        "moduleResolution": "Node",
        "lib": ["es6"]
    }
}

For example, compile this ts file:

function add(a: number, b: number): number {
    return a + b
}

export { add }

I got:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function add(a, b) {
    return a + b;
}
exports.add = add;
//# sourceMappingURL=App.js.map

How can I remove the second line?


问:
Is there a well-defined way to check if a path is a simple file/folder name in Python?
I'm trying to check if a given user-supplied string is a simple file/folder name. I plan on using os.path.join() to concatenate this name to a preset root directory, but I want to detect and prohibit paths that try to traverse anywhere outside of that root directory.

For example, a string with the value 'track001.mp3' would be fine, it would resolve to 'root_dir/track001.mp3'. However, these should be detected and disallowed:

```<code>'../other_root_dir/'
'/etc'
'/'
'~'
'subdir/inner_file'
</code>```

答:
I would advise you to create the path string as you normally would assuming that the user is behaving (e.g. passing a "simple" or conforming path name).  Then I'd use os.path.expandvars and os.path.normpath to get the actual path name.  Finally, I'd check to make sure that the actual path name resides within the root directory.  Something like:

```<code>from os.path import expandvars, normpath, join

ROOT_DIR = 'root_dir'

user_path = 'some_path'
test_path = normpath(expandvars(join(ROOT_DIR, user_path)))

expected_prefix = normpath(ROOT_DIR)
if not test_path.startswith(expected_prefix):
    raise ValueError(f'Invalid path "{user_path}"')  # python3.6 f-string.
</code>```

Body:
I'm trying to check if a given user-supplied string is a simple file/folder name. I plan on using os.path.join() to concatenate this name to a preset root directory, but I want to detect and prohibit paths that try to traverse anywhere outside of that root directory.

For example, a string with the value 'track001.mp3' would be fine, it would resolve to 'root_dir/track001.mp3'. However, these should be detected and disallowed:

'../other_root_dir/'
'/etc'
'/'
'~'
'subdir/inner_file'

Body:
I would advise you to create the path string as you normally would assuming that the user is behaving (e.g. passing a "simple" or conforming path name).  Then I'd use os.path.expandvars and os.path.normpath to get the actual path name.  Finally, I'd check to make sure that the actual path name resides within the root directory.  Something like:

from os.path import expandvars, normpath, join

ROOT_DIR = 'root_dir'

user_path = 'some_path'
test_path = normpath(expandvars(join(ROOT_DIR, user_path)))

expected_prefix = normpath(ROOT_DIR)
if not test_path.startswith(expected_prefix):
    raise ValueError(f'Invalid path "{user_path}"')  # python3.6 f-string.


问:
Java Simple date format - dd/MM/yy v/s dd/MM/yyyy
I need to parse a String into dd/MM/YY hh:mm:ss format.

Suppose if a String has value 09/06/17 05:59:59 then it should be parsed but if a String has value 09/06/2017 05:59:59 then this is also a valid format and getting parsed but in my requirement, a parse exception should be thrown for the later.

Code:

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {

    public static void main(String[] args) {

        String line=" 09/06/17 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";
        //String line=" 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";

        String dt=null;
        dt=line.substring(1, 19);

        SimpleDateFormat org_format = new SimpleDateFormat("dd/MM/YY hh:mm:ss");
        SimpleDateFormat tgt_format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
              dt=line.substring(1, 19);

              System.out.println(dt);
              Date date = org_format.parse(dt);
              System.out.println(date);

              String tgt_date=tgt_format.format(date);
              System.out.println(tgt_date);
         } catch (ParseException e) {
              System.out.println(line);
         }
    }
}
</code>```

Problem - In the code, uncommented line variable and commented line variable, both are giving result successfully. but the commented line should throw parsable exception as it's the pattern dd/MM/yyyy, not dd/MM/yy.

fmt.setLenient(false) is not working.

I'm using Java 7. Don't have option to use Java 8 or later so can't use java.time.

答:
You can use regex to check if year contains 4 digits and if so throw new ParseException. The program is:</p>

```<code>public static void main(String[] args) throws ParseException {

        String date = "09/06/17 05:59:59";

        if (date.matches("\\d{1,2}[/.-]\\d{1,2}[/.-]\\d{4} .*"))
            throw new ParseException("date has wrong format");
        else {

        }

    }
</code>```

Body:
I need to parse a String into dd/MM/YY hh:mm:ss format.

Suppose if a String has value 09/06/17 05:59:59 then it should be parsed but if a String has value 09/06/2017 05:59:59 then this is also a valid format and getting parsed but in my requirement, a parse exception should be thrown for the later.

Code:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {

    public static void main(String[] args) {

        String line=" 09/06/17 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";
        //String line=" 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";

        String dt=null;
        dt=line.substring(1, 19);

        SimpleDateFormat org_format = new SimpleDateFormat("dd/MM/YY hh:mm:ss");
        SimpleDateFormat tgt_format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
              dt=line.substring(1, 19);

              System.out.println(dt);
              Date date = org_format.parse(dt);
              System.out.println(date);

              String tgt_date=tgt_format.format(date);
              System.out.println(tgt_date);
         } catch (ParseException e) {
              System.out.println(line);
         }
    }
}

Problem - In the code, uncommented line variable and commented line variable, both are giving result successfully. but the commented line should throw parsable exception as it's the pattern dd/MM/yyyy, not dd/MM/yy.

fmt.setLenient(false) is not working.

I'm using Java 7. Don't have option to use Java 8 or later so can't use java.time.

Body:
You can use regex to check if year contains 4 digits and if so throw new ParseException. The program is:

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

        String date = "09/06/17 05:59:59";

        if (date.matches("\\d{1,2}[/.-]\\d{1,2}[/.-]\\d{4} .*"))
            throw new ParseException("date has wrong format");
        else {

        }

    }


问:
How to add the grad method to a theano Op?
I have create a theano.Op that returns distance between each pair of the two collections of inputs, converting the scipy cdist:

```<code>class Cdist(theano.Op):

    __props__ = ()

    def __init__(self):
        #self.fn = scipy_cdist2
        super(Cdist, self).__init__()

    def make_node(self, x, w):
        #print('make_node')
        return gof.Apply(self, [x, w], [x.type()])

    def perform(self, node, inputs, output_storage):
        #print('perform')
        x, w = inputs[0], inputs[1]
        z = output_storage[0]
        z[0] = distance.cdist(x, w, 'euclidean')
</code>```

It works, but now want to add the grad method. I have read the guide and the documentation about the grad method. But i still dont't understand how it works. For example in the guide to get the gradient of a method that return a*x + b, they use:

```<code>def grad(self, inputs, output_grads):
    return [a * output_grads[0] + b]
</code>```

why? I'm going to quote what is written in the documentation about the grad:

If the output list of the op is [f_1, ... f_n], then the list
  output_gradients is [grad_{f_1}(C), grad_{f_2}(C), ... ,
  grad_{f_n}(C)]. If inputs consists of the list [x_1, ..., x_m], then
  Op.grad should return the list [grad_{x_1}(C), grad_{x_2}(C), ...,
  grad_{x_m}(C)], where (grad_{y}(Z))_i = \frac{\partial Z}{\partial
  y_i} (and i can stand for multiple dimensions).

They are told me that i have to write the gradient? But in the example the make a combination of output_grads and integger values. Really i'm not understanding.

答:
There's nothing wrong about docs. In grad method you should write a symbolic expression, as opposed to perform method where you write a numerical expression.

grad method is called from theano.grad, while perform is called inside the compiled function.

For example, assuming euclidean distance:

```<code>def grad(self, inputs, out_grads):
    x, y = inputs   # matrices of shape [mA, n] and [mB, n]]
    g, = out_grads   # matrix of shape [mA, mB]
    diff = x.dimshuffle(0, 'x', 1) - y.dimshuffle('x', 0, 1)   # [mA, mB, n] tensor
    z = T.sqrt(T.sum(T.sqr(diff), axis=2, keepdims=True))
    diff = g * diff / z
    return [T.sum(diff, axis=1), -T.sum(diff, axis=0)]
</code>```

For this particular case, I'd suggest writing a L_op instead of grad. L_op additionally reuses output in the forward Op.

```<code>def L_op(self, inputs, outputs, out_grads):
    x, y = inputs   # matrices of shape [mA, n] and [mB, n]
    z, = outputs   # matrix of shape [mA, mB]
    g, = out_grads   # idem
    diff = x.dimshuffle(0, 'x', 1) - y.dimshuffle('x', 0, 1)   # [mA, mB, n] tensor
    diff = g.dimshuffle(0, 1, 'x') * diff / z.dimshuffle(0, 1, 'x')
    return [T.sum(diff, axis=1), -T.sum(diff, axis=0)]
</code>```

Well, the grad expressions are probably wrong but you get the idea.

As you can see, we are calling symbolic functions such as dimshuffle. However there are cases where you want to write a class for grad Op. Either because the symbolic graph is too inefficient or you want a custom gradient.

For example:

```<code>class CDistGrad(theano.Op):
    def __init__(...):
        # <...>
        pass
    def c_code(...):
        # implement this in case you want more performance
        pass
    def perform(...):
        # <...>
        pass
    def make_node(...):
        # <...>
        pass

class CDist(theano.Op):
    # <...>
    def grad(self, inputs, output_grads):
        return CDistGrad()(*inputs, *output_grads)
</code>```

Still, symbolic expression is used in grad method. Just a custom Op replaced vanilla Theano expression.

Body:
I have create a theano.Op that returns distance between each pair of the two collections of inputs, converting the scipy cdist:

class Cdist(theano.Op):

    __props__ = ()

    def __init__(self):
        #self.fn = scipy_cdist2
        super(Cdist, self).__init__()

    def make_node(self, x, w):
        #print('make_node')
        return gof.Apply(self, [x, w], [x.type()])

    def perform(self, node, inputs, output_storage):
        #print('perform')
        x, w = inputs[0], inputs[1]
        z = output_storage[0]
        z[0] = distance.cdist(x, w, 'euclidean')

It works, but now want to add the grad method. I have read the guide and the documentation about the grad method. But i still dont't understand how it works. For example in the guide to get the gradient of a method that return a*x + b, they use:

def grad(self, inputs, output_grads):
    return [a * output_grads[0] + b]

why? I'm going to quote what is written in the documentation about the grad:

If the output list of the op is [f_1, ... f_n], then the list
  output_gradients is [grad_{f_1}(C), grad_{f_2}(C), ... ,
  grad_{f_n}(C)]. If inputs consists of the list [x_1, ..., x_m], then
  Op.grad should return the list [grad_{x_1}(C), grad_{x_2}(C), ...,
  grad_{x_m}(C)], where (grad_{y}(Z))_i = \frac{\partial Z}{\partial
  y_i} (and i can stand for multiple dimensions).

They are told me that i have to write the gradient? But in the example the make a combination of output_grads and integger values. Really i'm not understanding.

Body:
There's nothing wrong about docs. In grad method you should write a symbolic expression, as opposed to perform method where you write a numerical expression.

grad method is called from theano.grad, while perform is called inside the compiled function.

For example, assuming euclidean distance:

def grad(self, inputs, out_grads):
    x, y = inputs   # matrices of shape [mA, n] and [mB, n]]
    g, = out_grads   # matrix of shape [mA, mB]
    diff = x.dimshuffle(0, 'x', 1) - y.dimshuffle('x', 0, 1)   # [mA, mB, n] tensor
    z = T.sqrt(T.sum(T.sqr(diff), axis=2, keepdims=True))
    diff = g * diff / z
    return [T.sum(diff, axis=1), -T.sum(diff, axis=0)]

For this particular case, I'd suggest writing a L_op instead of grad. L_op additionally reuses output in the forward Op.

def L_op(self, inputs, outputs, out_grads):
    x, y = inputs   # matrices of shape [mA, n] and [mB, n]
    z, = outputs   # matrix of shape [mA, mB]
    g, = out_grads   # idem
    diff = x.dimshuffle(0, 'x', 1) - y.dimshuffle('x', 0, 1)   # [mA, mB, n] tensor
    diff = g.dimshuffle(0, 1, 'x') * diff / z.dimshuffle(0, 1, 'x')
    return [T.sum(diff, axis=1), -T.sum(diff, axis=0)]

Well, the grad expressions are probably wrong but you get the idea.

As you can see, we are calling symbolic functions such as dimshuffle. However there are cases where you want to write a class for grad Op. Either because the symbolic graph is too inefficient or you want a custom gradient.

For example:

class CDistGrad(theano.Op):
    def __init__(...):
        # <...>
        pass
    def c_code(...):
        # implement this in case you want more performance
        pass
    def perform(...):
        # <...>
        pass
    def make_node(...):
        # <...>
        pass

class CDist(theano.Op):
    # <...>
    def grad(self, inputs, output_grads):
        return CDistGrad()(*inputs, *output_grads)

Still, symbolic expression is used in grad method. Just a custom Op replaced vanilla Theano expression.