问:
Send array of objects in alamofire
I need to to send a list of objects to an end point.
the required type has the following keys

```<code>{
  id: Int;
  all: Bool;
  batch: Bool;
  chapter: Bool;
  myNetwork: Bool;
  categoryId: Int;
}
</code>```

the api expected a list of the above object. i generated a list using Parameter type of Alamofire like this.

```<code>[
    ["chapter": "true", "myNetwork": "false", "id": "3", "categoryId": "1", "memberId": "13", "batch": "true", "all": "true"],
    ["categoryId": "2", "batch": "false", "myNetwork": "true", "all": "true", "id": "891", "memberId": "13", "chapter": "true"],
    ["batch": "false", "memberId": "13", "categoryId": "3", "all": "false", "id": "1779", "myNetwork": "false", "chapter": "false"],
    ["batch": "true", "id": "2667", "all": "false", "chapter": "true", "memberId": "13", "categoryId": "4", "myNetwork": "false"]
]
</code>```

but it shows error

Cannot convert value of type '[[String : Any]]' to expected argument
  type 'Parameters?' (aka 'Optional>')

How can i sent this list of objects to an API using Alamofire ? the code that dispatch request

Alamofire.request("(APIManager.url)/Privacy/Update", method: .post,
  parameters: params, encoding: JSONEncoding.default, headers:
  APIManager.headers)

答:
You can use this open source class JSONSerializer from https://github.com/peheje/JsonSerializerSwift/blob/master/JsonSerializerSwift/JsonSerializer.swift

I have made some changes in this class to append an array of objects with key in existing JSON

```<code>import Foundation

 /// Handles Convertion from instances of objects to JSON strings. Also helps with casting strings of JSON to Arrays or Dictionaries.
open class JSONSerializer {

/**
Errors that indicates failures of JSONSerialization
- JsonIsNotDictionary:  -
- JsonIsNotArray:           -
- JsonIsNotValid:           -
*/
public enum JSONSerializerError: Error {
    case jsonIsNotDictionary
    case jsonIsNotArray
    case jsonIsNotValid
}

//http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary
/**
Tries to convert a JSON string to a NSDictionary. NSDictionary can be easier to work with, and supports string bracket referencing. E.g. personDictionary["name"].
- parameter jsonString: JSON string to be converted to a NSDictionary.
- throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotDictionary. JsonIsNotDictionary will typically be thrown if you try to parse an array of JSON objects.
- returns: A NSDictionary representation of the JSON string.
*/
open static func toDictionary(_ jsonString: String) throws -> NSDictionary {
    if let dictionary = try jsonToAnyObject(jsonString) as? NSDictionary {
        return dictionary
    } else {
        throw JSONSerializerError.jsonIsNotDictionary
    }
}

/**
Tries to convert a JSON string to a NSArray. NSArrays can be iterated and each item in the array can be converted to a NSDictionary.
- parameter jsonString: The JSON string to be converted to an NSArray
- throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotArray. JsonIsNotArray will typically be thrown if you try to parse a single JSON object.
- returns: NSArray representation of the JSON objects.
*/
open static func toArray(_ jsonString: String) throws -> NSArray {
    if let array = try jsonToAnyObject(jsonString) as? NSArray {
        return array
    } else {
        throw JSONSerializerError.jsonIsNotArray
    }
}

/**
Tries to convert a JSON string to AnyObject. AnyObject can then be casted to either NSDictionary or NSArray.
- parameter jsonString: JSON string to be converted to AnyObject
- throws: Throws error of type JSONSerializerError.
- returns: Returns the JSON string as AnyObject
*/
fileprivate static func jsonToAnyObject(_ jsonString: String) throws -> Any? {
    var any: Any?

    if let data = jsonString.data(using: String.Encoding.utf8) {
        do {
            any = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        }
        catch let error as NSError {
            let sError = String(describing: error)
            NSLog(sError)
            throw JSONSerializerError.jsonIsNotValid
        }
    }
    return any
}

/**
Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented.
- parameter object: The instantiation of any custom class to be represented as JSON.
- returns: A string JSON representation of the object.
*/
open static func toJson(_ object: Any, prettify: Bool = false) -> String {
    var json = ""
    if (!(object is Array<Any>)) {
        json += "{"
    }
    let mirror = Mirror(reflecting: object)

    var children = [(label: String?, value: Any)]()

    if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) {
        children += mirrorChildrenCollection
    }
    else {
        let mirrorIndexCollection = AnyCollection(mirror.children)
        children += mirrorIndexCollection
    }

    var currentMirror = mirror
    while let superclassChildren = currentMirror.superclassMirror?.children {
        let randomCollection = AnyRandomAccessCollection(superclassChildren)!
        children += randomCollection
        currentMirror = currentMirror.superclassMirror!
    }

    var filteredChildren = [(label: String?, value: Any)]()

    for (optionalPropertyName, value) in children {

        if let optionalPropertyName = optionalPropertyName {

            if !optionalPropertyName.contains("notMapped_") {
                filteredChildren.append((optionalPropertyName, value))
            }

        }
        else {
            filteredChildren.append((nil, value))
        }
    }

    var skip = false
    let size = filteredChildren.count
    var index = 0

    var first = true

    for (optionalPropertyName, value) in filteredChildren {
        skip = false

        let propertyName = optionalPropertyName
        let property = Mirror(reflecting: value)

        var handledValue = String()

        if propertyName != nil && propertyName == "some" && property.displayStyle == Mirror.DisplayStyle.struct {
            handledValue = toJson(value)
            skip = true
        }
        else if (value is Int ||
                 value is Int32 ||
                 value is Int64 ||
                 value is Double ||
                 value is Float ||
                 value is Bool) && property.displayStyle != Mirror.DisplayStyle.optional {
            handledValue = String(describing: value)
        }
        else if let array = value as? [Int?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Double?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Float?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Bool?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [String?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? "\"\(value!)\"" : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [String] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += "\"\(value)\""
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? NSArray {
            handledValue += "["
            for (index, value) in array.enumerated() {
                if !(value is Int) &&
                   !(value is Int32) &&
                   !(value is Int64) &&
                   !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) {
                    handledValue += toJson(value)
                }
                else {
                    handledValue += "\(value)"
                }
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if property.displayStyle == Mirror.DisplayStyle.class ||
            property.displayStyle == Mirror.DisplayStyle.struct ||
            String(describing: value).contains("#") {
            handledValue = toJson(value)
        }
        else if property.displayStyle == Mirror.DisplayStyle.optional {
            let str = String(describing: value)
            if str != "nil" {
                // Some optional values cannot be unpacked if type is "Any"
                // We remove the "Optional(" and last ")" from the value by string manipulation
                var d = String(str).dropFirst(9)
                d = d.dropLast(1)
                handledValue = String(d)
            } else {
                handledValue = "null"
            }
        }
        else {
            handledValue = String(describing: value) != "nil" ? "\"\(value)\"" : "null"
        }

        if !skip {

            // if optional propertyName is populated we'll use it
            if let propertyName = propertyName {
                json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "")
            }
            // if not then we have a member an array
            else {
                // if it's the first member we need to prepend ]
                if first {
                    json += "["
                    first = false
                }
                // if it's not the last we need a comma. if it is the last we need to close ]
                json += "\(handledValue)" + (index < size-1 ? ", " : "]")
            }

        } else {
            json = "\(handledValue)" + (index < size-1 ? ", " : "")
        }

        index += 1
    }

    if !skip {
        if (!(object is Array<Any>)) {
            json += "}"
        }
    }

    if prettify {
       let jsonData = json.data(using: String.Encoding.utf8)!
       let jsonObject = try! JSONSerialization.jsonObject(with: jsonData, options: [])
       let prettyJsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
       json = NSString(data: prettyJsonData, encoding: String.Encoding.utf8.rawValue)! as String
    }

    return json
}
/**
 Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented.
 - parameter object:    The instantiation of any custom class to be represented as JSON.
 - returns: A string JSON representation of the object.
 */
open static func toJson(key: String, _ object: Any, existingJson: String = "", prettify: Bool = false) -> String {
    var json = ""
    if (!(object is Array<Any>)) {
        json += "{ "
    }
    let mirror = Mirror(reflecting: object)

    var children = [(label: String?, value: Any)]()

    if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) {
        children += mirrorChildrenCollection
    }
    else {
        let mirrorIndexCollection = AnyCollection(mirror.children)
        children += mirrorIndexCollection
    }

    var currentMirror = mirror
    while let superclassChildren = currentMirror.superclassMirror?.children {
        let randomCollection = AnyRandomAccessCollection(superclassChildren)!
        children += randomCollection
        currentMirror = currentMirror.superclassMirror!
    }

    var filteredChildren = [(label: String?, value: Any)]()

    for (optionalPropertyName, value) in children {

        if let optionalPropertyName = optionalPropertyName {

            if !optionalPropertyName.contains("notMapped_") {
                filteredChildren.append((optionalPropertyName, value))
            }

        }
        else {
            filteredChildren.append((nil, value))
        }
    }

    var skip = false
    let size = filteredChildren.count
    var index = 0

    var first = true

    for (optionalPropertyName, value) in filteredChildren {
        skip = false

        let propertyName = optionalPropertyName
        let property = Mirror(reflecting: value)

        var handledValue = String()

        if propertyName != nil && propertyName == "some" && property.displayStyle == Mirror.DisplayStyle.struct {
            handledValue = toJson(value)
            skip = true
        }
        else if (value is Int ||
            value is Int32 ||
            value is Int64 ||
            value is Double ||
            value is Float ||
            value is Bool) && property.displayStyle != Mirror.DisplayStyle.optional {
            handledValue = String(describing: value)
        }
        else if let array = value as? [Int?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Double?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Float?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Bool?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [String?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? "\"\(value!)\"" : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [String] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += "\"\(value)\""
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? NSArray {
            handledValue += "["
            for (index, value) in array.enumerated() {
                if !(value is Int) &&
                    !(value is Int32) &&
                    !(value is Int64) &&
                    !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) {
                    handledValue += toJson(value)
                }
                else {
                    handledValue += "\(value)"
                }
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if property.displayStyle == Mirror.DisplayStyle.class ||
            property.displayStyle == Mirror.DisplayStyle.struct ||
            String(describing: value).contains("#") {
            handledValue = toJson(value)
        }
        else if property.displayStyle == Mirror.DisplayStyle.optional {
            let str = String(describing: value)
            if str != "nil" {
                // Some optional values cannot be unpacked if type is "Any"
                // We remove the "Optional(" and last ")" from the value by string manipulation
                var d = String(str).dropFirst(9)
                d = d.dropLast(1)
                handledValue = String(d)
            } else {
                handledValue = "null"
            }
        }
        else {
            handledValue = String(describing: value) != "nil" ? "\"\(value)\"" : "null"
        }

        if !skip {

            // if optional propertyName is populated we'll use it
            if let propertyName = propertyName {
                json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "")
            }
                // if not then we have a member an array
            else {
                // if it's the first member we need to prepend ]
                if first {
                    json += "["
                    first = false
                }
                // if it's not the last we need a comma. if it is the last we need to close ]
                json += "\(handledValue)" + (index < size-1 ? ", " : "]")
            }

        } else {
            json = "\(handledValue)" + (index < size-1 ? ", " : "")
        }

        index += 1
    }

    if !skip {
        if (!(object is Array<Any>)) {
            json += "}"
        }
    }

    if !existingJson.isEmpty {
        var JSON = existingJson
        JSON.removeLast()
        JSON = JSON + ", \"\(key)\": " + json + " }"
        if prettify {
            return prettyJson(json: JSON)
        }
        return JSON
    } else if existingJson.isEmpty {
        if prettify {
            return prettyJson(json: "{ \"\(key)\": " + json + " }")
        }
        return "{ \"\(key)\": " + json + " }"
    }
    return prettyJson(json: json)
}

private static func prettyJson(json: String) -> String {
    let jsonData = json.data(using: String.Encoding.utf8)!
    let jsonObject = try! JSONSerialization.jsonObject(with: jsonData, options: [])
    let prettyJsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
    return NSString(data: prettyJsonData, encoding: String.Encoding.utf8.rawValue)! as String
}

}
</code>```

And here is the code to use this class

```<code>let params = [ "some key": "some value"]
     if let theJSONData = try? JSONSerialization.data(withJSONObject: params, options: []) {
         let theJSONText = String(data: theJSONData, encoding: .ascii)
         let json = JSONSerializer.toJson(key: "Products", Cart.sharedInstance.products, existingJson: theJSONText!, prettify: true)
         print("JSON string = \(json)")
         let finalParams = json.convertToDictionary()
         // pass finalParams as Alamofire param
}
</code>```

Replace Cart.sharedInstance.products with your array of objects and Products with your key.

You can see the overloaded methods as per your need.

Hope you get the desired result.

Title: Send array of objects in alamofire

Body:
I need to to send a list of objects to an end point.
the required type has the following keys

{
  id: Int;
  all: Bool;
  batch: Bool;
  chapter: Bool;
  myNetwork: Bool;
  categoryId: Int;
}

the api expected a list of the above object. i generated a list using Parameter type of Alamofire like this.

[
    ["chapter": "true", "myNetwork": "false", "id": "3", "categoryId": "1", "memberId": "13", "batch": "true", "all": "true"],
    ["categoryId": "2", "batch": "false", "myNetwork": "true", "all": "true", "id": "891", "memberId": "13", "chapter": "true"],
    ["batch": "false", "memberId": "13", "categoryId": "3", "all": "false", "id": "1779", "myNetwork": "false", "chapter": "false"],
    ["batch": "true", "id": "2667", "all": "false", "chapter": "true", "memberId": "13", "categoryId": "4", "myNetwork": "false"]
]

but it shows error

Cannot convert value of type '[[String : Any]]' to expected argument
  type 'Parameters?' (aka 'Optional>')

How can i sent this list of objects to an API using Alamofire ? the code that dispatch request

Alamofire.request("(APIManager.url)/Privacy/Update", method: .post,
  parameters: params, encoding: JSONEncoding.default, headers:
  APIManager.headers)

Body:
You can use this open source class JSONSerializer from https://github.com/peheje/JsonSerializerSwift/blob/master/JsonSerializerSwift/JsonSerializer.swift

I have made some changes in this class to append an array of objects with key in existing JSON

import Foundation

 /// Handles Convertion from instances of objects to JSON strings. Also helps with casting strings of JSON to Arrays or Dictionaries.
open class JSONSerializer {

/**
Errors that indicates failures of JSONSerialization
- JsonIsNotDictionary:  -
- JsonIsNotArray:           -
- JsonIsNotValid:           -
*/
public enum JSONSerializerError: Error {
    case jsonIsNotDictionary
    case jsonIsNotArray
    case jsonIsNotValid
}

//http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary
/**
Tries to convert a JSON string to a NSDictionary. NSDictionary can be easier to work with, and supports string bracket referencing. E.g. personDictionary["name"].
- parameter jsonString: JSON string to be converted to a NSDictionary.
- throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotDictionary. JsonIsNotDictionary will typically be thrown if you try to parse an array of JSON objects.
- returns: A NSDictionary representation of the JSON string.
*/
open static func toDictionary(_ jsonString: String) throws -> NSDictionary {
    if let dictionary = try jsonToAnyObject(jsonString) as? NSDictionary {
        return dictionary
    } else {
        throw JSONSerializerError.jsonIsNotDictionary
    }
}

/**
Tries to convert a JSON string to a NSArray. NSArrays can be iterated and each item in the array can be converted to a NSDictionary.
- parameter jsonString: The JSON string to be converted to an NSArray
- throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotArray. JsonIsNotArray will typically be thrown if you try to parse a single JSON object.
- returns: NSArray representation of the JSON objects.
*/
open static func toArray(_ jsonString: String) throws -> NSArray {
    if let array = try jsonToAnyObject(jsonString) as? NSArray {
        return array
    } else {
        throw JSONSerializerError.jsonIsNotArray
    }
}

/**
Tries to convert a JSON string to AnyObject. AnyObject can then be casted to either NSDictionary or NSArray.
- parameter jsonString: JSON string to be converted to AnyObject
- throws: Throws error of type JSONSerializerError.
- returns: Returns the JSON string as AnyObject
*/
fileprivate static func jsonToAnyObject(_ jsonString: String) throws -> Any? {
    var any: Any?

    if let data = jsonString.data(using: String.Encoding.utf8) {
        do {
            any = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        }
        catch let error as NSError {
            let sError = String(describing: error)
            NSLog(sError)
            throw JSONSerializerError.jsonIsNotValid
        }
    }
    return any
}

/**
Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented.
- parameter object: The instantiation of any custom class to be represented as JSON.
- returns: A string JSON representation of the object.
*/
open static func toJson(_ object: Any, prettify: Bool = false) -> String {
    var json = ""
    if (!(object is Array<Any>)) {
        json += "{"
    }
    let mirror = Mirror(reflecting: object)

    var children = [(label: String?, value: Any)]()

    if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) {
        children += mirrorChildrenCollection
    }
    else {
        let mirrorIndexCollection = AnyCollection(mirror.children)
        children += mirrorIndexCollection
    }

    var currentMirror = mirror
    while let superclassChildren = currentMirror.superclassMirror?.children {
        let randomCollection = AnyRandomAccessCollection(superclassChildren)!
        children += randomCollection
        currentMirror = currentMirror.superclassMirror!
    }

    var filteredChildren = [(label: String?, value: Any)]()

    for (optionalPropertyName, value) in children {

        if let optionalPropertyName = optionalPropertyName {

            if !optionalPropertyName.contains("notMapped_") {
                filteredChildren.append((optionalPropertyName, value))
            }

        }
        else {
            filteredChildren.append((nil, value))
        }
    }

    var skip = false
    let size = filteredChildren.count
    var index = 0

    var first = true

    for (optionalPropertyName, value) in filteredChildren {
        skip = false

        let propertyName = optionalPropertyName
        let property = Mirror(reflecting: value)

        var handledValue = String()

        if propertyName != nil && propertyName == "some" && property.displayStyle == Mirror.DisplayStyle.struct {
            handledValue = toJson(value)
            skip = true
        }
        else if (value is Int ||
                 value is Int32 ||
                 value is Int64 ||
                 value is Double ||
                 value is Float ||
                 value is Bool) && property.displayStyle != Mirror.DisplayStyle.optional {
            handledValue = String(describing: value)
        }
        else if let array = value as? [Int?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Double?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Float?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Bool?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [String?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? "\"\(value!)\"" : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [String] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += "\"\(value)\""
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? NSArray {
            handledValue += "["
            for (index, value) in array.enumerated() {
                if !(value is Int) &&
                   !(value is Int32) &&
                   !(value is Int64) &&
                   !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) {
                    handledValue += toJson(value)
                }
                else {
                    handledValue += "\(value)"
                }
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if property.displayStyle == Mirror.DisplayStyle.class ||
            property.displayStyle == Mirror.DisplayStyle.struct ||
            String(describing: value).contains("#") {
            handledValue = toJson(value)
        }
        else if property.displayStyle == Mirror.DisplayStyle.optional {
            let str = String(describing: value)
            if str != "nil" {
                // Some optional values cannot be unpacked if type is "Any"
                // We remove the "Optional(" and last ")" from the value by string manipulation
                var d = String(str).dropFirst(9)
                d = d.dropLast(1)
                handledValue = String(d)
            } else {
                handledValue = "null"
            }
        }
        else {
            handledValue = String(describing: value) != "nil" ? "\"\(value)\"" : "null"
        }

        if !skip {

            // if optional propertyName is populated we'll use it
            if let propertyName = propertyName {
                json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "")
            }
            // if not then we have a member an array
            else {
                // if it's the first member we need to prepend ]
                if first {
                    json += "["
                    first = false
                }
                // if it's not the last we need a comma. if it is the last we need to close ]
                json += "\(handledValue)" + (index < size-1 ? ", " : "]")
            }

        } else {
            json = "\(handledValue)" + (index < size-1 ? ", " : "")
        }

        index += 1
    }

    if !skip {
        if (!(object is Array<Any>)) {
            json += "}"
        }
    }

    if prettify {
       let jsonData = json.data(using: String.Encoding.utf8)!
       let jsonObject = try! JSONSerialization.jsonObject(with: jsonData, options: [])
       let prettyJsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
       json = NSString(data: prettyJsonData, encoding: String.Encoding.utf8.rawValue)! as String
    }

    return json
}
/**
 Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented.
 - parameter object:    The instantiation of any custom class to be represented as JSON.
 - returns: A string JSON representation of the object.
 */
open static func toJson(key: String, _ object: Any, existingJson: String = "", prettify: Bool = false) -> String {
    var json = ""
    if (!(object is Array<Any>)) {
        json += "{ "
    }
    let mirror = Mirror(reflecting: object)

    var children = [(label: String?, value: Any)]()

    if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) {
        children += mirrorChildrenCollection
    }
    else {
        let mirrorIndexCollection = AnyCollection(mirror.children)
        children += mirrorIndexCollection
    }

    var currentMirror = mirror
    while let superclassChildren = currentMirror.superclassMirror?.children {
        let randomCollection = AnyRandomAccessCollection(superclassChildren)!
        children += randomCollection
        currentMirror = currentMirror.superclassMirror!
    }

    var filteredChildren = [(label: String?, value: Any)]()

    for (optionalPropertyName, value) in children {

        if let optionalPropertyName = optionalPropertyName {

            if !optionalPropertyName.contains("notMapped_") {
                filteredChildren.append((optionalPropertyName, value))
            }

        }
        else {
            filteredChildren.append((nil, value))
        }
    }

    var skip = false
    let size = filteredChildren.count
    var index = 0

    var first = true

    for (optionalPropertyName, value) in filteredChildren {
        skip = false

        let propertyName = optionalPropertyName
        let property = Mirror(reflecting: value)

        var handledValue = String()

        if propertyName != nil && propertyName == "some" && property.displayStyle == Mirror.DisplayStyle.struct {
            handledValue = toJson(value)
            skip = true
        }
        else if (value is Int ||
            value is Int32 ||
            value is Int64 ||
            value is Double ||
            value is Float ||
            value is Bool) && property.displayStyle != Mirror.DisplayStyle.optional {
            handledValue = String(describing: value)
        }
        else if let array = value as? [Int?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Double?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Float?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [Bool?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? String(value!) : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [String?] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += value != nil ? "\"\(value!)\"" : "null"
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? [String] {
            handledValue += "["
            for (index, value) in array.enumerated() {
                handledValue += "\"\(value)\""
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if let array = value as? NSArray {
            handledValue += "["
            for (index, value) in array.enumerated() {
                if !(value is Int) &&
                    !(value is Int32) &&
                    !(value is Int64) &&
                    !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) {
                    handledValue += toJson(value)
                }
                else {
                    handledValue += "\(value)"
                }
                handledValue += (index < array.count-1 ? ", " : "")
            }
            handledValue += "]"
        }
        else if property.displayStyle == Mirror.DisplayStyle.class ||
            property.displayStyle == Mirror.DisplayStyle.struct ||
            String(describing: value).contains("#") {
            handledValue = toJson(value)
        }
        else if property.displayStyle == Mirror.DisplayStyle.optional {
            let str = String(describing: value)
            if str != "nil" {
                // Some optional values cannot be unpacked if type is "Any"
                // We remove the "Optional(" and last ")" from the value by string manipulation
                var d = String(str).dropFirst(9)
                d = d.dropLast(1)
                handledValue = String(d)
            } else {
                handledValue = "null"
            }
        }
        else {
            handledValue = String(describing: value) != "nil" ? "\"\(value)\"" : "null"
        }

        if !skip {

            // if optional propertyName is populated we'll use it
            if let propertyName = propertyName {
                json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "")
            }
                // if not then we have a member an array
            else {
                // if it's the first member we need to prepend ]
                if first {
                    json += "["
                    first = false
                }
                // if it's not the last we need a comma. if it is the last we need to close ]
                json += "\(handledValue)" + (index < size-1 ? ", " : "]")
            }

        } else {
            json = "\(handledValue)" + (index < size-1 ? ", " : "")
        }

        index += 1
    }

    if !skip {
        if (!(object is Array<Any>)) {
            json += "}"
        }
    }

    if !existingJson.isEmpty {
        var JSON = existingJson
        JSON.removeLast()
        JSON = JSON + ", \"\(key)\": " + json + " }"
        if prettify {
            return prettyJson(json: JSON)
        }
        return JSON
    } else if existingJson.isEmpty {
        if prettify {
            return prettyJson(json: "{ \"\(key)\": " + json + " }")
        }
        return "{ \"\(key)\": " + json + " }"
    }
    return prettyJson(json: json)
}

private static func prettyJson(json: String) -> String {
    let jsonData = json.data(using: String.Encoding.utf8)!
    let jsonObject = try! JSONSerialization.jsonObject(with: jsonData, options: [])
    let prettyJsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
    return NSString(data: prettyJsonData, encoding: String.Encoding.utf8.rawValue)! as String
}

}

And here is the code to use this class

let params = [ "some key": "some value"]
     if let theJSONData = try? JSONSerialization.data(withJSONObject: params, options: []) {
         let theJSONText = String(data: theJSONData, encoding: .ascii)
         let json = JSONSerializer.toJson(key: "Products", Cart.sharedInstance.products, existingJson: theJSONText!, prettify: true)
         print("JSON string = \(json)")
         let finalParams = json.convertToDictionary()
         // pass finalParams as Alamofire param
}

Replace Cart.sharedInstance.products with your array of objects and Products with your key.

You can see the overloaded methods as per your need.

Hope you get the desired result.


来源: stackexchange

问:
getting ValueError: Outputs of true_fn and false_fn must have the same type: int32, float32 while using tf.histogram_fixed_width_bins
Hope someone can help me with this or point me some hint/ideas I can fix this error.

I am trying to create a custom layer in SeqtoSeq model.I need to call the histogram in part of my code. however, when it touches this line of the code it raises an error:

```<code>ValueError: Outputs of true_fn and false_fn must have the same type: int32, float32
</code>```

this is my code for the layer:

```<code>class entropy_measure(Layer):

    def __init__(self, beta,batch, **kwargs):
        self.beta = beta
        self.batch = batch
        self.uses_learning_phase = True
        self.supports_masking = True
        super(entropy_measure, self).__init__(**kwargs)

    def call(self, x):
        return K.in_train_phase(self.rev_entropy(x, self.beta,self.batch), x)

    def get_config(self):
        config = {'beta': self.beta}
        base_config = super(entropy_measure, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

    def rev_entropy(self, x, beta,batch):

        value_ranges = [0.0, 10.0]
        nbins = 5
        converted_x = tf.cast(x,tf.float32)
        new_f_w_t = tf.histogram_fixed_width_bins(converted_x, value_ranges, nbins)

        return new_f_w_t
</code>```

I call this layer using:

```<code>encoded = entropy_measure(beta=0.08,batch=BATCH_SIZE)(encoded)
</code>```

This code written with keras tensorflow backend.

Any idea what is the root of error?

答:
K.in_train_phase requires that self.rev_entropy(x, self.beta,self.batch) and x must have the same type in this case. But tf.histogram_fixed_width_bins returns int32 when your x is float32.  So you need to change type.

new_f_w_t = tf.cast(new_f_w_t, tf.float32)
```

ContentLicense: CC BY-SA 4.0

Body:
Hope someone can help me with this or point me some hint/ideas I can fix this error.

I am trying to create a custom layer in SeqtoSeq model.I need to call the histogram in part of my code. however, when it touches this line of the code it raises an error:

ValueError: Outputs of true_fn and false_fn must have the same type: int32, float32

this is my code for the layer:

class entropy_measure(Layer):

    def __init__(self, beta,batch, **kwargs):
        self.beta = beta
        self.batch = batch
        self.uses_learning_phase = True
        self.supports_masking = True
        super(entropy_measure, self).__init__(**kwargs)

    def call(self, x):
        return K.in_train_phase(self.rev_entropy(x, self.beta,self.batch), x)

    def get_config(self):
        config = {'beta': self.beta}
        base_config = super(entropy_measure, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

    def rev_entropy(self, x, beta,batch):

        value_ranges = [0.0, 10.0]
        nbins = 5
        converted_x = tf.cast(x,tf.float32)
        new_f_w_t = tf.histogram_fixed_width_bins(converted_x, value_ranges, nbins)

        return new_f_w_t

I call this layer using:

encoded = entropy_measure(beta=0.08,batch=BATCH_SIZE)(encoded)

This code written with keras tensorflow backend.

Any idea what is the root of error?


问:
setState inside setInterval not behaving as expected
I want a simple counter to update the state every second (or whatever). I'm using setInterval because I don't know how else to do it. I want the state change to be reflected in the markup and change on the screen.

Currently the idea works without setState, but as soon as setState is added values become undefined, values jump incorrectly, and infinite loops occur.

```<code> this.state = {
    numberLine: {
    1: {
      end: 42
       }
      }
    }
</code>```

I change the value and then reassign the entire value of the object

```<code>  counter(start) {
    const that = this
    const copy = _.cloneDeep(this.state.numberLine)
    function timer() {
       copy['1'].end = start
       that.setState({
           numberLine: copy
        })
      }
       let counter = setInterval(timer, 1000)
      }

   renderCustomMarkUp(num) {
    this.counter(num)
     return (
       <span>
          {this.state.numberLine['1'].end}
        </span>
         )
       }

     // call in render
       {this.renderCustomMarkUp(this.state.numberLine['1'].end)}
</code>```

I'd expect the value to update by one each section here. Then when printing the state expect to see the value increase. Instead, I get either gibberish like the same number with occasional jumps, or it freezes. Check this demo out. Make sure to let the timer get to at least 55-60 before leaving.

It doesn't seem this setInterval thing is the correct approach. How should I fix it?

答:
I've fixed your demo in a Code Sandbox: https://codesandbox.io/s/fragrant-dawn-kwp1w

The issue you were running into was that you were calling setInterval(timer, 1000) on every render. So every time you updated state, you were calling setInterval(timer, 1000), which was setting up many timers that would get triggered at 1s intervals.

Instead I've changed your component so that it only calls setInterval(timer, 1000) when the component mounts and i'm also using state directly when it comes time to increment the value of your counter.

Body:
I want a simple counter to update the state every second (or whatever). I'm using setInterval because I don't know how else to do it. I want the state change to be reflected in the markup and change on the screen.

Currently the idea works without setState, but as soon as setState is added values become undefined, values jump incorrectly, and infinite loops occur.

 this.state = {
    numberLine: {
    1: {
      end: 42
       }
      }
    }

I change the value and then reassign the entire value of the object

  counter(start) {
    const that = this
    const copy = _.cloneDeep(this.state.numberLine)
    function timer() {
       copy['1'].end = start
       that.setState({
           numberLine: copy
        })
      }
       let counter = setInterval(timer, 1000)
      }

   renderCustomMarkUp(num) {
    this.counter(num)
     return (

          {this.state.numberLine['1'].end}

         )
       }

     // call in render
       {this.renderCustomMarkUp(this.state.numberLine['1'].end)}

I'd expect the value to update by one each section here. Then when printing the state expect to see the value increase. Instead, I get either gibberish like the same number with occasional jumps, or it freezes. Check this demo out. Make sure to let the timer get to at least 55-60 before leaving.

It doesn't seem this setInterval thing is the correct approach. How should I fix it?


问:
Can I pass custom data in the HTTP header?
I have a whole bunch of web services each with several web methods. The consumers of these services are varied and many. I want to augment each of these web methods with an extra optional parameter (Int64 or Int32) but adding new methods with this extra (optional parameter) is a lot of work and getting the clients to use the new methods will be even more time consuming.

So I was wondering if I could allow the clients that wanted to take advantage of the new feature that this param provides could pass this Int in the HTTP header or some other way.

So the first question is can I pass an int in the HTTP header? If so, how would one do that in C#/ASP.NET?

Otherwise, what other suggestions do you have for tackling this problem?

答: Note that while it's fine to consume custom headers in ASP.NET it's not always possible to produce custom headers in ASP.NET. You can only do this if you're running ASP.NET integrated mode (i.e. IIS 7.0).</p>

OwnerDisplayName: Guy

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: John


问:
Calling a class having its name as a string
I have a string which specifies the name of the call.
How can i call the particular class by using this string.am trying this in java.
A function will return me a list of strings which are class names.now task is to make a call to a  class by using this string.</p>

答: You can use Class.forName(className). See Java API.

ContentLicense: CC BY-SA 3.0


答:
You can do something like this:

const data = "07/05/2019;14:11:07;3234;0.00000038;2.00;-0.00000038;0;\n07/05/2019;16:11:07;1779;0.00000019;2.00;-0.00000019;0;\n07/05/2019;14:11:06;4120;0.00000304;2.00;0.00000304;1;\n26/05/2019;06:32:39;2167;0.00000015;2.00;-0.00000015;0;\n26/05/2019;06:32:38;5152;0.00000015;2.00;0.00000015;1;\n07/05/2019;14:11:18;7949;0.00000038;2.00;-0.00000038;0;"

// Convert to array of arrays
let dataArrays = data.split('\n').map(x => x.split(';'))

let extractDate = arr => {
  let dateParts = arr[0].split('/') // get the date parts array
  let [dd,mm,yyyy] = dateParts     // get the actual dd/mm/yyyy
  let [date, time] = arr          // we only care about the date time for the date
  return new Date(`${mm}/${dd}/${yyyy} ${time}`) // return valid date for the sort
}

// perform the actual sort
let result = dataArrays.sort((a,b) => extractDate(a) - extractDate(b))

console.log(result.map(x => x.join(';')).join('\n')) // join back to same format```

Where the idea is to convert the dd/mm/yyyy to a valid date per each row and then use Array.sort to sort the rows. Once rows are sorted you can convert back to one string via Array.join etc.

Title: How do i multiple sort an array per column for all lines ? (JavaScript)

Body:
I have created a var rows to generate a csv.
I would like to sort the content according 2 columns : DATE and TIME.

DATE;TIME;ID;FACE;TOTAL;VAL1;VAL2;
07/05/2019;14:11:07;3234;0.00000038;2.00;-0.00000038;0;
07/05/2019;**16:11:07**;1779;0.00000019;2.00;-0.00000019;0;
07/05/2019;14:11:06;4120;0.00000304;2.00;0.00000304;1;
26/05/2019;**06:32:39**;2167;0.00000015;2.00;-0.00000015;0;
26/05/2019;06:32:38;5152;0.00000015;2.00;0.00000015;1;
**07/05/2019**;14:11:18;7949;0.00000038;2.00;-0.00000038;0;

result expected :

DATE;TIME;ID;FACE;TOTAL;VAL1;VAL2;
07/05/2019;14:11:06;4120;0.00000304;2.00;0.00000304;1;
07/05/2019;14:11:07;3234;0.00000038;2.00;-0.00000038;0;
07/05/2019;14:11:18;7949;0.00000038;2.00;-0.00000038;0;
07/05/2019;16:11:07;1779;0.00000019;2.00;-0.00000019;0;
26/05/2019;06:32:38;2167;0.00000015;2.00;-0.00000015;0;
26/05/2019;06:32:39;5152;0.00000015;2.00;0.00000015;1;

var lines = rows.split('\n');
for(var loop = 0; loop < lines.length; loop++){
if (parseFloat(prev) > 0){val2= 1;}else {val2 = 0;}
(....)
lines[loop] = lines[loop].replace(/(\r\n|\n|\r|\s+)/gm,"").trim() + val1 + ";" + val2 + ";";
}
rows = lines.join('\n');

because it is complicated to use my array lines, I was thinking about using the index array properties. But lines is not considered as an array, so forEach is not usable.

var result = lines.reduce(function(r, a) {
        a.forEach(function(s, i) {
        var key = i === 0 ? 'headers' : 'col' + i;
        r[key] || (r[key] = []);
        r[key].push(s);
        });
        return r;
        }, {});

function compare(r,x,col) {
    if (r[x].col< r[x+1].col) return -1;
    if (r[x].col > r[x+1].col) return 1;
    return 0;
}
for(var loop = 0; loop < r.length; loop++){
        result.sort(compare(r,loop,col1));
        result.sort(compare(r,loop,col2));
}

How to have the double sorting criterias applied and get the rows as expected in this array?

my code is used on google chrome. Some functions like prototype don't work (or filter...)

Body:
You can do something like this:

const data = "07/05/2019;14:11:07;3234;0.00000038;2.00;-0.00000038;0;\n07/05/2019;16:11:07;1779;0.00000019;2.00;-0.00000019;0;\n07/05/2019;14:11:06;4120;0.00000304;2.00;0.00000304;1;\n26/05/2019;06:32:39;2167;0.00000015;2.00;-0.00000015;0;\n26/05/2019;06:32:38;5152;0.00000015;2.00;0.00000015;1;\n07/05/2019;14:11:18;7949;0.00000038;2.00;-0.00000038;0;"

// Convert to array of arrays
let dataArrays = data.split('\n').map(x => x.split(';'))

let extractDate = arr => {
  let dateParts = arr[0].split('/') // get the date parts array
  let [dd,mm,yyyy] = dateParts     // get the actual dd/mm/yyyy
  let [date, time] = arr          // we only care about the date time for the date
  return new Date(`${mm}/${dd}/${yyyy} ${time}`) // return valid date for the sort
}

// perform the actual sort
let result = dataArrays.sort((a,b) => extractDate(a) - extractDate(b))

console.log(result.map(x => x.join(';')).join('\n')) // join back to same format

Where the idea is to convert the dd/mm/yyyy to a valid date per each row and then use Array.sort to sort the rows. Once rows are sorted you can convert back to one string via Array.join etc.


问:
Should I send http data chunk by chunk if I use chunk encoding?
I understand that HTTP chunk is something like this

```<code>HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked

7\r\n
Mozilla\r\n
9\r\n
Developer\r\n
7\r\n
Network\r\n
0\r\n
\r\n
</code>```

When server send response data to client, should the server send the data chunk by chunk?

For example,

server ==> client, first send headers, then first chunk:

```<code>7\r\n
Mozilla\r\n
</code>```

then second chunk, and so on.

Can server send the data like follows:

first write

```<code>7\r\n
Mozill
</code>```

second write

```<code>a\r\n
9\r\n
Developer\r\n
7\r\n
</code>```

and so on?

答:
TCP is a protocol to transfer a byte stream. There are no boundaries relevant at the TCP level between data send by different write. In fact, if you do multiple write or send shortly after each other the data from these calls often end up together in the same network packet (Nagle algorithm) and they are also read together at the receivers end.

This means that it should not matter if you  write partial chunks like 3\r\n followed by 123\r\n instead of a full chunk 3\r\n123\r\n. You can even write multiple chunks or 1.5 chunks etc within a single write or send.

But note also that there are always clients where the developers did not properly understand how sockets and TCP work and assume that what you send is what you recv or assume that they will always get a full chunk with a single recv or have similar wrong assumptions. While you might try to be nice against such broken applications you might also deliberately try to break these so that they get fixed early instead of showing random and unreproducible problems later.

Body:
I understand that HTTP chunk is something like this

HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked

7\r\n
Mozilla\r\n
9\r\n
Developer\r\n
7\r\n
Network\r\n
0\r\n
\r\n

When server send response data to client, should the server send the data chunk by chunk?

For example,

server ==> client, first send headers, then first chunk:

7\r\n
Mozilla\r\n

then second chunk, and so on.

Can server send the data like follows:

first write

7\r\n
Mozill

second write

a\r\n
9\r\n
Developer\r\n
7\r\n

and so on?


答:
Here is my approach using tidyverse:

```<code>> as_tibble(DT) %>%
      arrange(Student, Month) %>%
      group_by(Student) %>%
      # create an identifier for the start of the sequence
      mutate(seq_id = ifelse(row_number() == 1 | Month - lag(Month) > 1,
                             letters[row_number()], NA)) %>%
      fill(seq_id) %>%
      # add another grouping level (sequence identifier)
      group_by(Student, seq_id) %>%
      # only keep data with attendance in 3 or more consecutive months
      filter(length(seq_id) > 2) %>%
      # n consecutive months => n - 2 periods
      slice(1:(n() - 2)) %>%
      # clean up
      ungroup() %>%
      select(Student, Month)
# A tibble: 11 x 2
#   Student Month
#    <dbl> <dbl>
#1       1     1
#2       1     5
#3       1     6
#4       2     2
#5       2     3
#6       2     7
#7       2     8
#8       3     1
#9       3     5
#10      3     6
#11      3     7
</code>```

Title: Identify groups of n consecutive numbers in a data.table field in a group

Body:
This data.table shows the months of year attended by students.

DT = data.table(
 Student = c(1, 1, 1, 1, 1, 1, 1, 1, 1,
             2, 2, 2, 2, 2, 2, 2, 2,
             3, 3, 3, 3, 3, 3, 3, 3),
 Month   = c(1, 2, 3, 5, 6, 7, 8, 11, 12,
             2, 3, 4, 5, 7, 8, 9, 10,
             1, 2, 3, 5, 6, 7, 8, 9))

DT
    Student Month
 1:       1     1
 2:       1     2
 3:       1     3
 4:       1     5
 5:       1     6
 6:       1     7
 7:       1     8
 8:       1    11
 9:       1    12
10:       2     2
11:       2     3
12:       2     4
13:       2     5
14:       2     7
15:       2     8
16:       2     9
17:       2    10
18:       3     1
19:       3     2
20:       3     3
21:       3     5
22:       3     6
23:       3     7
24:       3     8
25:       3     9

I want to identify periods of three consecutive months (identified by the first month in the period). This is visualization of the data table and the eligible periods.

       1   2   3   4   5   6   7   8   9   10  11  12

1      *   *   *       *   *   *   *           *   *
       [-------]       [-------]
                           [-------]

2          *   *   *   *       *   *   *   *
           [-------]           [-------]
               [-------]           [-------]

3      *   *   *       *   *   *   *   *
       [-------]       [-------]
                           [-------]
                               [-------]

Desired output:

id   First_month_in_the_period

1    1
1    5
1    6
2    2
2    3
2    7
2    8
3    1
3    5
3    6
3    7

Looking for data.table (or dplyr) solutions.

Body:
Here is my approach using tidyverse:

> as_tibble(DT) %>%
      arrange(Student, Month) %>%
      group_by(Student) %>%
      # create an identifier for the start of the sequence
      mutate(seq_id = ifelse(row_number() == 1 | Month - lag(Month) > 1,
                             letters[row_number()], NA)) %>%
      fill(seq_id) %>%
      # add another grouping level (sequence identifier)
      group_by(Student, seq_id) %>%
      # only keep data with attendance in 3 or more consecutive months
      filter(length(seq_id) > 2) %>%
      # n consecutive months => n - 2 periods
      slice(1:(n() - 2)) %>%
      # clean up
      ungroup() %>%
      select(Student, Month)
# A tibble: 11 x 2
#   Student Month
#    <dbl> <dbl>
#1       1     1
#2       1     5
#3       1     6
#4       2     2
#5       2     3
#6       2     7
#7       2     8
#8       3     1
#9       3     5
#10      3     6
#11      3     7


问:
How to generate random functions using a for loop?
I want to create a random set of functions using a for loop, but my functions end up being the same.

I guess this is related to the environment, but I could not fix it:

```<code>a <- runif(100)

for(i in 1:100){
  assign(paste0("r",i), function(x){a[i]*x})
  }

</code>```

All the one hundred (r1 until r100) functions created end up being the same.

I would like them to have random a parameters.

答:
Here's an adapted version from the link in user202729's comment:

```<code>a <- runif(100)

invisible(lapply(1:100, function(i) {
  assign(paste0("r",i), function(x){a[i]*x}, envir = .GlobalEnv)
  }))
</code>```

You might have noticed that the functions r1 to r100 always evaluated using a[100]. This was because i=100 at the end of the loop. If you changed i to something else, you'd get different function evaluations.

Body:
I want to create a random set of functions using a for loop, but my functions end up being the same.

I guess this is related to the environment, but I could not fix it:

a <- runif(100)

for(i in 1:100){
  assign(paste0("r",i), function(x){a[i]*x})
  }

All the one hundred (r1 until r100) functions created end up being the same.

I would like them to have random a parameters.

Body:
Here's an adapted version from the link in user202729's comment:

a <- runif(100)

invisible(lapply(1:100, function(i) {
  assign(paste0("r",i), function(x){a[i]*x}, envir = .GlobalEnv)
  }))

You might have noticed that the functions r1 to r100 always evaluated using a[100]. This was because i=100 at the end of the loop. If you changed i to something else, you'd get different function evaluations.


问:
Using Regex as delimeter to split a string
I want to split the following strings into two substrings.
"somestring(otherstring)"

I came with the following regex split

```<code>"somestring(otherstring)".split(/(.+)\((.+)\)/)
</code>```

but this excludes the following strings, which dont have the substring in braces..
"somestring"

how can change the regex so that, even if there is not substring of the pattern "(otherstring)", it still generates the first substring as output.

thanks a lot in advance!

答:
```<code>>> "somestring(otherstring)".split(/[()]/)
=> ["somestring", "otherstring"]
>> "somestring".split(/[()]/)
=> ["somestring"]
</code>```

Body:
I want to split the following strings into two substrings.
"somestring(otherstring)"

I came with the following regex split

"somestring(otherstring)".split(/(.+)\((.+)\)/)

but this excludes the following strings, which dont have the substring in braces..
"somestring"

how can change the regex so that, even if there is not substring of the pattern "(otherstring)", it still generates the first substring as output.

thanks a lot in advance!


问:
How Run a notebook that uses csv files in amazon EC2?
For a personal project, I have to use EC2 for a jupyter notebook. However, this notebook uses csv files from my computer. So, my question is how do you upload your csv files in the AWS server??

For the moment, I can run the notebook with the EC2 server, but that's all.

Thanks for your help !

答:
There are many ways to do that in AWS.

For example:

You can ssh or rdp to your EC2 server (depending on what connection protocol it is), then scp or simply copy your CSV files to the EC2 server. This is one of the most straightforward ways. Depending on what storage is available for your EC2 server, you might store it in the instance storage, an EFS, an EBS etc. But instance storage is only temporary. If you terminate the instance, the CSV files will be gone for example.

You can manually upload your CSV files to your S3 bucket, grant your EC2 permission to access the S3 bucket where it stores the CSV files

Mount the AWS EFS on your on-prem storage, and transfer the CSV files to the AWS EFS, which connects to the EC2 instance

Upload your CSV to a git repo, ssh into your EC2, and git clone your CSV to the EC2 instance

Use AWS Direct Connect to establish a network connection to your computer to access the CSV

The list goes on and among these options, there are many configurations that needed to be done, for example, setting up the IAM role, configuring the security group and NAT if you use them, etc.

Fastest way to do it, since you mention how do you upload the csv files in the AWS server, is just to ssh or rdp into your AWS EC2 instance depending on the connection protocol and copy the csv files to your EC2 instance.


问:
How do you auto layout constraint a notification label inside a button?
This is the screenshot of my issue.

My problem is the button label is not a view. I can not anchor that notification label to it. If I anchor that label to any of the sides, the screen size will affect it.

Example: 6s Plus

and iPhone SE

It's fine on the bigger phones.

答: BhargavR has the right idea. Subclass UIButton and add the badge as a subview constrained to the button's textLabel (the UILabel it uses) property.</p>


问:
Disable Cookies on Specific Routes - Laravel 5.7
Laravel 5.7

Hello, I have a (hopefully) fairly simple problem I can't seem to fix.

I have API routes that I have disabled the csrf token for, however the XSRF-TOKEN cookie still appears to be sent ( visible in postman ).

Along with this cookie, I have laravel_session cookie for sessions. ( also visible in postman)

The purpose of these routes does not require either of these cookies and I wish to increase response time and save bandwidth by sending less bytes ( remove the cookies ) since the actual cookie values pretty long strings, maybe a hundred character.

Is there anyway to prevent/disable these cookies from being sent on specific routes like I can with csrf-token verify?

Thanks y'all for any possible solutions.

Please comment if you'd like to see any code from any file and I'd be glad to add.

答: I solved this problem myself, I switched the route to a new middleware class that was not the default web (I guess the web middleware by default gives cookies) to a new minimal custom middleware.


问:
Why segmentation fault happened when i define a const string in a google test programe?
I want to run unit test with google test, but got Segmentation fault. I have just define a global const string, and RUN_ALL_TESTS, why?

the gdb result is :

```<code>[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (1 ms total)
[  PASSED  ] 0 tests.

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff6fe415c in __GI___libc_free (mem=0x603588) at malloc.c:2947
2947    malloc.c: No such file or directory.

</code>```

And flowing is the backtrace:

```<code>(gdb) bt
#0  0x00007ffff6fe415c in __GI___libc_free (mem=0x603588) at malloc.c:2947
#1  0x00007ffff75fa36f in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x00007ffff7bb25ba in void std::_Destroy<std::string>(std::string*) () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#3  0x00007ffff7bb04bd in void std::_Destroy_aux<false>::__destroy<std::string*>(std::string*, std::string*) () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#4  0x00007ffff7bac65c in void std::_Destroy<std::string*>(std::string*, std::string*) () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#5  0x00007ffff7ba68f3 in void std::_Destroy<std::string*, std::string>(std::string*, std::string*, std::allocator<std::string>&) () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#6  0x00007ffff7ba08b2 in std::vector<std::string, std::allocator<std::string> >::~vector() () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#7  0x00007ffff6f9d53a in __cxa_finalize (d=0x7ffff7b2b440) at cxa_finalize.c:56
#8  0x00007ffff78b7ea3 in __do_global_dtors_aux () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgmock.so
#9  0x00007fffffffd5e0 in ?? ()
#10 0x00007ffff7dea7da in _dl_fini () at dl-fini.c:252
Backtrace stopped: frame did not save the PC

</code>```

This is my whole source code:

#include <iostream>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
const std::string fsdfsdf = "sdfsdfsd";
int main(int argc, char* argv[]) {
    testing::InitGoogleMock(&argc, argv);
    RUN_ALL_TESTS();
    return 0;
}

```

I expect the programe finished without segmentation fault.

答:
why?

There doesn't appear to be anything wrong with your code. The problem is likely in the environment.

You didn't say where libgtest.so and libgmock.so came from. Perhaps they are incompatible with your version of g++. Hard to tell.

Running your program under Valgrind may provide additional clues.

Body:
I want to run unit test with google test, but got Segmentation fault. I have just define a global const string, and RUN_ALL_TESTS, why?

the gdb result is :

[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (1 ms total)
[  PASSED  ] 0 tests.

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff6fe415c in __GI___libc_free (mem=0x603588) at malloc.c:2947
2947    malloc.c: No such file or directory.

And flowing is the backtrace:

(gdb) bt
#0  0x00007ffff6fe415c in __GI___libc_free (mem=0x603588) at malloc.c:2947
#1  0x00007ffff75fa36f in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x00007ffff7bb25ba in void std::_Destroy<std::string>(std::string*) () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#3  0x00007ffff7bb04bd in void std::_Destroy_aux<false>::__destroy<std::string*>(std::string*, std::string*) () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#4  0x00007ffff7bac65c in void std::_Destroy<std::string*>(std::string*, std::string*) () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#5  0x00007ffff7ba68f3 in void std::_Destroy<std::string*, std::string>(std::string*, std::string*, std::allocator<std::string>&) () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#6  0x00007ffff7ba08b2 in std::vector<std::string, std::allocator<std::string> >::~vector() () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgtest.so
#7  0x00007ffff6f9d53a in __cxa_finalize (d=0x7ffff7b2b440) at cxa_finalize.c:56
#8  0x00007ffff78b7ea3 in __do_global_dtors_aux () from /home/caros/src/secsdk/datasecurity-upgrade/external/libgmock.so
#9  0x00007fffffffd5e0 in ?? ()
#10 0x00007ffff7dea7da in _dl_fini () at dl-fini.c:252
Backtrace stopped: frame did not save the PC

This is my whole source code:

#include <iostream>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
const std::string fsdfsdf = "sdfsdfsd";
int main(int argc, char* argv[]) {
    testing::InitGoogleMock(&argc, argv);
    RUN_ALL_TESTS();
    return 0;
}

I expect the programe finished without segmentation fault.


问:
How can I use same mouse events in another form / user control?
Im creating winforms c# application with multiple user controls. It's flat application without any borders, so the only way to move windows is by using mouse control events. I used this part of code in my main window, but I cant apply it in any other user controls. I don't want to copy & paste for all user controls, so is there any way to use it?

This code works in my main form, but when i create user control i dont have access to those and i cant wire them up to objects.

```<code>    private bool mouseDown;
    private Point lastLocation;

    private void _MouseDown(object sender, MouseEventArgs e)
    {
        mouseDown = true;
        lastLocation = e.Location;
    }

    private void _MouseMove(object sender, MouseEventArgs e)
    {
        if (mouseDown)
        {
            this.Location = new Point((this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
            this.Update();
        }
    }
    private void _MouseUp(object sender, MouseEventArgs e)
    {
        mouseDown = false;
    }
</code>```

Can I make event handler / delegate to solve it?

答:
Here's a helper class that you can pass a Form and a Control Type to and it will wire up all of the controls that match.  In this example, all Buttons are wired up so you can drag them around.  Just change "Button" to the type of control you're interested in:

```<code>public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.WireControlsOfType<Button>();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();
        f2.WireControlsOfType<Button>();
    }

}
</code>```

The helper class in a different file:

```<code>public static class FormHelper
{

    public static void WireUserControl(this UserControl uc)
    {
        uc.MouseDown += _MouseDown;
        uc.MouseMove += _MouseMove;
        uc.MouseUp += _MouseUp;
    }

    public static void WireControlsOfType<T>(this Control sourceControl)
    {
        foreach(var ctl in sourceControl.RecursiveFindControlsByType<T>())
        {
            ctl.MouseDown += _MouseDown;
            ctl.MouseMove += _MouseMove;
            ctl.MouseUp += _MouseUp;
        }
    }

    // Code by Jon Skeet: https://stackoverflow.com/a/2055946/2330053
    public static IEnumerable<Control> RecursiveFindControlsByType<T>(this Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is T)
            {
                yield return c;
            }

            if (c.Controls.Count > 0)
            {
                foreach (Control ctl in c.RecursiveFindControlsByType<T>())
                {
                    yield return ctl;
                }
            }
        }
    }

    private static bool mouseDown;
    private static Point lastLocation;

    private static void _MouseDown(object sender, MouseEventArgs e)
    {
        mouseDown = true;
        lastLocation = e.Location;
    }

    private static void _MouseMove(object sender, MouseEventArgs e)
    {
        Control source = (Control)sender;
        if (mouseDown)
        {
            source.Location = new Point((source.Location.X - lastLocation.X) + e.X, (source.Location.Y - lastLocation.Y) + e.Y);
        }
    }

    private static void _MouseUp(object sender, MouseEventArgs e)
    {
         mouseDown = false;
    }

}
</code>```

Note that I'm wiring up Form1 in the Load() event with "this", but I'm also demonstrating it for a new instance of Form2 in the Click() handler.

Additional Post Based on Comment Questions

Based on your comments, here's an example showing the Buttons inside a UserControl being wired up to allow them to be moved around.  (I changed the WireControlsOfType<> method to accept generic control instead of Form.)  Nothing was changed in the default UserControl properties to allow this:

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        panel1.Controls.Clear();

        UserControlA ucA = new UserControlA();
        ucA.Dock = DockStyle.Fill;
        panel1.Controls.Add(ucA);
        ucA.WireControlsOfType<Button>();
    }
</code>```

The static FormHelper class is what allows this magic.  It can be its own class and does not need to be copied/associated with any of the Forms/UserControls; in fact, it's independent of them and can be in its own file.

If you want the entire UserControl itself to be able to be dragged around its container, I added in a different helper method called WireUserControl() to the helper class above.  So the snippet below is adding multiple instances of UserControlA to panel1, and each one could be dragged around separately:

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        UserControlA ucA = new UserControlA();
        panel1.Controls.Add(ucA);
        ucA.WireUserControl();
    }
</code>```

Body:
Im creating winforms c# application with multiple user controls. It's flat application without any borders, so the only way to move windows is by using mouse control events. I used this part of code in my main window, but I cant apply it in any other user controls. I don't want to copy & paste for all user controls, so is there any way to use it?

This code works in my main form, but when i create user control i dont have access to those and i cant wire them up to objects.

    private bool mouseDown;
    private Point lastLocation;

    private void _MouseDown(object sender, MouseEventArgs e)
    {
        mouseDown = true;
        lastLocation = e.Location;
    }

    private void _MouseMove(object sender, MouseEventArgs e)
    {
        if (mouseDown)
        {
            this.Location = new Point((this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
            this.Update();
        }
    }
    private void _MouseUp(object sender, MouseEventArgs e)
    {
        mouseDown = false;
    }

Can I make event handler / delegate to solve it?

Body:
Here's a helper class that you can pass a Form and a Control Type to and it will wire up all of the controls that match.  In this example, all Buttons are wired up so you can drag them around.  Just change "Button" to the type of control you're interested in:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.WireControlsOfType<Button>();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();
        f2.WireControlsOfType<Button>();
    }

}

The helper class in a different file:

public static class FormHelper
{

    public static void WireUserControl(this UserControl uc)
    {
        uc.MouseDown += _MouseDown;
        uc.MouseMove += _MouseMove;
        uc.MouseUp += _MouseUp;
    }

    public static void WireControlsOfType<T>(this Control sourceControl)
    {
        foreach(var ctl in sourceControl.RecursiveFindControlsByType<T>())
        {
            ctl.MouseDown += _MouseDown;
            ctl.MouseMove += _MouseMove;
            ctl.MouseUp += _MouseUp;
        }
    }

    // Code by Jon Skeet: https://stackoverflow.com/a/2055946/2330053
    public static IEnumerable<Control> RecursiveFindControlsByType<T>(this Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is T)
            {
                yield return c;
            }

            if (c.Controls.Count > 0)
            {
                foreach (Control ctl in c.RecursiveFindControlsByType<T>())
                {
                    yield return ctl;
                }
            }
        }
    }

    private static bool mouseDown;
    private static Point lastLocation;

    private static void _MouseDown(object sender, MouseEventArgs e)
    {
        mouseDown = true;
        lastLocation = e.Location;
    }

    private static void _MouseMove(object sender, MouseEventArgs e)
    {
        Control source = (Control)sender;
        if (mouseDown)
        {
            source.Location = new Point((source.Location.X - lastLocation.X) + e.X, (source.Location.Y - lastLocation.Y) + e.Y);
        }
    }

    private static void _MouseUp(object sender, MouseEventArgs e)
    {
         mouseDown = false;
    }

}

Note that I'm wiring up Form1 in the Load() event with "this", but I'm also demonstrating it for a new instance of Form2 in the Click() handler.

Additional Post Based on Comment Questions

Based on your comments, here's an example showing the Buttons inside a UserControl being wired up to allow them to be moved around.  (I changed the WireControlsOfType<> method to accept generic control instead of Form.)  Nothing was changed in the default UserControl properties to allow this:

    private void button1_Click(object sender, EventArgs e)
    {
        panel1.Controls.Clear();

        UserControlA ucA = new UserControlA();
        ucA.Dock = DockStyle.Fill;
        panel1.Controls.Add(ucA);
        ucA.WireControlsOfType<Button>();
    }

The static FormHelper class is what allows this magic.  It can be its own class and does not need to be copied/associated with any of the Forms/UserControls; in fact, it's independent of them and can be in its own file.

If you want the entire UserControl itself to be able to be dragged around its container, I added in a different helper method called WireUserControl() to the helper class above.  So the snippet below is adding multiple instances of UserControlA to panel1, and each one could be dragged around separately:

    private void button1_Click(object sender, EventArgs e)
    {
        UserControlA ucA = new UserControlA();
        panel1.Controls.Add(ucA);
        ucA.WireUserControl();
    }


问:
Why is this login program can login when i correct putting the username and password just at the first time?
So, I tried to make a simple login program with python. And get stuck with the else condition thing, when the username and password don't match, I want to make it start all over again which is the Username input and Password input. Then I just wrote login() in else block. I can login when I put the correct username and password at the first try. But when I am wrong once, then input the correct username and password, it just goes back to the login() function.
 I'm new with python, so I think making a simple login is a good exercise for "if else condition". Sorry for my bad english, thank you.

```<code>admin = "admin"
key = "admin"

def login():
    access = False
    while access == False:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("Welcome admin")
        else:
            login()
</code>```

答:
The problem here is the while loop and recursion combined. The first time you enter the wrong inputs, the login() is called for a second time. And you enter the correct inputs now. So it sets access to True and prints Welcome admin and returns. But when it returns, the value of access now is False, hence it continues looping. You can fix this by either replacing the while with an if statement, or by removing recursion.

By replacing while with if:

admin = "admin"
key = "admin"

def login():
    access = False
    if not access:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("Welcome admin")
        else:
            login()

```

<p>Removing recursion:  </p>

<pre class="lang-py prettyprint-override"><code>admin = "admin"
key = "admin"

def login():
    access = False
    while not access:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("Welcome admin")
</code>```

This method is probably preferred because recursion is not really needed here.

Body:
So, I tried to make a simple login program with python. And get stuck with the else condition thing, when the username and password don't match, I want to make it start all over again which is the Username input and Password input. Then I just wrote login() in else block. I can login when I put the correct username and password at the first try. But when I am wrong once, then input the correct username and password, it just goes back to the login() function.
 I'm new with python, so I think making a simple login is a good exercise for "if else condition". Sorry for my bad english, thank you.

admin = "admin"
key = "admin"

def login():
    access = False
    while access == False:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("Welcome admin")
        else:
            login()

Body:
The problem here is the while loop and recursion combined. The first time you enter the wrong inputs, the login() is called for a second time. And you enter the correct inputs now. So it sets access to True and prints Welcome admin and returns. But when it returns, the value of access now is False, hence it continues looping. You can fix this by either replacing the while with an if statement, or by removing recursion.

By replacing while with if:

admin = "admin"
key = "admin"

def login():
    access = False
    if not access:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("Welcome admin")
        else:
            login()

Removing recursion:

admin = "admin"
key = "admin"

def login():
    access = False
    while not access:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("Welcome admin")

This method is probably preferred because recursion is not really needed here.


问:
Reactive bar chart in shiny R
I am trying build a reactive bar chart in shiny app. I have a small table named stats

```<code>Team      wins  loss  draws
Arsenal   533   120   256
Chelsea   489   201   153
Liverpool 584   186   246
</code>```

I want to build a bar chart which displays the wins, loss and draws based on the team selected. I'm not able to create a reactive bar chart for this. Can someone please suggest a code for this or guide me in a right direction?

答:
Here we go:</p>

```<code>library(highcharter)
library(shiny)
library(dplyr)

df = data.frame(
    team = c("Arsenal", "Chelsea", "Liverpool"),
    wins = c(533, 489, 584),
    loss = c(120, 201, 186),
    draws = c(156, 153, 246)
)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Football Analysis"),

    sidebarLayout(
        sidebarPanel(
            selectizeInput("teams", "Teams", choices = unique(df$team), selected = unique(df$team)[1])
        ),

        mainPanel(
           highchartOutput("plot")
        )
    )
)

server <- function(input, output) {

    reactivedf <- reactive({
        filtereddf <- df %>%
            dplyr::filter(team == input$teams)
        filtereddf
    })

    output$plot <- renderHighchart({
        highchart() %>%
            hc_add_series(type = "column", reactivedf()$wins, name = "wins") %>%
            hc_add_series(type = "column", reactivedf()$loss, name = "loss") %>%
            hc_add_series(type = "column", reactivedf()$draws, name = "draws") %>%
            hc_xAxis(labels = list(enabled = FALSE)) %>%
            hc_title(text = input$teams)
    })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Title: Reactive bar chart in shiny R

Body:
I am trying build a reactive bar chart in shiny app. I have a small table named stats

Team      wins  loss  draws
Arsenal   533   120   256
Chelsea   489   201   153
Liverpool 584   186   246

I want to build a bar chart which displays the wins, loss and draws based on the team selected. I'm not able to create a reactive bar chart for this. Can someone please suggest a code for this or guide me in a right direction?

Body:
Here we go:

library(highcharter)
library(shiny)
library(dplyr)

df = data.frame(
    team = c("Arsenal", "Chelsea", "Liverpool"),
    wins = c(533, 489, 584),
    loss = c(120, 201, 186),
    draws = c(156, 153, 246)
)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Football Analysis"),

    sidebarLayout(
        sidebarPanel(
            selectizeInput("teams", "Teams", choices = unique(df$team), selected = unique(df$team)[1])
        ),

        mainPanel(
           highchartOutput("plot")
        )
    )
)

server <- function(input, output) {

    reactivedf <- reactive({
        filtereddf <- df %>%
            dplyr::filter(team == input$teams)
        filtereddf
    })

    output$plot <- renderHighchart({
        highchart() %>%
            hc_add_series(type = "column", reactivedf()$wins, name = "wins") %>%
            hc_add_series(type = "column", reactivedf()$loss, name = "loss") %>%
            hc_add_series(type = "column", reactivedf()$draws, name = "draws") %>%
            hc_xAxis(labels = list(enabled = FALSE)) %>%
            hc_title(text = input$teams)
    })
}

# Run the application
shinyApp(ui = ui, server = server)


问:
How to handle token refresh with redux observable?
I've been learning rxjs and have put together a token refresh flow that works, but I'd like to make some improvements and am stuck.

```<code>export const makeApiRequest = <
  T extends (p: StandardAdminParams) => Promise<Request.ApiResult<any>>
>(
  req: T,
  params: RemainingApiCallArgs<T>,
  action$: ActionsObservable<any>,
  state$: StateObservable<RootState>
) =>
  mergeMap(() =>
    defer(() =>
      req({
        ...params,
        settings,
        token: getToken(state$.value)!
      })
    ).pipe(
      mergeMap(async v => {
        const resp = await v;
        if (!resp.ok) {
          // TODO find out if there's a better way here.
          throw resp.error;
        }

        return resp as ApiReturnType<T>;
      }),
      catchError((_, source) => {
        // TODO make this actually check if token is refreshing, etc.
        return action$.pipe(
          filter(isActionOf(authActions.refreshToken.success)),
          takeUntil(action$.ofType(AuthActionConsts.REFRESH_TOKEN_FAILED)),
          take(1),
          mergeMap(() => source),
          merge(of(authActions.refreshToken.request()))
        );
      })
    )
  );
</code>```

My API library doesn't throw exceptions, it returns ok: boolean. All the examples of refresh token tutorials I've found however, take advantage of the catchError() operator to allow for retrying the call on successful refresh. I was wondering if there was a way to achieve the same thing without having to throw a "fake" error here.

Here's an example use case:

```<code>const fetchCurrentEmployeeEpic: Epic<ActionTypes, any, RootState> = (
  action$,
  state$
) =>
  action$.pipe(
    filter(isActionOf(actions.requestCurrentEmployee.request)),
    makeApiRequest(Employees.getSingle, {}, action$, state$),
    mapApiResponse(v => {
      if (v.ok) {
        return actions.requestCurrentEmployee.success({
          employee: v.value.data
        });
      }
      return actions.requestCurrentEmployee.failure({
        error: v.error
      });
    })
  );
</code>```

and mapApiResponse handles both outputs, either a refresh action or the return type of the api call. Open to suggestions on a better way to do this:

```<code>type RefreshTokenAction = ReturnType<typeof authActions.refreshToken.request>;

// Remove refresh token action type from union because our map function is only going to ever receive API responses.
type ExpectedMapParams<
  T extends Request.ApiResult<any> | RefreshTokenAction
> = T extends RefreshTokenAction ? never : T;

/**  Pass through refresh token action, otherwise pass api result to our callback */
export const mapApiResponse = <
  T extends Request.ApiResult<any> | RefreshTokenAction,
  R extends Action
>(
  cb: (params: ExpectedMapParams<T>) => R
) =>
  map((v: T) => {
    if (isRefreshAction(v)) {
      return v;
    }

    return cb(v as ExpectedMapParams<T>);
  });

const isRefreshAction = <T extends Request.ApiResult<any> | RefreshTokenAction>(
  v: T
): v is ExpectedMapParams<T> => {
  if (isAction(v)) {
    return true;
  }

  return false;
};
</code>```

However I've discovered another problem - I can't use the passed action to format a payload (for ids, etc.) Is there another way to get the action as a parameter so that I can pass a callback to params, i.e.

```<code>export const makeApiRequest = <
  T extends (p: StandardAdminParams) => Promise<Request.ApiResult<any>>
>(
req: T,
params: (action: GETACTIONTYPEHERE) => RemainingApiCallArgs<T>,
  action$: ActionsObservable<any>,
  state$: StateObservable<RootState>
) =>

</code>```

EDIT: I managed to figure out the action payload signature by doing the following:

```<code>export const makeApiRequest = <
  T extends (p: any) => Promise<Request.ApiResult<any>>,
  K extends Action
>(
  req: T,
  params: RemainingApiCallArgs<T> | ((p: K) => RemainingApiCallArgs<T>),
  action$: ActionsObservable<any>,
  state$: StateObservable<RootState>
) =>
  mergeMap((action: K) =>
    defer(() => {
      const formattedParams =
        typeof params === "function" ? params(action) : params;
      return req({
        ...formattedParams,
        settings,
        token: getToken(state$.value)!
      });
    }).pipe(
    ...
</code>```

Thanks!

答:
In the original version of makeApiRequest, it feels a bit odd to create a custom operator. First, it doesn't actually operate on anything emitted by the source observable. Second, it uses hard-coded request parameters. You appear to have identified and addressed these concerns in the edited version.

Whether you emit an error and use catchError or emit two different types of items and check the type is really a question about coding style. They both work, and it's akin to the difference between this:

function fetchCurrentEmployee() {
  const result = makeApiRequest()
  if (isRefreshAction(result)) {
    ...
  } else {
    ...
  }
}
```

<p>... and this:</p>

<pre class="lang-js prettyprint-override"><code>function fetchCurrentEmployee() {
  try {
    const resp = makeApiRequest()
    ...
  } catch (error) {
    ...
  }
}
</code>```

The difference is that, with the try-catch route, you simply don't need the isRefreshAction check. If you apply this to your epics/operators and emit an error, mapApiResponse simply reduces to a plain map operator.

Body:
I've been learning rxjs and have put together a token refresh flow that works, but I'd like to make some improvements and am stuck.

export const makeApiRequest = <
  T extends (p: StandardAdminParams) => Promise<Request.ApiResult<any>>
>(
  req: T,
  params: RemainingApiCallArgs<T>,
  action$: ActionsObservable<any>,
  state$: StateObservable<RootState>
) =>
  mergeMap(() =>
    defer(() =>
      req({
        ...params,
        settings,
        token: getToken(state$.value)!
      })
    ).pipe(
      mergeMap(async v => {
        const resp = await v;
        if (!resp.ok) {
          // TODO find out if there's a better way here.
          throw resp.error;
        }

        return resp as ApiReturnType<T>;
      }),
      catchError((_, source) => {
        // TODO make this actually check if token is refreshing, etc.
        return action$.pipe(
          filter(isActionOf(authActions.refreshToken.success)),
          takeUntil(action$.ofType(AuthActionConsts.REFRESH_TOKEN_FAILED)),
          take(1),
          mergeMap(() => source),
          merge(of(authActions.refreshToken.request()))
        );
      })
    )
  );

My API library doesn't throw exceptions, it returns ok: boolean. All the examples of refresh token tutorials I've found however, take advantage of the catchError() operator to allow for retrying the call on successful refresh. I was wondering if there was a way to achieve the same thing without having to throw a "fake" error here.

Here's an example use case:

const fetchCurrentEmployeeEpic: Epic<ActionTypes, any, RootState> = (
  action$,
  state$
) =>
  action$.pipe(
    filter(isActionOf(actions.requestCurrentEmployee.request)),
    makeApiRequest(Employees.getSingle, {}, action$, state$),
    mapApiResponse(v => {
      if (v.ok) {
        return actions.requestCurrentEmployee.success({
          employee: v.value.data
        });
      }
      return actions.requestCurrentEmployee.failure({
        error: v.error
      });
    })
  );

and mapApiResponse handles both outputs, either a refresh action or the return type of the api call. Open to suggestions on a better way to do this:

type RefreshTokenAction = ReturnType<typeof authActions.refreshToken.request>;

// Remove refresh token action type from union because our map function is only going to ever receive API responses.
type ExpectedMapParams<
  T extends Request.ApiResult<any> | RefreshTokenAction
> = T extends RefreshTokenAction ? never : T;

/**  Pass through refresh token action, otherwise pass api result to our callback */
export const mapApiResponse = <
  T extends Request.ApiResult<any> | RefreshTokenAction,
  R extends Action
>(
  cb: (params: ExpectedMapParams<T>) => R
) =>
  map((v: T) => {
    if (isRefreshAction(v)) {
      return v;
    }

    return cb(v as ExpectedMapParams<T>);
  });

const isRefreshAction = <T extends Request.ApiResult<any> | RefreshTokenAction>(
  v: T
): v is ExpectedMapParams<T> => {
  if (isAction(v)) {
    return true;
  }

  return false;
};

However I've discovered another problem - I can't use the passed action to format a payload (for ids, etc.) Is there another way to get the action as a parameter so that I can pass a callback to params, i.e.

export const makeApiRequest = <
  T extends (p: StandardAdminParams) => Promise<Request.ApiResult<any>>
>(
req: T,
params: (action: GETACTIONTYPEHERE) => RemainingApiCallArgs<T>,
  action$: ActionsObservable<any>,
  state$: StateObservable<RootState>
) =>

EDIT: I managed to figure out the action payload signature by doing the following:

export const makeApiRequest = <
  T extends (p: any) => Promise<Request.ApiResult<any>>,
  K extends Action
>(
  req: T,
  params: RemainingApiCallArgs<T> | ((p: K) => RemainingApiCallArgs<T>),
  action$: ActionsObservable<any>,
  state$: StateObservable<RootState>
) =>
  mergeMap((action: K) =>
    defer(() => {
      const formattedParams =
        typeof params === "function" ? params(action) : params;
      return req({
        ...formattedParams,
        settings,
        token: getToken(state$.value)!
      });
    }).pipe(
    ...

Thanks!

Body:
In the original version of makeApiRequest, it feels a bit odd to create a custom operator. First, it doesn't actually operate on anything emitted by the source observable. Second, it uses hard-coded request parameters. You appear to have identified and addressed these concerns in the edited version.

Whether you emit an error and use catchError or emit two different types of items and check the type is really a question about coding style. They both work, and it's akin to the difference between this:

function fetchCurrentEmployee() {
  const result = makeApiRequest()
  if (isRefreshAction(result)) {
    ...
  } else {
    ...
  }
}

... and this:

function fetchCurrentEmployee() {
  try {
    const resp = makeApiRequest()
    ...
  } catch (error) {
    ...
  }
}

The difference is that, with the try-catch route, you simply don't need the isRefreshAction check. If you apply this to your epics/operators and emit an error, mapApiResponse simply reduces to a plain map operator.