repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
joezhang2/JojangWeather
SwiftyJSON.swift
3
41502
// SwiftyJSON.swift // // Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type :Int{ case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(jsonObject: object) } catch let aError as NSError { if error != nil { error?.pointee = aError } self.init(jsonObject: NSNull()) } } /** Creates a JSON object - parameter object: the object - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - returns: the created JSON object */ public init(_ object: Any) { switch object { case let object as [JSON] where object.count > 0: self.init(array: object) case let object as [String: JSON] where object.count > 0: self.init(dictionary: object) case let object as Data: self.init(data: object) default: self.init(jsonObject: object) } } /** Parses the JSON string into a JSON object - parameter json: the JSON string - returns: the created JSON object */ public init(parseJSON jsonString: String) { if let data = jsonString.data(using: .utf8) { self.init(data) } else { self.init(NSNull()) } } /** Creates a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") public static func parse(json: String) -> JSON { return json.data(using: String.Encoding.utf8) .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ private init(jsonObject: Any) { self.object = jsonObject } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ private init(array: [JSON]) { self.init(array.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ private init(dictionary: [String: JSON]) { var newDictionary = [String: Any](minimumCapacity: dictionary.count) for (key, json) in dictionary { newDictionary[key] = json.object } self.init(newDictionary) } /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } /** Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - parameter other: The JSON which gets merged into this JSON - returns: New merged JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public func merged(with other: JSON) throws -> JSON { var merged = self try merged.merge(with: other, typecheck: true) return merged } // Private woker function which does the actual merging // Typecheck is set to true for the first recursion level to prevent total override of the source JSON private mutating func merge(with other: JSON, typecheck: Bool) throws { if self.type == other.type { switch self.type { case .dictionary: for (key, _) in other { try self[key].merge(with: other[key], typecheck: false) } case .array: self = JSON(self.arrayValue + other.arrayValue) default: self = other } } else { if typecheck { throw NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) } else { self = other } } } /// Private object fileprivate var rawArray: [Any] = [] fileprivate var rawDictionary: [String : Any] = [:] fileprivate var rawString: String = "" fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false /// Private type fileprivate var _type: Type = .null /// prviate error fileprivate var _error: NSError? = nil /// Object in JSON public var object: Any { get { switch self.type { case .array: return self.rawArray case .dictionary: return self.rawDictionary case .string: return self.rawString case .number: return self.rawNumber case .bool: return self.rawBool default: return self.rawNull } } set { _error = nil switch newValue { case let number as NSNumber: if number.isBool { _type = .bool self.rawBool = number.boolValue } else { _type = .number self.rawNumber = number } case let string as String: _type = .string self.rawString = string case _ as NSNull: _type = .null case _ as [JSON]: _type = .array case nil: _type = .null case let array as [Any]: _type = .array self.rawArray = array case let dictionary as [String : Any]: _type = .dictionary self.rawDictionary = dictionary default: _type = .unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// JSON type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } public enum Index<T: Any>: Comparable { case array(Int) case dictionary(DictionaryIndex<String, T>) case null static public func ==(lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): return left == right case (.null, .null): return true default: return false } } static public func <(lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): return left < right default: return false } } } public typealias JSONIndex = Index<JSON> public typealias JSONRawIndex = Index<Any> extension JSON: Collection { public typealias Index = JSONRawIndex public var startIndex: Index { switch type { case .array: return .array(rawArray.startIndex) case .dictionary: return .dictionary(rawDictionary.startIndex) default: return .null } } public var endIndex: Index { switch type { case .array: return .array(rawArray.endIndex) case .dictionary: return .dictionary(rawDictionary.endIndex) default: return .null } } public func index(after i: Index) -> Index { switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) default: return .null } } public subscript (position: Index) -> (String, JSON) { switch position { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): let (key, value) = self.rawDictionary[idx] return (key, JSON(value)) default: return ("", JSON.null) } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey:JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } set { if self.type == .array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return r } set { if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let array = elements self.init(dictionaryLiteral: array) } public init(dictionaryLiteral elements: [(String, Any)]) { let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in if let value = dictionary[key] { return (key, value) } return nil } return JSON(dictionaryLiteral: initializeElement) } var dict = [String : Any](minimumCapacity: elements.count) for element in elements { let elementToSet: Any if let json = element.1 as? JSON { elementToSet = json.object } else if let jsonArray = element.1 as? [JSON] { elementToSet = JSON(jsonArray).object } else if let dictionary = element.1 as? [String : Any] { elementToSet = jsonFromDictionaryLiteral(dictionary).object } else if let dictArray = element.1 as? [[String : Any]] { let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } elementToSet = JSON(jsonArray).object } else { elementToSet = element.1 } dict[element.0] = elementToSet } self.init(dict) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements as Any) } } extension JSON: Swift.ExpressibleByNilLiteral { @available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions") public init(nilLiteral: ()) { self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return self.object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } return try JSONSerialization.data(withJSONObject: self.object, options: opt) } public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { do { return try _rawString(encoding, options: [.jsonSerialization: opt]) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } public func rawString(options: [writtingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } private func _rawString( _ encoding: String.Encoding = .utf8, options: [writtingOptionsKeys: Any], maxObjectDepth: Int = 10 ) throws -> String? { if (maxObjectDepth < 0) { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"]) } switch self.type { case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let dict = self.object as? [String: Any?] else { return nil } let body = try dict.keys.map { key throws -> String in guard let value = dict[key] else { return "\"\(key)\": null" } guard let unwrappedValue = value else { return "\"\(key)\": null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return "\"\(key)\": \(nestedString)" } } return "{\(body.joined(separator: ","))}" } catch _ { return nil } case .array: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let array = self.object as? [Any?] else { return nil } let body = try array.map { value throws -> String in guard let unwrappedValue = value else { return "null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return nestedString } } return "[\(body.joined(separator: ","))]" } catch _ { return nil } case .string: return self.rawString case .number: return self.rawNumber.stringValue case .bool: return self.rawBool.description case .null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { if let string = self.rawString(options:.prettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [Any] public var arrayObject: [Any]? { get { switch self.type { case .array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array as Any } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { var d = [String : JSON](minimumCapacity: rawDictionary.count) for (key, value) in rawDictionary { d[key] = JSON(value) } return d } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : Any] public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v as Any } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { switch self.type { case .bool: return self.rawBool default: return nil } } set { if let newValue = newValue { self.object = newValue as Bool } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .bool: return self.rawBool case .number: return self.rawNumber.boolValue case .string: return ["true", "y", "t"].contains() { (truthyString) in return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame } default: return false } } set { self.object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .string: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .string: return self.object as? String ?? "" case .number: return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .number: return self.rawNumber case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber { // indicates parse error return NSDecimalNumber.zero } return decimal case .number: return self.object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func exists() -> Bool{ if let errorValue = error, errorValue.code == ErrorNotExist || errorValue.code == ErrorIndexOutOfBounds || errorValue.code == ErrorWrongType { return false } return true } } //MARK: - URL extension JSON { //Optional URL public var url: URL? { get { switch self.type { case .string: // Check for existing percent escapes first to prevent double-escaping of % character if let _ = self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) { return Foundation.URL(string: self.rawString) } else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(value: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(value: newValue) } } public var int: Int? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.intValue } set { self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return self.number?.uintValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.uintValue } set { self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { return self.number?.int8Value } set { if let newValue = newValue { self.object = NSNumber(value: Int(newValue)) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.int8Value } set { self.object = NSNumber(value: Int(newValue)) } } public var uInt8: UInt8? { get { return self.number?.uint8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value } set { self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { return self.number?.int16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.int16Value } set { self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return self.number?.uint16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value } set { self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { return self.number?.int32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.int32Value } set { self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return self.number?.uint32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value } set { self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { return self.number?.int64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.int64Value } set { self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return self.number?.uint64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value } set { self.object = NSNumber(value: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(cString: trueNumber.objCType) private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){ return true } else { return false } } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedAscending } } public enum writtingOptionsKeys { case jsonSerialization case castNilToNSNull case maxObjextDepth case encoding }
gpl-3.0
21aa2b05d9d7f069c610a99553d93b96
26.947475
265
0.546504
4.6553
false
false
false
false
jish/yelp
yelp/FilterViewController.swift
1
4467
// // FilterViewController.swift // yelp // // Created by Josh Lubaway on 2/12/15. // Copyright (c) 2015 Frustrated Inc. All rights reserved. // import UIKit protocol FilterViewDelegate { func filtersChanged(dict: NSDictionary) } struct Category { let title: String let key: String var on: Bool } class FilterViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, FilterCellDelegate, UIPickerViewDataSource, UIPickerViewDelegate { var delegate: FilterViewDelegate! var categories: [Category] = [ Category(title: "Chinese", key: "chinese", on: false), Category(title: "Italian", key: "italian", on: false), Category(title: "Japanese", key: "japanese", on: false), Category(title: "Mexican", key: "mexican", on: false), Category(title: "Thai", key: "thai", on: false) ] var settings: [String: AnyObject] = [:] let pickerData = [ "Best matched", "Distance", "Highest rated" ] @IBOutlet weak var tableView: UITableView! @IBOutlet weak var pickerView: UIPickerView! @IBOutlet weak var radiusControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 50 settings["categories"] = [] pickerView.dataSource = self pickerView.delegate = self println("View did load") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { for category in categories { println("\(category.title) is \(category.on)") } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("filter-cell") as FilterTableViewCell let category = categories[indexPath.row] println("Hydrating cell \(indexPath.row) with \(category.on)") cell.hydrate(category, delegate: self, index: indexPath.row) return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categories.count } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.preservesSuperviewLayoutMargins = false cell.layoutMargins = UIEdgeInsetsZero } @IBAction func onApplyButtonPressed(sender: AnyObject) { println("Apply button pressed") println(delegate) navigationController?.popViewControllerAnimated(true) var array: [String] = [] settings["categories"] = [] for category in categories { if category.on { array.insert(category.key, atIndex: array.count) } } settings["categories"] = array delegate.filtersChanged(settings) } func categoryChanged(index: Int, on: Bool) { println("Controller category \(index) changed to: \(on)") categories[index].on = on for category in categories { println("\(category.title) is \(category.on)") } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return pickerData[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { settings["sort"] = row } @IBAction func radiusDidChange(sender: UISegmentedControl) { settings["radius"] = (sender.selectedSegmentIndex + 1) * 5 * 1000 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d18c6f15377cff81f3aa968379f093d9
29.806897
156
0.659055
5.019101
false
false
false
false
ustwo/videoplayback-ios
DemoVideoPlaybackKit/DemoVideoPlaybackKit/ViewController/DemoViewController.swift
1
2152
// // ViewController.swift // DemoVideoPlaybackKit // // Created by Sonam on 4/25/17. // Copyright © 2017 ustwo. All rights reserved. // import UIKit import SnapKit import RxSwift import RxCocoa private enum DemoOption: String { case SingleVideoView, SingleViewViewAutoplay, CustomToolBar, FeedView, FeedAutoplayView } class DemoViewController: UIViewController { private let tableView = UITableView(frame: .zero) private let disposeBag = DisposeBag() private let demoList = Variable([DemoOption.SingleVideoView, DemoOption.SingleViewViewAutoplay, DemoOption.CustomToolBar, DemoOption.FeedView, DemoOption.FeedAutoplayView]) override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalTo(view) } tableView.register(BasicTableViewCell.self, forCellReuseIdentifier: BasicTableViewCell.identifier) tableView.estimatedRowHeight = 300 tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = .none setupDemoList() } private func setupDemoList() { demoList.asObservable().bindTo(tableView.rx.items(cellIdentifier: BasicTableViewCell.identifier)) { index, model, cell in guard let cell = cell as? BasicTableViewCell else { return } cell.titleText = model.rawValue }.addDisposableTo(disposeBag) tableView.rx.modelSelected(DemoOption.self).subscribe(onNext: { demoOption in switch demoOption { case .SingleVideoView: self.navigationController?.pushViewController(SingleVideoPlaybackViewController(), animated: true) case .SingleViewViewAutoplay: self.navigationController?.pushViewController(SingleVideoPlaybackViewController(shouldAutoPlay: true), animated: true) default: print("not ready") break } }).addDisposableTo(disposeBag) } }
mit
71a871686df03697eeff8de681879f4b
32.092308
176
0.668991
5.272059
false
false
false
false
seeaya/Simplex
Simplex/Input/Keyboard.swift
1
12427
// // Keyboard.swift // Simplex // // Created by Connor Barnes on 6/13/17. // Copyright © 2017 Connor Barnes. All rights reserved. // import Cocoa extension GameView { open override func keyDown(with event: NSEvent) { // Get key from keycode if let key = Keyboard.Key(rawValue: Int(event.keyCode)) { // Make sure the key is not already marked as down if !keyboard.keysDown.contains(key) { // Get characters pressed if let eventCharacters = event.characters { keyboard._charactersJustPressed.append(eventCharacters) // Add released keys keyboard._charactersDown.append(eventCharacters) } keyboard._keysJustPressed.append(key) // Add pressed keys keyboard._keysDown.append(key) } } } open override func keyUp(with event: NSEvent) { // Get key from keycode if let key = Keyboard.Key(rawValue: Int(event.keyCode)) { // Get characters pressed if let eventCharacters = event.characters { keyboard._charactersJustReleased.append(eventCharacters) // Remove released characters while keyboard._charactersDown.contains(eventCharacters) { keyboard._charactersDown.remove(at: keyboard._charactersDown.index(of: eventCharacters)!) } } keyboard._keysJustReleased.append(key) // Remove released keys while keyboard._keysDown.contains(key) { keyboard._keysDown.remove(at: keyboard._keysDown.index(of: key)!) } } } open override func flagsChanged(with event: NSEvent) { // Handle caps lock key if event.modifierFlags.contains(.capsLock) { if !keyboard.keysDown.contains(.capsLock) { // Caps lock just pressed keyboard._keysDown.append(.capsLock) keyboard._keysJustPressed.append(.capsLock) } } else { if keyboard.keysDown.contains(.capsLock) { while keyboard._keysDown.contains(.capsLock) { // Caps lock just released keyboard._keysDown.remove(at: keyboard._keysDown.index(of: .capsLock)!) } } } // Handle command key if event.modifierFlags.contains(.command) { if !keyboard.keysDown.contains(.command) { // Caps lock just pressed keyboard._keysDown.append(.command) keyboard._keysJustPressed.append(.command) } } else { if keyboard.keysDown.contains(.command) { while keyboard._keysDown.contains(.command) { // Caps lock just released keyboard._keysDown.remove(at: keyboard._keysDown.index(of: .command)!) } } } // Handle control key if event.modifierFlags.contains(.control) { if !keyboard.keysDown.contains(.control) { // Caps lock just pressed keyboard._keysDown.append(.control) keyboard._keysJustPressed.append(.control) } } else { if keyboard.keysDown.contains(.control) { while keyboard._keysDown.contains(.control) { // Caps lock just released keyboard._keysDown.remove(at: keyboard._keysDown.index(of: .control)!) } } } // Handle function key if event.modifierFlags.contains(.function) { if !keyboard.keysDown.contains(.function) { // Caps lock just pressed keyboard._keysDown.append(.function) keyboard._keysJustPressed.append(.function) } } else { if keyboard.keysDown.contains(.function) { while keyboard._keysDown.contains(.function) { // Caps lock just released keyboard._keysDown.remove(at: keyboard._keysDown.index(of: .function)!) } } } // Handle option key if event.modifierFlags.contains(.option) { if !keyboard.keysDown.contains(.option) { // Caps lock just pressed keyboard._keysDown.append(.option) keyboard._keysJustPressed.append(.option) } } else { if keyboard.keysDown.contains(.option) { while keyboard._keysDown.contains(.option) { // Caps lock just released keyboard._keysDown.remove(at: keyboard._keysDown.index(of: .option)!) } } } // Handle shift key if event.modifierFlags.contains(.shift) { if !keyboard.keysDown.contains(.shift) { // Caps lock just pressed keyboard._keysDown.append(.shift) keyboard._keysJustPressed.append(.shift) } } else { if keyboard.keysDown.contains(.shift) { while keyboard._keysDown.contains(.shift) { // Caps lock just released keyboard._keysDown.remove(at: keyboard._keysDown.index(of: .shift)!) } } } } // Required to respond to keyboard events override open var acceptsFirstResponder: Bool { return true } } /// Representation of keyboard events in the game. public class Keyboard { /// Key associated with a given keycode. These values represent the location of the key, and do not necessarily represent a character. The following enumeration represents a typical US QWERTY keyboard. /// /// - tilde: ` and ~ key /// - leftBracket: [ and { key /// - rightBracket: ] and } key /// - backSlash: \ and | key /// - semiColon: ; and : key /// - apostrophe: ' and " key /// - dash: - and _ key /// - equals: = and + key /// - comma: , and < key /// - period: . and > key /// - forwardSlash: / and ? key /// - numpad1: 1 on the numberpad (on extended keyboards) /// - numpad2: 2 on the numberpad (on extended keyboards) /// - numpad3: 3 on the numberpad (on extended keyboards) /// - numpad4: 4 on the numberpad (on extended keyboards) /// - numpad5: 5 on the numberpad (on extended keyboards) /// - numpad6: 6 on the numberpad (on extended keyboards) /// - numpad7: 7 on the numberpad (on extended keyboards) /// - numpad8: 8 on the numberpad (on extended keyboards) /// - numpad9: 9 on the numberpad (on extended keyboards) /// - numpad0: 0 on the numberpad (on extended keyboards) /// - numpadMultiply: * on the numberpad (on extended keyboards) /// - numpadDivide: / on the numberpad (on extended keyboards) /// - numpadAdd: + on the numberpad (on extended keyboards) /// - numpadSubtract: - on the numberpad (on extended keyboards) /// - numpadEquals: = on the numberpad (on extended keyboards) /// - numpadPeriod: . on the numberpad (on extended keyboards) /// - numpadClear: Clear key on the numberpad (on extended keyboards) (⌧) /// - `return`: Return key (not on numberpad) (↩︎) /// - enter: Enter key (on numberpad) (on extended keyboards) (⌤) /// - function: Function key (fn) /// - control: Control key (^) /// - option: Left option key (⌥) /// - command: Left or right command key (⌘) /// - shift: Shift key (⇧) /// - arrowUp: Up arrow key (⇡) /// - arrowDown: Down arrow key (⇣) /// - arrowLeft: Left arrow key (⇠) /// - arrowRight: Right arrow key (⇢) /// - home: Home key (on extended keyboards) (↖︎) /// - end: End key (on extended keyboards) (↘︎) /// - pageUp: Page up key (on extended keyboards) (⇞) /// - pageDown: page down key (on extended keyboards) (⇟) /// - escape: Escape key (esc) /// - capsLock: Caps lock key (⇪) /// - space: Spacebar /// - tab: Tab key (⇥) /// - delete: Delete key (not to be confused with the forward delete key on extended keyboards) (⌫) /// - forwardDelete: Forward delete key (on extended keyboards) (⌦) /// - f1: F1 key (top row) /// - f2: F2 key (top row) /// - f3: F3 key (top row) /// - f4: F4 key (top row) /// - f5: F5 key (top row) /// - f6: F6 key (top row) /// - f7: F7 key (top row) /// - f8: F8 key (top row) /// - f9: F9 key (top row) /// - f10: F10 key (top row) /// - f11: F11 key (top row) /// - f12: F12 key (top row) /// - f13: F13 key (top row on extended keyboards) /// - f14: F14 key (top row on extended keyboards) /// - f15: F15 key (top row on extended keyboards) /// - f16: F16 key (top row on extended keyboards) /// - f17: F17 key (top row on extended keyboards) /// - f18: F18 key (top row on extended keyboards) /// - f19: F19 key (top row on extended keyboards) /// - f20: F20 key (top row on extended keyboards) public enum Key: Int { case a = 0 case b = 11 case c = 8 case d = 2 case e = 14 case f = 3 case g = 5 case h = 4 case i = 34 case j = 38 case k = 40 case l = 37 case m = 46 case n = 45 case o = 31 case p = 35 case q = 12 case r = 15 case s = 1 case t = 17 case u = 32 case v = 9 case w = 13 case x = 7 case y = 16 case z = 6 case one = 18 case two = 19 case three = 20 case four = 21 case five = 23 case six = 22 case seven = 26 case eight = 28 case nine = 25 case zero = 29 case tilde = 50 case leftBracket = 33 case rightBracket = 30 case backSlash = 42 case semiColon = 41 case apostrophe = 39 case dash = 27 case equals = 24 case comma = 43 case period = 47 case forwardSlash = 44 case numpad1 = 83 case numpad2 = 84 case numpad3 = 85 case numpad4 = 86 case numpad5 = 87 case numpad6 = 88 case numpad7 = 89 case numpad8 = 91 case numpad9 = 92 case numpad0 = 82 case numpadMultiply = 67 case numpadDivide = 75 case numpadAdd = 69 case numpadSubtract = 78 case numpadEquals = 81 case numpadPeriod = 65 case numpadClear = 71 case `return` = 36 case enter = 76 case function = 63 case control = 59 case option = 58 case command = 55 case shift = 56 case arrowUp = 126 case arrowDown = 125 case arrowLeft = 123 case arrowRight = 124 case home = 115 case end = 119 case pageUp = 116 case pageDown = 121 case escape = 53 case capsLock = 57 case space = 49 case tab = 48 case delete = 51 case forwardDelete = 117 case f1 = 122 case f2 = 120 case f3 = 99 case f4 = 118 case f5 = 96 case f6 = 97 case f7 = 98 case f8 = 100 case f9 = 101 case f10 = 109 case f11 = 103 case f12 = 111 case f13 = 105 case f14 = 107 case f15 = 113 case f16 = 106 case f17 = 64 case f18 = 79 case f19 = 80 case f20 = 90 } // Variables storing actual keyboard data var _keysDown: [Key] = [] var _charactersDown: [String] = [] var _keysJustPressed: [Key] = [] var _keysJustReleased: [Key] = [] var _charactersJustPressed: [String] = [] var _charactersJustReleased: [String] = [] // Public gettable keyboard data (to prevent manually setting keyboard data) /// The current keys that are pressed down. public var keysDown: [Key] { get { return _keysDown } } /// The current characters that are on the keys being pressed down. public var charactersDown: [String] { get { return _charactersDown } } /// The keys that were just pressed public var keysJustPressed: [Key] { get { return _keysJustPressed } } /// The keys that were just released public var keysJustReleased: [Key] { get { return _keysJustReleased } } /// The characters that were just pressed public var charactersJustPressed: [String] { get { return _charactersJustPressed } } /// The characters that were just released public var charactersJustReleased: [String] { get { return _charactersJustReleased } } } /// The protocol that is adopted by nodes that need to run code when a key is pressed or released. public protocol KeyboardRespondable { /// Called when a key (or multiple keys) are pressed. /// /// - Parameters: /// - keys: the keys that were pressed (based off keycode) /// - characters: the characters on the keys that were pressed func keyboardPressed(keys: [Keyboard.Key], characters: String?) /// Called when a key (or multiple keys) are released. /// /// - Parameters: /// - keys: the keys that were released (based off keycode) /// - characters: the characters on the keys that were released func keyboardReleased(keys: [Keyboard.Key], characters: String?) } // Keyboard event types enum KeyboardEvent { case up (keys: [Keyboard.Key], characters: String?) case down (keys: [Keyboard.Key], characters: String?) } extension Node { // Called each frame there is a keyboard event to run keyboard events on all nodes in the hierarchy func superKeyboard(events: [KeyboardEvent]) { // Runs keyboard events on children for child in children { child.superKeyboard(events: events) } // Runs keyboard events if the node conforms to KeyboardRespondable if let keyboardRespondableSelf = self as? KeyboardRespondable { for event in events { switch event { case .down(keys: let keys, characters: let characters): keyboardRespondableSelf.keyboardPressed(keys: keys, characters: characters) case .up(keys: let keys, characters: let characters): keyboardRespondableSelf.keyboardReleased(keys: keys, characters: characters) } } } } }
gpl-3.0
0781f60d2cc69abc777580ec9a6b2b02
27.8
202
0.661176
3.195046
false
false
false
false
STMicroelectronics-CentralLabs/BlueSTSDK_iOS
BlueSTSDK/BlueSTSDK/Features/BlueSTSDKFeatureAudioCalssification.swift
1
4927
/******************************************************************************* * COPYRIGHT(c) 2018 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ import Foundation @objc public class BlueSTSDKFeatureAudioCalssification : BlueSTSDKFeature { private static let FEATURE_NAME = "Audio Scene Classification"; private static let FIELDS:[BlueSTSDKFeatureField] = [ BlueSTSDKFeatureField(name: "SceneType", unit: nil, type: .uInt8, min: NSNumber(value: 0), max: NSNumber(value:4)), BlueSTSDKFeatureField(name: "Algorithm", unit: nil, type: .uInt8, min: NSNumber(value: 0), max: NSNumber(value:0xFF)) ]; public override func getFieldsDesc() -> [BlueSTSDKFeatureField] { return BlueSTSDKFeatureAudioCalssification.FIELDS; } public static func getAudioScene(_ sample:BlueSTSDKFeatureSample)->AudioClass{ guard sample.data.count > 0 else { return AudioClass.Unknown } let rawValue = sample.data[0].uint8Value return AudioClass.init(rawValue: rawValue) ?? AudioClass.Unknown } public static func getAlgorythmType(_ sample:BlueSTSDKFeatureSample) -> UInt8{ guard sample.data.count > 1 else { return 0 } return sample.data[1].uint8Value } public enum AudioClass : UInt8{ public typealias RawValue = UInt8 case Unknown = 0xFF case Indoor = 0x00 case Outdoor = 0x01 case InVehicle = 0x02 case BabyIsCrying = 0x03 } public override init(whitNode node: BlueSTSDKNode) { super.init(whitNode: node, name: BlueSTSDKFeatureAudioCalssification.FEATURE_NAME) } private func extractAudioClass(_ timestamp: UInt64, _ data: Data,_ offset: Int) -> BlueSTSDKExtractResult{ let sample = BlueSTSDKFeatureSample(timestamp: timestamp, data: [ NSNumber(value: data[offset]) ]) return BlueSTSDKExtractResult(whitSample: sample, nReadData: 1) } private func extractAudioClassAndAlgo(_ timestamp: UInt64, _ data: Data,_ offset: Int) -> BlueSTSDKExtractResult{ let sample = BlueSTSDKFeatureSample(timestamp: timestamp, data: [ NSNumber(value: data[offset]), NSNumber(value: data[offset+1]) ]) return BlueSTSDKExtractResult(whitSample: sample, nReadData: 2) } public override func extractData(_ timestamp: UInt64, data: Data, dataOffset offset: UInt32) -> BlueSTSDKExtractResult { let intOffset = Int(offset) let availableData = (data.count-intOffset) if( availableData < 1){ NSException(name: NSExceptionName(rawValue: "Invalid Audio Scene Classification data "), reason: "There are no bytes available to read", userInfo: nil).raise() return BlueSTSDKExtractResult(whitSample: nil, nReadData: 0) } if(availableData == 1) { return extractAudioClass(timestamp,data,intOffset) }else{ return extractAudioClassAndAlgo(timestamp,data,intOffset) } } }
bsd-3-clause
1603ef4908e9c7493b88a4200f831232
46.375
117
0.63629
5.017312
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactory/SBAActiveTask.swift
1
22495
// // SBAActiveTaskFactory.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit import AVFoundation public enum SBAActiveTaskType { case custom(String?) case activeTask(Identifier) public enum Identifier : String { case cardio case goNoGo case memory case moodSurvey case tapping case trailmaking case tremor case voice case walking } init(name: String?) { guard (name != nil), let identifier = Identifier(rawValue: name!) else { self = .custom(name) return } self = .activeTask(identifier) } func isNilType() -> Bool { if case .custom(let customType) = self { return (customType == nil) } return false } func activeTaskIdentifier() -> Identifier? { if case .activeTask(let identifier) = self { return identifier } return nil } } extension SBAActiveTaskType: Equatable { } public func ==(lhs: SBAActiveTaskType, rhs: SBAActiveTaskType) -> Bool { switch (lhs, rhs) { case (.activeTask(let lhsValue), .activeTask(let rhsValue)): return lhsValue == rhsValue; case (.custom(let lhsValue), .custom(let rhsValue)): return lhsValue == rhsValue; default: return false } } extension ORKPredefinedTaskHandOption { init(name: String?) { let name = name ?? "both" switch name { case "right" : self = .right case "left" : self = .left default : self = .both } } } extension ORKTremorActiveTaskOption { init(excludes: [String]?) { guard let excludes = excludes else { self.init(rawValue: 0) return } let rawValue: UInt = excludes.map({ (exclude) -> ORKTremorActiveTaskOption in switch exclude { case "inLap" : return .excludeHandInLap case "shoulderHeight" : return .excludeHandAtShoulderHeight case "elbowBent" : return .excludeHandAtShoulderHeightElbowBent case "touchNose" : return .excludeHandToNose case "queenWave" : return .excludeQueenWave default : return [] } }).reduce(0) { (raw, option) -> UInt in return option.rawValue | raw } self.init(rawValue: rawValue) } } extension ORKMoodSurveyFrequency { init(name: String?) { let name = name ?? "daily" switch name { case "weekly" : self = .weekly default : self = .daily } } } public protocol SBAActiveTask: SBABridgeTask, SBAStepTransformer { var taskType: SBAActiveTaskType { get } var intendedUseDescription: String? { get } var taskOptions: [String : Any]? { get } var predefinedExclusions: ORKPredefinedTaskOption? { get } var localizedSteps: [SBASurveyItem]? { get } var optional: Bool { get } var ignorePermissions: Bool { get } } extension SBAActiveTask { func createDefaultORKActiveTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask? { guard let activeTaskIdentifier = self.taskType.activeTaskIdentifier() else { return nil } let predefinedExclusions = self.predefinedExclusions ?? options var task:ORKOrderedTask = { switch activeTaskIdentifier { case .cardio: return cardioTask(predefinedExclusions) case .goNoGo: return goNoGoTask(predefinedExclusions) case .memory: return memoryTask(predefinedExclusions) case .moodSurvey: return moodSurveyTask(predefinedExclusions) case .tapping: return tappingTask(predefinedExclusions) case .trailmaking: return trailmakingTask(predefinedExclusions) case .tremor: return tremorTask(predefinedExclusions) case .voice: return voiceTask(predefinedExclusions) case .walking: return walkingTask(predefinedExclusions) } }() // Modify the instruction step if this is an optional task if self.optional { task = taskWithSkipAction(task) } // Add the permissions step if !self.ignorePermissions, let permissionTypes = SBAPermissionsManager.shared.permissionsTypeFactory.permissionTypes(for: task) { task = taskWithPermissions(task, permissionTypes) } // map the localized steps mapLocalizedSteps(task) return task } // MARK: modification functions fileprivate func taskWithPermissions(_ task: ORKOrderedTask, _ permissions: [SBAPermissionObjectType]) -> ORKOrderedTask { // Add the permission step let permissionsStep = SBAPermissionsStep(identifier: "SBAPermissionsStep") permissionsStep.text = Localization.localizedString("PERMISSIONS_TASK_TEXT") permissionsStep.permissionTypes = permissions permissionsStep.isOptional = false var steps = task.steps let idx = steps.first is ORKInstructionStep ? 1 : 0 steps.insert(permissionsStep, at: idx) if let navTask = task as? ORKNavigableOrderedTask { // If this is a navigation task then create a navgiation rule // and use that to setup the skip rules let copy = navTask.copy(with: steps) let skipRule = SBAPermissionsSkipRule(permissionTypes: permissions) copy.setSkip(skipRule, forStepIdentifier: permissionsStep.identifier) return copy } else if type(of: task) === ORKOrderedTask.self { // If this is an ORKOrderedTask then turn it into an SBANavigableOrderedTask return SBANavigableOrderedTask(identifier: task.identifier, steps: steps) } else if let navTask = task as? SBANavigableOrderedTask { // If this is a subclass of an SBANavigableOrderedTask then copy it return navTask.copy(with: steps) } else { // Otherwise, adding the permissions isn't supported. assertionFailure("Handling of permissions task is not implemented for this task: \(task)") return task } } fileprivate func taskWithSkipAction(_ task: ORKOrderedTask) -> ORKOrderedTask { guard type(of: task) === ORKOrderedTask.self else { assertionFailure("Handling of an optional task is not implemented for any class other than ORKOrderedTask") return task } guard let introStep = task.steps.first as? ORKInstructionStep else { assertionFailure("Handling of an optional task is not implemented for tasks that do not start with ORKIntructionStep") return task } guard let conclusionStep = task.steps.last as? ORKInstructionStep else { assertionFailure("Handling of an optional task is not implemented for tasks that do not end with ORKIntructionStep") return task } // Replace the intro step with a direct navigation step that has a skip button // to skip to the conclusion let replaceStep = SBAInstructionStep(identifier: introStep.identifier) replaceStep.title = introStep.title replaceStep.text = introStep.text let skipExplanation = Localization.localizedString("SBA_SKIP_ACTIVITY_INSTRUCTION") let detail = introStep.detailText ?? "" replaceStep.detailText = "\(detail)\n\(skipExplanation)\n" replaceStep.learnMoreAction = SBASkipAction(identifier: conclusionStep.identifier) replaceStep.learnMoreAction!.learnMoreButtonText = Localization.localizedString("SBA_SKIP_ACTIVITY") var steps: [ORKStep] = task.steps steps.removeFirst() steps.insert(replaceStep, at: 0) // Return a navigable ordered task return SBANavigableOrderedTask(identifier: task.identifier, steps: steps) } fileprivate func mapLocalizedSteps(_ task: ORKOrderedTask) { // Map the title, text and detail from the localizedSteps to their matching step from the // base factory method defined if let items = self.localizedSteps { for item in items { if let step = task.steps.find({ return $0.identifier == item.identifier }) { step.title = item.stepTitle ?? step.title step.text = item.stepText ?? step.text if let instructionItem = item as? SBAInstructionStepSurveyItem, let detail = instructionItem.stepDetail, let instructionStep = step as? ORKInstructionStep { instructionStep.detailText = detail } if let activeStep = step as? ORKActiveStep, let activeItem = item as? SBAActiveStepSurveyItem { if let spokenInstruction = activeItem.stepSpokenInstruction { activeStep.spokenInstruction = spokenInstruction } if let finishedSpokenInstruction = activeItem.stepFinishedSpokenInstruction { activeStep.finishedSpokenInstruction = finishedSpokenInstruction } } } } } } // MARK: active task factory func cardioTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { let walkDuration: TimeInterval = taskOptions?["walkDuration"] as? TimeInterval ?? 6 * 60.0 let restDuration: TimeInterval = taskOptions?["restDuration"] as? TimeInterval ?? 0.0 if #available(iOS 10.0, *) { return ORKOrderedTask.cardioChallenge(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, walkDuration: walkDuration, restDuration: restDuration, relativeDistanceOnly: !SBAInfoManager.shared.currentParticipant.isTestUser, options: options) } else { return ORKOrderedTask.fitnessCheck(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, walkDuration: walkDuration, restDuration: restDuration, options: options) } } func goNoGoTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { let maximumStimulusInterval: TimeInterval = taskOptions?["maximumStimulusInterval"] as? TimeInterval ?? 10.0 let minimumStimulusInterval: TimeInterval = taskOptions?["minimumStimulusInterval"] as? TimeInterval ?? 4.0 let thresholdAcceleration: Double = taskOptions?["thresholdAcceleration"] as? Double ?? 0.5 let numberOfAttempts: Int32 = taskOptions?["numberOfAttempts"] as? Int32 ?? 9 let timeout: TimeInterval = taskOptions?["timeout"] as? TimeInterval ?? 3.0 func findSoundID(key: String, defaultSound:SystemSoundID) -> SystemSoundID { guard let sound = taskOptions?["key"] else { return defaultSound } if let resource = sound as? String { let soundID = SBAResourceFinder.shared.systemSoundID(forResource: resource) return soundID > 0 ? soundID : defaultSound } else if let soundID = sound as? SystemSoundID { return soundID } return defaultSound } let successSound = findSoundID(key: "successSound", defaultSound: 1013) let timeoutSound = findSoundID(key: "timeoutSound", defaultSound: 0) let failureSound = findSoundID(key: "failureSound", defaultSound: SystemSoundID(kSystemSoundID_Vibrate)) return ORKOrderedTask.gonogoTask(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, maximumStimulusInterval: maximumStimulusInterval, minimumStimulusInterval: minimumStimulusInterval, thresholdAcceleration: thresholdAcceleration, numberOfAttempts: numberOfAttempts, timeout: timeout, successSound: successSound, timeoutSound: timeoutSound, failureSound: failureSound, options: options) } func memoryTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { let initialSpan: Int = (taskOptions?["initialSpan"] as? NSNumber)?.intValue ?? 3 let minimumSpan: Int = (taskOptions?["minimumSpan"] as? NSNumber)?.intValue ?? 2 let maximumSpan: Int = (taskOptions?["maximumSpan"] as? NSNumber)?.intValue ?? 15 let playSpeed: TimeInterval = taskOptions?["playSpeed"] as? TimeInterval ?? 1.0 let maxTests: Int = (taskOptions?["maxTests"] as? NSNumber)?.intValue ?? 5 let maxConsecutiveFailures: Int = (taskOptions?["maxConsecutiveFailures"] as? NSNumber)?.intValue ?? 3 var customTargetImage: UIImage? = nil if let imageName = taskOptions?["customTargetImageName"] as? String { customTargetImage = SBAResourceFinder.shared.image(forResource: imageName) } let customTargetPluralName: String? = taskOptions?["customTargetPluralName"] as? String let requireReversal: Bool = taskOptions?["requireReversal"] as? Bool ?? false return ORKOrderedTask.spatialSpanMemoryTask(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, initialSpan: initialSpan, minimumSpan: minimumSpan, maximumSpan: maximumSpan, playSpeed: playSpeed, maximumTests: maxTests, maximumConsecutiveFailures: maxConsecutiveFailures, customTargetImage: customTargetImage, customTargetPluralName: customTargetPluralName, requireReversal: requireReversal, options: options) } func moodSurveyTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { let frequency = ORKMoodSurveyFrequency(name: taskOptions?["frequency"] as? String) let customQuestionText = taskOptions?["customQuestionText"] as? String return ORKOrderedTask.moodSurvey(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, frequency: frequency, customQuestionText: customQuestionText, options: options) } func tappingTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0 let handOptions = ORKPredefinedTaskHandOption(name: taskOptions?["handOptions"] as? String) return ORKOrderedTask.twoFingerTappingIntervalTask(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, duration: duration, handOptions: handOptions, options: options) } func trailmakingTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { let trailType: ORKTrailMakingTypeIdentifier = { guard let trailType = taskOptions?["trailType"] as? String else { return ORKTrailMakingTypeIdentifier.B } return ORKTrailMakingTypeIdentifier(rawValue: trailType) }() let trailmakingInstruction = taskOptions?["trailmakingInstruction"] as? String return ORKOrderedTask.trailmakingTask(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, trailmakingInstruction: trailmakingInstruction, trailType: trailType, options: options) } func tremorTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0 let handOptions = ORKPredefinedTaskHandOption(name: taskOptions?["handOptions"] as? String) let excludeOptions = ORKTremorActiveTaskOption(excludes: taskOptions?["excludePostions"] as? [String]) return ORKOrderedTask.tremorTest(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, activeStepDuration: duration, activeTaskOptions: excludeOptions, handOptions: handOptions, options: options) } func voiceTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { let speechInstruction: String? = taskOptions?["speechInstruction"] as? String let shortSpeechInstruction: String? = taskOptions?["shortSpeechInstruction"] as? String let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0 let recordingSettings: [String: AnyObject]? = taskOptions?["recordingSettings"] as? [String: AnyObject] return ORKOrderedTask.audioTask(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, speechInstruction: speechInstruction, shortSpeechInstruction: shortSpeechInstruction, duration: duration, recordingSettings: recordingSettings, checkAudioLevel: true, options: options) } func walkingTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask { // The walking activity is assumed to be walking back and forth rather than trying to walk down a long hallway. let walkDuration: TimeInterval = taskOptions?["walkDuration"] as? TimeInterval ?? 30.0 let restDuration: TimeInterval = taskOptions?["restDuration"] as? TimeInterval ?? 30.0 return ORKOrderedTask.walkBackAndForthTask(withIdentifier: self.schemaIdentifier, intendedUseDescription: self.intendedUseDescription, walkDuration: walkDuration, restDuration: restDuration, options: options) } }
bsd-3-clause
eaa1feaf308ccdf6404cfebafcf1279d
46.256303
130
0.578376
5.707688
false
false
false
false
sekouperry/pulltomakesoup-fix
PullToMakeSoup/PullToMakeSoup/CAKeyframeAnimation+Extensions.swift
1
2217
// // CAKeyframeAnimation+Extensions.swift // PullToMakeSoup // // Created by Anastasiya Gorban on 4/20/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import CoreGraphics enum AnimationType: String { case Rotation = "transform.rotation.z" case Opacity = "opacity" case TranslationX = "transform.translation.x" case TranslationY = "transform.translation.y" } enum TimingFunction { case Linear, EaseIn, EaseOut, EaseInEaseOut } func mediaTimingFunction(function: TimingFunction) -> CAMediaTimingFunction { switch function { case .Linear: return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) case .EaseIn: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) case .EaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) case .EaseInEaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } } extension CAKeyframeAnimation { class func animationWith( type: AnimationType, values:[Double], keyTimes:[Double], duration: Double, beginTime: Double) -> CAKeyframeAnimation { let animation = CAKeyframeAnimation(keyPath: type.rawValue) animation.values = values animation.keyTimes = keyTimes animation.duration = duration animation.beginTime = beginTime animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) return animation } class func animationPosition(path: CGPath, duration: Double, timingFunction: TimingFunction, beginTime: Double) -> CAKeyframeAnimation { let animation = CAKeyframeAnimation(keyPath: "position") animation.path = path animation.duration = duration animation.beginTime = beginTime animation.timingFunction = mediaTimingFunction(timingFunction) return animation } } extension UIView { func addAnimation(animation: CAKeyframeAnimation) { layer.addAnimation(animation, forKey: description + animation.keyPath!) layer.speed = 0 } func removeAllAnimations() { layer.removeAllAnimations() } }
mit
9970149c1f3ebcfa29615cc3f9bf97bf
31.130435
140
0.704556
5.447174
false
false
false
false
shirai/SwiftLearning
playground/継承.playground/Contents.swift
1
9450
//: Playground - noun: a place where people can play import UIKit /* * * サブクラス クラスを定義する時にクラス名の後に: * */ /* モンスタークラス(親) */ class Monster { var name: String var level: Int // イニシャライザ init(name: String, level: Int = 1) { self.name = name self.level = level } // ステータス表示 func printStatus() { print("名前:\(name) レベル:\(level)") } // 攻撃 func attackMonster(enemy: Monster) { print("\(name)は\(enemy.name)を攻撃した。"); } } /* スライムクラス(子) */ class Slime: Monster { // イニシャライザ init(level: Int = 1) { super.init(name: "スライム", level: level) //superで、スーパークラスのメソッドやプロパティにアクセス } } /* ドラゴンクラス(子) */ class Dragon: Monster { // イニシャライザ init(level: Int = 1) { super.init(name: "ドラゴン", level: level) //superで、スーパークラスのメソッドやプロパティにアクセス } // 攻撃 override func attackMonster(enemy: Monster) { print("\(name)は\(enemy.name)に火を吐いた。"); } } let monster = Monster(name: "踊るガイコツ", level:3) //インスタンスの生成 let slime = Slime() //インスタンスの生成 let dragon = Dragon(level: 10) //インスタンスの生成 monster.printStatus() //メソッドの呼び出し slime.printStatus() //メソッドの呼び出し dragon.printStatus() //メソッドの呼び出し //オーバーライド:スーパークラスのメソッド名、戻り値の型、引数の型と個数を同じにしてサブクラスで再定義すること /* メタルスライムクラス */ class GoldSilme: Slime { // イニシャライザ override init(level: Int = 1) { //overrideを指定する super.init(level: level) self.name = "メタルスライム" } } let goldSilme = GoldSilme() print(goldSilme.name) /* メタルスライムクラス */ class MetalSilme: Slime { var isStrayed: Bool //サブクラスの自身のプロパティの初期化 // イニシャライザ init(isStrayed: Bool, level: Int = 1) { self.isStrayed = isStrayed super.init(level: level) //スーパークラスのイニシャライザ if self.isStrayed { //追加の設定 self.name = "メタルスライム" } else { self.name = "はぐれメタル" } } } /* * *ポリモーフィズム * */ var skeleton : Monster skeleton = Monster(name: "踊るガイコツ") skeleton.attackMonster(enemy: slime) // 踊るガイコツはスライムを攻撃した。 <== Monsterクラスのメソッドが呼ばれた slime.attackMonster(enemy: skeleton) // スライムは踊るガイコツを攻撃した。 <== Slimeクラスのメソッドが呼ばれた dragon.attackMonster(enemy: slime) // ドラゴンはスライムに火を吐いた。 <== Dragonクラスのメソッドが呼ばれた /* * *オーバーライド * */ /* ポケモンクラス */ class ポケモン { // 名前 var name: String // レベル var level: Int { didSet { maxHitPoint = level * 5 } } // ヒットポイント var hitPoint: Int = 0 { didSet { if hitPoint <= 0 { print("\(name)を倒した!") } } } // 最大ヒットポイント var maxHitPoint: Int { get { return level * 5 } set { level = newValue / 5 } } // 死んだ? var isDead: Bool { return hitPoint <= 0 } // イニシャライザ init(name: String, level: Int = 1) { self.name = name self.level = level self.hitPoint = self.maxHitPoint } // ダメージ計算 func calculateDamage(enemy: ポケモン) -> Int { // 計算は適当 return max(0, (level * 5 - enemy.level) + (Int(arc4random_uniform(10)) % level)) //arc4random_uniform乱数の生成 } // 攻撃 func attackMonster(enemy: ポケモン) { let damage = self.calculateDamage(enemy: enemy) print("\(name)のこうげき!\(enemy.name)は\(damage)のダメージを受けた。") enemy.hitPoint -= damage } } /* ピカチュウクラス */ class Pikatyu: ポケモン { override var level: Int { //オーバーライド didSet { maxHitPoint = level * 100 } } override var maxHitPoint: Int { //オーバーライド get { return level * 100 } set { level = newValue / 100 } } // イニシャライザ init(level: Int = 1) { super.init(name: "ピカチュウ", level: level) } // ダメージ計算 override func calculateDamage(enemy: ポケモン) -> Int { // 計算は適当 return max(0, (level * 100 - enemy.level) + (Int(arc4random_uniform(10)) % level)) } } var ポッポ, ピカチュウ: ポケモン ポッポ = ポケモン(name: "ポッポ") ピカチュウ = Pikatyu() ポッポ.attackMonster(enemy: ピカチュウ) ピカチュウ.attackMonster(enemy: ポッポ) //マジックナンバーをリファクタリングしてクラス変数にする。 /* ポケモンクラス2 */ class ポケモン2 { // レベル係数 class var levelFactor: Int { return 5 } // 名前 var name: String // レベル var level: Int { didSet { maxHitPoint = level * type(of: self).levelFactor } } // ヒットポイント var hitPoint: Int = 0 { didSet { if hitPoint <= 0 { print("\(name)を倒した!") } } } // 最大ヒットポイント var maxHitPoint: Int { get { return level * type(of: self).levelFactor } set { level = newValue / type(of: self).levelFactor } } // 死んだ? var isDead: Bool { return hitPoint <= 0 } // イニシャライザ init(name: String, level: Int = 1) { self.name = name self.level = level self.hitPoint = self.maxHitPoint } // ダメージ計算 func calculateDamage(enemy: ポケモン2) -> Int { // 計算は適当 return max(0, (level * type(of: self).levelFactor - enemy.level) + (Int(arc4random_uniform(10)) % level)) //arc4random_uniform乱数の生成 } // 攻撃 func attackMonster(enemy: ポケモン2) { let damage = self.calculateDamage(enemy: enemy) print("\(name)のこうげき!\(enemy.name)は\(damage)のダメージを受けた。") enemy.hitPoint -= damage } } /* イーブイクラス */ class Eevee: ポケモン2 { // レベル係数 override class var levelFactor: Int { return 100 } override var level: Int { //オーバーライド didSet { level * type(of: self).levelFactor } } override var maxHitPoint: Int { //オーバーライド get { return level * type(of: self).levelFactor } set { level = newValue / type(of: self).levelFactor //インスタンスのクラスからクラス変数を取得 } } // イニシャライザ init(level: Int = 1) { super.init(name: "イーブイ", level: level) } // ダメージ計算 override func calculateDamage(enemy: ポケモン2) -> Int { // 計算は適当 return max(0, (level * type(of: self).levelFactor - enemy.level) + (Int(arc4random_uniform(10)) % level)) //インスタンスのクラスからクラス変数を取得 } } var プリン, イーブイ: ポケモン2 プリン = ポケモン2(name: "プリン") イーブイ = Eevee() プリン.attackMonster(enemy: イーブイ) イーブイ.attackMonster(enemy: プリン) /* * *オーバーライドの禁止 オーバーライドを禁止するには、宣言の頭にfinalを指定 * */ /* 幻のポケモンクラス */ class ReaPokemon { // レベル係数 class var levelFactor: Int { return 100 } // レベル final var level: Int = 0 { didSet { maxHitPoint = level * type(of: self).levelFactor } } // 最大ヒットポイント final var maxHitPoint: Int { get { return level * type(of: self).levelFactor } set { level = newValue / type(of: self).levelFactor } } // ダメージ計算 final func calculateDamage(enemy: Monster) -> Int { // 計算は適当 return max(0, (level * type(of: self).levelFactor - enemy.level) + (Int(arc4random_uniform(10)) % level)) } } /* ミュウクラス */ class Miu: ReaPokemon { // // エラー // override var level: Int { // } // // エラー // override var maxHitPoint: Int { // } // // エラー // override func calculateDamage(enemy: Monster) -> Int { // } //} //クラス自体にfinalをつけて、継承を禁止 /* モンスタークラス */ final class Monster3 { } // エラー //class Slime: Monster3 { //} }
mit
2da178dc6673354833958d18d3711187
21.105105
136
0.551766
2.767958
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Search/Query/Auxiliary/Point.swift
1
2929
// // Point.swift // // // Created by Vladislav Fitc on 20/03/2020. // import Foundation /** A set of geo-coordinates latitude and longitude. */ public struct Point: Equatable { public let latitude: Double public let longitude: Double public init(latitude: Double, longitude: Double) { self.latitude = latitude self.longitude = longitude } var stringForm: String { return "\(latitude),\(longitude)" } } extension Point: RawRepresentable { public var rawValue: [Double] { return [latitude, longitude] } public init?(rawValue: [Double]) { guard rawValue.count > 1 else { return nil } self.init(latitude: rawValue[0], longitude: rawValue[1]) } } extension Point: Codable { struct StringForm: Decodable { let point: Point public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let stringValue = try container.decode(String.self) let rawValue = stringValue.split(separator: ",").compactMap(Double.init) guard rawValue.count == 2 else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Decoded string must contain two floating point values separated by comma character") } point = .init(latitude: rawValue[0], longitude: rawValue[1]) } } struct DictionaryForm: Decodable { let point: Point enum CodingKeys: String, CodingKey { case latitude = "lat" case longitude = "lng" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let latitude: Double = try container.decode(forKey: .latitude) let longitude: Double = try container.decode(forKey: .longitude) self.point = .init(latitude: latitude, longitude: longitude) } } public init(from decoder: Decoder) throws { if let arrayForm = try? [DictionaryForm](from: decoder) { guard let firstPoint = arrayForm.first else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "Empty points list")) } self = firstPoint.point } else if let dictionaryForm = try? DictionaryForm(from: decoder) { self = dictionaryForm.point } else if let stringForm = try? StringForm(from: decoder) { self = stringForm.point } else { let encoded = (try? String(data: JSONEncoder().encode(JSON(from: decoder)), encoding: .utf8)) ?? "" let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "The format \(encoded) doesn't match \"22.2268,84.8463\" string or {\"lat\": 22.2268, \"lng\": 84.8463 } dictionary") throw DecodingError.dataCorrupted(context) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode("\(latitude),\(longitude)") } }
mit
1dd141f39a38c22b13ea6422e277b4e5
27.715686
177
0.66917
4.32644
false
false
false
false
kobe41999/transea-mumble
Source/Classes/NCCU/PopUp/PopUpVC.swift
1
4117
// // PopUpVC.swift // Mumble // // Created by Roger's Mac on 2017/4/24. // // import UIKit import STPopup import FBSDKCoreKit import ParseFacebookUtilsV4 class PopUpVC: UIViewController { @IBOutlet var labelLanguage: UILabel! @IBOutlet var labelUserName: UILabel! @IBOutlet var fieldPricing: UITextField! @IBOutlet var imgIcon: UIImageView! var currentRequestUser: String = "" var appDelegate: AppDelegate? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. appDelegate = (UIApplication.shared.delegate as? AppDelegate) let array: [Any]? = appDelegate?.currentRequestUser.replacingOccurrences(of: "info:", with: "User:").components(separatedBy: "@") labelUserName.text = array?[0] as! String currentRequestUser = (appDelegate?.currentRequestUser)! } func bid() { let serverURL: String = "http://162.243.49.105:8888/bid" let currentUser = PFUser.current() let userID: String = currentUser!.username! print("userid=\(userID)") if !(currentUser != nil) { return } var resultsDictionary: [AnyHashable: Any] // 返回的 JSON 数据 let starter: String = currentRequestUser let bid = Int(CDouble(fieldPricing.text!)!) let userData: [AnyHashable: Any] = [ "userid" : userID, "starter" : starter, "bid" : bid ] let mainJson: [AnyHashable: Any] = [ "data" : userData, "type" : "bid" ] var error: Error? let jsonData: Data? = try? JSONSerialization.data(withJSONObject: mainJson, options: JSONSerialization.WritingOptions.prettyPrinted) let post = String(data:jsonData!, encoding: String.Encoding.utf8) print("\(post)") //NSString *queryString = [NSString stringWithFormat:@"http://example.com/username.php?name=%@", [self.txtName text]]; var theRequest = NSMutableURLRequest(url: URL(string: serverURL)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 60.0) theRequest.httpMethod = "POST" theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") // should check for and handle errors here but we aren't theRequest.httpBody = jsonData NSURLConnection.sendAsynchronousRequest(theRequest as URLRequest, queue: OperationQueue.main, completionHandler: {(_ response: URLResponse, _ data: Data, _ error: Error?) -> Void in if error != nil { //do something with error print("\(error?.localizedDescription)") } else { var responseText = String(data: data, encoding: String.Encoding.ascii) print("Response: \(responseText)") let newLineStr: String = "\n" responseText = responseText?.replacingOccurrences(of: "<br />", with: newLineStr) } } as! (URLResponse?, Data?, Error?) -> Void) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func btnAccept(_ sender: Any) { bid() popupController?.dismiss() } @IBAction func btnDecline(_ sender: Any) { popupController?.dismiss() } override func awakeFromNib() { super.awakeFromNib() contentSizeInPopup = CGSize(width: CGFloat(260), height: CGFloat(190)) landscapeContentSizeInPopup = CGSize(width: CGFloat(260), height: CGFloat(190)) } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ deinit { } }
bsd-3-clause
64011ed05ad52cb3400c4a3672d5b21e
37.383178
189
0.623813
4.837456
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/User/ZMSearchUser.swift
1
22199
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation public extension Notification.Name { static let searchUserDidRequestPreviewAsset = Notification.Name("SearchUserDidRequestPreviewAsset") static let searchUserDidRequestCompleteAsset = Notification.Name("SearchUserDidRequestCompleteAsset") } private enum ResponseKey: String { case pictureTag = "tag" case pictures = "picture" case id case pictureInfo = "info" case assets case assetSize = "size" case assetKey = "key" case assetType = "type" } private enum ImageTag: String { case smallProfile case medium } private enum AssetSize: String { case preview case complete } private enum AssetKind: String { case image } public struct SearchUserAssetKeys { public let preview: String? public let complete: String? init?(payload: [String: Any]) { if let assetsPayload = payload[ResponseKey.assets.rawValue] as? [[String: Any]], assetsPayload.count > 0 { var previewKey: String?, completeKey: String? for asset in assetsPayload { guard let size = (asset[ResponseKey.assetSize.rawValue] as? String).flatMap(AssetSize.init), let key = asset[ResponseKey.assetKey.rawValue] as? String, let type = (asset[ResponseKey.assetType.rawValue] as? String).flatMap(AssetKind.init), type == .image else { continue } switch size { case .preview: previewKey = key case .complete: completeKey = key } } if nil != previewKey || nil != completeKey { preview = previewKey complete = completeKey return } } return nil } } extension ZMSearchUser: SearchServiceUser { public var serviceIdentifier: String? { return remoteIdentifier?.transportString() } } // MARK: NSManagedObjectContext let NSManagedObjectContextSearchUserCacheKey = "zm_searchUserCache" extension NSManagedObjectContext { @objc public var zm_searchUserCache: NSCache<NSUUID, ZMSearchUser>? { get { guard zm_isUserInterfaceContext else { return nil } return self.userInfo[NSManagedObjectContextSearchUserCacheKey] as? NSCache } set { guard zm_isUserInterfaceContext else { return } self.userInfo[NSManagedObjectContextSearchUserCacheKey] = newValue } } } @objc public class ZMSearchUser: NSObject, UserType { public var providerIdentifier: String? public var summary: String? public var assetKeys: SearchUserAssetKeys? public var remoteIdentifier: UUID? public var teamIdentifier: UUID? @objc public var contact: ZMAddressBookContact? @objc public var user: ZMUser? public private(set) var hasDownloadedFullUserProfile: Bool = false fileprivate weak var contextProvider: ContextProvider? fileprivate var internalDomain: String? fileprivate var internalName: String fileprivate var internalInitials: String? fileprivate var internalHandle: String? fileprivate var internalIsConnected: Bool = false fileprivate var internalIsTeamMember: Bool = false fileprivate var internalTeamCreatedBy: UUID? fileprivate var internalTeamPermissions: Permissions? fileprivate var internalAccentColorValue: ZMAccentColor fileprivate var internalPendingApprovalByOtherUser: Bool = false fileprivate var internalConnectionRequestMessage: String? fileprivate var internalPreviewImageData: Data? fileprivate var internalCompleteImageData: Data? fileprivate var internalIsAccountDeleted: Bool? @objc public var hasTeam: Bool { return user?.hasTeam ?? false } /// Whether all user's devices are verified by the selfUser public var isTrusted: Bool { return user?.isTrusted ?? false } public var teamCreatedBy: UUID? { return user?.membership?.createdBy?.remoteIdentifier ?? internalTeamCreatedBy } public var emailAddress: String? { return user?.emailAddress } public var phoneNumber: String? { return user?.phoneNumber } public var domain: String? { return user?.domain ?? internalDomain } public var name: String? { return user?.name ?? internalName } public var handle: String? { return user?.handle ?? internalHandle } public var initials: String? { return user?.initials ?? internalInitials } public var availability: AvailabilityKind { get { return user?.availability ?? .none } set { user?.availability = newValue } } public var isFederated: Bool { guard let contextProvider = contextProvider else { return false } return ZMUser.selfUser(inUserSession: contextProvider).isFederating(with: self) } public var isSelfUser: Bool { guard let user = user else { return false } return user.isSelfUser } public var teamName: String? { return user?.teamName } public var isTeamMember: Bool { if let user = user { return user.isTeamMember } else { return internalIsTeamMember } } public var hasDigitalSignatureEnabled: Bool { return user?.hasDigitalSignatureEnabled ?? false } public var teamRole: TeamRole { guard let user = user else { return (internalTeamPermissions?.rawValue).flatMap(TeamRole.init(rawPermissions:)) ?? .none } return user.teamRole } public var isServiceUser: Bool { return providerIdentifier != nil } public var usesCompanyLogin: Bool { return user?.usesCompanyLogin == true } public var readReceiptsEnabled: Bool { return user?.readReceiptsEnabled ?? false } public var activeConversations: Set<ZMConversation> { return user?.activeConversations ?? Set() } public var allClients: [UserClientType] { return user?.allClients ?? [] } public var isVerified: Bool { return user?.isVerified ?? false } public var managedByWire: Bool { return user?.managedByWire != false } public var isPendingApprovalByOtherUser: Bool { if let user = user { return user.isPendingApprovalByOtherUser } else { return internalPendingApprovalByOtherUser } } public var isConnected: Bool { get { if let user = user { return user.isConnected } else { return internalIsConnected } } set { internalIsConnected = newValue } } public var oneToOneConversation: ZMConversation? { if isTeamMember, let uiContext = contextProvider?.viewContext { return materialize(in: uiContext)?.oneToOneConversation } else { return user?.oneToOneConversation } } public var isBlocked: Bool { return user?.isBlocked == true } public var blockState: ZMBlockState { user?.blockState ?? .none } public var isExpired: Bool { return user?.isExpired == true } public var isIgnored: Bool { return user?.isIgnored == true } public var isPendingApprovalBySelfUser: Bool { return user?.isPendingApprovalBySelfUser == true } public var isAccountDeleted: Bool { if let isDeleted = internalIsAccountDeleted { return isDeleted } else if let user = user { return user.isAccountDeleted } return false } public var isUnderLegalHold: Bool { return user?.isUnderLegalHold == true } public var accentColorValue: ZMAccentColor { if let user = user { return user.accentColorValue } else { return internalAccentColorValue } } public var isWirelessUser: Bool { return user?.isWirelessUser ?? false } public var expiresAfter: TimeInterval { return user?.expiresAfter ?? 0 } public var connectionRequestMessage: String? { user?.connectionRequestMessage ?? internalConnectionRequestMessage } public var previewImageData: Data? { user?.previewImageData ?? internalPreviewImageData } public var completeImageData: Data? { user?.completeImageData ?? internalCompleteImageData } public var richProfile: [UserRichProfileField] { return user?.richProfile ?? [] } public func canAccessCompanyInformation(of otherUser: UserType) -> Bool { return user?.canAccessCompanyInformation(of: otherUser) ?? false } public func canCreateConversation(type: ZMConversationType) -> Bool { return user?.canCreateConversation(type: type) ?? false } public var canCreateService: Bool { return user?.canCreateService ?? false } public var canManageTeam: Bool { return user?.canManageTeam ?? false } public func canAddService(to conversation: ZMConversation) -> Bool { return user?.canAddService(to: conversation) == true } public func canRemoveService(from conversation: ZMConversation) -> Bool { return user?.canRemoveService(from: conversation) == true } public func canAddUser(to conversation: ConversationLike) -> Bool { return user?.canAddUser(to: conversation) == true } public func canRemoveUser(from conversation: ZMConversation) -> Bool { return user?.canRemoveUser(from: conversation) == true } public func canDeleteConversation(_ conversation: ZMConversation) -> Bool { return user?.canDeleteConversation(conversation) == true } public func canModifyTitle(in conversation: ConversationLike) -> Bool { return user?.canModifyTitle(in: conversation) == true } public func canModifyOtherMember(in conversation: ZMConversation) -> Bool { return user?.canModifyOtherMember(in: conversation) == true } public func canModifyEphemeralSettings(in conversation: ConversationLike) -> Bool { return user?.canModifyEphemeralSettings(in: conversation) == true } public func canModifyReadReceiptSettings(in conversation: ConversationLike) -> Bool { return user?.canModifyReadReceiptSettings(in: conversation) == true } public func canModifyNotificationSettings(in conversation: ConversationLike) -> Bool { return user?.canModifyNotificationSettings(in: conversation) == true } public func canModifyAccessControlSettings(in conversation: ConversationLike) -> Bool { return user?.canModifyAccessControlSettings(in: conversation) == true } public func canLeave(_ conversation: ZMConversation) -> Bool { return user?.canLeave(conversation) == true } public func isGroupAdmin(in conversation: ConversationLike) -> Bool { return user?.isGroupAdmin(in: conversation) == true } public override func isEqual(_ object: Any?) -> Bool { guard let otherSearchUser = object as? ZMSearchUser else { return false } if let lhsRemoteIdentifier = remoteIdentifier, let rhsRemoteIdentifier = otherSearchUser.remoteIdentifier { return lhsRemoteIdentifier == rhsRemoteIdentifier } else if let lhsContact = contact, let rhsContact = otherSearchUser.contact, otherSearchUser.user == nil { return lhsContact == rhsContact } return false } public override var hash: Int { return remoteIdentifier?.hashValue ?? super.hash } public static func searchUsers(from payloadArray: [[String: Any]], contextProvider: ContextProvider) -> [ZMSearchUser] { return payloadArray.compactMap({ searchUser(from: $0, contextProvider: contextProvider) }) } public static func searchUser(from payload: [String: Any], contextProvider: ContextProvider) -> ZMSearchUser? { guard let uuidString = payload["id"] as? String, let remoteIdentifier = UUID(uuidString: uuidString) else { return nil } let domain = payload.optionalDictionary(forKey: "qualified_id")?.string(forKey: "domain") let localUser = ZMUser.fetch(with: remoteIdentifier, domain: domain, in: contextProvider.viewContext) if let searchUser = contextProvider.viewContext.zm_searchUserCache?.object(forKey: remoteIdentifier as NSUUID) { searchUser.user = localUser return searchUser } else { return ZMSearchUser(from: payload, contextProvider: contextProvider, user: localUser) } } @objc public init(contextProvider: ContextProvider, name: String, handle: String?, accentColor: ZMAccentColor, remoteIdentifier: UUID?, domain: String? = nil, teamIdentifier: UUID? = nil, user existingUser: ZMUser? = nil, contact: ZMAddressBookContact? = nil ) { let personName = PersonName.person(withName: name, schemeTagger: nil) self.internalName = name self.internalHandle = handle self.internalInitials = personName.initials self.internalAccentColorValue = accentColor self.user = existingUser self.internalDomain = domain self.remoteIdentifier = existingUser?.remoteIdentifier ?? remoteIdentifier self.teamIdentifier = existingUser?.teamIdentifier ?? teamIdentifier self.contact = contact self.contextProvider = contextProvider let selfUser = ZMUser.selfUser(inUserSession: contextProvider) self.internalIsTeamMember = teamIdentifier != nil && selfUser.teamIdentifier == teamIdentifier self.internalIsConnected = internalIsTeamMember super.init() if let remoteIdentifier = self.remoteIdentifier { contextProvider.viewContext.zm_searchUserCache?.setObject(self, forKey: remoteIdentifier as NSUUID) } } @objc public convenience init(contextProvider: ContextProvider, user: ZMUser) { self.init(contextProvider: contextProvider, name: user.name ?? "", handle: user.handle, accentColor: user.accentColorValue, remoteIdentifier: user.remoteIdentifier, domain: user.domain, teamIdentifier: user.teamIdentifier, user: user) } @objc public convenience init(contextProvider: ContextProvider, contact: ZMAddressBookContact, user: ZMUser? = nil) { self.init(contextProvider: contextProvider, name: contact.name, handle: user?.handle, accentColor: .undefined, remoteIdentifier: user?.remoteIdentifier, domain: user?.domain, teamIdentifier: user?.teamIdentifier, user: user, contact: contact) } convenience init?(from payload: [String: Any], contextProvider: ContextProvider, user: ZMUser? = nil) { guard let uuidString = payload["id"] as? String, let remoteIdentifier = UUID(uuidString: uuidString), let name = payload["name"] as? String else { return nil } let teamIdentifier = (payload["team"] as? String).flatMap({ UUID(uuidString: $0) }) let handle = payload["handle"] as? String let qualifiedID = payload["qualified_id"] as? [String: Any] let domain = qualifiedID?["domain"] as? String let accentColor = ZMUser.accentColor(fromPayloadValue: payload["accent_id"] as? NSNumber) self.init(contextProvider: contextProvider, name: name, handle: handle, accentColor: accentColor, remoteIdentifier: remoteIdentifier, domain: domain, teamIdentifier: teamIdentifier, user: user ) self.providerIdentifier = payload["provider"] as? String self.summary = payload["summary"] as? String self.assetKeys = SearchUserAssetKeys(payload: payload) self.internalIsAccountDeleted = payload["deleted"] as? Bool } public var smallProfileImageCacheKey: String? { if let user = user { return user.smallProfileImageCacheKey } else if let remoteIdentifier = remoteIdentifier { return "\(remoteIdentifier.transportString())_preview" } return nil } public var mediumProfileImageCacheKey: String? { if let user = user { return user.mediumProfileImageCacheKey } else if let remoteIdentifier = remoteIdentifier { return "\(remoteIdentifier.transportString())_complete" } return nil } public func refreshData() { user?.refreshData() } public func refreshRichProfile() { user?.refreshRichProfile() } public func refreshMembership() { user?.refreshMembership() } public func refreshTeamData() { user?.refreshTeamData() } public func connect(completion: @escaping (Error?) -> Void) { let selfUser = ZMUser.selfUser(inUserSession: contextProvider!) selfUser.sendConnectionRequest(to: self) { [weak self] result in switch result { case .success: self?.internalPendingApprovalByOtherUser = true self?.updateLocalUser() self?.notifySearchUserChanged() completion(nil) case .failure(let error): completion(error) } } } private func updateLocalUser() { guard let userID = remoteIdentifier, let viewContext = contextProvider?.viewContext else { return } user = ZMUser.fetch(with: userID, domain: domain, in: viewContext) } private func notifySearchUserChanged() { contextProvider?.viewContext.searchUserObserverCenter.notifyUpdatedSearchUser(self) } public func accept(completion: @escaping (Error?) -> Void) { user?.accept(completion: completion) } public func ignore(completion: @escaping (Error?) -> Void) { user?.ignore(completion: completion) } public func block(completion: @escaping (Error?) -> Void) { user?.block(completion: completion) } public func cancelConnectionRequest(completion: @escaping (Error?) -> Void) { user?.cancelConnectionRequest(completion: completion) } @objc public var canBeConnected: Bool { guard !isServiceUser else { return false } if let user = user { return user.canBeConnected } else { return !internalIsConnected && remoteIdentifier != nil } } public func requestPreviewProfileImage() { guard previewImageData == nil else { return } if let user = self.user { user.requestPreviewProfileImage() } else if let notificationContext = contextProvider?.viewContext.notificationContext { NotificationInContext(name: .searchUserDidRequestPreviewAsset, context: notificationContext, object: self, userInfo: nil).post() } } public func requestCompleteProfileImage() { guard completeImageData == nil else { return } if let user = self.user { user.requestCompleteProfileImage() } else if let notificationContext = contextProvider?.viewContext.notificationContext { NotificationInContext(name: .searchUserDidRequestCompleteAsset, context: notificationContext, object: self, userInfo: nil).post() } } public func isGuest(in conversation: ConversationLike) -> Bool { guard let user = user else { return false } return user.isGuest(in: conversation) } public func imageData(for size: ProfileImageSize, queue: DispatchQueue, completion: @escaping (Data?) -> Void) { if let user = self.user { user.imageData(for: size, queue: queue, completion: completion) } else { let imageData = size == .complete ? completeImageData : previewImageData queue.async { completion(imageData) } } } @objc public func updateImageData(for size: ProfileImageSize, imageData: Data) { switch size { case .preview: internalPreviewImageData = imageData case .complete: internalCompleteImageData = imageData } contextProvider?.viewContext.searchUserObserverCenter.notifyUpdatedSearchUser(self) } public func update(from payload: [String: Any]) { hasDownloadedFullUserProfile = true self.assetKeys = SearchUserAssetKeys(payload: payload) } public func reportImageDataHasBeenDeleted() { self.assetKeys = nil } public func updateWithTeamMembership(permissions: Permissions?, createdBy: UUID?) { self.internalTeamPermissions = permissions self.internalTeamCreatedBy = createdBy } }
gpl-3.0
3eb83c63f265f8acc945c43d092b2f6f
30.849354
141
0.641876
5.149385
false
false
false
false
crazymaik/AssertFlow
Tests/Helpers/AssertFlowTestCase.swift
1
949
// Copyright © 2015 Michael Zoech. All rights reserved. import Foundation import XCTest import AssertFlow /** Base class for tests using the AssertHandler for verification if the SUT functions correctly. */ class AssertFlowTestCase: XCTestCase { var assertHandler: CaptureAssertHandler = CaptureAssertHandler() override func setUp() { super.setUp() continueAfterFailure = false assertHandler = CaptureAssertHandler() AssertHandler.instance = assertHandler } /// Asserts that the AssertHandler.fail() has been called. func assertCalled(_ file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(assertHandler.called, file: file, line: line) } /// Asserts that the AssertHandler.fail() method has not been called. func assertNotCalled(_ file: StaticString = #file, line: UInt = #line) { XCTAssertFalse(assertHandler.called, file: file, line: line) } }
mit
87c47cb7663e8f8b2b01a9df7e378450
29.580645
76
0.702532
4.471698
false
true
false
false
IvanVorobei/RequestPermission
Example/SPPermission/SPPermission/Frameworks/SparrowKit/UI/Controllers/SPProposeController.swift
1
11585
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPProposeController: SPController { private let data: Data internal let areaView = AreaView() private var isPresent: Bool = false private var animationDuration: TimeInterval { return 0.5 } private var gradeFactor: CGFloat { return 0.6 } private var space: CGFloat { return 6 } init(title: String, subtitle: String, buttonTitle: String, imageLink: String? = nil, image: UIImage? = nil, complection: @escaping (_ isConfirmed: Bool)->() = {_ in }) { self.data = Data( title: title, subtitle: subtitle, buttonTitle: buttonTitle, imageLink: imageLink, image: image, complection: complection ) super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .overCurrentContext self.view.backgroundColor = UIColor.black.withAlphaComponent(0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.areaView.isHidden = true self.areaView.titleLabel.text = self.data.title self.areaView.subtitleLabel.text = self.data.subtitle self.areaView.button.setTitle(self.data.buttonTitle, for: UIControl.State.normal) self.areaView.button.addTarget(self, action: #selector(self.open), for: UIControl.Event.touchUpInside) self.areaView.closeButton.addTarget(self, action: #selector(self.close), for: UIControl.Event.touchUpInside) self.view.addSubview(self.areaView) let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(self.handleGesture(sender:))) panGesture.maximumNumberOfTouches = 1 self.areaView.addGestureRecognizer(panGesture) self.areaView.imageView.setParalax(amount: 0.1) if let image = self.data.image { self.areaView.imageView.setImage(image: image, animatable: false) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !self.isPresent { self.present() self.isPresent = true } } private func present() { SPVibration.impact(.warning) self.areaView.frame.origin.y = self.view.frame.size.height self.areaView.isHidden = false SPAnimationSpring.animate(self.animationDuration, animations: { self.view.backgroundColor = UIColor.black.withAlphaComponent(self.gradeFactor) self.areaView.frame.origin.y = self.view.frame.size.height - self.areaView.frame.height - (self.bottomSafeArea / 2) - self.space }, spring: 1, velocity: 1, options: .transitionCurlUp) } override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { let hide = { self.view.backgroundColor = UIColor.black.withAlphaComponent(0) self.areaView.frame.origin.y = self.view.frame.size.height } let dismiss = { super.dismiss(animated: false) { completion?() } } if flag { SPAnimationSpring.animate(self.animationDuration, animations: { hide() }, spring: 1, velocity: 1, options: .transitionCurlDown, withComplection: { dismiss() }) } else { hide() dismiss() } } override func updateLayout(with size: CGSize) { super.updateLayout(with: size) self.areaView.layout(origin: CGPoint.init(x: self.space, y: 0), width: size.width - (self.space * 2)) self.areaView.frame.origin.y = self.view.frame.size.height - self.areaView.frame.height - (self.bottomSafeArea / 2) - self.space } @objc func handleGesture(sender: UIPanGestureRecognizer) { let returnAreaViewToPoint = { SPAnimationSpring.animate(self.animationDuration, animations: { self.areaView.frame.origin.y = self.view.frame.size.height - self.areaView.frame.height - (self.bottomSafeArea / 2) - self.space self.view.backgroundColor = UIColor.black.withAlphaComponent(self.gradeFactor) }, spring: 1, velocity: 1, options: .transitionCurlDown, withComplection: { }) } switch sender.state { case .began: break case .cancelled: returnAreaViewToPoint() case .changed: let translation = sender.translation(in: self.view) self.areaView.center = CGPoint(x: areaView.center.x + 0, y: areaView.center.y + translation.y / 4) sender.setTranslation(CGPoint.zero, in: self.view) let baseY = self.view.frame.size.height - self.areaView.frame.height - (self.bottomSafeArea / 2) - self.space let dem = -(baseY - self.areaView.frame.origin.y) / 6 var newGrade = self.gradeFactor - (dem / 100) newGrade.setIfFewer(when: 0.2) newGrade.setIfMore(when: self.gradeFactor + 0.05) self.view.backgroundColor = UIColor.black.withAlphaComponent(newGrade) case .ended: returnAreaViewToPoint() default: break } } @objc func open() { self.data.complection(true) self.dismiss(animated: true) } @objc func close() { self.data.complection(false) self.dismiss(animated: true) } class AreaView: UIView { let titleLabel = UILabel() let subtitleLabel = UILabel() let imageView = SPDownloadingImageView() let button = SPNativeLargeButton() let closeButton = SPSystemIconButton(type: SPSystemIcon.close) var imageSideSize: CGFloat = 160 private let space: CGFloat = 36 init() { super.init(frame: CGRect.zero) self.backgroundColor = UIColor.white self.layer.masksToBounds = true self.layer.cornerRadius = 34 self.titleLabel.font = UIFont.system(weight: .regular, size: 28) self.titleLabel.textColor = UIColor.init(hex: "939393") self.titleLabel.numberOfLines = 1 self.titleLabel.adjustsFontSizeToFitWidth = true self.titleLabel.minimumScaleFactor = 0.5 self.titleLabel.setCenterAlignment() self.addSubview(self.titleLabel) self.subtitleLabel.font = UIFont.system(weight: .regular, size: 16) self.subtitleLabel.textColor = SPNativeColors.black self.subtitleLabel.numberOfLines = 0 self.subtitleLabel.setCenterAlignment() self.addSubview(self.subtitleLabel) self.imageView.gradeView.backgroundColor = UIColor.white self.imageView.contentMode = .scaleAspectFit self.imageView.layer.masksToBounds = true self.addSubview(self.imageView) self.button.titleLabel?.font = UIFont.system(weight: UIFont.FontWeight.medium, size: 15) self.button.setTitleColor(SPNativeColors.black) self.button.layer.cornerRadius = 13 self.button.backgroundColor = SPNativeColors.lightGray self.addSubview(self.button) self.closeButton.widthIconFactor = 0.4 self.closeButton.heightIconFactor = 0.4 self.closeButton.backgroundColor = SPNativeColors.lightGray.withAlphaComponent(0.6) self.closeButton.color = UIColor.init(hex: "979797") self.addSubview(self.closeButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.titleLabel.sizeToFit() self.titleLabel.frame.origin.y = self.space * 0.9 self.titleLabel.frame.set(width: self.frame.width - self.space * 3) self.titleLabel.setXCenter() self.subtitleLabel.sizeToFit() self.subtitleLabel.frame.origin.y = self.titleLabel.frame.bottomY + 8 self.subtitleLabel.frame.set(width: self.frame.width - self.space * 2) self.subtitleLabel.setXCenter() self.imageView.frame = CGRect.init( x: 0, y: self.subtitleLabel.frame.bottomY + self.space / 2, width: self.imageSideSize, height: self.imageSideSize ) self.imageView.setXCenter() self.button.sizeToFit() self.button.frame.set(height: 52) self.button.frame.set(width: self.frame.width - self.space * 2) self.button.frame.origin.y = self.imageView.frame.bottomY + self.space / 1.8 self.button.setXCenter() self.closeButton.frame = CGRect.init(x: 0, y: 0, width: 24, height: 24) self.closeButton.frame.origin.x = self.frame.width - self.closeButton.frame.width - 20 self.closeButton.frame.origin.y = 20 self.closeButton.round() self.frame.set(height: self.button.frame.bottomY + self.space) } func layout(origin: CGPoint, width: CGFloat) { self.frame.origin = origin self.frame.set(width: width) self.layoutSubviews() } } struct Data { var title: String var subtitle: String var buttonTitle: String var imageLink: String? var image: UIImage? var complection: (_ isConfirmed: Bool)->() } var bottomSafeArea: CGFloat { var bottomSafeArea: CGFloat = 0 if let window = UIApplication.shared.keyWindow { if #available(iOS 11.0, *) { bottomSafeArea = window.safeAreaInsets.bottom } } else { bottomSafeArea = 0 } return bottomSafeArea } }
mit
bd07f8ccafc0d4ada095a26985817db8
37.872483
173
0.604454
4.631747
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/Extensions/URL+MIME.swift
1
1026
import Foundation import MobileCoreServices extension URL { /// Returns the **MIME** type of the current file. If an error occurs, `"application/octet-stream"` is returned. var contentType: String { let defaultMime = "application/octet-stream" guard !pathExtension.isEmpty else { return defaultMime } let uti: CFString? = { let utiRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil) let uti = utiRef?.takeUnretainedValue() utiRef?.release() return uti }() let mime: String? = { guard let uti = uti else { return nil } let mimeRef = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType) let mime = mimeRef?.takeUnretainedValue() mimeRef?.release() return mime as String? }() return mime ?? defaultMime } }
gpl-3.0
8ee157413035a87eb02b1915e7e8fefb
27.5
124
0.576023
5.731844
false
false
false
false
IngmarStein/Set
SetTests/MultisetHigherOrderFunctionTests.swift
1
545
// Copyright (c) 2014 Rob Rix. All rights reserved. import XCTest import Set final class MultisetHigherOrderFunctionTests: XCTestCase { func testFilter() { XCTAssert(Multiset(1, 2, 3).filter { $0 == 2 } == Multiset(2)) } func testReducible() { XCTAssert(Multiset(1, 2, 3).reduce(0, +) == 6) } func testMappable() { XCTAssert(Multiset(1, 2, 3).map(toString) == Multiset("1", "2", "3")) } func testFlatMapReturnsTheUnionOfAllResultingSets() { XCTAssertEqual(Multiset(1, 2).flatMap { [$0, $0 * 2] }, Multiset(1, 2, 2, 4)) } }
mit
ffe991f10b9e0a1caa688dc847484982
23.772727
79
0.656881
2.853403
false
true
false
false
hongqingWang/HQSwiftMVVM
HQSwiftMVVM/HQSwiftMVVM/Classes/NewFeature/View/HQWelcomeView.swift
1
3101
// // HQWelcomeView.swift // HQSwiftMVVM // // Created by 王红庆 on 2017/8/17. // Copyright © 2017年 王红庆. All rights reserved. // import UIKit class HQWelcomeView: UIView { fileprivate lazy var backImageView: UIImageView = UIImageView(hq_imageName: "ad_background") /// 头像 fileprivate lazy var avatarImageView: UIImageView = { let iv = UIImageView(hq_imageName: "avatar_default_big") iv.layer.cornerRadius = 45 iv.layer.masksToBounds = true return iv }() fileprivate lazy var welcomeLabel: UILabel = { let label = UILabel(hq_title: "欢迎归来", fontSize: 18, color: UIColor.hq_titleTextColor) label.alpha = 0 return label }() override init(frame: CGRect) { super.init(frame: frame) self.frame = UIScreen.main.bounds setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Animation extension HQWelcomeView { /// 视图被添加到`window`上,表示视图已经显示 override func didMoveToWindow() { super.didMoveToWindow() // 将代码布局的约束都创建好并显示出来,然后再进行下一步的更新动画 layoutIfNeeded() /// 设置头像 setAvatar() avatarImageView.snp.updateConstraints { (make) in make.bottom.equalTo(self).offset(-bounds.size.height + 200) } UIView.animate(withDuration: 2.0, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { self.layoutIfNeeded() }) { (_) in UIView.animate(withDuration: 1.0, animations: { self.welcomeLabel.alpha = 1 }, completion: { (_) in self.removeFromSuperview() }) } } /// 设置头像 fileprivate func setAvatar() { guard let urlString = HQNetWorkManager.shared.userAccount.avatar_large else { return } avatarImageView.hq_setImage(urlString: urlString, placeholderImage: UIImage(named: "avatar_default_big")) } } // MARK: - UI extension HQWelcomeView { fileprivate func setupUI() { addSubview(backImageView) addSubview(avatarImageView) addSubview(welcomeLabel) backImageView.frame = self.bounds avatarImageView.snp.makeConstraints { (make) in make.bottom.equalTo(self).offset(-200) make.centerX.equalTo(self) make.width.equalTo(90) make.height.equalTo(90) } welcomeLabel.snp.makeConstraints { (make) in make.top.equalTo(avatarImageView.snp.bottom).offset(16) make.centerX.equalTo(avatarImageView) } } }
mit
baa98223eb6cd0a91b22e9f3ca91c444
26.462963
113
0.553608
4.700475
false
false
false
false
lionadi/Objective-CCocos2DToSwift
Game Objects and Actors/Hunter.swift
1
5717
// // Hunter.swift // // Created by Adrian Simionescu on 05/09/14. // import Foundation public enum HunterState { case HunterStateIdle, HunterStateAiming, HunterStateReloading } public class Hunter : CCSprite { var torso : CCSprite?; var hunterState : HunterState; override init() { self.hunterState = HunterState.HunterStateIdle; super.init(imageNamed: "hunter_bottom.png"); self.torso = CCSprite(imageNamed: "hunter_top_0.png"); self.torso!.anchorPoint = CGPointMake( 0.5,10/44); self.torso!.position = CGPointMake(self.boundingBox().size.width/2, self.boundingBox().size.height); self.addChild(torso, z: -1); } func torsoRotation() -> Float { return self.torso!.rotation; } func torsoCenterInWorldCoordinates() -> CGPoint { var torsoCenterLocal : CGPoint; torsoCenterLocal = CGPointMake(self.torso!.contentSize.width / 2.0, self.torso!.contentSize.height / 2.0); var torsoCenterWorld : CGPoint; torsoCenterWorld = self.torso!.convertToWorldSpace(torsoCenterLocal); return torsoCenterWorld; } func calculateTorsoRotationToLookAtPoint(targetPoint : CGPoint) -> Float { var torsoCenterWorld : CGPoint; torsoCenterWorld = self.torsoCenterInWorldCoordinates(); var pointStraightAhead : CGPoint; pointStraightAhead = CGPointMake(torsoCenterWorld.x + 1.0, torsoCenterWorld.y); var forwardVector : CGPoint; forwardVector = CGPoint.Sub(pointStraightAhead, v2: torsoCenterWorld); var targetVector : CGPoint; targetVector = CGPoint.Sub(targetPoint, v2: torsoCenterWorld); var angleRadians : Float; angleRadians = CGPoint.AngleSigned(forwardVector, b: targetVector); var angleDegrees : Float; angleDegrees = -1 * angleRadians * MathGlobals.RADIANS_TO_DEGREES; angleDegrees = clampf(angleDegrees, -60, 25); return angleDegrees; } func aimAtPoint(point : CGPoint) { self.torso!.rotation = calculateTorsoRotationToLookAtPoint(point); } func shootAtPoint(point : CGPoint) -> CCSprite { self.aimAtPoint(point); var arrow : CCSprite = CCSprite(imageNamed: "arrow.png"); arrow.anchorPoint = CGPointMake(0, 0.5); var torsoCenterGlobal : CGPoint = self.torsoCenterInWorldCoordinates(); arrow.position = torsoCenterGlobal; arrow.rotation = self.torso!.rotation; self.parent.addChild(arrow); var viewSize : CGSize = CCDirector.sharedDirector().viewSize(); var forwardVector : CGPoint = CGPointMake(1.0, 0); var angleRadians : Float = -1 * MathGlobals.RADIANS_TO_DEGREES * self.torso!.rotation; var arrowMovementVector : CGPoint = CGPoint.RotateByAngle(forwardVector, pivot: CGPointZero, angle: angleRadians); arrowMovementVector = CGPoint.Normalize(arrowMovementVector); arrowMovementVector = CGPoint.Mult(arrowMovementVector, s: viewSize.width * 2.0); var moveAction : CCActionMoveBy = CCActionMoveBy(duration: 2.0, position: arrowMovementVector); arrow.runAction(moveAction); self.reloadArrow(); return arrow; } func getReadyToShootAgain() { self.hunterState = HunterState.HunterStateIdle; } func reloadArrow() { self.hunterState = HunterState.HunterStateReloading; var frameNameFormat : String = "hunter_top_%d.png"; var frames = Array<CCSpriteFrame>(); for (var i : Int = 0; i < 6; i++) { var frameName : String = String(format: frameNameFormat, i); var frame : CCSpriteFrame = CCSpriteFrame.frameWithImageNamed(frameName) as CCSpriteFrame; frames.append(frame); } var reloadAnimation : CCAnimation = CCAnimation.animationWithSpriteFrames(frames, delay: 0.5) as CCAnimation; reloadAnimation.restoreOriginalFrame = true; var reloadAnimAction : CCActionAnimate = CCActionAnimate.actionWithAnimation(reloadAnimation) as CCActionAnimate; let mySelectorGetReadyToShootAgain: Selector = "getReadyToShootAgain"; var readyToShootAgain : CCActionCallFunc = CCActionCallFunc.actionWithTarget(self, selector: mySelectorGetReadyToShootAgain) as CCActionCallFunc; var delay : CCActionDelay = CCActionDelay.actionWithDuration(0.25) as CCActionDelay; var actions = Array<CCAction>(); actions.append(reloadAnimAction); actions.append(delay); actions.append(readyToShootAgain); var reloadAndGetReady : CCActionSequence = CCActionSequence.actionWithArray(actions) as CCActionSequence; self.torso!.runAction(reloadAndGetReady); } override init(texture: CCTexture!, rect: CGRect, rotated: Bool) { self.torso = CCSprite(); self.hunterState = HunterState.HunterStateIdle; super.init(texture: texture, rect: rect, rotated: rotated); } override init(spriteFrame: CCSpriteFrame!) { self.torso = CCSprite(); self.hunterState = HunterState.HunterStateIdle; super.init(spriteFrame: spriteFrame); } override init(texture: CCTexture!, rect: CGRect) { self.torso = CCSprite(); self.hunterState = HunterState.HunterStateIdle; super.init(texture: texture, rect: rect); } }
mit
36c797eda7082a51966257186061cc78
33.239521
153
0.640196
4.370795
false
false
false
false
punty/FPActivityIndicator
FPActivityLoader/FPActivityLoader.swift
1
4983
// // FPActivityLoader.swift // FPActivityLoader // // Created by Francesco Puntillo on 04/04/2016. // Copyright © 2016 Francesco Puntillo. All rights reserved. // import UIKit @IBDesignable class FPActivityLoader: UIView { static let defaultColor = UIColor.blackColor() static let defaultLineWidth: CGFloat = 2.0 static let defaultCircleTime: Double = 1.5 private var strokeAnimation: CAAnimationGroup { get { return generateAnimation() } } private var rotationAnimation: CABasicAnimation { get { return generateRotationAnimation() } } private var circleLayer: CAShapeLayer = CAShapeLayer() @IBInspectable var strokeColor: UIColor = UIColor.blackColor() { didSet { circleLayer.strokeColor = strokeColor.CGColor } } @IBInspectable var animating: Bool = true { didSet { updateAnimation() } } @IBInspectable var hideWhenNotAnimating: Bool = true { didSet { self.hidden = (self.hideWhenNotAnimating) && (!self.animating) } } @IBInspectable var lineWidth: CGFloat = CGFloat(2) { didSet { circleLayer.lineWidth = lineWidth } } @IBInspectable var circleTime: Double = 1.5 { didSet { circleLayer.removeAllAnimations() updateAnimation() } } //init methods override init(frame: CGRect) { lineWidth = FPActivityLoader.defaultLineWidth circleTime = FPActivityLoader.defaultCircleTime strokeColor = FPActivityLoader.defaultColor super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { lineWidth = FPActivityLoader.defaultLineWidth circleTime = FPActivityLoader.defaultCircleTime strokeColor = FPActivityLoader.defaultColor super.init(coder: aDecoder) setupView() } convenience init() { self.init(frame: CGRect.zero) lineWidth = FPActivityLoader.defaultLineWidth circleTime = FPActivityLoader.defaultCircleTime strokeColor = FPActivityLoader.defaultColor setupView() } func generateAnimation() -> CAAnimationGroup { let headAnimation = CABasicAnimation(keyPath: "strokeStart") headAnimation.beginTime = self.circleTime/3.0 headAnimation.fromValue = 0 headAnimation.toValue = 1 headAnimation.duration = self.circleTime/1.5 headAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let tailAnimation = CABasicAnimation(keyPath: "strokeEnd") tailAnimation.fromValue = 0 tailAnimation.toValue = 1 tailAnimation.duration = self.circleTime/1.5 tailAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let groupAnimation = CAAnimationGroup() groupAnimation.duration = self.circleTime groupAnimation.repeatCount = Float.infinity groupAnimation.animations = [headAnimation, tailAnimation] return groupAnimation } func generateRotationAnimation() -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "transform.rotation") animation.fromValue = 0 animation.toValue = 2*M_PI animation.duration = self.circleTime animation.repeatCount = Float.infinity return animation } func setupView() { layer.addSublayer(self.circleLayer) backgroundColor = UIColor.clearColor() circleLayer.fillColor = nil circleLayer.lineWidth = lineWidth circleLayer.lineCap = kCALineCapRound circleLayer.strokeColor = strokeColor.CGColor } override func layoutSubviews() { super.layoutSubviews() let center = CGPoint(x: bounds.size.width/2.0, y: bounds.size.height/2.0) let radius = min(bounds.size.width, bounds.size.height)/2.0 - circleLayer.lineWidth/2.0 let endAngle = CGFloat(2*M_PI) let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true) circleLayer.path = path.CGPath circleLayer.frame = bounds } func updateAnimation() { self.hidden = (self.hideWhenNotAnimating) && (!self.animating) if animating { circleLayer.addAnimation(strokeAnimation, forKey: "strokeLineAnimation") circleLayer.addAnimation(rotationAnimation, forKey: "rotationAnimation") } else { circleLayer.removeAllAnimations() } } override func prepareForInterfaceBuilder() { setupView() } deinit { circleLayer.removeAllAnimations() circleLayer.removeFromSuperlayer() } }
mit
3a9ee55672e4b386655aabb27013aa12
29.193939
118
0.639703
5.334047
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Widgets/ActionOverlayTableViewController.swift
1
7555
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Storage class ActionOverlayTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { private var site: Site private var actions: [ActionOverlayTableViewAction] private var tableView = UITableView() private var headerImage: UIImage? private var headerImageBackgroundColor: UIColor? lazy var tapRecognizer: UITapGestureRecognizer = { let tapRecognizer = UITapGestureRecognizer() tapRecognizer.addTarget(self, action: #selector(ActionOverlayTableViewController.dismiss(_:))) tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.cancelsTouchesInView = false return tapRecognizer }() lazy var visualEffectView: UIVisualEffectView = { let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) visualEffectView.frame = self.view.bounds visualEffectView.alpha = 0.90 return visualEffectView }() init(site: Site, actions: [ActionOverlayTableViewAction], siteImage: UIImage?, siteBGColor: UIColor?) { self.site = site self.actions = actions self.headerImage = siteImage self.headerImageBackgroundColor = siteBGColor super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.clearColor().colorWithAlphaComponent(0.4) view.addGestureRecognizer(tapRecognizer) view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag tableView.registerClass(ActionOverlayTableViewCell.self, forCellReuseIdentifier: "ActionOverlayTableViewCell") tableView.registerClass(ActionOverlayTableViewHeader.self, forHeaderFooterViewReuseIdentifier: "ActionOverlayTableViewHeader") tableView.backgroundColor = UIConstants.PanelBackgroundColor tableView.scrollEnabled = false tableView.layer.cornerRadius = 10 tableView.separatorStyle = .None tableView.cellLayoutMarginsFollowReadableWidth = false tableView.accessibilityIdentifier = "Context Menu" tableView.snp_makeConstraints { make in make.center.equalTo(self.view) make.width.equalTo(290) make.height.equalTo(74 + actions.count * 56) } } func dismiss(gestureRecognizer: UIGestureRecognizer) { self.dismissViewControllerAnimated(true, completion: nil) } deinit { // The view might outlive this view controller thanks to animations; // explicitly nil out its references to us to avoid crashes. Bug 1218826. tableView.dataSource = nil tableView.delegate = nil } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return actions.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let action = actions[indexPath.row] guard let handler = actions[indexPath.row].handler else { return } return handler(action) } func tableView(tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 56 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 74 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ActionOverlayTableViewCell", forIndexPath: indexPath) as! ActionOverlayTableViewCell let action = actions[indexPath.row] cell.configureCell(action.title, imageString: action.iconString) return cell } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("ActionOverlayTableViewHeader") as! ActionOverlayTableViewHeader header.configureWithSite(site, image: headerImage, imageBackgroundColor: headerImageBackgroundColor) return header } } class ActionOverlayTableViewHeader: UITableViewHeaderFooterView { lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontMediumBold titleLabel.textColor = SimpleHighlightCellUX.LabelColor titleLabel.textAlignment = .Left titleLabel.numberOfLines = 3 return titleLabel }() lazy var descriptionLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontDescriptionActivityStream titleLabel.textColor = SimpleHighlightCellUX.DescriptionLabelColor titleLabel.textAlignment = .Left titleLabel.numberOfLines = 1 return titleLabel }() lazy var siteImageView: UIImageView = { let siteImageView = UIImageView() siteImageView.contentMode = UIViewContentMode.Center siteImageView.layer.cornerRadius = SimpleHighlightCellUX.CornerRadius return siteImageView }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) layer.shouldRasterize = true layer.rasterizationScale = UIScreen.mainScreen().scale isAccessibilityElement = true descriptionLabel.numberOfLines = 1 titleLabel.numberOfLines = 1 contentView.backgroundColor = UIConstants.PanelBackgroundColor contentView.addSubview(siteImageView) contentView.addSubview(descriptionLabel) contentView.addSubview(titleLabel) siteImageView.snp_remakeConstraints { make in make.centerY.equalTo(contentView) make.leading.equalTo(contentView).offset(12) make.size.equalTo(SimpleHighlightCellUX.SiteImageViewSize) } titleLabel.snp_remakeConstraints { make in make.leading.equalTo(siteImageView.snp_trailing).offset(12) make.trailing.equalTo(contentView).inset(12) make.top.equalTo(siteImageView).offset(7) } descriptionLabel.snp_remakeConstraints { make in make.leading.equalTo(titleLabel) make.bottom.equalTo(siteImageView).inset(7) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureWithSite(site: Site, image: UIImage?, imageBackgroundColor: UIColor?) { self.siteImageView.backgroundColor = imageBackgroundColor self.siteImageView.image = image?.createScaled(SimpleHighlightCellUX.IconSize) ?? SimpleHighlightCellUX.PlaceholderImage self.titleLabel.text = site.title.characters.count <= 1 ? site.url : site.title self.descriptionLabel.text = site.tileURL.baseDomain() } }
mpl-2.0
3edb33450543c376aae07d809759a312
38.554974
148
0.708802
5.6171
false
false
false
false
mosluce/GUCustomizeViews
Classes/GUTextField.swift
1
4427
// // GUTextField.swift // GUCustomizeViews // // Created by 默司 on 2016/8/23. // Copyright © 2016年 默司. All rights reserved. // import UIKit import SnapKit @IBDesignable public class GUTextField: UITextField { private var tfdelegate: GUTextFieldDelegate? @IBInspectable public var designedFontSize: CGFloat = 60 { didSet { updateFontSize() } } @IBInspectable public var designedFontName: String = "PingFangTC-Semibold" { didSet { updateFontSize() } } public var invalid: Bool = false { didSet { updateSideViews() } } public override var delegate: UITextFieldDelegate? { didSet { tfdelegate = delegate as? GUTextFieldDelegate updateSideViews() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } //初始化寫這裡不需要 override 兩個 init func commonInit() { //TODO: write initialize codes } public override func didMoveToSuperview() { super.didMoveToSuperview() updateSideViews() } public override func layoutSubviews() { super.layoutSubviews() self.borderStyle = .None self.backgroundColor = GUColors.BlueGrey800.colorWithAlphaComponent(0.1) self.layer.cornerRadius = self.bounds.height / 2 } public override func leftViewRectForBounds(bounds: CGRect) -> CGRect { if validateDelegate(#selector(GUTextFieldDelegate.rectForLeftView(_:))) { return tfdelegate!.rectForLeftView!(bounds) } return CGRectZero } public override func rightViewRectForBounds(bounds: CGRect) -> CGRect { if !invalid { if validateDelegate(#selector(GUTextFieldDelegate.rectForRightView(_:))) { return tfdelegate!.rectForRightView!(bounds) } } else { if validateDelegate(#selector(GUTextFieldDelegate.rectForRightErrorView(_:))) { return tfdelegate!.rectForRightErrorView!(bounds) } } return CGRectZero } public override func editingRectForBounds(bounds: CGRect) -> CGRect { return textRectForBounds(bounds) } public override func textRectForBounds(bounds: CGRect) -> CGRect { var left = leftViewRectForBounds(bounds).width var right = rightViewRectForBounds(bounds).width if left == 0 { left = bounds.height / 2 } if right == 0 { right = bounds.height / 2 } return CGRectMake(left, 0, bounds.width-(left+right), bounds.height) } func validateDelegate(selector: Selector) -> Bool { guard let delegate = tfdelegate else { return false } if !delegate.respondsToSelector(selector) { return false } return true } func updateSideViews() { leftView = tfdelegate?.viewForLeftView?() if invalid { rightView = tfdelegate?.viewForRightErrorView?() } else { rightView = tfdelegate?.viewForRightView?() } if leftView != nil { leftViewMode = .Always } else { leftViewMode = .Never } if rightView != nil { rightViewMode = .Always } else { rightViewMode = .Never } } func updateFontSize() { if let font = UIFont(name: designedFontName, size: designedFontSize * proportionForView()) { self.font = font } } } @objc public protocol GUTextFieldDelegate: UITextFieldDelegate { optional func viewForLeftView() -> UIView optional func rectForLeftView(bounds: CGRect) -> CGRect optional func viewForRightView() -> UIView optional func rectForRightView(bounds: CGRect) -> CGRect optional func viewForRightErrorView() -> UIView optional func rectForRightErrorView(bounds: CGRect) -> CGRect optional func didFontChanged(font: UIFont?) }
mit
57fd8d20c8e083363ff3cfb7125d9187
25.311377
100
0.577833
5.230952
false
false
false
false
hrscy/TodayNews
News/News/Classes/Mine/View/MyConcernCell.swift
1
1306
// // MyConcernCell.swift // News // // Created by 杨蒙 on 2017/9/16. // Copyright © 2017年 hrscy. All rights reserved. // import UIKit import Kingfisher class MyConcernCell: UICollectionViewCell, RegisterCellFromNib { /// 头像 @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var vipImageView: UIImageView! /// 用户名 @IBOutlet weak var nameLabel: UILabel! /// 新通知 @IBOutlet weak var tipsButton: UIButton! var myConcern = MyConcern() { didSet { avatarImageView.kf.setImage(with: URL(string: (myConcern.icon))) nameLabel.text = myConcern.name vipImageView.isHidden = !myConcern.is_verify tipsButton.isHidden = !myConcern.tips vipImageView.image = myConcern.user_auth_info.auth_type == 1 ? UIImage(named: "all_v_avatar_star_16x16_") : UIImage(named: "all_v_avatar_18x18_") } } override func awakeFromNib() { super.awakeFromNib() tipsButton.layer.borderWidth = 1 tipsButton.layer.theme_borderColor = "colors.cellBackgroundColor" theme_backgroundColor = "colors.cellBackgroundColor" tipsButton.theme_backgroundColor = "colors.globalRedColor" nameLabel.theme_textColor = "colors.black" } }
mit
900dd1c8cb4339bdfa5af050d02a1ff3
30.292683
157
0.657054
4.021944
false
false
false
false
art-divin/SwiperView
SwiperDemo/ViewController.swift
1
1494
// // ViewController.swift // SwiperDemo // // Created by Ruslan Alikhamov on 30/01/15. // Copyright (c) 2015 Ruslan Alikhamov. All rights reserved. // import UIKit class ViewController: UITableViewController { let cellID = "cellID" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.tableView.registerClass(SwiperCell.self, forCellReuseIdentifier: cellID) self.tableView.separatorStyle = .None } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // :MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! SwiperCell cell.leftLbl.text = "Left" cell.rightLbl.text = "Right" cell.textLbl.text = "Some text on vibrancy effect view" cell.leftCallback = { println("left callback toggled") } cell.rightCallback = { println("right callback toggled") } return cell } // :MARK: UITableViewDelegate override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44.0 } }
mit
cb4b9b0822de086c3030f07f2df0f9b5
24.758621
115
0.743641
4.016129
false
false
false
false
kunwang/absnetwork
ABSNetwork/Sources/ABSCompleteHandlerDelegate.swift
1
1777
// // ABSCompleteHandlerDelegate.swift // ABSNetwork // // Created by abstractwang on 2017/10/9. // Copyright © 2017年 com.abswang. All rights reserved. // import Foundation public protocol ABSCompleteHandlerDelegate: class { func success(_ request: ABSRequest, _ response: ABSResponse) func fail(_ request: ABSRequest, _ response: ABSResponse) } public extension ABSCompleteHandlerDelegate { func success(_ request: ABSRequest, _ response: ABSResponse) { // default do nothing } func fail(_ request: ABSRequest, _ response: ABSResponse) { // default do nothing } } public class ABSBaseCompleteHandler: ABSCompleteHandlerDelegate { // first way: delegate style weak var delegate: ABSCompleteHandlerDelegate? // second way: closure style, closure must weak reference private var _fail: ((ABSRequest, ABSResponse)->())? private var _success: ((ABSRequest, ABSResponse)->())? public init(success: ((ABSRequest, ABSResponse)->())? = nil, fail: ((ABSRequest, ABSResponse)->())? = nil) { self._success = success self._fail = fail } public init(delegate: ABSCompleteHandlerDelegate?) { self.delegate = delegate } public func fail(_ request: ABSRequest, _ response: ABSResponse) { if let theDelegate = self.delegate { theDelegate.fail(request, response) } else { self._fail?(request, response) } } public func success(_ request: ABSRequest, _ response: ABSResponse) { if let theDelegate = self.delegate { theDelegate.success(request, response) } else { self._success?(request, response) } } }
mit
138d261e6ac639932be9aaaebfbaeabc
25.878788
112
0.625141
4.513995
false
false
false
false
NatashaTheRobot/Quick
Quick/Configuration/Configuration.swift
22
5533
/** A closure that temporarily exposes a Configuration object within the scope of the closure. */ public typealias QuickConfigurer = (configuration: Configuration) -> () /** A closure that, given metadata about an example, returns a boolean value indicating whether that example should be run. */ public typealias ExampleFilter = (example: Example) -> Bool /** A configuration encapsulates various options you can use to configure Quick's behavior. */ @objc final public class Configuration { internal let exampleHooks = ExampleHooks() internal let suiteHooks = SuiteHooks() internal var exclusionFilters: [ExampleFilter] = [{ example in if let pending = example.filterFlags[Filter.pending] { return pending } else { return false } }] internal var inclusionFilters: [ExampleFilter] = [{ example in if let focused = example.filterFlags[Filter.focused] { return focused } else { return false } }] /** Run all examples if none match the configured filters. True by default. */ public var runAllWhenEverythingFiltered = true /** Registers an inclusion filter. All examples are filtered using all inclusion filters. The remaining examples are run. If no examples remain, all examples are run. - parameter filter: A filter that, given an example, returns a value indicating whether that example should be included in the examples that are run. */ public func include(filter: ExampleFilter) { inclusionFilters.append(filter) } /** Registers an exclusion filter. All examples that remain after being filtered by the inclusion filters are then filtered via all exclusion filters. - parameter filter: A filter that, given an example, returns a value indicating whether that example should be excluded from the examples that are run. */ public func exclude(filter: ExampleFilter) { exclusionFilters.append(filter) } /** Identical to Quick.Configuration.beforeEach, except the closure is provided with metadata on the example that the closure is being run prior to. */ @objc(beforeEachWithMetadata:) public func beforeEach(closure: BeforeExampleWithMetadataClosure) { exampleHooks.appendBefore(closure) } /** Like Quick.DSL.beforeEach, this configures Quick to execute the given closure before each example that is run. The closure passed to this method is executed before each example Quick runs, globally across the test suite. You may call this method multiple times across mulitple +[QuickConfigure configure:] methods in order to define several closures to run before each example. Note that, since Quick makes no guarantee as to the order in which +[QuickConfiguration configure:] methods are evaluated, there is no guarantee as to the order in which beforeEach closures are evaluated either. Mulitple beforeEach defined on a single configuration, however, will be executed in the order they're defined. - parameter closure: The closure to be executed before each example in the test suite. */ public func beforeEach(closure: BeforeExampleClosure) { exampleHooks.appendBefore(closure) } /** Identical to Quick.Configuration.afterEach, except the closure is provided with metadata on the example that the closure is being run after. */ @objc(afterEachWithMetadata:) public func afterEach(closure: AfterExampleWithMetadataClosure) { exampleHooks.appendAfter(closure) } /** Like Quick.DSL.afterEach, this configures Quick to execute the given closure after each example that is run. The closure passed to this method is executed after each example Quick runs, globally across the test suite. You may call this method multiple times across mulitple +[QuickConfigure configure:] methods in order to define several closures to run after each example. Note that, since Quick makes no guarantee as to the order in which +[QuickConfiguration configure:] methods are evaluated, there is no guarantee as to the order in which afterEach closures are evaluated either. Mulitple afterEach defined on a single configuration, however, will be executed in the order they're defined. - parameter closure: The closure to be executed before each example in the test suite. */ public func afterEach(closure: AfterExampleClosure) { exampleHooks.appendAfter(closure) } /** Like Quick.DSL.beforeSuite, this configures Quick to execute the given closure prior to any and all examples that are run. The two methods are functionally equivalent. */ public func beforeSuite(closure: BeforeSuiteClosure) { suiteHooks.appendBefore(closure) } /** Like Quick.DSL.afterSuite, this configures Quick to execute the given closure after all examples have been run. The two methods are functionally equivalent. */ public func afterSuite(closure: AfterSuiteClosure) { suiteHooks.appendAfter(closure) } }
apache-2.0
6f092927e25e4d0dd48041546dc7f790
36.639456
87
0.673233
5.408602
false
true
false
false
kaunteya/ProgressKit
InDeterminate/RotatingArc.swift
1
2952
// // RotatingArc.swift // ProgressKit // // Created by Kauntey Suryawanshi on 26/10/15. // Copyright © 2015 Kauntey Suryawanshi. All rights reserved. // import Foundation import Cocoa private let duration = 0.25 @IBDesignable open class RotatingArc: IndeterminateAnimation { var backgroundCircle = CAShapeLayer() var arcLayer = CAShapeLayer() @IBInspectable open var strokeWidth: CGFloat = 5 { didSet { notifyViewRedesigned() } } @IBInspectable open var arcLength: Int = 35 { didSet { notifyViewRedesigned() } } @IBInspectable open var clockWise: Bool = true { didSet { notifyViewRedesigned() } } var radius: CGFloat { return (self.frame.width / 2) * CGFloat(0.75) } var rotationAnimation: CABasicAnimation = { var tempRotation = CABasicAnimation(keyPath: "transform.rotation") tempRotation.repeatCount = .infinity tempRotation.fromValue = 0 tempRotation.toValue = 1 tempRotation.isCumulative = true tempRotation.duration = duration return tempRotation }() override func notifyViewRedesigned() { super.notifyViewRedesigned() arcLayer.strokeColor = foreground.cgColor backgroundCircle.strokeColor = foreground.withAlphaComponent(0.4).cgColor backgroundCircle.lineWidth = self.strokeWidth arcLayer.lineWidth = strokeWidth rotationAnimation.toValue = clockWise ? -1 : 1 let arcPath = NSBezierPath() let endAngle: CGFloat = CGFloat(-360) * CGFloat(arcLength) / 100 arcPath.appendArc(withCenter: self.bounds.mid, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true) arcLayer.path = arcPath.CGPath } override func configureLayers() { super.configureLayers() let rect = self.bounds // Add background Circle do { backgroundCircle.frame = rect backgroundCircle.lineWidth = strokeWidth backgroundCircle.strokeColor = foreground.withAlphaComponent(0.5).cgColor backgroundCircle.fillColor = NSColor.clear.cgColor let backgroundPath = NSBezierPath() backgroundPath.appendArc(withCenter: rect.mid, radius: radius, startAngle: 0, endAngle: 360) backgroundCircle.path = backgroundPath.CGPath self.layer?.addSublayer(backgroundCircle) } // Arc Layer do { arcLayer.fillColor = NSColor.clear.cgColor arcLayer.lineWidth = strokeWidth arcLayer.frame = rect arcLayer.strokeColor = foreground.cgColor self.layer?.addSublayer(arcLayer) } } override func startAnimation() { arcLayer.add(rotationAnimation, forKey: "") } override func stopAnimation() { arcLayer.removeAllAnimations() } }
mit
96d98fce32553b8b4ff5c9636916251b
27.375
122
0.638428
5.195423
false
false
false
false
Jpadilla1/react-native-ios-charts
RNiOSCharts/BalloonMarker.swift
1
4165
// // BalloonMarker.swift // ChartsDemo // // Created by Daniel Cohen Gindi on 19/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // https://github.com/danielgindi/Charts/blob/1788e53f22eb3de79eb4f08574d8ea4b54b5e417/ChartsDemo/Classes/Components/BalloonMarker.swift // Edit: Added textColor import Foundation; import Charts; public class BalloonMarker: ChartMarker { public var color: UIColor? public var arrowSize = CGSize(width: 15, height: 11) public var font: UIFont? public var textColor: UIColor? public var insets = UIEdgeInsets() public var minimumSize = CGSize() private var labelns: NSString? private var _labelSize: CGSize = CGSize() private var _size: CGSize = CGSize() private var _paragraphStyle: NSMutableParagraphStyle? private var _drawAttributes = [String : AnyObject]() public init(color: UIColor, font: UIFont, textColor: UIColor, insets: UIEdgeInsets) { super.init() self.color = color self.font = font self.textColor = textColor self.insets = insets _paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as? NSMutableParagraphStyle _paragraphStyle?.alignment = .Center } public override var size: CGSize { return _size; } public override func draw(context context: CGContext, point: CGPoint) { if (labelns == nil) { return } var rect = CGRect(origin: point, size: _size) rect.origin.x -= _size.width / 2.0 rect.origin.y -= _size.height CGContextSaveGState(context) CGContextSetFillColorWithColor(context, color?.CGColor) CGContextBeginPath(context) CGContextMoveToPoint(context, rect.origin.x, rect.origin.y) CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y) CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height - arrowSize.height) CGContextAddLineToPoint(context, rect.origin.x + (rect.size.width + arrowSize.width) / 2.0, rect.origin.y + rect.size.height - arrowSize.height) CGContextAddLineToPoint(context, rect.origin.x + rect.size.width / 2.0, rect.origin.y + rect.size.height) CGContextAddLineToPoint(context, rect.origin.x + (rect.size.width - arrowSize.width) / 2.0, rect.origin.y + rect.size.height - arrowSize.height) CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height - arrowSize.height) CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y) CGContextFillPath(context) rect.origin.y += self.insets.top rect.size.height -= self.insets.top + self.insets.bottom UIGraphicsPushContext(context) labelns?.drawInRect(rect, withAttributes: _drawAttributes) UIGraphicsPopContext() CGContextRestoreGState(context) } public override func refreshContent(entry entry: ChartDataEntry, highlight: ChartHighlight) { let label = entry.value.description labelns = label as NSString _drawAttributes.removeAll() _drawAttributes[NSFontAttributeName] = self.font _drawAttributes[NSParagraphStyleAttributeName] = _paragraphStyle _drawAttributes[NSForegroundColorAttributeName] = self.textColor _labelSize = labelns?.sizeWithAttributes(_drawAttributes) ?? CGSizeZero _size.width = _labelSize.width + self.insets.left + self.insets.right _size.height = _labelSize.height + self.insets.top + self.insets.bottom _size.width = max(minimumSize.width, _size.width) _size.height = max(minimumSize.height, _size.height) } }
mit
b4f511d5ed7e0b284c29bce112baf511
34.598291
137
0.640336
4.556893
false
false
false
false
jensmeder/DarkLightning
Sources/Daemon/Sources/Daemon/USBDaemonSocket.swift
1
3743
/** * * DarkLightning * * * * The MIT License (MIT) * * Copyright (c) 2017 Jens Meder * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation internal final class USBDaemonSocket: Daemon { // MARK: Constants private static let USBMuxDPath = "/var/run/usbmuxd" // MARK: Members private let handle: Memory<CFSocketNativeHandle> private let queue: DispatchQueue private let stream: DataStream private let state: Memory<Int> private let newState: Int // MARK: Init internal required init(socket: Memory<CFSocketNativeHandle>, queue: DispatchQueue, stream: DataStream, state: Memory<Int>, newState: Int) { self.handle = socket self.queue = queue self.stream = stream self.state = state self.newState = newState } // MARK: Internal private func addr() -> sockaddr_un { let length = USBDaemonSocket.USBMuxDPath.withCString { Int(strlen($0)) } var addr: sockaddr_un = sockaddr_un() addr.sun_family = sa_family_t(AF_UNIX) _ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in USBDaemonSocket.USBMuxDPath.withCString { strncpy(ptr, $0, length) } } return addr } private func configure(socketHandle: CFSocketNativeHandle) { var on: Int = Int(true) setsockopt(socketHandle, SOL_SOCKET, SO_NOSIGPIPE, &on, socklen_t(MemoryLayout<Int>.size)) setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(MemoryLayout<Int>.size)) setsockopt(socketHandle, SOL_SOCKET, SO_REUSEPORT, &on, socklen_t(MemoryLayout<Int>.size)) } // MARK: Daemon internal func start() { if handle.rawValue == CFSocketInvalidHandle { let socketHandle = socket(AF_UNIX, SOCK_STREAM, 0) if socketHandle != CFSocketInvalidHandle { configure(socketHandle: socketHandle) var addr = self.addr() let result = withUnsafeMutablePointer(to: &addr) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(socketHandle, $0, socklen_t(MemoryLayout.size(ofValue: addr))) } } if result != CFSocketInvalidHandle { handle.rawValue = socketHandle stream.open(in: queue) } } } } func stop() { if handle.rawValue != CFSocketInvalidHandle { stream.close() state.rawValue = newState handle.rawValue = CFSocketInvalidHandle } } }
mit
af51b26aef38b341bc022e30fc7c7625
34.990385
143
0.634785
4.388042
false
false
false
false
paulot/Homepwner
Item.swift
1
1968
// // Item.swift // Homepwner // // Created by Paulo Tanaka on 2/4/16. // Copyright © 2016 Paulo Tanaka. All rights reserved. // import UIKit class Item: NSObject, NSCoding { var name: String var valueInDollars: Int var serialNumber: String? let dateCreated: NSDate let itemKey: String init(name: String, serialNumber: String?, valueInDollars: Int) { self.name = name self.serialNumber = serialNumber self.valueInDollars = valueInDollars self.dateCreated = NSDate() self.itemKey = NSUUID().UUIDString super.init() } required init(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey("name") as! String dateCreated = aDecoder.decodeObjectForKey("dateCreated") as! NSDate itemKey = aDecoder.decodeObjectForKey("itemKey") as! String valueInDollars = aDecoder.decodeIntegerForKey("valueInDollars") super.init() } convenience init(random: Bool) { if (!random) { self.init(name: "", serialNumber: nil, valueInDollars: 0) } else { let adjectives = ["Fluffy", "Rusty", "Shiny"] let nouns = ["Bear", "Spork", "Mac"] var idx = arc4random_uniform(UInt32(adjectives.count)) let randomAdjective = adjectives[Int(idx)] idx = arc4random_uniform(UInt32(nouns.count)) let randomNoun = nouns[Int(idx)] let randomName = "\(randomAdjective) \(randomNoun)" let randomValue = Int(arc4random_uniform(100)) let randomSerialNumber = NSUUID().UUIDString.componentsSeparatedByString("-").first! self.init(name: randomName, serialNumber: randomSerialNumber, valueInDollars: randomValue) } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(dateCreated, forKey: "dateCreated") aCoder.encodeObject(itemKey, forKey: "itemKey") aCoder.encodeObject(serialNumber, forKey: "serialNumber") aCoder.encodeInteger(valueInDollars, forKey: "valueInDollars") } }
mit
df0f1933791c53655069ad287d72c291
28.818182
96
0.694967
4.211991
false
false
false
false
mendesbarreto/IOS
Bike 2 Work/Bike 2 Work/UserSettings.swift
1
1021
// // UserSettings.swift // Bike 2 Work // // Created by Douglas Barreto on 1/22/16. // Copyright © 2016 Douglas Mendes. All rights reserved. // import Foundation public class UserSettings { public static let sharedInstance = UserSettings(); public var hourToBike: HourToBike; public var humidity: Humidity; public var temperature: BWTemperatureBetween; public var city:String; private init(){ hourToBike = HourToBike(); humidity = Humidity(); temperature = BWTemperatureBetween(start: 20, end: 30); city = "Choose a City" } public func beginBikeAt( hours:Int , minutes: Int){ hourToBike.start = Hour(hour: hours, minutes: minutes); } public func endBikeAt( hours:Int , minutes:Int){ hourToBike.end = Hour(hour: hours, minutes: minutes); } public func beginHumidity( start: Int){ humidity.start = start; } public func endHumidity( end: Int){ humidity.end = end; } }
mit
c071c918f0bd742f12525727b7a85640
23.902439
63
0.632353
4.063745
false
false
false
false
freshOS/Komponents
KomponentsExample/StaticTableVC.swift
1
1724
// // StaticTableVC.swift // KomponentsExample // // Created by Sacha Durand Saint Omer on 08/05/2017. // Copyright © 2017 Octopepper. All rights reserved. // import UIKit import Komponents public extension UIColor { convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a) } } class StaticTableVC: UIViewController, StatelessComponent { var fences = ["fence 1", "fence 2", "A cool 3"] override func loadView() { loadComponent() } override func viewDidLoad() { super.viewDidLoad() title = "Static Table" } func render() -> Tree { weak var weakSelf = self return Table(.grouped, layout: .fill, data: weakSelf?.fences, refresh: { done in weakSelf?.fakeFetchFences { newFences in weakSelf?.fences = newFences done() } }, delete: { index, shouldDelete in weakSelf?.fences.remove(at: index) shouldDelete(true) }, configure: { fence in return FenceCell(fence, didActivate: { b in print("did activate \(b) for: \(fence)") }) } ) } func fakeFetchFences(completion:@escaping ([String]) -> Void ) { DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { completion(["fence A", "fence B", "fence C", "fence D"]) }) } deinit { print("DEstroy StaticTableVC") } }
mit
58b5b5273cc706b37d3e492ed7d4907f
27.245902
107
0.507255
4.440722
false
false
false
false
nekrich/GlobalMessageService-iOS
Source/Core/GlobalMessageServiceErrors.swift
1
13041
// // GlobalMessageServiceErrors.swift // GlobalMessageService // // Created by Vitalii Budnik on 12/10/15. // Copyright © 2015 Global Messages Services Worldwide. All rights reserved. // import Foundation /// Object containing the localized description of `self` public protocol CustomLocalizedDescriptionConvertible { /// A string containing the localized description of the object. (read-only) var localizedDescription: String { get } } // MARK: - GlobalMessageServiceError /** Enum represents GlobalMessageService framework errors - RequestError: A HTTP request error. Contains `GlobalMessageServiceError.Request` - ResultParsingError: An error occured when parsing result. Contains `GlobalMessageServiceError.ResultParsing` - SubscriberError: An error occured when adding new subscriber. Contains `GlobalMessageServiceError.Subscriber` - AnotherTaskInProgressError: Another task in progress error. Contains `GlobalMessageServiceError.AnotherTaskInProgress` - MessageFetcherError: Error occurred when retrieving messages. Contains `GlobalMessageServiceError.MessageFetcher` - GMSTokenIsNotSet: Global Message Service token is not set - GCMTokenIsNotSet: Google Cloud Messaging token is not set - NoPhoneOrEmailPassed: No phone or e-mail is passed - UnknownError: An unknown error occurred */ public enum GlobalMessageServiceError: ErrorType { /// A HTTP request error. Contains `GlobalMessageServiceError.Request` case RequestError(Request) /// An error occured when parsing result. Contains `GlobalMessageServiceError.ResultParsing` case ResultParsingError(ResultParsing) /// An error occured when adding new subscriber. Contains `GlobalMessageServiceError.Subscriber` case SubscriberError(Subscriber) /// Another task in progress error. Contains `GlobalMessageServiceError.AnotherTaskInProgress` case AnotherTaskInProgressError(AnotherTaskInProgress) /// Error occurred when retrieving messages. Contains `GlobalMessageServiceError.MessageFetcher` case MessageFetcherError(MessageFetcher) /// Global Message Service token is not set case GMSTokenIsNotSet /// Google Cloud Messaging token is not set case GCMTokenIsNotSet /// An unknown error occurred case NotAuthorized /// No phone or e-mail is passed case NoPhoneOrEmailPassed /// An unknown error occurred case UnknownError /// A string containing the localized **template** of the object. (read-only) private var localizedTemplate: String { let enumPresentation: String switch self { case RequestError(let error): enumPresentation = error.localizedTemplate break case ResultParsingError(let error): enumPresentation = error.localizedTemplate break case SubscriberError(let error): enumPresentation = error.localizedTemplate break case AnotherTaskInProgressError(let error): enumPresentation = error.localizedTemplate break case MessageFetcherError(let error): enumPresentation = error.localizedTemplate break default: enumPresentation = "\(self)" break } return GlobalMessageService.bundle.localizedStringForKey( "GlobalMessageServiceError.\(enumPresentation)", value: .None, table: "GlobalMessageServiceErrors") } /// A string containing the localized description of the object. (read-only) public var localizedDescription: String { let localizedString: String switch self { case RequestError(let error): localizedString = error.localizedDescription break case ResultParsingError(let error): localizedString = error.localizedDescription break case SubscriberError(let error): localizedString = error.localizedDescription break case AnotherTaskInProgressError(let error): localizedString = error.localizedDescription break case MessageFetcherError(let error): localizedString = error.localizedDescription break default: localizedString = localizedTemplate break } return localizedString } } // MARK: - GlobalMessageServiceError.AnotherTaskInProgress public extension GlobalMessageServiceError { /** Enum represents errors occured when you trying launch - AddSubscriber: Adding new subscriber - UpdateSubscriber: Updating subscriber's info - UpdateGCMToken: Updating Google Cloud Messaging token */ public enum AnotherTaskInProgress: ErrorType, CustomLocalizedDescriptionConvertible { /// Adding new subscriber case AddSubscriber /// Updating subscriber's info case UpdateSubscriber /// Updating Google Cloud Messaging token // case UpdateGCMToken /// A string containing the localized **template** of the object. (read-only) private var localizedTemplate: String { let enumPresentation: String = "\(self)" return GlobalMessageService.bundle.localizedStringForKey( "AnotherTaskInProgress.\(enumPresentation)", value: .None, table: "GlobalMessageServiceErrors") } /// A string containing the localized description of the object. (read-only) public var localizedDescription: String { let localizedString: String switch self { default: localizedString = localizedTemplate break } return localizedString } } } // MARK: - GlobalMessageServiceError.Subscriber public extension GlobalMessageServiceError { /** Enum represents response errors occured when adding new subscriber - NoAppDeviceId: There is no expexted `uniqAppDeviceId` field in response data - AppDeviceIdWrondType: Can't convert recieved `uniqAppDeviceId` to `UInt64` - AppDeviceIdLessOrEqualZero: Recieved `uniqAppDeviceId` is `0` or less */ public enum Subscriber: ErrorType, CustomLocalizedDescriptionConvertible { /// here is no expexted `uniqAppDeviceId` field in response data case NoAppDeviceId /// Can't convert recieved `uniqAppDeviceId` to `UInt64` case AppDeviceIdWrondType /// Recieved `uniqAppDeviceId` is `0` or less case AppDeviceIdLessOrEqualZero /// A string containing the localized **template** of the object. (read-only) private var localizedTemplate: String { let enumPresentation: String = "\(self)" return GlobalMessageService.bundle.localizedStringForKey( "Subscriber.\(enumPresentation)", value: .None, table: "GlobalMessageServiceErrors") } /// A string containing the localized description of the object. (read-only) public var localizedDescription: String { let localizedString: String switch self { default: localizedString = localizedTemplate break } return localizedString } } } // MARK: - GlobalMessageServiceError.ResultParsing public extension GlobalMessageServiceError { /** Enum represents response parsing errors - CantRepresentResultAsDictionary: Request returned response `NSData`, that can't be represented as `[String: AnyObject]` - JSONSerializationError: Request returned response `NSData`, that can't be serialized to JSON. Contains `NSError?` - description of error, that occurred on serialization attempt - NoStatus: There is no expexted `status` flag in response data - StatusIsFalse: `status` flag in response data is `false`. Contains `String?` - description of error, that occurred on a remote server - UnknownError: Unknown error occurred when parsing response */ public enum ResultParsing: ErrorType, CustomLocalizedDescriptionConvertible { /// Request returned response `NSData`, that can't be represented as `[String: AnyObject]` case CantRepresentResultAsDictionary /** Request returned response `NSData`, that can't be serialized to JSON. Contains `NSError?` - description of error, that occurred on serialization attempt */ case JSONSerializationError(NSError) /// There is no expexted `status` flag in response data case NoStatus /** `status` flag in response data is `false`. Contains `String?` - description of error, that occurred on a remote server */ case StatusIsFalse(String?) /// Unknown error occurred when parsing response case UnknownError /// A string containing the localized **template** of the object. (read-only) private var localizedTemplate: String { let enumPresentation: String switch self { case StatusIsFalse: enumPresentation = "StatusIsFalse" break default: enumPresentation = "\(self)" break } return GlobalMessageService.bundle.localizedStringForKey( "ResultParsing.\(enumPresentation)", value: .None, table: "GlobalMessageServiceErrors") } /// A string containing the localized description of the object. (read-only) public var localizedDescription: String { let localizedString: String switch self { case StatusIsFalse(let errorString): localizedString = String(format: localizedTemplate, errorString ?? "") break default: localizedString = localizedTemplate break } return localizedString } } } // MARK: - GlobalMessageServiceError.Request public extension GlobalMessageServiceError { /** Enum represents request errors - Error: Request failed. Contains a pointer to `NSError` object. - ParametersSerializationError: Failed to serialize parameters, passed to request. Contains a pointer to `NSError` object. - UnknownError: Request failed but there is no any represenative error */ public enum Request: ErrorType, CustomLocalizedDescriptionConvertible { /// Request failed. Contains a pointer to `NSError` object. case Error(NSError) /// Failed to serialize parameters, passed to request. Contains a pointer to `NSError` object. case ParametersSerializationError(NSError) /// Request failed but there is no any represenative error case UnknownError /// A string containing the localized **template** of the object. (read-only) private var localizedTemplate: String { let enumPresentation: String switch self { case Error: enumPresentation = "Error" break case ParametersSerializationError: enumPresentation = "ParametersSerializationError" break default: enumPresentation = "\(self)" break } return GlobalMessageService.bundle.localizedStringForKey( "Request.\(enumPresentation)", value: .None, table: "GlobalMessageServiceErrors") } /// A string containing the localized description of the object. (read-only) public var localizedDescription: String { let localizedString: String switch self { case Error(let error): localizedString = String(format: localizedTemplate, error.localizedDescription) break case ParametersSerializationError(let error): localizedString = String(format: localizedTemplate, error.localizedDescription) break default: localizedString = localizedTemplate break } return localizedString } } } // MARK: - GlobalMessageServiceError.MessageFetcher public extension GlobalMessageServiceError { /** Enum represents errors occurred when retrieving messages - NoPhone: Subscribers profile has no phone number - CoreDataSaveError(NSError): An error occurred while saving new messages. Contains a pointer to `NSError` object. */ public enum MessageFetcher: ErrorType, CustomLocalizedDescriptionConvertible { /// Subscribers profile has no phone number case NoPhone /// An error occurred while saving new messages. Contains a pointer to `NSError` object. case CoreDataSaveError(NSError) /// A string containing the localized **template** of the object. (read-only) private var localizedTemplate: String { let enumPresentation: String switch self { case CoreDataSaveError: enumPresentation = "CoreDataSaveError" break default: enumPresentation = "\(self)" break } return GlobalMessageService.bundle.localizedStringForKey( "MessageFetcher.\(enumPresentation)", value: .None, table: "GlobalMessageServiceErrors") } /// A string containing the localized description of the object. (read-only) public var localizedDescription: String { let localizedString: String switch self { case CoreDataSaveError(let error): localizedString = String(format: localizedTemplate, error.localizedDescription) break default: localizedString = localizedTemplate break } return localizedString } } }
apache-2.0
ea0ac0c7a937885871bde263d4263ca9
31.763819
98
0.709433
5.307285
false
false
false
false
mathewsheets/SwiftLearningExercises
Exercise_6.playground/Sources/Functions.swift
1
2990
import Foundation public typealias Student = [String:String] func iterator(students: [Student], closure: (_ student: Student) -> Void) { for index in 0..<students.count { closure(students[index]) } } // Iterate over each element in the array public func each(students: [Student], closure: (_ student: Student, _ index: Int) -> Void) { var index = 0 iterator(students: students) { closure($0, index) index += 1 } } // Returns true if all of the elements is not false public func all(students: [Student], closure: (_ student: Student) -> Bool) -> Bool { var all = true iterator(students: students) { (student) -> Void in if all && !closure(student) { all = false } } return all } // Returns true if at least one of the elements is not false public func any(students: [Student], closure: (_ student: Student) -> Bool) -> Bool { var any = false iterator(students: students) { (student) -> Void in if !any && closure(student) { any = true } } return any } // Returns the index at which element can be found public func indexOf(students: [Student], closure: (_ student: Student) -> Bool) -> Int? { var index = -1 var found = false iterator(students: students) { (student) -> Void in if !found { if closure(student) { found = true } index += 1 } } return index == -1 || !found ? nil : index } // Returns true if the element is present public func contains(students: [Student], closure: (_ student: Student) -> Bool) -> Bool { var found = false iterator(students: students) { (student) -> Void in if !found && closure(student) { found = true } } return found } // Returns an array of all the elements that pass a truth test public func filter(students: [Student], closure: (_ student: Student) -> Bool) -> [Student]? { var filter = [Student]() iterator(students: students) { (student) -> Void in if closure(student) { filter.append(student) } } return !filter.isEmpty ? filter : nil } // Returns the elements in the array without the elements that pass a truth test public func reject(students: [Student], closure: (_ student: Student) -> Bool) -> [Student]? { var keep = [Student]() iterator(students: students) { (student) -> Void in if !closure(student) { keep.append(student) } } return !keep.isEmpty ? keep : nil } // Returns an array of a specific value from all the elements public func pluck(students: [Student], closure: (_ student: Student) -> String) -> [String] { var plucked = [String]() iterator(students: students) { plucked.append(closure($0)) } return plucked }
mit
f06676bee6d62466c9bdae2a1f80aa1b
21.148148
94
0.571906
4.199438
false
false
false
false
networkextension/SSencrypt
SSencrypt/SFEncrypt.swift
1
30965
//Copyright (c) 2016, networkextension //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, this //list of conditions and the following disclaimer. // //* Redistributions in binary form must reproduce the above copyright notice, //this list of conditions and the following disclaimer in the documentation //and/or other materials provided with the distribution. // //* Neither the name of SSencrypt nor the names of its //contributors may be used to endorse or promote products derived from //this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE //IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE //FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL //DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR //SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE //OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation import CommonCrypto import Security let supported_ciphers_iv_size = [ 0, 0, 16, 16, 16, 16, 8, 16, 16, 16, 8, 8, 8, 8, 16, 8, 8, 12 ]; let supported_ciphers_key_size = [ 0, 16, 16, 16, 24, 32, 16, 16, 24, 32, 16, 8, 16, 16, 16, 32, 32, 32 ]; let SODIUM_BLOCK_SIZE:UInt64 = 64 public enum CryptoMethod:Int,CustomStringConvertible{ //case NONE = -1 case TABLE = 0 case RC4 = 1 case RC4_MD5 = 2 case AES_128_CFB = 3 case AES_192_CFB = 4 case AES_256_CFB = 5 case BF_CFB = 6 case CAMELLIA_128_CFB = 7 case CAMELLIA_192_CFB = 8 case CAMELLIA_256_CFB = 9 case CAST5_CFB = 10 case DES_CFB = 11 case IDEA_CFB = 12 case RC2_CFB = 13 case SEED_CFB = 14 case SALSA20 = 15 case CHACHA20 = 16 case CHACHA20IETF = 17 public var description: String { switch self { //case NONE: return "NONE" case TABLE: return "TABLE" case RC4: return "RC4" case RC4_MD5: return "RC4-MD5" case AES_128_CFB: return "AES-128-CFB" case AES_192_CFB: return "AES_192-CFB" case AES_256_CFB: return "AES-256-CFB" case BF_CFB: return "BF-CFB" case CAMELLIA_128_CFB: return "CAMELLIA-128-CFB" case CAMELLIA_192_CFB: return "CAMELLIA-192-CFB" case CAMELLIA_256_CFB: return "CAMELLIA-256-CFB" case CAST5_CFB: return "CAST5-CFB" case DES_CFB: return "DES-CFB" case IDEA_CFB: return "IDEA-CFB" case RC2_CFB: return "RC2-CFB" case SEED_CFB: return "SEED-CFB" case SALSA20: return "SALSA20" case CHACHA20: return "CHACHA20" case CHACHA20IETF: return "CHACHA20IETF" } } public var support:Bool { switch self { //case NONE: return false case TABLE: return false case RC4: return false case RC4_MD5: return false case AES_128_CFB: return true case AES_192_CFB: return true case AES_256_CFB: return true case BF_CFB: return false case CAMELLIA_128_CFB: return false case CAMELLIA_192_CFB: return false case CAMELLIA_256_CFB: return false case CAST5_CFB: return false case DES_CFB: return false case IDEA_CFB: return false case RC2_CFB: return false case SEED_CFB: return false case SALSA20: return true case CHACHA20: return true case CHACHA20IETF: return true } } public var ccmode:CCMode { switch self { // public var kCCModeECB: Int { get } 1 // public var kCCModeCBC: Int { get } 2 // public var kCCModeCFB: Int { get } 3 // public var kCCModeCTR: Int { get } 4 // public var kCCModeF8: Int { get } 5// Unimplemented for now (not included) // public var kCCModeLRW: Int { get } 6// Unimplemented for now (not included) // public var kCCModeOFB: Int { get } 7 // public var kCCModeXTS: Int { get } 8 // public var kCCModeRC4: Int { get } 9 // public var kCCModeCFB8: Int { get } 10 case RC4: return 9//4 case RC4_MD5: return 9//4 case AES_128_CFB: return 3 case AES_192_CFB: return 3 case AES_256_CFB: return 3 case BF_CFB: return 3 // case CAMELLIA_128_CFB: return false // case CAMELLIA_192_CFB: return false // case CAMELLIA_256_CFB: return false case CAST5_CFB: return 3 case DES_CFB: return 3 case IDEA_CFB: return 3 case RC2_CFB: return 3 case SEED_CFB: return 3 // case SALSA20: return true // case CHACHA20: return true // case CHACHA20IETF: return true default: return UInt32.max } } // func supported_ciphers() ->CCAlgorithm { // if self.rawValue != -1{ // let algorithm = findCCAlgorithm(Int32(self.rawValue)) // return algorithm // }else { // return UInt32.max // } // // } public var iv_size:Int { return supported_ciphers_iv_size[self.rawValue] } public var key_size:Int { return supported_ciphers_key_size[self.rawValue] } init(cipher:String){ let up = cipher.uppercaseString var raw = 0 switch up { //case "NONE": raw = -1 case "TABLE": raw = 0 case "RC4": raw = 1 case "RC4-MD5": raw = 2 case "AES-128-CFB": raw = 3 case "AES-192-CFB": raw = 4 case "AES-256-CFB": raw = 5 case "BF-CFB": raw = 6 case "CAMELLIA-128-CFB": raw = 7 case "CAMELLIA-192-CFB": raw = 8 case "CAMELLIA-256-CFB": raw = 9 case "CAST5-CFB": raw = 10 case "DES-CFB": raw = 11 case "IDEA-CFB": raw = 12 case "RC2-CFB": raw = 13 case "SEED-CFB": raw = 14 case "SALSA20": raw = 15 case "CHACHA20": raw = 16 case "CHACHA20IETF": raw = 17 default: raw = 0 } self = CryptoMethod(rawValue:raw)! } } let config_ciphers = [ "table":false, "rc4":false, "rc4-md5":false, "aes-128-cfb":false, "aes-192-cfb":false, "aes-256-cfb":true, "bf-cfb":false, "camellia-128-cfb":false, "camellia-192-cfb":false, "camellia-256-cfb":false, "salsa20":false, "chacha20":false, "chacha20-ietf":false ] let ONETIMEAUTH_BYTES = 10 let MAX_KEY_LENGTH = 64 let MAX_IV_LENGTH = 16 let CLEN_BYTES = 2 class enc_ctx { var m:CryptoMethod static var sodiumInited = false var counter:UInt64 = 0 var IV:NSData var ctx:CCCryptorRef func test (){ let abcd = "aaaa" if abcd.hasPrefix("aa"){ } } static func setupSodium() { if !enc_ctx.sodiumInited { if sodium_init() == -1 { //print("sodium_init failure") AxLogger.log("sodium_init failure",level: .Error) } } } static func create_enc(op:CCOperation,key:NSData,iv:NSData,m:CryptoMethod) -> CCCryptorRef { let algorithm:CCAlgorithm = findCCAlgorithm(Int32(m.rawValue)) var cryptor :CCCryptorRef = nil let key_size = m.key_size // print("key_size:\(m.key_size) iv_size:\(m.iv_size)") // print("iv :\(iv)") // print("key: \(key)") let createDecrypt:CCCryptorStatus = CCCryptorCreateWithMode(op, // operation m.ccmode, // mode CTR kCCModeRC4= 9 algorithm,//CCAlgorithm(0),//kCCAlgorithmAES, // Algorithm CCPadding(0), // padding iv.bytes, // can be NULL, because null is full of zeros key.bytes, // key key_size, // keylength nil, //const void *tweak 0, //size_t tweakLength, 0, //int numRounds, 0, //CCModeOptions options, &cryptor); //CCCryptorRef *cryptorRef if (createDecrypt == CCCryptorStatus(0)){ return cryptor }else { AxLogger.log("create crypto ctx error") return nil } } init(key:NSData,iv:NSData,encrypt:Bool,method:CryptoMethod){ if method.iv_size != iv.length { fatalError() } let c = findCCAlgorithm(Int32(method.rawValue)) //m.supported_ciphers() var true_key:NSData if method == .RC4_MD5 { let key_iv = NSMutableData.init(data: key) key_iv.length = 16 key_iv.appendData(iv) true_key = key_iv.md5x //iv_len = 0; }else { true_key = key } m = method if c != UInt32.max { if encrypt { ctx = enc_ctx.create_enc(CCOperation(0), key: true_key,iv: iv,m:method) }else { ctx = enc_ctx.create_enc(CCOperation(1), key: true_key,iv: iv,m:method) } IV = iv }else { ctx = nil if method == .SALSA20 || method == .CHACHA20 || method == .CHACHA20IETF { //let sIV = NSMutableData.init(data: iv) //sIV.length = 16 IV = iv enc_ctx.setupSodium() }else { IV = iv } } } func setIV(iv:NSData){ } deinit { if ctx != nil { CCCryptorRelease(ctx) } } } class SSEncrypt { var m:CryptoMethod var testenable:Bool = false var send_ctx:enc_ctx? var recv_ctx:enc_ctx? //let block_size = 16 var ramdonKey:NSData? var ivBuffer:NSMutableData = NSMutableData.init() static var iv_cache:[NSData] = [] static func have_iv(i:NSData,m:CryptoMethod) ->Bool { let x = CryptoMethod.RC4_MD5 if m.rawValue >= x.rawValue { for x in SSEncrypt.iv_cache { if x.isEqualToData(i){ return true } } } SSEncrypt.iv_cache.append(i) return false } deinit { } func dataWithHexString(hex: String) -> NSData { var hex = hex let data = NSMutableData() while(hex.characters.count > 0) { let c: String = hex.substringToIndex(hex.startIndex.advancedBy(2)) hex = hex.substringFromIndex(hex.startIndex.advancedBy(2)) var ch: UInt32 = 0 NSScanner(string: c).scanHexInt(&ch) data.appendBytes(&ch, length: 1) } return data } init(password:String,method:String) { m = CryptoMethod.init(cipher: method) //print("method:\(m.description)") ramdonKey = SSEncrypt.evpBytesToKey(password,keyLen: m.key_size) // if m.rawValue >= CryptoMethod.SALSA20.rawValue { // let k = NSMutableData.init(data: ramdonKey!) // k.length = 64 // ramdonKey = k // } //print("\(m.description) key_size:\(m.key_size) iv_size:\(m.iv_size) ramdonkey len\(ramdonKey!.length)") //let a = "d5921d56e0db2bd5"//0000000000000000" //let b = dataWithHexString(a) //let c = NSMutableData.init(data: b) //c.length = 16 let iv = SSEncrypt.getSecureRandom(m.iv_size) //AxLogger.log("\(m.key_size) \(m.iv_size) \(method)",level: .Debug) // let x = password.dataUsingEncoding(NSUTF8StringEncoding)! // let data = NSMutableData.init(length: 32) //memcpy((data?.mutableBytes)!, x.bytes, x.length) //receive_ctx = create_enc(CCOperation(kCCDecrypt), key: key) send_ctx = enc_ctx.init(key: ramdonKey!, iv: iv, encrypt: true,method:m ) debugLog("cache add iv:\(iv) ") // SSEncrypt.iv_cache.append(iv) } func recvCTX(iv:NSData){ debugLog("use iv create ctx \(iv)") if SSEncrypt.have_iv(iv,m:m) && !testenable{ //print("cryto iv dup error") NSLog("iv_cachae %@",SSEncrypt.iv_cache) NSLog("recv_ctx_iv: %@",iv) AxLogger.log("cryto iv dup error") }else { recv_ctx = enc_ctx.init(key: ramdonKey!, iv: iv, encrypt: false,method:m) } } static func evpBytesToKey(password:String, keyLen:Int) ->NSData { let md5Len:Int = 16 let cnt = (keyLen - 1)/md5Len + 1 let m = NSMutableData.init(length: cnt*md5Len)! let bytes = password.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! // memcpy((m?.mutableBytes)!, bytes.bytes , password.characters.count) let md5 = bytes.md5 m.setData(md5) // Repeatedly call md5 until bytes generated is enough. // Each call to md5 uses data: prev md5 sum + password. let d = NSMutableData.init(length: md5Len+bytes.length)! //d := make([]byte, md5Len+len(password)) var start = 0 for _ in 0 ..< cnt {//最长32,算法还不支持>32 的情况 start += md5Len memcpy(d.mutableBytes,m.bytes , m.length) memcpy(d.mutableBytes+md5Len, bytes.bytes, bytes.length) let md5 = d.md5 m.appendData(md5) if m.length >= keyLen { break; } } m.length = keyLen return m } func crypto_stream_xor_ic(cd:NSMutableData,md:NSData,mlen: UInt64, nd:NSData, ic:UInt64, kd:NSData) ->Int32{ let c:UnsafeMutablePointer<CUnsignedChar> = UnsafeMutablePointer<CUnsignedChar>.init(cd.mutableBytes) let m:UnsafePointer<UInt8> = UnsafePointer<UInt8>.init(md.bytes) let n:UnsafePointer<UInt8> = UnsafePointer<UInt8>.init(nd.bytes) let k:UnsafePointer<UInt8> = UnsafePointer<UInt8>.init(kd.bytes) var ret:Int32 = 0 //let xx = Int32(send_ctx!.m.rawValue) // int crypto_stream_chacha20_xor_ic(unsigned char *c, const unsigned char *m, // unsigned long long mlen, // const unsigned char *n, uint64_t ic, // const unsigned char *k); switch send_ctx!.m{ case .SALSA20: ret = crypto_stream_salsa20_xor_ic(c, m, mlen, n, ic, k); //return crypto_stream_xor_icc(c, m, mlen, n, ic, k,xx) case .CHACHA20: ret = crypto_stream_chacha20_xor_ic(c, m, mlen, n, ic, k); //return crypto_stream_xor_icc(c, m, mlen, n, ic, k,xx) case .CHACHA20IETF: ret = crypto_stream_chacha20_ietf_xor_ic(c, m, mlen, n, UInt32(ic), k); default: break } //print("sodium ret \(ret)") return ret } func genData(encrypt_bytes:NSData) ->NSData?{ //Empty IV: initialization vector //self.iv = ivt let cipher:NSData? if recv_ctx == nil { let iv_len = send_ctx!.m.iv_size if encrypt_bytes.length + ivBuffer.length < iv_len { ivBuffer.appendData(encrypt_bytes) AxLogger.log("recv iv not finished,waiting recv iv") return nil }else { let iv_need_len = iv_len - ivBuffer.length ivBuffer.appendData(encrypt_bytes.subdataWithRange(NSMakeRange(0,iv_need_len))) recvCTX(ivBuffer) // //ivBuffer cipher = encrypt_bytes.subdataWithRange(NSMakeRange(iv_need_len,encrypt_bytes.length - iv_need_len )); } // print("iv \(iv) \(iv_len)") // print("ramdonKey \(ramdonKey!)") // print("data \(cipher!) \(cipher?.length) \(encrypt_bytes.length - iv_len)") // print("encrypt_bytes 000 \(encrypt_bytes)") }else { cipher = encrypt_bytes } return cipher } func decrypt(encrypt_bytes:NSData) ->NSData?{ if ( encrypt_bytes.length == 0 ) { return nil; } if recv_ctx == nil && encrypt_bytes.length < send_ctx!.m.iv_size { AxLogger.log("socket read less iv_len",level: .Error) } if let left = genData(encrypt_bytes) { // Alloc Data Out guard let ctx = recv_ctx else { //print("ctx error") AxLogger.log("recv_ctx not init ",level: .Error) return nil } if ctx.m.rawValue >= CryptoMethod.SALSA20.rawValue { // print("iv \(ctx.IV)") // print("ramdonKey \(ramdonKey!)") // print("data \(left)") let padding = ctx.counter % SODIUM_BLOCK_SIZE; let cipher = NSMutableData.init(length: left.length + Int(padding)) //cipher.length += encrypt_bytes.length // brealloc(cipher, iv_len + (padding + cipher->len) * 2, capacity); var plain:NSMutableData if padding != 0 { plain = NSMutableData.init(length: Int(padding))! plain.appendData(left) //plain.length = plain.length + Int(padding) // brealloc(plain, plain->len + padding, capacity); // memmove(plain->array + padding, plain->array, plain->len); //sodium_memzero(plain->array, padding); }else { plain = NSMutableData.init(data: left) } //let enc_key = NSMutableData.init(data: ramdonKey!) //enc_key.length = ctx.m.key_size // let ptr:UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.init((cipher?.mutableBytes)!) // let ptr2:UnsafePointer<UInt8> = UnsafePointer<UInt8>.init(encrypt_bytes.bytes) //let vvv = NSMutableData.init(data: ctx.IV) //vvv.length = 16 crypto_stream_xor_ic(cipher! , md: plain, mlen: UInt64(plain.length), nd: ctx.IV, ic: ctx.counter / SODIUM_BLOCK_SIZE, kd: ramdonKey!) ctx.counter += UInt64(left.length) let result = cipher!.subdataWithRange(NSMakeRange(Int(padding),left.length)) return result }else { let cipherDataDecrypt:NSMutableData = NSMutableData.init(length: left.length)!; //alloc number of bytes written to data Out var outLengthDecrypt:NSInteger = 0 //Update Cryptor let updateDecrypt:CCCryptorStatus = CCCryptorUpdate(ctx.ctx, left.bytes, //const void *dataIn, left.length, //size_t dataInLength, cipherDataDecrypt.mutableBytes, //void *dataOut, cipherDataDecrypt.length, // size_t dataOutAvailable, &outLengthDecrypt); // size_t *dataOutMoved) if (updateDecrypt == CCCryptorStatus(0)) { //Cut Data Out with nedded length cipherDataDecrypt.length = outLengthDecrypt; // Data to String //NSString* cipherFinalDecrypt = [[NSString alloc] initWithData:cipherDataDecrypt encoding:NSUTF8StringEncoding]; //Final Cryptor let final:CCCryptorStatus = CCCryptorFinal(ctx.ctx, //CCCryptorRef cryptorRef, cipherDataDecrypt.mutableBytes, //void *dataOut, cipherDataDecrypt.length, // size_t dataOutAvailable, &outLengthDecrypt); // size_t *dataOutMoved) if (final != CCCryptorStatus( 0)) { AxLogger.log("decrypt CCCryptorFinal failure") //Release Cryptor //CCCryptorStatus release = //CCCryptorRelease(cryptor); //CCCryptorRef cryptorRef } return cipherDataDecrypt ;//cipherFinalDecrypt; }else { AxLogger.log("decrypt CCCryptorUpdate failure") } } }else { AxLogger.log("decrypt no Data") } return nil } static func getSecureRandom(bytesCount:Int) ->NSData { // Swift //import Security //let bytesCount = 4 // number of bytes //var randomNum: UInt32 = 0 // variable for random unsigned 32 bit integer var randomBytes = [UInt8](count: bytesCount, repeatedValue: 0) // array to hold randoms bytes // Gen random bytes SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomBytes) // Turn bytes into data and pass data bytes into int return NSData(bytes: randomBytes, length: bytesCount) //getBytes(&randomNum, length: bytesCount) } // func padding(d:NSData) ->NSData{ // let l = d.length % block_size // if l != 0 { // let x = NSMutableData.init(data: d) // x.length += l // return x // }else { // return d // } // } func encrypt(encrypt_bytes:NSData) ->NSData?{ //let iv:NSData = NSData(); //[NSMutableData dataWithLength:kCCBlockSizeAES128] //let encrypt_bytes = padding(encrypt_bytes_org) //alloc number of bytes written to data Out guard let ctx = send_ctx else { AxLogger.log("ss ctx error") return nil } //Update Cryptor if ctx.m.rawValue >= CryptoMethod.SALSA20.rawValue { debugLog("111 encrypt") let padding = ctx.counter % SODIUM_BLOCK_SIZE; let cipher = NSMutableData.init(length: 2*(encrypt_bytes.length + Int(padding))) //cipher.length += encrypt_bytes.length // brealloc(cipher, iv_len + (padding + cipher->len) * 2, capacity); var plain:NSMutableData if padding != 0 { plain = NSMutableData.init(length: Int(padding))! plain.appendData(encrypt_bytes) //plain.length = plain.length + Int(padding) // brealloc(plain, plain->len + padding, capacity); // memmove(plain->array + padding, plain->array, plain->len); //sodium_memzero(plain->array, padding); }else { plain = NSMutableData.init(data: encrypt_bytes) } let riv = NSMutableData.init(data: ctx.IV) riv.length = 32 debugLog("222 encrypt ") //let enc_key = NSMutableData.init(data: ramdonKey!) //enc_key.length = send_ctx!.m.key_size // let ptr:UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.init((cipher?.mutableBytes)!) // let ptr2:UnsafePointer<UInt8> = UnsafePointer<UInt8>.init(encrypt_bytes.bytes) debugLog("333 encrypt") crypto_stream_xor_ic(cipher! , md: plain, mlen: UInt64(plain.length), nd: riv,//ctx.IV, ic: ctx.counter / SODIUM_BLOCK_SIZE, kd: ramdonKey!) var result:NSMutableData if ctx.counter == 0 { result = NSMutableData.init(data: ctx.IV) result.length = m.iv_size }else { result = NSMutableData.init() } ctx.counter += UInt64(encrypt_bytes.length) // print("cipher \(cipher)") // if padding != 0 { //// memmove(cipher->array + iv_len, //// cipher->array + iv_len + padding, cipher->len); // result.appendData(cipher!.subdataWithRange(NSMakeRange(Int(padding), encrypt_bytes.length // ))) // }else { // result.appendData(cipher!.subdataWithRange(NSMakeRange(0, encrypt_bytes.length // ))) // // } result.appendData(cipher!.subdataWithRange(NSMakeRange(Int(padding), encrypt_bytes.length ))) //debugLog("000 encrypt") return result }else { var outLength:NSInteger = 0 ; // Alloc Data Out let cipherData:NSMutableData = NSMutableData.init(length: encrypt_bytes.length)!; let update:CCCryptorStatus = CCCryptorUpdate(ctx.ctx, encrypt_bytes.bytes, encrypt_bytes.length, cipherData.mutableBytes, cipherData.length, &outLength); if (update == CCCryptorStatus(0)) { //Cut Data Out with nedded length cipherData.length = outLength; //Final Cryptor let final:CCCryptorStatus = CCCryptorFinal(ctx.ctx, //CCCryptorRef cryptorRef, cipherData.mutableBytes, //void *dataOut, cipherData.length, // size_t dataOutAvailable, &outLength); // size_t *dataOutMoved) if (final == CCCryptorStatus(0)) { if ctx.counter == 0 { ctx.counter += 1 let d:NSMutableData = NSMutableData() d.appendData(ctx.IV); d.appendData(cipherData) return d }else { return cipherData } }else { AxLogger.log("CCCryptorFinal error \(final)") } //AxLogger.log("cipher length:\(d.length % 16)") }else { AxLogger.log("CCCryptorUpdate error \(update)") } } return nil } static func encryptErrorReason(r:Int32) { // kCCSuccess = 0, // kCCParamError = -4300, // kCCBufferTooSmall = -4301, // kCCMemoryFailure = -4302, // kCCAlignmentError = -4303, // kCCDecodeError = -4304, // kCCUnimplemented = -4305, // kCCOverflow = -4306, // kCCRNGFailure = -4307, var message:String = "undefine error" switch r{ case -4300: message = "kCCParamError" case -4301: message = "kCCBufferTooSmall" case -4302: message = "kCCMemoryFailure" case -4303: message = "kCCAlignmentError" case -4304: message = "kCCDecodeError" case -4305: message = "kCCUnimplemented" case -4306: message = "kCCOverflow" case -4307: message = "kCCRNGFailure" default: break } print("\(message)") } func ss_onetimeauth(buffer:NSData) ->NSData { let keyData = NSMutableData.init(data: send_ctx!.IV) //let key_size = send_ctx!.m.key_size //let ramdonK2 = ramdonKey?.subdataWithRange(NSMakeRange(0, key_size)) // var true_key:NSData // if send_ctx!.m == .RC4_MD5 { // let key_iv = NSMutableData.init(data: ramdonKey!) // key_iv.length = 16 // key_iv.appendData(send_ctx!.IV) // // // true_key = key_iv.md5x // //iv_len = 0; // }else { // true_key = ramdonKey! // } keyData.appendData(ramdonKey!) let hash = buffer.hmacsha1(keyData) //let result = NSMutableData.init(data: buffer) //result.appendData(hash) //=result.sha1 return hash } func ss_gen_hash(buffer:NSData,counter:Int32) ->NSData { let blen = buffer.length var chunk_len:UInt16 = UInt16(blen).bigEndian var c = counter.bigEndian let keyData = NSMutableData.init(data: send_ctx!.IV) keyData.appendBytes(&c, length: 4) let hash = buffer.hmacsha1(keyData) let result = NSMutableData.init(bytes: &chunk_len, length: 2) result.appendData(hash) //result.appendData(buffer) //=result.sha1 return result } }
bsd-3-clause
3c720e865bca69b781bfcba4dcf41c2b
36.689403
133
0.506932
4.119143
false
false
false
false
trill-lang/trill
Sources/Runtime/RuntimeSearcher.swift
2
2709
import Foundation #if os(macOS) import Darwin #elseif os(Linux) import Glibc #endif public struct RuntimeLocation { public let includeDir: URL public let header: URL public let libraryDir: URL public let library: URL public let stdlib: URL } func findObject(forAddress address: UnsafeRawPointer) -> URL? { var info = dl_info() guard dladdr(address, &info) != 0 else { return nil } let path = String(cString: info.dli_fname) return URL(fileURLWithPath: path) } public enum RuntimeLocationError: Error { case couldNotLocateBinary case invalidInstallDir(URL) case invalidIncludeDir(URL) case invalidHeader(URL) case invalidLibDir(URL) case invalidLibrary(URL) case invalidStdLibDir(URL) } public enum RuntimeLocator { public static func findRuntime(forAddress address: UnsafeRawPointer) throws -> RuntimeLocation { guard let url = findObject(forAddress: address) else { throw RuntimeLocationError.couldNotLocateBinary } // Walk up the directory tree until we find `bin`. var installDir = url while installDir.lastPathComponent != "bin" { installDir = installDir.deletingLastPathComponent() } // Walk one directory above `bin` installDir = installDir.deletingLastPathComponent() guard FileManager.default.fileExists(atPath: installDir.path) else { throw RuntimeLocationError.invalidInstallDir(installDir) } let includeDir = installDir.appendingPathComponent("include") guard FileManager.default.fileExists(atPath: includeDir.path) else { throw RuntimeLocationError.invalidIncludeDir(includeDir) } let header = includeDir.appendingPathComponent("runtime") .appendingPathComponent("trill.h") guard FileManager.default.fileExists(atPath: header.path) else { throw RuntimeLocationError.invalidHeader(header) } let libraryDir = installDir.appendingPathComponent("lib") guard FileManager.default.fileExists(atPath: libraryDir.path) else { throw RuntimeLocationError.invalidLibDir(libraryDir) } let library = libraryDir.appendingPathComponent("libtrillRuntime.a") guard FileManager.default.fileExists(atPath: library.path) else { throw RuntimeLocationError.invalidLibrary(library) } let stdlib = installDir.appendingPathComponent("stdlib") guard FileManager.default.fileExists(atPath: stdlib.path) else { throw RuntimeLocationError.invalidStdLibDir(stdlib) } return RuntimeLocation(includeDir: includeDir, header: header, libraryDir: libraryDir, library: library, stdlib: stdlib) } }
mit
c44298a04b3f908bbd12ed8eaf74299f
33.730769
98
0.714286
4.686851
false
false
false
false
amoriello/trust-line-ios
Trustline/AccountsTableViewController.swift
1
9569
// // PasswordsTableViewController.swift // Trustline // // Created by matt on 05/10/2015. // Copyright © 2015 amoriello.hutti. All rights reserved. // import UIKit import CoreData class AccountsTableViewController: UITableViewController, AddAccountDelegate, NSFetchedResultsControllerDelegate { // MARK: - Injected var dataController: DataController! var token :Token! var profile: CDProfile! // MARK: - Attributes var navigationLocked = true; var fetchedAccountController: NSFetchedResultsController! override func viewDidLoad() { super.viewDidLoad() unlockCapabilities() } override func viewWillAppear(animated: Bool) { dataController = (UIApplication.sharedApplication().delegate as! AppDelegate).dataController initializeFetchedAccountController(dataController.managedObjectContext) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initializeFetchedAccountController(moc: NSManagedObjectContext) { let request = NSFetchRequest(entityName: "CDAccount") let firstLetterSort = NSSortDescriptor(key: "firstLetterAsCap", ascending: true) let accountTitleSort = NSSortDescriptor(key: "title", ascending: true) request.sortDescriptors = [firstLetterSort, accountTitleSort] fetchedAccountController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: "firstLetterAsCap", cacheName: "rootCache") self.fetchedAccountController.delegate = self do { try self.fetchedAccountController.performFetch() } catch { fatalError("Failed to initialize fetchedAccountController: \(error)") } } func configureCell(cell: AccountTableViewCell, indexPath: NSIndexPath) { let account = accountAtIndexPath(indexPath) cell.account = account cell.keyboardTriggeredHandler = self.onKeyboardTriggered cell.showPasswordTriggeredHandler = self.onShowPasswordTriggered cell.clipboardTriggeredHandler = self.onClipboardTriggered } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return fetchedAccountController.sections!.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let sections = fetchedAccountController.sections! let sectionInfo = sections[section] return sectionInfo.name } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sections = fetchedAccountController.sections! let sectionInfo = sections[section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("AccountCell", forIndexPath: indexPath) as! AccountTableViewCell; configureCell(cell, indexPath: indexPath) return cell; } // MARK: - NSFetchedResultsControllerDelegate func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Move: break case .Update: break } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: let cell = self.tableView.cellForRowAtIndexPath(indexPath!)! as! AccountTableViewCell self.configureCell(cell, indexPath: indexPath!) case .Move: self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) self.tableView.insertRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if navigationLocked { return } if let identifier = segue.identifier { switch identifier { case "showAccountDetail": let accountDetailVC = segue.destinationViewController as! AccountDetailTableViewController if let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell) { accountDetailVC.account = accountAtIndexPath(indexPath) } case "addAccount": let addAccountVC = segue.destinationViewController as! AddAccountViewController addAccountVC.token = token addAccountVC.profile = profile addAccountVC.dataController = dataController addAccountVC.delegate = self default: break; } } } func lockCapabilities() { navigationLocked = true; navigationController?.navigationBar.userInteractionEnabled = false } func unlockCapabilities() { navigationLocked = false; navigationController?.navigationBar.userInteractionEnabled = true } // MARK: - AddAccountDelegate func accoundAdded(controller: AddAccountViewController, newAccount: CDAccount) { dataController.save() controller.navigationController?.popViewControllerAnimated(true) } // MARK: - Helper Methods func accountAtIndexPath(indexPath: NSIndexPath) -> CDAccount { return fetchedAccountController.objectAtIndexPath(indexPath) as! CDAccount } func phoneticDescription(password: String) -> String { let phoneticAlphabet : [Character : String] = [ "a" : "alfa", "b" : "bravo", "c" : "charlie", "d" : "delta", "e" : "echo", "f" : "foxtrot", "g" : "golf", "h" : "hotel", "i" : "india", "j" : "juliette", "k" : "kilo", "l" : "lima", "m" : "mike", "n" : "november", "o" : "oscar", "p" : "papa", "q" : "quebec", "r" : "romeo", "s" : "sierra", "t" : "tango", "u" : "uniform", "v" : "victor", "w" : "whiskey", "x" : "xray", "y" : "yankee", "z" : "zulu"] var resultString = "" for character in password.characters { let lowerCaseCharacter = String(character).lowercaseString.characters.first!; if let phoneticName = phoneticAlphabet[lowerCaseCharacter] { if character == lowerCaseCharacter { resultString += " " + phoneticName } else { resultString += " " + phoneticName.uppercaseString } } else { // Character is a numeric or special one resultString += " " + String(character) } } return resultString } // MARK: - Shortcuts Events Management func onKeyboardTriggered(account: CDAccount) { if token == nil { showMessage("Cannot handle action", subtitle: "Token is not connected") return } var additionalKeys = [UInt8](); additionalKeys.append(0xB0); showMessage("Sending Keystrokes...", hideOnTap: false, showAnnimation: true) token.writePassword(account.enc_password.arrayOfBytes(), additionalKeys: additionalKeys) { (error) in if let err = error { showError("Woww...", error: err) } else { self.dataController.updateUsageInfo(account, type: .Keyboard) self.tableView.reloadData() hideMessage() } } } func onShowPasswordTriggered(account: CDAccount) { if token == nil { showMessage("Cannot handle action", subtitle: "Token is not connected") return } showMessage("Retrieving password...", hideOnTap: false, showAnnimation: true) token.retrievePassword(account.enc_password.arrayOfBytes()) { (clearPassword, error) in if let err = error { showError(error: err) } else { let passwordFont = UIFont(name: "Menlo-Regular", size: 18) let phoneticDesciprion = self.phoneticDescription(clearPassword) showMessage(clearPassword, subtitle: phoneticDesciprion, font: passwordFont) self.dataController.updateUsageInfo(account, type: .Display) } } } func onClipboardTriggered(account: CDAccount) { if token == nil { showMessage("Cannot handle action", subtitle: "Token is not connected") return } showMessage("Retrieving password...", hideOnTap: false, showAnnimation: true) token.retrievePassword(account.enc_password.arrayOfBytes()) { (clearPassword, error) in if let err = error { showError(error: err) } else { UIPasteboard.generalPasteboard().string = clearPassword; self.dataController.updateUsageInfo(account, type: .Clipboard) showMessage("Password copied to clipboard") } } } }
mit
58ce75f6f747be2ea60feca5dc7983cf
31.879725
209
0.683842
4.934502
false
false
false
false
PigDogBay/swift-utils
SwiftUtils/RandomQuery.swift
1
4856
// // RandomQuery.swift // SwiftUtils // // Created by Mark Bailey on 14/08/2020. // Copyright © 2020 MPD Bailey Technology. All rights reserved. // import Foundation public struct RandomQuery { let vowels = ["a","e","i","o","u"] let consonants = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"] let letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] let examples = ["m?g??","moonstarer","z9","james-bond","scrabb++","kayleigh*","super@ted","..112332", "r??p?????", "c??v?r","????ial","eprsu" , "manchester-united", "cli-ntea-stwood", "google++++", "stratus+", "sup@x?", "microsoft*", "?a???p??", "steam", "hearts", "@ace", "zslteram", "thidgof" , "m.z@", ".m.z.", "vegdances", "c....w...", "itchysemi", "w ackoanglo rocker", "*", "++++", "...", "@x@", "llan@", "British Broadcasting Corporation" , "$qautein","$grvceno","$dcmnuro","$glapemx","$inwdalf","$"] public init(){ } public func query() -> String{ let r = Int.random(in: 1...3) if r == 1 { return example() } let randomSearchType = SearchType.allCases.randomElement()! switch randomSearchType { case .crossword: return crossword() case .anagram: return anagram() case .twoWordAnagram: return twoWords() case .wildcard: return prefixSuffix() case .wildcardAndCrossword: return wildcardCrossword() case .blanks: return blankLetters() case .supergram: return supergram() case .codeword: return codeword() case .spellingBee: return spellingBee() } } public func anagram() -> String { let v = Int.random(in: 1...5) let c = Int.random(in: 2...10) return anagram(numberOfVowels: v, numberOfConsonants: c) } public func anagram(numberOfVowels v: Int, numberOfConsonants c: Int) -> String { var builder = "" for _ in 1...v { builder = builder + vowels.randomElement()! } for _ in 1...c { builder = builder + consonants.randomElement()! } return shuffle(ordered: builder) } public func crossword(numberOfLetters l : Int, numberOfUnknowns u : Int) -> String{ var builder = "" for _ in 1...l { builder = builder + letters.randomElement()! } for _ in 1...u { builder = builder + WordSearch.CROSSWORD_STR } return shuffle(ordered: builder) } public func crossword() -> String { let l = Int.random(in: 1...5) let u = Int.random(in: 2...10) return crossword(numberOfLetters: l, numberOfUnknowns: u) } public func twoWords() -> String { var anag = anagram() + WordSearch.TWO_WORD_STR if anag.first == " " || anag.last == " " { anag = shuffle(ordered: anag) } return shuffle(ordered: anag) } public func supergram() -> String { return anagram() + WordSearch.SUPERGRAM_STR } public func blankLetters() -> String { let b = Int.random(in: 1...3) var builder = anagram() for _ in 1...b { builder = builder + WordSearch.BLANK_STR } return builder } public func prefixSuffix() -> String { let v = Int.random(in: 1...2) let c = Int.random(in: 1...4) let anag = anagram(numberOfVowels: v, numberOfConsonants: c) + WordSearch.WILDCARD_STR return shuffle(ordered: anag) } public func wildcardCrossword() -> String { let l = Int.random(in: 1...3) let u = Int.random(in: 1...3) let anag = crossword(numberOfLetters: l, numberOfUnknowns: u) + WordSearch.WILDCARD_STR return shuffle(ordered: anag) } public func codeword()-> String { let c = Int.random(in: 1...2) var builder = anagram(numberOfVowels: 1, numberOfConsonants: c) + "11.." let r = Int.random(in: 1...3) if r > 2 { builder = builder + "33" } if r > 1 { builder = builder + "22" } return shuffle(ordered: builder) } public func spellingBee() -> String { let v = Int.random(in: 1...3) let c = Int.random(in: 4...6) return WordSearch.SPELLING_BEE_STR + anagram(numberOfVowels: v, numberOfConsonants: c) } public func example() -> String { return examples.randomElement()! } private func shuffle(ordered : String) -> String { var a = Array(ordered) a.shuffle() return String(a) } }
apache-2.0
2105cdda026e80e15ed2c9041b93d3c6
30.940789
160
0.522966
3.62584
false
false
false
false
Detailscool/YHFanfou
YHFanfou/Pods/OAuthSwift/OAuthSwift/NSURL+OAuthSwift.swift
22
722
// // NSURL+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension NSURL { func URLByAppendingQueryString(queryString: String) -> NSURL { if queryString.utf16.count == 0 { return self } var absoluteURLString = self.absoluteString if absoluteURLString.hasSuffix("?") { absoluteURLString = (absoluteURLString as NSString).substringToIndex(absoluteURLString.utf16.count - 1) } let URLString = absoluteURLString + (absoluteURLString.rangeOfString("?") != nil ? "&" : "?") + queryString return NSURL(string: URLString)! } }
mit
809efa7a1618f09e20c37a31578f98a3
23.066667
115
0.641274
4.658065
false
false
false
false
lukesutton/uut
Sources/PropertyValues-List.swift
1
1914
extension PropertyValues { public enum CounterReset: PropertyValue { case None case Name(String) case Number(Int) case Intial case Inherit public var stringValue: String { switch self { case let Name(s): return s case let Number(n): return String(n) default: return String(self).lowercaseString } } } public enum ListStyle: PropertyValue { case Config(ListStyleType, ListStylePosition, PropertyValues.URL) case Initial case Inherit public var stringValue: String { switch self { case let Config(style, pos, URL): return "\(style.stringValue) \(pos.stringValue) \(URL.stringValue)" default: return String(self).lowercaseString } } } public enum ListStylePosition: String, PropertyValue { case Inside = "inside" case Outside = "outside" case Initial = "initial" case Inherit = "inherit" public var stringValue: String { return rawValue } } public enum ListStyleType: String, PropertyValue { case Disc = "disc" case Armenian = "armenian" case Circle = "circle" case CJKIdeographic = "cjk-ideographic" case Decimal = "decimal" case DecimalLeadingZero = "decimal-leading-zero" case Georgian = "georgian" case Hebrew = "hebrew" case Hiragana = "hiragana" case HiraganaIroha = "hiragana-iroha" case Katakana = "katakana" case KatakanaIroha = "katakana-iroha" case LowerAlpha = "lower-alpha" case LowerGreek = "lower-greek" case LowerLatin = "lower-latin" case LowerRoman = "lower-roman" case None = "none" case Square = "square" case UpperAlpha = "upper-alpha" case UpperLatin = "upper-latin" case UpperRoman = "upper-roman" case Initial = "initial" case Inherit = "inherit" public var stringValue: String { return rawValue } } }
mit
4826b433e59a169b6a910cdfed04577a
25.219178
77
0.64629
4.063694
false
false
false
false
huaf22/zhihuSwiftDemo
zhihuSwiftDemo/Views/WLYScrollImageView.swift
1
6988
// // WLYScrollImageVIew.swift // zhihuSwiftDemo // // Created by Afluy on 16/7/30. // Copyright © 2016年 helios. All rights reserved. // import UIKit import Kingfisher // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } class WLYScrollImageView: UIView, UIScrollViewDelegate { let AnimationDuration: TimeInterval = 1 let TimerDuration: TimeInterval = 3 let BaseTagIndex = 10000 var pageControl: UIPageControl! var scrollView: UIScrollView! var scrollTimer: Timer? var currentIndex: Int = 0 { didSet { self.pageControl.currentPage = currentIndex } } var imageURLs : Array<URL>? { didSet { self.initScrollViewContent() self.startAutoScroll() } } override init(frame: CGRect) { super.init(frame: frame); self.setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setupView() { self.scrollView = UIScrollView() self.scrollView.frame = self.frame self.scrollView.delegate = self self.scrollView.showsVerticalScrollIndicator = false self.scrollView.showsVerticalScrollIndicator = false self.scrollView.scrollsToTop = false self.scrollView.isPagingEnabled = true self.scrollView.bounces = true self.addSubview(self.scrollView) self.scrollView.snp.makeConstraints { (make) in make.edges.equalTo(self) } self.pageControl = UIPageControl() self.addSubview(self.pageControl) self.pageControl.snp.makeConstraints { (make) in make.bottom.equalTo(self) make.centerX.equalTo(self) make.height.equalTo(50) } } func initScrollViewContent() { let count = self.imageURLs?.count > 1 ? 3 : 1; self.scrollView.contentSize = CGSize(width: self.wly_width * CGFloat(count), height: self.frame.size.height) //clear all content view for view in self.scrollView.subviews { view.removeFromSuperview() } for index in 0..<count { let imageView = UIImageView() self.scrollView.addSubview(imageView) imageView.tag = BaseTagIndex + index imageView.contentMode = .scaleAspectFill imageView.snp.makeConstraints { (make) in make.left.equalTo(self.wly_width * CGFloat(index)) make.top.bottom.equalTo(self) make.width.equalTo(self.wly_width) } } self.pageControl.numberOfPages = self.imageURLs != nil ? (self.imageURLs?.count)! : 0 self.updateScrollViewContent() } func updateScrollViewContent() { if self.imageURLs?.count <= 1 { let imagView = self.scrollView.viewWithTag(0) as! UIImageView imagView.kf.setImage(with:self.imageURLs!.first) self.scrollView.setContentOffset(CGPoint.zero, animated:false) return; } self.currentIndex = self.calcuateCurrentIndex() let leftImageIndex = self.calculateLeftIndex() let rightImageIndex = self.calculateRightIndex() (self.scrollView.viewWithTag(BaseTagIndex + 0) as? UIImageView)!.kf.setImage(with:self.imageURLs![leftImageIndex]) (self.scrollView.viewWithTag(BaseTagIndex + 1) as? UIImageView)!.kf.setImage(with:self.imageURLs![self.currentIndex]) (self.scrollView.viewWithTag(BaseTagIndex + 2) as? UIImageView)!.kf.setImage(with:self.imageURLs![rightImageIndex]) self.scrollView.setContentOffset(CGPoint(x: self.scrollView.wly_width, y: 0), animated: false) } func calcuateCurrentIndex() -> Int { let offset : CGPoint = self.scrollView.contentOffset let totalCount : Int = (self.imageURLs?.count)! var index : Int = 0 if offset.x > self.scrollView.wly_width { index = (self.currentIndex + 1) % totalCount } else if offset.x < self.scrollView.wly_width { index = (self.currentIndex + totalCount - 1) % totalCount } if index >= totalCount { index = 0 } // print("calcuateCurrentIndex: \(index)") return index } func calculateLeftIndex() -> Int { let totalCount : Int = (self.imageURLs?.count)! return (self.currentIndex + totalCount - 1) % totalCount } func calculateRightIndex() -> Int { let totalCount : Int = (self.imageURLs?.count)! return (self.currentIndex + 1) % totalCount } func scrollToNextPage() { UIView.animate(withDuration: AnimationDuration, animations: { self.scrollView.setContentOffset(CGPoint(x: self.scrollView.wly_width * 2.0, y: 0), animated: false) }, completion: { (finished) in self.updateScrollViewContent() }) } func startAutoScroll() { self.stopAutoScroll() if self.imageURLs != nil && (self.imageURLs?.count)! > 1 { self.scrollTimer = Timer.scheduledTimer(timeInterval: TimerDuration, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true) RunLoop.current.add(self.scrollTimer!, forMode: RunLoopMode.defaultRunLoopMode) } } func stopAutoScroll() { if self.scrollTimer != nil { self.scrollTimer?.invalidate() self.scrollTimer = nil } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.updateScrollViewContent() } }
mit
3401798ef4d843be4105969a41d85414
32.421053
125
0.589263
4.703704
false
false
false
false
catloafsoft/AudioKit
AudioKit/Common/Nodes/Mixing/Mixer/AKMixer.swift
1
1870
// // AKMixer.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AVFoundation /// AudioKit version of Apple's Mixer Node public class AKMixer: AKNode, AKToggleable { private let mixerAU = AVAudioMixerNode() /// Output Volume (Default 1) public var volume: Double = 1.0 { didSet { if volume < 0 { volume = 0 } mixerAU.outputVolume = Float(volume) } } private var lastKnownVolume: Double = 1.0 /// Determine if the mixer is serving any output or if it is stopped. public var isStarted: Bool { return volume != 0.0 } /// Initialize the mixer node /// /// - parameter inputs: A varaiadic list of AKNodes /// public init(_ inputs: AKNode...) { super.init() self.avAudioNode = mixerAU AudioKit.engine.attachNode(self.avAudioNode) for input in inputs { connect(input) } } /// Connnect another input after initialization /// /// - parameter input: AKNode to connect /// public func connect(input: AKNode) { input.connectionPoints.append(AVAudioConnectionPoint(node: mixerAU, bus: mixerAU.numberOfInputs)) AudioKit.engine.connect(input.avAudioNode, toConnectionPoints: input.connectionPoints, fromBus: 0, format: AudioKit.format) } /// Function to start, play, or activate the node, all do the same thing public func start() { if isStopped { volume = lastKnownVolume } } /// Function to stop or bypass the node, both are equivalent public func stop() { if isPlaying { lastKnownVolume = volume volume = 0 } } }
mit
95dc714ec93aede19fba010a2dc5ccc7
26.086957
131
0.599786
4.626238
false
false
false
false
casche/moving-helper
MovingHelperTests/TaskCellTests.swift
1
2694
// // TaskCellTests.swift // MovingHelper // // Created by Ellen Shapiro on 6/28/15. // Copyright (c) 2015 Razeware. All rights reserved. // import UIKit import XCTest import MovingHelper class TaskCellTests: XCTestCase { func testCheckingCheckboxMarksTaskDone() { var testCell: TaskTableViewCell? let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) if let navVC = mainStoryboard.instantiateInitialViewController() as? UINavigationController, listVC = navVC.topViewController as? MasterViewController { let tasks = TaskLoader.loadStockTasks() listVC.createdMovingTasks(tasks) testCell = listVC.tableView(listVC.tableView, cellForRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as? TaskTableViewCell if let cell = testCell { //1: Create an expectation to wait for let expectation = expectationWithDescription("Task updated") //2: Create an inline struct which conforms to the test delegate // which allows you to check and see whether it was called or not. struct TestDelegate: TaskUpdatedDelegate { let testExpectation: XCTestExpectation let expectedDone: Bool init(updatedExpectation: XCTestExpectation, expectedDoneStateAfterToggle: Bool) { testExpectation = updatedExpectation expectedDone = expectedDoneStateAfterToggle } func taskUpdated(task: Task) { XCTAssertEqual(expectedDone, task.done, "Task done state did not match expected!") testExpectation.fulfill() } } //3: Set up the test task and the cell. let testTask = Task(aTitle: "TestTask", aDueDate: .OneMonthAfter) XCTAssertFalse(testTask.done, "Newly created task is already done!") cell.delegate = TestDelegate(updatedExpectation: expectation, expectedDoneStateAfterToggle: true) cell.configureForTask(testTask) //4: Make sure the checkbox has the proper starting value XCTAssertFalse(cell.checkbox.isChecked, "Checkbox checked for not-done task!") //5: Send a "tap" event cell.checkbox.sendActionsForControlEvents(.TouchUpInside) //6: Make sure everything got updated. XCTAssertTrue(cell.checkbox.isChecked, "Checkbox not checked after tap!") waitForExpectationsWithTimeout(1, handler: nil) } else { XCTFail("Test cell was nil!") } } else { XCTFail("Could not get reference to list VC!") } } }
mit
e34720ac1c87392ea80f12c515496c64
39.223881
136
0.64291
5.313609
false
true
false
false
joshoconnor89/BoardView_DragNDrop
KDDragAndDropCollectionViews/KDDragAndDropCollectionView.swift
1
12616
// // KDDragAndDropCollectionView.swift // KDDragAndDropCollectionViews // // Created by Michael Michailidis on 10/04/2015. // Copyright (c) 2015 Karmadust. All rights reserved. // import UIKit @objc protocol KDDragAndDropCollectionViewDataSource : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath? func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to : IndexPath) -> Void func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem : AnyObject, atIndexPath indexPath: IndexPath) -> Void func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath: IndexPath) -> Void } class KDDragAndDropCollectionView: UICollectionView, KDDraggable, KDDroppable { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var draggingPathOfCellBeingDragged : IndexPath? var iDataSource : UICollectionViewDataSource? var iDelegate : UICollectionViewDelegate? override func awakeFromNib() { super.awakeFromNib() } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) } // MARK : KDDraggable func canDragAtPoint(_ point : CGPoint) -> Bool { guard let _ = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return false } return self.indexPathForItem(at: point) != nil } func representationImageAtPoint(_ point : CGPoint) -> UIView? { guard let indexPath = self.indexPathForItem(at: point) else { return nil } guard let cell = self.cellForItem(at: indexPath) else { return nil } UIGraphicsBeginImageContextWithOptions(cell.bounds.size, cell.isOpaque, 0) cell.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageView = UIImageView(image: image) imageView.frame = cell.frame return imageView } func dataItemAtPoint(_ point : CGPoint) -> AnyObject? { guard let indexPath = self.indexPathForItem(at: point) else { return nil } guard let dragDropDS = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return nil } return dragDropDS.collectionView(self, dataItemForIndexPath: indexPath) } func startDraggingAtPoint(_ point : CGPoint) -> Void { self.draggingPathOfCellBeingDragged = self.indexPathForItem(at: point) self.reloadData() } func stopDragging() -> Void { if let idx = self.draggingPathOfCellBeingDragged { if let cell = self.cellForItem(at: idx) { cell.isHidden = false } } self.draggingPathOfCellBeingDragged = nil self.reloadData() } func dragDataItem(_ item : AnyObject) -> Void { guard let dragDropDataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return } guard let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else { return } dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath) self.animating = true self.performBatchUpdates({ () -> Void in self.deleteItems(at: [existngIndexPath]) }, completion: { complete -> Void in self.animating = false self.reloadData() }) } // MARK : KDDroppable func canDropAtRect(_ rect : CGRect) -> Bool { return (self.indexPathForCellOverlappingRect(rect) != nil) } func indexPathForCellOverlappingRect( _ rect : CGRect) -> IndexPath? { var overlappingArea : CGFloat = 0.0 var cellCandidate : UICollectionViewCell? let visibleCells = self.visibleCells if visibleCells.count == 0 { return IndexPath(row: 0, section: 0) } if isHorizontal && rect.origin.x > self.contentSize.width || !isHorizontal && rect.origin.y > self.contentSize.height { return IndexPath(row: visibleCells.count - 1, section: 0) } for visible in visibleCells { let intersection = visible.frame.intersection(rect) if (intersection.width * intersection.height) > overlappingArea { overlappingArea = intersection.width * intersection.height cellCandidate = visible } } if let cellRetrieved = cellCandidate { return self.indexPath(for: cellRetrieved) } return nil } fileprivate var currentInRect : CGRect? func willMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void { let dragDropDataSource = self.dataSource as! KDDragAndDropCollectionViewDataSource // its guaranteed to have a data source if let _ = dragDropDataSource.collectionView(self, indexPathForDataItem: item) { // if data item exists return } if let indexPath = self.indexPathForCellOverlappingRect(rect) { dragDropDataSource.collectionView(self, insertDataItem: item, atIndexPath: indexPath) self.draggingPathOfCellBeingDragged = indexPath self.animating = true self.performBatchUpdates({ () -> Void in self.insertItems(at: [indexPath]) }, completion: { complete -> Void in self.animating = false // if in the meantime we have let go if self.draggingPathOfCellBeingDragged == nil { self.reloadData() } }) } currentInRect = rect } var isHorizontal : Bool { return (self.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection == .horizontal } var animating: Bool = false var paging : Bool = false func checkForEdgesAndScroll(_ rect : CGRect) -> Void { if paging == true { return } let currentRect : CGRect = CGRect(x: self.contentOffset.x, y: self.contentOffset.y, width: self.bounds.size.width, height: self.bounds.size.height) var rectForNextScroll : CGRect = currentRect if isHorizontal { let leftBoundary = CGRect(x: -30.0, y: 0.0, width: 30.0, height: self.frame.size.height) let rightBoundary = CGRect(x: self.frame.size.width, y: 0.0, width: 30.0, height: self.frame.size.height) if rect.intersects(leftBoundary) == true { rectForNextScroll.origin.x -= self.bounds.size.width * 0.5 if rectForNextScroll.origin.x < 0 { rectForNextScroll.origin.x = 0 } } else if rect.intersects(rightBoundary) == true { rectForNextScroll.origin.x += self.bounds.size.width * 0.5 if rectForNextScroll.origin.x > self.contentSize.width - self.bounds.size.width { rectForNextScroll.origin.x = self.contentSize.width - self.bounds.size.width } } } else { // is vertical let topBoundary = CGRect(x: 0.0, y: -30.0, width: self.frame.size.width, height: 30.0) let bottomBoundary = CGRect(x: 0.0, y: self.frame.size.height, width: self.frame.size.width, height: 30.0) if rect.intersects(topBoundary) == true { } else if rect.intersects(bottomBoundary) == true { } } // check to see if a change in rectForNextScroll has been made if currentRect.equalTo(rectForNextScroll) == false { self.paging = true self.scrollRectToVisible(rectForNextScroll, animated: true) let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime) { self.paging = false } } } func didMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void { let dragDropDS = self.dataSource as! KDDragAndDropCollectionViewDataSource // guaranteed to have a ds if let existingIndexPath = dragDropDS.collectionView(self, indexPathForDataItem: item), let indexPath = self.indexPathForCellOverlappingRect(rect) { if indexPath.item != existingIndexPath.item { dragDropDS.collectionView(self, moveDataItemFromIndexPath: existingIndexPath, toIndexPath: indexPath) self.animating = true self.performBatchUpdates({ () -> Void in self.moveItem(at: existingIndexPath, to: indexPath) }, completion: { (finished) -> Void in self.animating = false self.reloadData() }) self.draggingPathOfCellBeingDragged = indexPath } } // Check Paging var normalizedRect = rect normalizedRect.origin.x -= self.contentOffset.x normalizedRect.origin.y -= self.contentOffset.y currentInRect = normalizedRect self.checkForEdgesAndScroll(normalizedRect) } func didMoveOutItem(_ item : AnyObject) -> Void { guard let dragDropDataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource, let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else { return } dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath) self.animating = true self.performBatchUpdates({ () -> Void in self.deleteItems(at: [existngIndexPath]) }, completion: { (finished) -> Void in self.animating = false; self.reloadData() }) if let idx = self.draggingPathOfCellBeingDragged { if let cell = self.cellForItem(at: idx) { cell.isHidden = false } } self.draggingPathOfCellBeingDragged = nil currentInRect = nil } func dropDataItem(_ item : AnyObject, atRect : CGRect) -> Void { // show hidden cell if let index = draggingPathOfCellBeingDragged, let cell = self.cellForItem(at: index), cell.isHidden == true { cell.alpha = 1.0 cell.isHidden = false } currentInRect = nil self.draggingPathOfCellBeingDragged = nil self.reloadData() } }
mit
3743c628fa16d1a53a849c62d355a642
31.020305
155
0.545101
5.729337
false
false
false
false
modnovolyk/903WVideoCapture
WIFIAV/RawH264NaluBuffer.swift
1
1699
// // RawH264Buffer.swift // WIFIAV // // Created by Max Odnovolyk on 2/1/17. // Copyright © 2017 Max Odnovolyk. All rights reserved. // import Foundation enum NaluBufferError: Error { case bufferTooSmall case notEnoughSpace } class RawH264NaluBuffer: NaluBuffer { weak var delegate: NaluBufferDelegate? let length: Int var bytes: Data { return Data(bytes: buffer, count: endIndex) } private let buffer: UnsafeMutablePointer<UInt8> private(set) var endIndex = 0 required init(length: Int, delegate: NaluBufferDelegate? = nil) { self.length = length self.delegate = delegate buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: length) } deinit { buffer.deallocate(capacity: length) } func append(_ data: Data) { guard data.count <= length else { delegate?.didFail(with: .bufferTooSmall, in: self) return } if data.beginsWithNaluStartCode { flush() } if data.count > length - endIndex { delegate?.didFail(with: .notEnoughSpace, in: self) endIndex = 0 } data.copyBytes(to: buffer + endIndex, count: data.count) endIndex += data.count } func flush() { if endIndex > 0 { delegate?.didGatherUp(frame: bytes, in: self) } endIndex = 0 } } extension Data { var beginsWithNaluStartCode: Bool { if count < 4 { return false } return self[0] == 0x00 && self[1] == 0x00 && self[2] == 0x00 && self[3] == 0x01 } }
mit
fe193fbbf8a4be8e2c618b7e1035c39b
21.945946
87
0.56066
4.052506
false
false
false
false
gregomni/swift
test/IDE/complete_in_closures.swift
2
13719
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t // EMTPY: Token // EMPTY-NOT: Begin completions //===--- Helper types that are used in this test struct FooStruct { var instanceVar : Int func instanceFunc0() {} } // FOO_OBJECT_DOT: Begin completions // FOO_OBJECT_DOT-NEXT: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self // FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal{{(/TypeRelation\[Convertible\])?}}: instanceFunc0()[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: End completions // WITH_GLOBAL_DECLS: Begin completions // WITH_GLOBAL_DECLS: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_GLOBAL_DECLS: End completions //===--- Check that we can resolve closure parameters. func testResolveClosureParam1() { var x = { (fs: FooStruct) in fs.#^RESOLVE_CLOSURE_PARAM_1?check=FOO_OBJECT_DOT^# } } func testResolveClosureParam2() { { (fs: FooStruct) in fs.#^RESOLVE_CLOSURE_PARAM_2?check=FOO_OBJECT_DOT^# } } //===--- Check that we can resolve parent function parameters. func testResolveParentParam1(_ fs: FooStruct) { { (a: Int) in fs.#^RESOLVE_PARENT_PARAM_1?check=FOO_OBJECT_DOT^# } } func testResolveParentParam2(_ fs: FooStruct) { { fs.#^RESOLVE_PARENT_PARAM_2?check=FOO_OBJECT_DOT^# } } class TestResolveParentParam3 { func testResolveParentParam3a(_ fs: FooStruct) { { (a: Int) in fs.#^RESOLVE_PARENT_PARAM_3?check=FOO_OBJECT_DOT^# } } } class TestResolveParentParam4 { func testResolveParentParam4a(_ fs: FooStruct) { { fs.#^RESOLVE_PARENT_PARAM_4?check=FOO_OBJECT_DOT^# } } } func testResolveParentParam5(_ fs: FooStruct) { func testResolveParentParam5a() { { fs.#^RESOLVE_PARENT_PARAM_5?check=FOO_OBJECT_DOT^# } } } func testResolveParentParam6() { func testResolveParentParam6a(_ fs: FooStruct) { { fs.#^RESOLVE_PARENT_PARAM_6?check=FOO_OBJECT_DOT^# } } } //===--- Test completion in various statements in closures. func testReturnInClosure1() { var f = { () -> Int in return #^RETURN_1?check=WITH_GLOBAL_DECLS^# } } //===--- Test that we do delayed parsing of closures. var topLevelClosure1 = { #^DELAYED_1?check=WITH_GLOBAL_DECLS^# } var topLevelClosure2 = { func f() { #^DELAYED_2?check=WITH_GLOBAL_DECLS^# } } var topLevelClosure3 = { class C { func f() { #^DELAYED_3?check=WITH_GLOBAL_DECLS^# } } } class ClassWithClosureMember1 { var c1 = { #^DELAYED_4?check=WITH_GLOBAL_DECLS^# } lazy var c2 = { #^DELAYED_5?check=WITH_GLOBAL_DECLS^# } var c3 = ({ #^DELAYED_6?check=WITH_GLOBAL_DECLS^# })() lazy var c4 = ({ #^DELAYED_7?check=WITH_GLOBAL_DECLS^# })() } struct NestedStructWithClosureMember1 { struct Nested { var c1 = { #^DELAYED_8?check=WITH_GLOBAL_DECLS^# } lazy var c2 = { #^DELAYED_9?check=WITH_GLOBAL_DECLS^# } } } // WITH_GLOBAL_DECLS_AND_LOCAL1: Begin completions // WITH_GLOBAL_DECLS_AND_LOCAL1: Decl[LocalVar]/Local: x[#Int#] // WITH_GLOBAL_DECLS_AND_LOCAL1: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_GLOBAL_DECLS_AND_LOCAL1: End completions struct StructWithClosureMemberAndLocal { var c = { var x = 0 #^DELAYED_10?check=WITH_GLOBAL_DECLS_AND_LOCAL1;xfail=sr16012^# } } func acceptsTrailingClosureFooVoid(_ code: (FooStruct) -> Void) {} acceptsTrailingClosureFooVoid { #^IN_TRAILING_CLOSURE_1?check=WITH_GLOBAL_DECLS^# } acceptsTrailingClosureFooVoid { $0.#^IN_TRAILING_CLOSURE_2?check=FOO_OBJECT_DOT^# } acceptsTrailingClosureFooVoid { item in #^IN_TRAILING_CLOSURE_3?check=WITH_GLOBAL_DECLS^# } acceptsTrailingClosureFooVoid { item in item.#^IN_TRAILING_CLOSURE_4?check=FOO_OBJECT_DOT^# } acceptsTrailingClosureFooVoid { item in item.instanceFunc0() item.#^IN_TRAILING_CLOSURE_5?check=FOO_OBJECT_DOT^# } func acceptsListAndTrailingClosureFooVoid( _ list: [FooStruct], code: (FooStruct) -> Void) { } acceptsListAndTrailingClosureFooVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { #^IN_TRAILING_CLOSURE_6?check=WITH_GLOBAL_DECLS^# } acceptsListAndTrailingClosureFooVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { $0.#^IN_TRAILING_CLOSURE_7?check=FOO_OBJECT_DOT^# } acceptsListAndTrailingClosureFooVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { item in #^IN_TRAILING_CLOSURE_8?check=WITH_GLOBAL_DECLS^# } acceptsListAndTrailingClosureFooVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { item in item.#^IN_TRAILING_CLOSURE_9?check=FOO_OBJECT_DOT^# } acceptsListAndTrailingClosureFooVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { item in item.instanceFunc0() item.#^IN_TRAILING_CLOSURE_10?check=FOO_OBJECT_DOT^# } func acceptsListAndTrailingClosureTVoid<T>(_ list: [T], code: (T) -> Void) {} acceptsListAndTrailingClosureTVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { #^IN_TRAILING_CLOSURE_11?check=WITH_GLOBAL_DECLS^# } acceptsListAndTrailingClosureTVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { $0.#^IN_TRAILING_CLOSURE_12?check=FOO_OBJECT_DOT^# } acceptsListAndTrailingClosureTVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { item in #^IN_TRAILING_CLOSURE_13?check=WITH_GLOBAL_DECLS^# } acceptsListAndTrailingClosureTVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { item in item.#^IN_TRAILING_CLOSURE_14?check=FOO_OBJECT_DOT^# } acceptsListAndTrailingClosureTVoid( [ FooStruct(instanceVar: 0), FooStruct(instanceVar: 0) ]) { item in item.instanceFunc0() item.#^IN_TRAILING_CLOSURE_15?check=FOO_OBJECT_DOT^# } func getInt() -> Int? { return 0 } func testAcceptsTrailingClosureInt1() { acceptsTrailingClosureFooVoid { #^IN_TRAILING_CLOSURE_16?check=EMPTY^# in if let myvar = getInt() { } } } func testAcceptsTrailingClosureInt2() { acceptsTrailingClosureFooVoid { #^IN_TRAILING_CLOSURE_17?check=WITH_GLOBAL_DECLS^# if let myvar = getInt() { } } } func testAcceptsTrailingClosureInt3() { acceptsTrailingClosureFooVoid { if let myvar = getInt() { } #^IN_TRAILING_CLOSURE_18?check=WITH_GLOBAL_DECLS^# } } func testAcceptsTrailingClosureInt4() { acceptsTrailingClosureFooVoid { if let myvar = getInt() { #^IN_TRAILING_CLOSURE_19?check=WITH_GLOBAL_DECLS^# } } } func testTypeInClosure1() { acceptsTrailingClosureFooVoid { struct S : #^STRUCT_INHERITANCE_IN_CLOSURE_0?check=WITH_GLOBAL_DECLS^# } } func testTypeInClosure2() { acceptsTrailingClosureFooVoid { class S : #^CLASS_INHERITANCE_IN_CLOSURE_0?check=WITH_GLOBAL_DECLS^# } } func testTypeInClosure3() { acceptsTrailingClosureFooVoid { func test(_ x: #^ARGUMENT_TYPE_IN_CLOSURE_0?check=WITH_GLOBAL_DECLS^# } } acceptsTrailingClosureFooVoid { struct S : #^STRUCT_INHERITANCE_IN_CLOSURE_1?check=WITH_GLOBAL_DECLS^# } acceptsTrailingClosureFooVoid { class S : #^CLASS_INHERITANCE_IN_CLOSURE_1?check=WITH_GLOBAL_DECLS^# } acceptsTrailingClosureFooVoid { func test(_ x: #^ARGUMENT_TYPE_IN_CLOSURE_1?check=WITH_GLOBAL_DECLS^# } struct LazyVar1 { lazy var x: Int = { struct S : #^STRUCT_INHERITANCE_IN_CLOSURE_2?check=WITH_GLOBAL_DECLS^# }() } struct LazyVar2 { lazy var x: Int = { class S : #^CLASS_INHERITANCE_IN_CLOSURE_2?check=WITH_GLOBAL_DECLS^# }() } struct LazyVar3 { lazy var x: Int = { func test(_ x: #^ARGUMENT_TYPE_IN_CLOSURE_2?check=WITH_GLOBAL_DECLS^# }() } func closureTaker(_ theFunc:(theValue: Int) -> ()) {} func closureTaker2(_ theFunc: (Value1: Int, Value2: Int) -> ()) {} func testClosureParam1() { closureTaker { (theValue) -> () in #^CLOSURE_PARAM_1^# } } // CLOSURE_PARAM_1: Begin completions // CLOSURE_PARAM_1-DAG: Decl[LocalVar]/Local: theValue[#Int#]{{; name=.+$}} func testClosureParam2() { closureTaker2 { (Value1, Value2) -> () in #^CLOSURE_PARAM_2^# } } // CLOSURE_PARAM_2: Begin completions // CLOSURE_PARAM_2-DAG: Decl[LocalVar]/Local: Value1[#Int#]{{; name=.+$}} // CLOSURE_PARAM_2-DAG: Decl[LocalVar]/Local: Value2[#Int#]{{; name=.+$}} enum SomeEnum { case north, south } struct BarStruct { var enumVal: SomeEnum = .north } var testIIFEVar: BarStruct = { var obj = BarStruct() obj.enumVal = .#^IN_IIFE_1^# return obj }() testIIFEVar = { var obj = BarStruct() obj.enumVal = .#^IN_IIFE_2?check=IN_IIFE_1^# return obj }() func testIIFE() { var testIIFEVar: FooStruct = { var obj = BarStruct() obj.enumVal = .#^IN_IIFE_3?check=IN_IIFE_1^# return obj }() testIIFEVar = { var obj = BarStruct() obj.enumVal = .#^IN_IIFE_4?check=IN_IIFE_1^# return obj }() } // IN_IIFE_1: Begin completions // IN_IIFE_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: north[#SomeEnum#] // IN_IIFE_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: south[#SomeEnum#] extension Error { var myErrorNumber: Int { return 0 } } class C { var foo: String = { do { } catch { error.#^ERROR_IN_CLOSURE_IN_INITIALIZER^# // ERROR_IN_CLOSURE_IN_INITIALIZER: Begin completions // ERROR_IN_CLOSURE_IN_INITIALIZER-DAG: Keyword[self]/CurrNominal: self[#Error#]; name=self // ERROR_IN_CLOSURE_IN_INITIALIZER-DAG: Decl[InstanceVar]/CurrNominal: myErrorNumber[#Int#]; name=myErrorNumber // ERROR_IN_CLOSURE_IN_INITIALIZER: End completions } return "" }() } var foo = { let x = "Siesta:\(3)".#^DECL_IN_CLOSURE_IN_TOPLEVEL_INIT^# // DECL_IN_CLOSURE_IN_TOPLEVEL_INIT: Begin completions // DECL_IN_CLOSURE_IN_TOPLEVEL_INIT-DAG: Keyword[self]/CurrNominal: self[#String#]; name=self // DECL_IN_CLOSURE_IN_TOPLEVEL_INIT-DAG: Decl[InstanceVar]/CurrNominal/IsSystem: count[#Int#]; name=count // DECL_IN_CLOSURE_IN_TOPLEVEL_INIT-DAG: Decl[InstanceVar]/CurrNominal/IsSystem: unicodeScalars[#String.UnicodeScalarView#]; name=unicodeScalars // DECL_IN_CLOSURE_IN_TOPLEVEL_INIT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: hasPrefix({#(prefix): String#})[#Bool#]; name=hasPrefix(:) // DECL_IN_CLOSURE_IN_TOPLEVEL_INIT-DAG: Decl[InstanceVar]/CurrNominal/IsSystem: utf16[#String.UTF16View#]; name=utf16 // DECL_IN_CLOSURE_IN_TOPLEVEL_INIT-DAG: Decl[InstanceMethod]/Super/IsSystem: dropFirst()[#Substring#]; name=dropFirst() // DECL_IN_CLOSURE_IN_TOPLEVEL_INIT: End completions } func testWithMemoryRebound(_ bar: UnsafePointer<UInt64>) { _ = bar.withMemoryRebound(to: Int64.self, capacity: 3) { ptr in return ptr #^SINGLE_EXPR_CLOSURE_CONTEXT^# // SINGLE_EXPR_CLOSURE_CONTEXT: Begin completions // SINGLE_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: .deallocate()[#Void#]; name=deallocate() // SINGLE_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceVar]/CurrNominal/IsSystem: .pointee[#Int64#]; name=pointee // SINGLE_EXPR_CLOSURE_CONTEXT: End completions } } func testInsideTernaryClosureReturn(test: Bool) -> [String] { return "hello".map { thing in test ? String(thing #^SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT^#).uppercased() : String(thing).lowercased() // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT: Begin completions // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceVar]/CurrNominal/IsSystem: .utf8[#Character.UTF8View#]; name=utf8 // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceVar]/CurrNominal/IsSystem: .description[#String#]; name=description // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceVar]/CurrNominal/IsSystem: .isWhitespace[#Bool#]; name=isWhitespace // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: .uppercased()[#String#]; name=uppercased() // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]/IsSystem: [' ']... {#String.Element#}[#ClosedRange<String.Element>#]; name=... // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]/IsSystem: [' ']< {#Character#}[#Bool#]; name=< // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]/IsSystem: [' ']>= {#String.Element#}[#Bool#]; name=>= // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]/IsSystem: [' ']== {#Character#}[#Bool#]; name=== // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Keyword[self]/CurrNominal: .self[#String.Element#]; name=self // SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT: End completions } } func testSignature() { func accept<T>(_: () -> T) {} accept { #^PARAM_BARE_1?check=EMPTY^# in } accept { #^PARAM_BARE_2?check=EMPTY^#, arg2 in } accept { arg1, #^PARAM_BARE_3?check=EMPTY^# in } accept { (#^PARAM_PAREN_1?check=EMPTY^#) in } accept { (#^PARAM_PAREN_2?check=EMPTY^#, arg2) in } accept { (arg1, #^PARAM_PAREN_3?check=EMPTY^#) in } accept { (arg1: #^PARAMTYPE_1?check=WITH_GLOBAL_DECLS^#) in } accept { (arg1: Int, arg2: #^PARAMTYPE_2?check=WITH_GLOBAL_DECLS^#) in } accept { [#^CAPTURE_1?check=WITH_GLOBAL_DECLS^#] in } accept { [weak #^CAPTURE_2?check=WITH_GLOBAL_DECLS^#] in } accept { [#^CAPTURE_3?check=EMPTY^# = capture] in } accept { [weak #^CAPTURE_4?check=EMPTY^# = capture] in } accept { () -> #^RESULTTYPE_1?check=WITH_GLOBAL_DECLS^# in } accept { arg1, arg2 -> #^RESULTTYPE_2?check=WITH_GLOBAL_DECLS^# in } // NOTE: For effects specifiers completion (e.g. '() <HERE> -> Void') see test/IDE/complete_concurrency_specifier.swift }
apache-2.0
cc78d6d180b3344c70b44e1aa3bd9929
33.469849
177
0.690429
3.537648
false
true
false
false
kortnee1021/Kortnee
03-Single View App/Swift 1/BMI-Step6/BMI/ViewController.swift
4
1753
// // ViewController.swift // BMI // // Created by Nicholas Outram on 30/12/2014. // Copyright (c) 2014 Plymouth University. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { var weight : Double? var height : Double? var bmi : Double? { get { if (weight != nil) && (height != nil) { return weight! / (height! * height!) } else { return nil } } } @IBOutlet weak var bmiLabel: UILabel! @IBOutlet weak var heightTextField: UITextField! @IBOutlet weak var weightTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() updateUI() return true } func updateUI() { if let b = self.bmi { self.bmiLabel.text = String(format: "%4.1f", b) } } func textFieldDidEndEditing(textField: UITextField) { let conv = { NSNumberFormatter().numberFromString($0)?.doubleValue } switch (textField) { case self.weightTextField: self.weight = conv(textField.text) case self.heightTextField: self.height = conv(textField.text) default: println("Something has gone very wrong!") //Or just write 'break' } updateUI() } }
mit
14851d12a51e79d376dab30c9a218dd9
24.042857
80
0.575585
4.896648
false
false
false
false
Mattmlm/codepath-twitter-redux
Codepath Twitter/Codepath Twitter/Tweet.swift
1
1313
// // Tweet.swift // Codepath Twitter // // Created by admin on 10/2/15. // Copyright © 2015 mattmo. All rights reserved. // import UIKit class Tweet: NSObject { var user: User? var text: String? var createdAtString: String? var createdAt: Date? var retweetCount: Int? var favoriteCount: Int? var favorited: Bool? var id: Int? var idString: String? init(dictionary: NSDictionary) { user = User(dictionary: dictionary["user"] as! NSDictionary) text = dictionary["text"] as? String createdAtString = dictionary["created_at"] as? String retweetCount = dictionary["retweet_count"] as? Int favoriteCount = dictionary["favorite_count"] as? Int favorited = dictionary["favorited"] as? Bool id = dictionary["id"] as? Int idString = dictionary["id_str"] as? String TweetDateFormatter.setDateFormatterForInterpretingJSON() let formatter = TweetDateFormatter.shared createdAt = formatter.date(from: createdAtString!) } class func tweetsWithArray(array: [NSDictionary]) -> [Tweet] { var tweets = [Tweet]() for dictionary in array { tweets.append(Tweet(dictionary: dictionary)) } return tweets } }
mit
0923fe6fa13d52961cc599f8903030c5
27.521739
68
0.621951
4.373333
false
false
false
false
lulee007/GankMeizi
GankMeizi/BaseModel.swift
1
1397
// // BaseModel.swift // GankMeizi // // Created by 卢小辉 on 16/5/23. // Copyright © 2016年 lulee007. All rights reserved. // import Foundation import Moya import CocoaLumberjack import RxSwift import ObjectMapper class BaseModel { var provider: RxMoyaProvider<GankIOService> var page = 1 var offset = 20 var backgroundWorkScheduler: OperationQueueScheduler! init(){ let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 3 operationQueue.qualityOfService = NSQualityOfService.UserInitiated backgroundWorkScheduler = OperationQueueScheduler(operationQueue: operationQueue) let networkActivityPlugin = NetworkActivityPlugin { (change) -> () in DDLogDebug("network request: \(change)") switch (change) { case .Ended: UIApplication.sharedApplication().networkActivityIndicatorVisible = false case .Began: UIApplication.sharedApplication().networkActivityIndicatorVisible = true } } self.provider = RxMoyaProvider<GankIOService>(plugins: [networkActivityPlugin ,NetworkLoggerPlugin.init()]) } func parseObject<T: Mappable>(reponse: Response) throws-> T { return try Mapper<T>().map(reponse.mapString())! } }
mit
480da3fc9f2a06327647c044a5b4e070
28.553191
115
0.654179
5.443137
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCCharacterAttributes.swift
2
7352
// // NCCharacterAttributes.swift // Neocom // // Created by Artem Shimanski on 02.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import Foundation import EVEAPI class NCCharacterAttributes { var intelligence: Int = 20 var memory: Int = 20 var perception: Int = 20 var willpower: Int = 20 var charisma: Int = 19 struct Augmentations { var intelligence: Int = 0 var memory: Int = 0 var perception: Int = 0 var willpower: Int = 0 var charisma: Int = 0 } var augmentations = Augmentations() { didSet { intelligence += augmentations.intelligence - oldValue.intelligence memory += augmentations.memory - oldValue.memory perception += augmentations.perception - oldValue.perception willpower += augmentations.willpower - oldValue.willpower charisma += augmentations.charisma - oldValue.charisma } } init() { } init(attributes: ESI.Skills.CharacterAttributes, implants: [Int]?) { self.intelligence = attributes.intelligence self.memory = attributes.memory self.perception = attributes.perception self.willpower = attributes.willpower self.charisma = attributes.charisma var augmentations = Augmentations() if let implants = implants { NCDatabase.sharedDatabase?.performTaskAndWait({ (managedObjectContext) in let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext) for implant in implants { if let attributes = invTypes[implant]?.allAttributes { if let value = attributes[NCDBAttributeID.intelligenceBonus.rawValue]?.value, value > 0 { augmentations.intelligence += Int(value) } if let value = attributes[NCDBAttributeID.memoryBonus.rawValue]?.value, value > 0 { augmentations.memory += Int(value) } if let value = attributes[NCDBAttributeID.perceptionBonus.rawValue]?.value, value > 0 { augmentations.perception += Int(value) } if let value = attributes[NCDBAttributeID.willpowerBonus.rawValue]?.value, value > 0 { augmentations.willpower += Int(value) } if let value = attributes[NCDBAttributeID.charismaBonus.rawValue]?.value, value > 0 { augmentations.charisma += Int(value) } } } }) } self.augmentations = augmentations } /*init(clones: EVE.Char.Clones) { self.intelligence = clones.attributes.intelligence self.memory = clones.attributes.memory self.perception = clones.attributes.perception self.willpower = clones.attributes.willpower self.charisma = clones.attributes.charisma var augmentations = Augmentations() NCDatabase.sharedDatabase?.performTaskAndWait({ (managedObjectContext) in let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext) for implant in clones.implants ?? [] { if let attributes = invTypes[implant.typeID]?.allAttributes { if let value = attributes[NCDBAttributeID.intelligenceBonus.rawValue]?.value, value > 0 { augmentations.intelligence += Int(value) } if let value = attributes[NCDBAttributeID.memoryBonus.rawValue]?.value, value > 0 { augmentations.memory += Int(value) } if let value = attributes[NCDBAttributeID.perceptionBonus.rawValue]?.value, value > 0 { augmentations.perception += Int(value) } if let value = attributes[NCDBAttributeID.willpowerBonus.rawValue]?.value, value > 0 { augmentations.willpower += Int(value) } if let value = attributes[NCDBAttributeID.charismaBonus.rawValue]?.value, value > 0 { augmentations.charisma += Int(value) } } } }) self.augmentations = augmentations intelligence += augmentations.intelligence memory += augmentations.memory perception += augmentations.perception willpower += augmentations.willpower charisma += augmentations.charisma }*/ func skillpointsPerSecond(forSkill skill: NCSkill) -> Double { return skillpointsPerSecond(primaryAttributeID: skill.primaryAttributeID, secondaryAttribute: skill.secondaryAttributeID) } func skillpointsPerSecond(primaryAttributeID: NCDBAttributeID, secondaryAttribute: NCDBAttributeID) -> Double { let effectivePrimaryAttribute = effectiveAttributeValue(attributeID: primaryAttributeID) let effectiveSecondaryAttribute = effectiveAttributeValue(attributeID: secondaryAttribute) return (Double(effectivePrimaryAttribute) + Double(effectiveSecondaryAttribute) / 2.0) / 60.0; } func effectiveAttributeValue(attributeID: NCDBAttributeID) -> Int { switch attributeID { case .intelligence: return intelligence case .memory: return memory case .perception: return perception case .willpower: return willpower case .charisma: return charisma default: return 0 } } struct SkillKey: Hashable { let primary: NCDBAttributeID let secondary: NCDBAttributeID func hash(into hasher: inout Hasher) { hasher.combine((primary.rawValue << 16) + secondary.rawValue) } public static func ==(lhs: SkillKey, rhs: SkillKey) -> Bool { return lhs.primary == rhs.primary && lhs.secondary == rhs.secondary } } class func optimal(for trainingQueue: NCTrainingQueue) -> NCCharacterAttributes? { var skillPoints: [SkillKey: Int] = [:] for skill in trainingQueue.skills { let sp = skill.skill.skillPointsToLevelUp let key = SkillKey(primary: skill.skill.primaryAttributeID, secondary: skill.skill.secondaryAttributeID) skillPoints[key] = (skillPoints[key] ?? 0) + sp } let basePoints = 17 let bonusPoints = 14 let maxPoints = 27 let totalMaxPoints = basePoints * 5 + bonusPoints var minTrainingTime = TimeInterval.greatestFiniteMagnitude var optimal: [NCDBAttributeID: Int]? for intelligence in basePoints...maxPoints { for memory in basePoints...maxPoints { for perception in basePoints...maxPoints { guard intelligence + memory + perception < totalMaxPoints - basePoints * 2 else {break} for willpower in basePoints...maxPoints { guard intelligence + memory + perception + willpower < totalMaxPoints - basePoints else {break} let charisma = totalMaxPoints - (intelligence + memory + perception + willpower) guard charisma <= maxPoints else {continue} let attributes = [NCDBAttributeID.intelligence: intelligence, NCDBAttributeID.memory: memory, NCDBAttributeID.perception: perception, NCDBAttributeID.willpower: willpower, NCDBAttributeID.charisma: charisma] let trainingTime = skillPoints.reduce(0) { (t, i) -> TimeInterval in let primary = attributes[i.key.primary]! let secondary = attributes[i.key.secondary]! return t + TimeInterval(i.value) / (TimeInterval(primary) + TimeInterval(secondary) / 2) } if trainingTime < minTrainingTime { minTrainingTime = trainingTime optimal = attributes } } } } } if let optimal = optimal { let attributes = NCCharacterAttributes() attributes.intelligence = optimal[.intelligence]! attributes.memory = optimal[.memory]! attributes.perception = optimal[.perception]! attributes.willpower = optimal[.willpower]! attributes.charisma = optimal[.charisma]! return attributes } else { return nil } } }
lgpl-2.1
d479bd1f9032e22252cd7664e46f3c45
32.56621
123
0.706434
3.997281
false
false
false
false
weareyipyip/SwiftStylable
Sources/SwiftStylable/Classes/Style/Dimensions/DimensionHolder.swift
1
1614
// // DimensionHolder.swift // Pods-SwiftStylableExample // // Created by Rens Wijnmalen on 04/02/2019. // import UIKit open class DimensionHolder { internal private(set) var reference: DimensionHolder? private var _size: CGFloat? internal var size: CGFloat { if let reference = self.reference { return reference.size } if let size = self._size { return size } print("WARNING: one of the DimensionHolder objects has no reference or size property set, the default value 0 will be retunred") return 0 } // ----------------------------------------------------------------------------------------------------------------------- // // MARK: - Initializers // // ----------------------------------------------------------------------------------------------------------------------- init(size: CGFloat) { self._size = size } init(reference: DimensionHolder) { self.reference = reference } // ----------------------------------------------------------------------------------------------------------------------- // // MARK: - Setter methods // // ----------------------------------------------------------------------------------------------------------------------- internal func set(with size: CGFloat) { self.reference = nil self._size = size } internal func set(with reference: DimensionHolder) { self.reference = reference self._size = nil } }
mit
ffba66517f8b207921f4b9ffce2d813d
27.315789
136
0.387856
6.207692
false
false
false
false
Groupr-Purdue/Groupr-Backend
Sources/Library/Controllers/UsersController.swift
1
4250
import Vapor import HTTP import Foundation public final class UsersController: ResourceRepresentable { var droplet: Droplet public init(droplet: Droplet) { self.droplet = droplet } // replace, clear, about* -- ? public func makeResource() -> Resource<User> { return Resource( index: index, show: show, modify: update, destroy: destroy ) } public func registerRoutes() { droplet.post("register", handler: register) droplet.group("users", ":id") { users in users.get("courses", handler: courses) } } /// GET : Show all user entries. public func index(request: Request) throws -> ResponseRepresentable { return try JSON(node: User.all().makeNode(context: UserSensitiveContext())) } /// GET: Show the user entry. public func show(request: Request, user: User) throws -> ResponseRepresentable { guard ((try User.authenticateWithToken(fromRequest: request)) != nil) else { return try JSON(node: ["error" : "Not authorized"]) } return try JSON(node: user.makeNode(context: UserSensitiveContext())) } /// Patch: Update the user entry. public func update(request: Request, user: User) throws -> ResponseRepresentable { guard try User.authorize(user, withRequest: request) else { return try JSON(node: ["error" : "Not authorized"]) } let newUser = try request.user() var user = user if let firstName = newUser.first_name { user.first_name = firstName } if let lastName = newUser.last_name { user.last_name = lastName } if let careerAccount = newUser.career_account { user.career_account = careerAccount } try user.save() try RealtimeController.send(try JSON(node: [ "endpoint": "users", "method": "update", "item": user ])) return try user.userJson() } /// DELETE: Delete the user entry and return a HTTP 204 No-Content status public func destroy(request: Request, user: User) throws -> ResponseRepresentable { guard try User.authorize(user, withRequest: request) else { return try JSON(node: ["error" : "Not authorized"]).makeResponse() } let ret_user = user try user.delete() try RealtimeController.send(try JSON(node: [ "endpoint": "users", "method": "destroy", "item": ret_user ])) return try Response(status: .noContent, json: JSON(nil)) } public struct StderrOutputStream: TextOutputStream { public mutating func write(_ string: String) { fputs(string, stderr) } } public var errStream = StderrOutputStream() /// POST: Registers the user entry and returns the user public func register(request: Request) throws -> ResponseRepresentable { guard let career_account = request.json?["career_account"]?.string, let rawPassword = request.json?["password"]?.string, let firstName = request.json?["first_name"]?.string, let lastName = request.json?["last_name"]?.string else { return try JSON(node: ["error": "Missing credentials"]) } guard let newUser = try? User.register(career_account: career_account, rawPassword: rawPassword, first_name: firstName, last_name: lastName) else { let response = Response(status: .conflict, headers: ["Content-Type": "text/json"], body: try JSON(node: ["error" : "Account already registered"])) return response } return try newUser.userJson() } /// GET: Returns the courses the user is enrolled in public func courses(request: Request) throws -> ResponseRepresentable { guard let userId = request.parameters["id"]?.int else { throw Abort.badRequest } guard let user = try User.find(userId) else { throw Abort.notFound } guard try User.authorize(user, withRequest: request) else { return try JSON(node: ["error" : "Not authorized"]).makeResponse() } return try user.courses().all().makeJSON() } }
mit
83d020d969e5a148310064600d6f6171
37.636364
158
0.612471
4.550321
false
false
false
false
danielgindi/Charts
Source/Charts/Utils/Fill.swift
2
5283
// // Fill.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(ChartFill) public protocol Fill { /// Draws the provided path in filled mode with the provided area @objc func fillPath(context: CGContext, rect: CGRect) } @objc(ChartEmptyFill) public class EmptyFill: NSObject, Fill { public func fillPath(context: CGContext, rect: CGRect) { } } @objc(ChartColorFill) public class ColorFill: NSObject, Fill { @objc public let color: CGColor @objc public init(cgColor: CGColor) { self.color = cgColor super.init() } @objc public convenience init(color: NSUIColor) { self.init(cgColor: color.cgColor) } public func fillPath(context: CGContext, rect: CGRect) { context.saveGState() defer { context.restoreGState() } context.setFillColor(color) context.fillPath() } } @objc(ChartImageFill) public class ImageFill: NSObject, Fill { @objc public let image: CGImage @objc public let isTiled: Bool @objc public init(cgImage: CGImage, isTiled: Bool = false) { image = cgImage self.isTiled = isTiled super.init() } @objc public convenience init(image: NSUIImage, isTiled: Bool = false) { self.init(cgImage: image.cgImage!, isTiled: isTiled) } public func fillPath(context: CGContext, rect: CGRect) { context.saveGState() defer { context.restoreGState() } context.clip() context.draw(image, in: rect, byTiling: isTiled) } } @objc(ChartLayerFill) public class LayerFill: NSObject, Fill { @objc public let layer: CGLayer @objc public init(layer: CGLayer) { self.layer = layer super.init() } public func fillPath(context: CGContext, rect: CGRect) { context.saveGState() defer { context.restoreGState() } context.clip() context.draw(layer, in: rect) } } @objc(ChartLinearGradientFill) public class LinearGradientFill: NSObject, Fill { @objc public let gradient: CGGradient @objc public let angle: CGFloat @objc public init(gradient: CGGradient, angle: CGFloat = 0) { self.gradient = gradient self.angle = angle super.init() } public func fillPath(context: CGContext, rect: CGRect) { context.saveGState() defer { context.restoreGState() } let radians = (360.0 - angle).DEG2RAD let centerPoint = CGPoint(x: rect.midX, y: rect.midY) let xAngleDelta = cos(radians) * rect.width / 2.0 let yAngleDelta = sin(radians) * rect.height / 2.0 let startPoint = CGPoint( x: centerPoint.x - xAngleDelta, y: centerPoint.y - yAngleDelta ) let endPoint = CGPoint( x: centerPoint.x + xAngleDelta, y: centerPoint.y + yAngleDelta ) context.clip() context.drawLinearGradient( gradient, start: startPoint, end: endPoint, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation] ) } } @objc(ChartRadialGradientFill) public class RadialGradientFill: NSObject, Fill { @objc public let gradient: CGGradient @objc public let startOffsetPercent: CGPoint @objc public let endOffsetPercent: CGPoint @objc public let startRadiusPercent: CGFloat @objc public let endRadiusPercent: CGFloat @objc public init( gradient: CGGradient, startOffsetPercent: CGPoint, endOffsetPercent: CGPoint, startRadiusPercent: CGFloat, endRadiusPercent: CGFloat) { self.gradient = gradient self.startOffsetPercent = startOffsetPercent self.endOffsetPercent = endOffsetPercent self.startRadiusPercent = startRadiusPercent self.endRadiusPercent = endRadiusPercent super.init() } @objc public convenience init(gradient: CGGradient) { self.init( gradient: gradient, startOffsetPercent: .zero, endOffsetPercent: .zero, startRadiusPercent: 0, endRadiusPercent: 1 ) } @objc public func fillPath(context: CGContext, rect: CGRect) { context.saveGState() defer { context.restoreGState() } let centerPoint = CGPoint(x: rect.midX, y: rect.midY) let radius = max(rect.width, rect.height) / 2.0 context.clip() context.drawRadialGradient( gradient, startCenter: CGPoint( x: centerPoint.x + rect.width * startOffsetPercent.x, y: centerPoint.y + rect.height * startOffsetPercent.y ), startRadius: radius * startRadiusPercent, endCenter: CGPoint( x: centerPoint.x + rect.width * endOffsetPercent.x, y: centerPoint.y + rect.height * endOffsetPercent.y ), endRadius: radius * endRadiusPercent, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation] ) } }
apache-2.0
8e140de6b1e4a800cce3a3641dbb5efa
24.157143
74
0.620859
4.417224
false
false
false
false
orta/eidolon
Kiosk/Bid Fulfillment/ConfirmYourBidViewController.swift
1
2114
import UIKit class ConfirmYourBidViewController: UIViewController { dynamic var number: String = "" let phoneNumberFormatter = ECPhoneNumberFormatter() @IBOutlet var numberAmountTextField: UITextField! @IBOutlet var keypadContainer: KeypadContainerView! class func instantiateFromStoryboard() -> ConfirmYourBidViewController { return UIStoryboard.fulfillment().viewControllerWithID(.ConfirmYourBid) as ConfirmYourBidViewController } override func viewDidLoad() { super.viewDidLoad() let numberIsZeroLengthSignal = RACObserve(self, "number").map({ (number) -> AnyObject! in let number = number as String return (number.utf16Count == 0) }) RAC(enterButton, "enabled") <~ numberIsZeroLengthSignal.notEach() RAC(numberAmountTextField, "text") <~ RACObserve(self, "number").map(toPhoneNumberString) keypadSignal.subscribeNext({ [weak self] (input) -> Void in let input = String(input as Int) let newNumber = self?.number.stringByAppendingString(input) self?.number = newNumber! }) } @IBOutlet var enterButton: UIButton! @IBAction func enterButtonTapped(sender: AnyObject) { } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } lazy var keypadSignal:RACSignal! = self.keypadContainer.keypad?.keypadSignal } private extension ConfirmYourBidViewController { func toOpeningBidString(cents:AnyObject!) -> AnyObject! { if let dollars = NSNumberFormatter.currencyStringForCents(cents as? Int) { return "Enter \(dollars) or more" } return "" } func toPhoneNumberString(number:AnyObject!) -> AnyObject! { return self.phoneNumberFormatter.stringForObjectValue(number as String) } @IBAction func dev_noPhoneNumberFoundTapped(sender: AnyObject) { self.performSegue(.ConfirmyourBidBidderNotFound) } @IBAction func dev_phoneNumberFoundTapped(sender: AnyObject) { self.performSegue(.ConfirmyourBidBidderFound) } }
mit
20030602194c2464ce51a240b0a9d41a
30.567164
111
0.693472
5.021378
false
false
false
false
goRestart/restart-backend-app
Sources/Domain/Model/Image/Image.swift
1
595
import Foundation public struct Image { public let identifier: String public let url: String public let width: Double public let height: Double public let size: Double public let color: Int? public init(identifier: String, url: String, width: Double, height: Double, size: Double, color: Int?) { self.identifier = identifier self.url = url self.width = width self.height = height self.size = size self.color = color } }
gpl-3.0
f094dc70e9de772d235bcbe856fb175e
21.884615
36
0.536134
4.917355
false
false
false
false
yuyedaidao/YQRefresh
Classes/YQAutoRefreshFooter.swift
1
6660
// // YQAutoRefreshFooter.swift // YQRefresh // // Created by 王叶庆 on 2021/9/18. // Copyright © 2021 王叶庆. All rights reserved. // import UIKit public class YQAutoRefreshFooter: UIView, FooterRefresher { public var automaticVisiable: Bool = true public var emptyContentHeight: CGFloat = 1 { didSet { guard let scrollView = scrollView else { return } isVisiable = scrollView.contentSize.height <= emptyContentHeight } } public var actor: YQRefreshActor? { didSet { guard let actor = actor else { return } if let old = oldValue { old.removeFromSuperview() } addSubview(actor) } } public var action: YQRefreshAction? public var refresherHeight: CGFloat = YQRefresherHeight public var originalInset = UIEdgeInsets.zero public var pullingPercentOffset: CGFloat = YQRefresherHeight / 2 public var yOffset: CGFloat = 0 public var topSpaceConstraint: NSLayoutConstraint! var headerRefreshObserver: NSObjectProtocol? private var triggerOffset = CGFloat.infinity public var state: YQRefreshState = .default { didSet { guard oldValue != state else { return } actor?.state = state } } public weak var scrollView: UIScrollView? { didSet { if let scroll = scrollView { scroll.addObserver(self, forKeyPath: YQKVOContentOffset, options: .new, context: UnsafeMutableRawPointer(&YQKVOContentOffset)) scroll.addObserver(self, forKeyPath: YQKVOContentSize, options: .new, context: UnsafeMutableRawPointer(&YQKVOContentSize)) } } } public var pullingPercent: Double = 0 { didSet { actor?.pullingPrecent = pullingPercent } } public init(actor: YQRefreshActor? = YQRefreshActorProvider.shared.footerActor?() ?? FooterActor(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: YQRefresherHeight))), action: @escaping YQRefreshAction) { self.actor = actor self.action = action super.init(frame: CGRect.zero) if let actor = self.actor { addSubview(actor) isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction)) addGestureRecognizer(tap) } dealHeaderRefreshNotification() } @objc func tapAction() { guard state == .default, let action = action else { return } beginRefreshing() action() } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { if let observer = headerRefreshObserver { NotificationCenter.default.removeObserver(observer) } } override open func layoutSubviews() { super.layoutSubviews() guard let actor = actor else { return } actor.center = CGPoint(x: bounds.midX, y: bounds.midY) } override public func willMove(toSuperview newSuperview: UIView?) { func removeObservers(on view: UIView?) { view?.removeObserver(self, forKeyPath: YQKVOContentOffset, context: UnsafeMutableRawPointer(&YQKVOContentOffset)) view?.removeObserver(self, forKeyPath: YQKVOContentSize, context: UnsafeMutableRawPointer(&YQKVOContentSize)) } if let scroll = newSuperview as? UIScrollView { var contentInset = scroll.contentInset contentInset.bottom += refresherHeight scroll.contentInset = contentInset scrollView = scroll if scroll.contentSize.height <= emptyContentHeight { isVisiable = false } } else { removeObservers(on: superview) } } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let scroll = scrollView else {return} if context == UnsafeMutableRawPointer(&YQKVOContentOffset) { guard isVisiable else {return} guard state != .noMore, state != .refreshing else { return } let visibleMaxY = scroll.contentOffset.y + scroll.bounds.height + scroll.contentInset.top guard visibleMaxY >= triggerOffset else { return } if state != .refreshing { if visibleMaxY > triggerOffset { state = .refreshing if let action = self.action { action() } } } } else if context == UnsafeMutableRawPointer(&YQKVOContentSize) { let contentSize = change![NSKeyValueChangeKey.newKey] as! CGSize if contentSize.height <= emptyContentHeight { isVisiable = false } else { if contentSize.height <= scroll.bounds.height { triggerOffset = scroll.bounds.height + refresherHeight / 2 } else { triggerOffset = contentSize.height + refresherHeight } topSpaceConstraint.constant = contentSize.height + yOffset isVisiable = true } } } private var isVisiable: Bool = true { didSet { guard automaticVisiable else { return } isHidden = !isVisiable } } private func dealHeaderRefreshNotification() { headerRefreshObserver = NotificationCenter.default.addObserver(forName: Notification.Name(YQNotificatonHeaderRefresh), object: nil, queue: nil) {[weak self] notificiation in guard let self = self, let view = notificiation.object as? UIScrollView, view == self.scrollView else { return } if self.state == .noMore { self.state = .default } } } // public public func beginRefreshing() { state = .refreshing } public func endRefreshing() { state = .default } public func noMore() { state = .noMore } public func reset() { state = .default } }
mit
9d258d4f22e678afdcd82230faabce2b
33.087179
228
0.575598
5.321857
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/GSR-Booking/Controllers/GSRGroupNewIntialController.swift
1
13269
// // GSRGroupNewIntialController.swift // PennMobile // // Created by Lucy Yuewei Yuan on 10/18/19. // Copyright © 2019 PennLabs. All rights reserved. // import UIKit protocol NewGroupInitialDelegate: GSRGroupController { func fetchGroups() } class GSRGroupNewIntialController: UIViewController { fileprivate var closeButton: UIButton! fileprivate var nameField: UITextField! fileprivate var groupForLabel: UILabel! fileprivate var barView: UISegmentedControl! fileprivate var colorLabel: UILabel! fileprivate var colorPanel: UIView! fileprivate var createButton: UIButton! fileprivate var colorCollectionView: UICollectionView! fileprivate var colors: [UIColor] = [ UIColor.baseBlue, UIColor.baseGreen, UIColor.baseYellow, UIColor.baseOrange, UIColor.baseRed, UIColor.blueDarker ] fileprivate var chosenColor: UIColor! fileprivate var nameChanged: Bool! fileprivate var colorNames: [String] = ["Labs Blue", "College Green", "Locust Yellow", "Cheeto Orange", "Red-ing Terminal", "Baltimore Blue", "Purple"] weak var delegate: NewGroupInitialDelegate! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white // Do any additional setup after loading the view. prepareUI() } override func viewDidAppear(_ animated: Bool) { colorCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: UICollectionView.ScrollPosition.centeredHorizontally) // collectionView(colorCollectionView, didSelectItemAt: IndexPath(item: 0, section:0)) } func prepareCloseButton() { closeButton = UIButton() view.addSubview(closeButton) closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 40).isActive = true closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true closeButton.backgroundColor = UIColor(red: 118/255, green: 118/255, blue: 128/255, alpha: 12/100) closeButton.heightAnchor.constraint(equalToConstant: 30).isActive = true closeButton.widthAnchor.constraint(equalToConstant: 30).isActive = true closeButton.layer.cornerRadius = 15 closeButton.layer.masksToBounds = false closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.setTitle("x", for: UIControl.State.normal) // closeButton.setImage(image: , for: UIControl.State.normal) closeButton.addTarget(self, action: #selector(cancelBtnAction), for: .touchUpInside) } func prepareNameField() { nameField = UITextField() nameField.placeholder = "New Group Name" nameField.textColor = UIColor.init(red: 216, green: 216, blue: 216) nameField.font = UIFont.boldSystemFont(ofSize: 24) // rgb 18 39 75 nameField.textColor = UIColor(r: 18/255, g: 39/255, b: 75/255) nameField.keyboardType = .alphabet nameField.textAlignment = .natural nameField.autocorrectionType = .no nameField.spellCheckingType = .no nameField.autocapitalizationType = .none view.addSubview(nameField) nameField.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 14).isActive = true nameField.topAnchor.constraint(equalTo: view.topAnchor, constant: 79.5).isActive = true nameField.translatesAutoresizingMaskIntoConstraints = false nameField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControl.Event.editingChanged) } @objc func textFieldDidChange(_ textField: UITextField) { if textField.text != "" && textField.text != "New Group Name" { createButton.isUserInteractionEnabled = true if chosenColor != nil { createButton.backgroundColor = chosenColor } else { createButton.backgroundColor = UIColor.init(red: 216, green: 216, blue: 216) } nameChanged = true } else { createButton.isUserInteractionEnabled = false createButton.backgroundColor = UIColor.init(red: 216, green: 216, blue: 216) nameChanged = false } } func prepareGroupForLabel() { groupForLabel = UILabel() groupForLabel.text = "Who is this group for?" groupForLabel.font = UIFont.systemFont(ofSize: 17) groupForLabel.textColor = UIColor.init(red: 153, green: 153, blue: 153) groupForLabel.textAlignment = .center view.addSubview(groupForLabel) groupForLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true groupForLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true groupForLabel.topAnchor.constraint(equalTo: nameField.bottomAnchor, constant: 35).isActive = true groupForLabel.translatesAutoresizingMaskIntoConstraints = false } func prepareSegmentedControl() { let items = ["Friends", "Classmates", "Club"] barView = UISegmentedControl(items: items) let font = UIFont.systemFont(ofSize: 14, weight: .semibold) barView.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: font], for: .normal) barView.backgroundColor = UIColor.init(red: 216, green: 216, blue: 216) barView.layer.borderWidth = 1 barView.layer.borderColor = UIColor.init(red: 216, green: 216, blue: 216).cgColor barView.layer.cornerRadius = 6.9 barView.layer.masksToBounds = true barView.tintColor = UIColor.init(red: 153, green: 153, blue: 153) barView.selectedSegmentIndex = 0 view.addSubview(barView) barView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16).isActive = true barView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16).isActive = true barView.topAnchor.constraint(equalTo: groupForLabel.bottomAnchor, constant: 14).isActive = true barView.translatesAutoresizingMaskIntoConstraints = false } func prepareCreateButton() { createButton = UIButton() createButton.backgroundColor = UIColor.init(red: 216, green: 216, blue: 216) createButton.setTitle("Create Group", for: .normal) createButton.setTitleColor(UIColor.white, for: .normal) createButton.layer.cornerRadius = 8 createButton.layer.masksToBounds = true createButton.isEnabled = false createButton.addTarget(self, action: #selector(createGroupBtnAction), for: .touchUpInside) view.addSubview(createButton) createButton.topAnchor.constraint(equalTo: colorCollectionView.bottomAnchor, constant: 45).isActive = true createButton.heightAnchor.constraint(equalToConstant: 50).isActive = true createButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 15).isActive = true createButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -15).isActive = true createButton.translatesAutoresizingMaskIntoConstraints = false // button unclickable until group name changed and not empty createButton.isUserInteractionEnabled = false nameChanged = false } func prepareColorLabel() { colorLabel = UILabel() colorLabel.text = "Pick a color:" colorLabel.font = UIFont.systemFont(ofSize: 17) colorLabel.textColor = UIColor.init(red: 153, green: 153, blue: 153) colorLabel.textAlignment = .center view.addSubview(colorLabel) colorLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true colorLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true colorLabel.topAnchor.constraint(equalTo: barView.bottomAnchor, constant: 35).isActive = true colorLabel.translatesAutoresizingMaskIntoConstraints = false } func prepareColorCollection() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) colorCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) colorCollectionView.register(GSRColorCell.self, forCellWithReuseIdentifier: GSRColorCell.identifier) colorCollectionView.backgroundColor = .clear colorCollectionView.showsHorizontalScrollIndicator = false colorCollectionView.delegate = self colorCollectionView.dataSource = self colorCollectionView.allowsSelection = true colorCollectionView.allowsMultipleSelection = false colorCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: UICollectionView.ScrollPosition.centeredHorizontally) view.addSubview(colorCollectionView) colorCollectionView.topAnchor.constraint(equalTo: colorLabel.bottomAnchor, constant: 20).isActive = true colorCollectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true colorCollectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true colorCollectionView.heightAnchor.constraint(equalToConstant: 40).isActive = true colorCollectionView.translatesAutoresizingMaskIntoConstraints = false } @objc func createGroupBtnAction(sender: UIButton!) { // TODO: Consider adding appropriate error messages guard let name = nameField.text else {return} guard let color = colorLabel.text else {return} GSRGroupNetworkManager.instance.createGroup(name: name, color: color) { (success, _) in if success { // This reloads the groups on the GSRGroupController - this should be done after invites / end of the flow // self.delegate.fetchGroups() DispatchQueue.main.async { let controller = GSRGroupInviteViewController() self.navigationController?.pushViewController(controller, animated: true) } } } } @objc func cancelBtnAction(sender: UIButton!) { self.delegate.fetchGroups() dismiss(animated: true, completion: nil) } } // MARK: Setup UI extension GSRGroupNewIntialController { fileprivate func prepareUI() { prepareCloseButton() prepareNameField() prepareGroupForLabel() prepareSegmentedControl() prepareColorLabel() prepareColorCollection() prepareCreateButton() } } extension GSRGroupNewIntialController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 7 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GSRColorCell.identifier, for: indexPath) as! GSRColorCell let color = colors[indexPath.item % colors.count] cell.color = color cell.borderColor = color.borderColor(multiplier: 1.5) return cell } // MARK: - Collection View Delegate Methods func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as? GSRColorCell cell?.toggleBorder() createButton.isEnabled = true if nameChanged { createButton.backgroundColor = cell?.colorView.backgroundColor } else { createButton.backgroundColor = UIColor.init(red: 216, green: 216, blue: 216) } chosenColor = cell?.colorView.backgroundColor colorLabel.textColor = cell?.colorView.backgroundColor colorLabel.text = colorNames[indexPath.item % colorNames.count] colorLabel.font = UIFont.boldSystemFont(ofSize: 17) } // Deselect this time slot and all select ones that follow it func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as? GSRColorCell cell?.toggleBorder() } } extension UIColor { // for getting a lighter variant (using a multiplier) func borderColor(multiplier: CGFloat) -> UIColor { let rgba = self.rgba return UIColor(red: rgba.red * multiplier, green: rgba.green * multiplier, blue: rgba.blue * multiplier, alpha: rgba.alpha) } //https://www.hackingwithswift.com/example-code/uicolor/how-to-read-the-red-green-blue-and-alpha-color-components-from-a-uicolor var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) // returns rgba colors. return (red, green, blue, alpha) } }
mit
a02773c29b456fb2e70e2fa53d869dc4
43.976271
161
0.695131
5.008683
false
false
false
false
codercd/LoadingView
LoadingView/RootTableViewController.swift
1
3628
// // RootTableViewController.swift // LoadingView // // Created by LiChendi on 16/2/17. // Copyright © 2016年 LiChendi. All rights reserved. // import UIKit class RootTableViewController: UITableViewController { let items = ["文字loading", "待完成", "待完成", "待完成", "待完成", "待完成", ""] override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) cell.textLabel?.text = items[indexPath.row] // Configure the cell... return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row { case 0: self.navigationController?.pushViewController(LoadingViewController_1(), animated: true) break case 1: self.navigationController?.pushViewController(LoadingViewController_1(), animated: true) default: break } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
ad3c0981aa324ec08995fd31c9ee08c8
32.560748
157
0.674464
5.474085
false
false
false
false
practicalswift/swift
test/IRGen/weak_import_availability.swift
1
3735
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -emit-module-path %t/weak_import_availability_helper.swiftmodule -parse-as-library %S/Inputs/weak_import_availability_helper.swift -enable-resilience // // RUN: %target-swift-frontend -primary-file %s -I %t -emit-ir | %FileCheck %s --check-prefix=CHECK-OLD // RUN: %target-swift-frontend -primary-file %s -I %t -emit-ir -target x86_64-apple-macosx10.50 | %FileCheck %s --check-prefix=CHECK-NEW // RUN: %target-swift-frontend -primary-file %s -I %t -emit-ir -target x86_64-apple-macosx10.60 | %FileCheck %s --check-prefix=CHECK-NEW // REQUIRES: OS=macosx // REQUIRES: CPU=x86_64 import weak_import_availability_helper public func useConditionallyAvailableCase(e: AlwaysAvailableEnum) { switch e { case .alwaysAvailableCase: break case .conditionallyAvailableCase: break } } // CHECK-OLD-LABEL: @"$s31weak_import_availability_helper19AlwaysAvailableEnumO013conditionallyF4CaseyA2CmFWC" = extern_weak constant i32 // CHECK-NEW-LABEL: @"$s31weak_import_availability_helper19AlwaysAvailableEnumO013conditionallyF4CaseyA2CmFWC" = external constant i32 func useConformance<T : AlwaysAvailableProtocol>(_: T.Type) {} @available(macOS 10.50, *) public func useConditionallyAvailableConformance() { useConformance(AlwaysAvailableStruct.self) } // FIXME: We reference the witness table directly -- that's a bug since the module is resilient. Should reference the // conformance descriptor instead. // CHECK-OLD-LABEL: @"$s31weak_import_availability_helper21AlwaysAvailableStructVAA0eF8ProtocolAAWP" = extern_weak global i8* // CHECK-NEW-LABEL: @"$s31weak_import_availability_helper21AlwaysAvailableStructVAA0eF8ProtocolAAWP" = external global i8* @available(macOS 10.50, *) public func callConditionallyAvailableFunction() { conditionallyAvailableFunction() } // CHECK-OLD-LABEL: declare extern_weak swiftcc void @"$s31weak_import_availability_helper30conditionallyAvailableFunctionyyF"() // CHECK-NEW-LABEL: declare swiftcc void @"$s31weak_import_availability_helper30conditionallyAvailableFunctionyyF"() @available(macOS 10.50, *) public func useConditionallyAvailableGlobal() { _ = conditionallyAvailableGlobal conditionallyAvailableGlobal = 0 conditionallyAvailableGlobal += 1 } // CHECK-OLD-LABEL: declare extern_weak swiftcc i64 @"$s31weak_import_availability_helper28conditionallyAvailableGlobalSivg"() // CHECK-NEW-LABEL: declare swiftcc i64 @"$s31weak_import_availability_helper28conditionallyAvailableGlobalSivg"() // CHECK-OLD-LABEL: declare extern_weak swiftcc void @"$s31weak_import_availability_helper28conditionallyAvailableGlobalSivs"(i64) // CHECK-NEW-LABEL: declare swiftcc void @"$s31weak_import_availability_helper28conditionallyAvailableGlobalSivs"(i64) func blackHole<T>(_: T) {} @available(macOS 10.50, *) public func useConditionallyAvailableStruct() { blackHole(ConditionallyAvailableStruct.self) } // CHECK-OLD-LABEL: declare extern_weak swiftcc %swift.metadata_response @"$s31weak_import_availability_helper28ConditionallyAvailableStructVMa"(i64) // CHECK-NEW-LABEL: declare swiftcc %swift.metadata_response @"$s31weak_import_availability_helper28ConditionallyAvailableStructVMa"(i64) @available(macOS 10.50, *) public func useConditionallyAvailableMethod(s: ConditionallyAvailableStruct) { s.conditionallyAvailableMethod() } // CHECK-OLD-LABEL: declare extern_weak swiftcc void @"$s31weak_import_availability_helper28ConditionallyAvailableStructV013conditionallyF6MethodyyF"(%swift.opaque* noalias nocapture swiftself) // CHECK-NEW-LABEL: declare swiftcc void @"$s31weak_import_availability_helper28ConditionallyAvailableStructV013conditionallyF6MethodyyF"(%swift.opaque* noalias nocapture swiftself)
apache-2.0
24ccc886dffbed1bb408de3408147eec
50.164384
193
0.798929
3.842593
false
false
false
false
kayak/attributions
Attributions/Attributions/Attribution.swift
1
1198
import Foundation public class Attribution { public let name: String public let displayedForMainBundleIDs: [String] public let license: License convenience init?(json: [AnyHashable: Any]) { guard let name = json["name"] as? String, let licenseJSON = json["license"] as? [AnyHashable: Any], let license = License(json: licenseJSON) else { return nil } let displayedForMainBundleIDs = json["displayedForMainBundleIDs"] as? [String] ?? [] self.init(name: name, displayedForMainBundleIDs: displayedForMainBundleIDs, license: license) } public init(name: String, displayedForMainBundleIDs: [String], license: License) { self.name = name self.displayedForMainBundleIDs = displayedForMainBundleIDs self.license = license } func isDisplayed(in mainBundle: Bundle) -> Bool { guard let mainBundleIdentifier = mainBundle.bundleIdentifier else { return true } guard displayedForMainBundleIDs.count > 0 else { return true } return displayedForMainBundleIDs.contains(mainBundleIdentifier) } }
apache-2.0
b2eb262f47122cf73933911ef86766df
30.526316
101
0.646912
4.811245
false
false
false
false
qidafang/iOS_427studio
studio427/LoginRest.swift
1
2140
// // MyRest.swift // testall // // Created by 祁达方 on 15/10/15. // Copyright © 2015年 祁达方. All rights reserved. // import UIKit ///rest客户端的演示 ///要继承NSObject否则说没实现啥协议 class LoginRest: NSObject, NSURLConnectionDataDelegate { var loginController:LoginController!; //保存数据列表 var objects = NSMutableArray() //接收从服务器返回数据。 var datas : NSMutableData! func login(username:String, password:String){ ///地址 var strURL = "http://427studio.net/api/login"; strURL = strURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! let url = NSURL(string: strURL)! ///请求 let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST"//post请求 request.HTTPBody = ("username="+username+"&password="+password).dataUsingEncoding(NSUTF8StringEncoding); ///连接 let connection = NSURLConnection(request: request, delegate: self) ///初始化桶子 if connection != nil { self.datas = NSMutableData() } } ///数据接收中的回调 func connection(connection: NSURLConnection, didReceiveData data: NSData) { self.datas.appendData(data) } ///数据接收错误的回调 func connection(connection: NSURLConnection, didFailWithError error: NSError) { NSLog("%@",error.localizedDescription) } ///数据都接收完的回调 ///关键的类:NSMutableArray和NSMutableDictionary func connectionDidFinishLoading(connection: NSURLConnection) { do{ let json:NSMutableDictionary = try NSJSONSerialization.JSONObjectWithData(self.datas, options: .AllowFragments) as! NSMutableDictionary let token:String = json.objectForKey("token") as! String; Holder.token = token; self.loginController.closeLogin(); }catch let error as NSError{ loginController.info.text = "登录失败!"; } } }
apache-2.0
5ba4df4c5d54a91225a660fee60bf895
27.779412
147
0.627491
4.615566
false
false
false
false
InAppPurchase/InAppPurchase
InAppPurchaseTests/IAPResponseSaveReceiptTests.swift
1
3747
// The MIT License (MIT) // // Copyright (c) 2015 Chris Davis // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // IAPResponseSaveReceiptTests.swift // InAppPurchase // // Created by Chris Davis on 15/12/2015. // Email: [email protected] // Copyright © 2015 nthState. All rights reserved. // import XCTest class IAPResponseSaveReceiptTests: XCTestCase { func testFrameworkNeedsToBeInitalizedBeforeSaveReceiptCalled() { // Arrange let iap = InAppPurchase(apiKey: "", userId: "") iap.networkService = MockIAPNetworkService(obj: nil) let expectation = self.expectationWithDescription(__FUNCTION__) // Act iap.saveReceipt { (_, error:NSError?) -> () in // Assert XCTAssertNotNil(error, "IAP should not have been initalized") expectation.fulfill() } // Async wait self.waitForExpectationsWithTimeout(0.1) { (error:NSError?) -> Void in IAPLog("\(__FUNCTION__) failed to return") } } func testSaveReceiptReturnsTrue() { // Arrange let iap = InAppPurchase(apiKey: "a", userId: "b") let dataToReturn = "{\"validReceipt\":true}".dataUsingEncoding(NSUTF8StringEncoding)! let mockNetwork = MockIAPNetworkService(obj: dataToReturn) iap.networkService = mockNetwork let expectation = self.expectationWithDescription(__FUNCTION__) // Act iap.saveReceipt { (model:IAPModel?, _) -> () in // Assert XCTAssertTrue(model!.validReceipt, "Receipt should be valid") expectation.fulfill() } // Async wait self.waitForExpectationsWithTimeout(0.1) { (error:NSError?) -> Void in IAPLog("\(__FUNCTION__) failed to return") } } func testBadDataReturnsError() { // Arrange let iap = InAppPurchase(apiKey: "a", userId: "b") let dataToReturn = "{\"garbage\":".dataUsingEncoding(NSUTF8StringEncoding)! let mockNetwork = MockIAPNetworkService(obj: dataToReturn) iap.networkService = mockNetwork let expectation = self.expectationWithDescription(__FUNCTION__) // Act iap.saveReceipt { (_, error:NSError?) -> () in // Assert XCTAssertNotNil(error, "Should have an error") expectation.fulfill() } // Async wait self.waitForExpectationsWithTimeout(0.1) { (error:NSError?) -> Void in IAPLog("\(__FUNCTION__) failed to return") } } }
mit
6828082eb1bf97e3c3d5ab19dd0ce59d
35.019231
93
0.628137
4.747782
false
true
false
false
evgenyneu/moa
MoaTests/Utils/MoaTimeTests.swift
1
506
import Foundation import XCTest class MoaTimeTests: XCTestCase { func testLogTimeDate() { let calendar = Calendar.current let components = NSDateComponents() components.year = 2027 components.month = 11 components.day = 21 components.hour = 13 components.minute = 51 components.second = 41 let date = calendar.date(from: components as DateComponents)! let result = MoaTime.logTime(date) XCTAssertEqual("2027-11-21 02:51:41.000", result) } }
mit
806b9feb73d3793e48d99b9091578a6a
22
65
0.679842
4.113821
false
true
false
false
jpush/jchat-swift
JChat/Src/UserModule/ViewController/MyQRCodeViewController.swift
1
8313
// // MyQRCodeViewController.swift // JChat // // Created by JIGUANG on 2017/8/15. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit class MyQRCodeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() _init() } fileprivate lazy var infoView: UIView = { var infoView = UIView() infoView.backgroundColor = .white return infoView }() private lazy var avator: UIImageView = { var avator = UIImageView() return avator }() private lazy var qrcode: UIImageView = { var qrcode = UIImageView() return qrcode }() private lazy var tipsLabel: UILabel = { var tipsLabel = UILabel() tipsLabel.textAlignment = .center tipsLabel.text = "扫一扫上面二维码,加我为好友吧!" tipsLabel.font = UIFont.systemFont(ofSize: 12) tipsLabel.textColor = UIColor(netHex: 0x999999) return tipsLabel }() private lazy var usernameLabel: UILabel = { var usernameLabel = UILabel() usernameLabel.textAlignment = .center usernameLabel.font = UIFont.systemFont(ofSize: 15) usernameLabel.textColor = UIColor(netHex: 0x999999) return usernameLabel }() private func _init() { self.title = "我的二维码" self.view.backgroundColor = UIColor(netHex: 0xE8EDF3) _setupNavigation() infoView.addSubview(avator) infoView.addSubview(usernameLabel) infoView.addSubview(qrcode) infoView.addSubview(tipsLabel) view.addSubview(infoView) view.addConstraint(_JCLayoutConstraintMake(infoView, .left, .equal, view, .left, 22.5)) view.addConstraint(_JCLayoutConstraintMake(infoView, .right, .equal, view, .right, -22.5)) view.addConstraint(_JCLayoutConstraintMake(infoView, .top, .equal, view, .top, 64 + 41.5)) view.addConstraint(_JCLayoutConstraintMake(infoView, .bottom, .equal, view, .bottom, -80.5)) infoView.addConstraint(_JCLayoutConstraintMake(avator, .centerX, .equal, infoView, .centerX)) infoView.addConstraint(_JCLayoutConstraintMake(avator, .top, .equal, infoView, .top, 44.5)) infoView.addConstraint(_JCLayoutConstraintMake(avator, .width, .equal, nil, .notAnAttribute, 80)) infoView.addConstraint(_JCLayoutConstraintMake(avator, .height, .equal, nil, .notAnAttribute, 80)) infoView.addConstraint(_JCLayoutConstraintMake(usernameLabel, .left, .equal, infoView, .left)) infoView.addConstraint(_JCLayoutConstraintMake(usernameLabel, .top, .equal, avator, .bottom, 11.5)) infoView.addConstraint(_JCLayoutConstraintMake(usernameLabel, .right, .equal, infoView, .right)) infoView.addConstraint(_JCLayoutConstraintMake(usernameLabel, .height, .equal, nil, .notAnAttribute, 21)) infoView.addConstraint(_JCLayoutConstraintMake(qrcode, .centerX, .equal, infoView, .centerX)) infoView.addConstraint(_JCLayoutConstraintMake(qrcode, .top, .equal, avator, .bottom, 60)) infoView.addConstraint(_JCLayoutConstraintMake(qrcode, .width, .equal, nil, .notAnAttribute, 240)) infoView.addConstraint(_JCLayoutConstraintMake(qrcode, .height, .equal, nil, .notAnAttribute, 240)) infoView.addConstraint(_JCLayoutConstraintMake(tipsLabel, .left, .equal, infoView, .left)) infoView.addConstraint(_JCLayoutConstraintMake(tipsLabel, .top, .equal, qrcode, .bottom, 19)) infoView.addConstraint(_JCLayoutConstraintMake(tipsLabel, .right, .equal, infoView, .right)) infoView.addConstraint(_JCLayoutConstraintMake(tipsLabel, .height, .equal, nil, .notAnAttribute, 16.5)) _bindData() } private func _bindData() { let user = JMSGUser.myInfo() let username = user.username let appkey = user.appKey user.thumbAvatarData { (data, id, error) in if let data = data { self.avator.image = UIImage(data: data) } else { self.avator.image = UIImage.loadImage("com_icon_user_80") } } usernameLabel.text = "用户名:\(username)" let url = "{\"type\":\"user\",\"user\": {\"appkey\":\"\(appkey ?? "")\",\"username\": \"\(username)\",\"platform\": \"iOS\"}}" qrcode.image = createQRForString(qrString: url, qrImageName: nil) } func createQRForString(qrString: String?, qrImageName: String?) -> UIImage?{ if let sureQRString = qrString{ let stringData = sureQRString.data(using: String.Encoding.utf8, allowLossyConversion: false) //创建一个二维码的滤镜 let qrFilter = CIFilter(name: "CIQRCodeGenerator") qrFilter?.setValue(stringData, forKey: "inputMessage") qrFilter?.setValue("H", forKey: "inputCorrectionLevel") let qrCIImage = qrFilter?.outputImage // 创建一个颜色滤镜,黑白色 let colorFilter = CIFilter(name: "CIFalseColor")! colorFilter.setDefaults() colorFilter.setValue(qrCIImage, forKey: "inputImage") colorFilter.setValue(CIColor(red: 0, green: 0, blue: 0), forKey: "inputColor0") colorFilter.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1") // 返回二维码image let codeImage = UIImage(ciImage: (colorFilter.outputImage!.transformed(by: CGAffineTransform(scaleX: 5, y: 5)))) // 中间一般放logo guard let imageName = qrImageName else { return codeImage } if let iconImage = UIImage(named: imageName) { let rect = CGRect(x: 0, y: 0, width: codeImage.size.width, height: codeImage.size.height) UIGraphicsBeginImageContext(rect.size) codeImage.draw(in: rect) let avatarSize = CGSize(width: rect.size.width*0.25, height: rect.size.height*0.25) let x = (rect.width - avatarSize.width) * 0.5 let y = (rect.height - avatarSize.height) * 0.5 iconImage.draw(in: CGRect(x: x, y: y, width: avatarSize.width, height: avatarSize.height)) let resultImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resultImage } return codeImage } return nil } private func _setupNavigation() { let navButton = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 18)) navButton.setImage(UIImage.loadImage("com_icon_file_more"), for: .normal) navButton.addTarget(self, action: #selector(_saveImage), for: .touchUpInside) let item1 = UIBarButtonItem(customView: navButton) navigationItem.rightBarButtonItems = [item1] } @objc func _saveImage() { let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "保存图片") actionSheet.show(in: view) } func makeImage(_ view: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(view.size, false, UIScreen.main.scale) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } extension MyQRCodeViewController: UIActionSheetDelegate { func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) { if buttonIndex == 1 { let image = makeImage(infoView) UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil) } } @objc func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer){ if error == nil { MBProgressHUD_JChat.show(text: "保存成功", view: view) } else { MBProgressHUD_JChat.show(text: "保存失败,请重试", view: view) } } }
mit
b750a25558fab31aad5604f49e7b4255
42.88172
148
0.629258
4.704323
false
false
false
false
coderMONSTER/iosstar
iOSStar/AppAPI/SocketAPI/SocketReqeust/APISocketHelper.swift
1
4330
// // APISocketHelper.swift // viossvc // // Created by yaowang on 2016/11/21. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit import CocoaAsyncSocket //import XCGLogger import SVProgressHUD class APISocketHelper:NSObject, GCDAsyncSocketDelegate,SocketHelper { var socket: GCDAsyncSocket?; var dispatch_queue: DispatchQueue!; var mutableData: NSMutableData = NSMutableData(); var packetHead:SocketPacketHead = SocketPacketHead(); var isConnected : Bool { return socket!.isConnected } override init() { super.init() dispatch_queue = DispatchQueue(label: "APISocket_Queue", attributes: DispatchQueue.Attributes.concurrent) socket = GCDAsyncSocket.init(delegate: self, delegateQueue: dispatch_queue); connect() } func connect() { mutableData = NSMutableData() do { if !socket!.isConnected { var host = "" var port: UInt16 = 0 if AppConst.isMock{ host = AppConst.Network.TcpServerIP port = AppConst.Network.TcpServerPort }else{ host = AppConst.Network.TcpServerIP port = AppConst.Network.TcpServerPort } try socket?.connect(toHost: host, onPort: port, withTimeout: 5) } } catch GCDAsyncSocketError.closedError { print("¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯") } catch GCDAsyncSocketError.connectTimeoutError { print("<<<<<<<<<<<<<<<<<<<<<<<<") } catch { print(">>>>>>>>>>>>>>>>>>>>>>>") } } func disconnect() { socket?.delegate = nil; socket?.disconnect() } func sendData(_ data: Data) { objc_sync_enter(self) socket?.write(data, withTimeout: -1, tag: 0) objc_sync_exit(self) } func onPacketData(_ data: Data) { memset(&packetHead,0, MemoryLayout<SocketPacketHead>.size) (data as NSData).getBytes(&packetHead, length: MemoryLayout<SocketPacketHead>.size) if( Int(packetHead.packet_length) - MemoryLayout<SocketPacketHead>.size == Int(packetHead.data_length) ) { let packet: SocketDataPacket = SocketDataPacket(socketData: data as NSData) SocketRequestManage.shared.notifyResponsePacket(packet) } else { debugPrint("onPacketData error packet_length:\(packetHead.packet_length) packet_length:\(packetHead.data_length) data:\(data.count)"); } } //MARK: GCDAsyncSocketDelegate @objc func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { debugPrint("didConnectToHost host:\(host) port:\(port)") sock.perform({ () -> Void in sock.enableBackgroundingOnSocket() }); socket?.readData(withTimeout: -1, tag: 0) } @objc func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: CLong) { // XCGLogger.debug("socket:\(data)") mutableData.append(data) while mutableData.length >= 26 { var packetLen: Int16 = 0; mutableData.getBytes(&packetLen, length: MemoryLayout<Int16>.size) if mutableData.length >= Int(packetLen) { var range: NSRange = NSMakeRange(0, Int(packetLen)) onPacketData(mutableData.subdata(with: range)) range.location = range.length; range.length = mutableData.length - range.location; mutableData = (mutableData.subdata(with: range) as NSData).mutableCopy() as! NSMutableData; } else { break } } socket?.readData(withTimeout: -1, tag: 0) } @objc func socket(_ sock: GCDAsyncSocket, shouldTimeoutReadWithTag tag: CLong, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval { return 0 } @objc func socket(_ sock: GCDAsyncSocket, shouldTimeoutWriteWithTag tag: CLong, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval { return 0 } @objc func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { } deinit { socket?.disconnect() } }
gpl-3.0
258a62ec90c5b008f9ced19b873fcd21
34.00813
148
0.594055
4.660173
false
false
false
false
Railsreactor/json-data-sync-swift
JDSKit/Utils/CoreError.swift
1
3006
// // CoreError.swift // JDSKit // // Created by Igor Reshetnikov on 10/25/15. // Copyright © 2015 IT. All rights reserved. // import UIKit typealias RetryHandler = () -> Void public let SNLocalizedTitleKey: String = "kSNLocalizedTitle" public let SNAPIErrorSourceKey: String = "kSNAAPISource" public let SNAPIErrorsKey: String = "kSNAPIErrors" public enum CoreError: Error { case runtimeError(description: String, cause: NSError?) case connectionProblem(description: String, cause: NSError?) case wrongCredentials case serviceError(description: String, cause: NSError?) case validationError(apiErrors: [NSError]) case entityMisstype(input: String, target: String) public var errorInfo: (code: Int, message: String?, cause: NSError?, actionTitle: String?) { var code: Int, message: String?, cause: NSError?, actionTitle: String? switch self { case .runtimeError(let aDescription, let aCause): code = 0 cause = aCause message = aDescription case .connectionProblem(let aDescription, let aCause): code = 1 cause = aCause message = aDescription case .serviceError(let aDescription, let aCause): code = 2 cause = aCause message = aDescription case .validationError(let apiErrors): code = 3 if apiErrors.count > 0 { message = localizedDescriptionFromAPIErrors() } case .wrongCredentials: code = 4 message = "Wrong username or password." actionTitle = "Logout" case .entityMisstype(let input, let target): code = 8 message = "Failed to save entity of type \(input). Expected: \(target)" actionTitle = "OK" } return (code: code, message: message, cause: cause, actionTitle: actionTitle) } public func extractAPIErrors() -> [NSError] { switch self { case .validationError(let apiErrors): return apiErrors default: break } return [NSError]() } public func localizedDescriptionFromAPIErrors() -> String { var description = "" for apiError in extractAPIErrors() { if let source = apiError.userInfo[SNAPIErrorSourceKey] as? [String: String] { if let pointer = source["pointer"] { let titleChars = pointer.characters.split { $0 == "/" }.last if titleChars != nil && !titleChars!.elementsEqual("base".characters) { description += String(titleChars!).capitalized + " " } } description += apiError.localizedDescription + "\n" } } return description } }
mit
5df5bf2abe7cff467b9e8522f3b54959
30.631579
96
0.560399
4.942434
false
false
false
false
codeWorm2015/LRLPhotoBrowser
Sources/LRLPBVideoView.swift
1
7849
// // LRLPBVideoView.swift // LRLPhotoBrowserDemo // // Created by liuRuiLong on 2017/6/18. // Copyright © 2017年 codeWorm. All rights reserved. // import UIKit import AVFoundation import MBProgressHUD class LRLPBVideoView: LRLPBImageView { let statuKey = "status" let keepUpKey = "playbackLikelyToKeepUp" let bufferEmptyKey = "playbackBufferEmpty" let bufferFullKey = "playbackBufferFull" let presentationSizeKey = "presentationSize" var playerLayer: AVPlayerLayer = AVPlayerLayer() var playerUrl: URL? var videoSize: CGSize? private lazy var startButton: UIButton = { let img = LRLPBAssetManager.getImage(named: "btn_play") let button = UIButton(frame: CGRect(x: self.bounds.size.width/2 - 25, y:self.bounds.size.height/2 - 25, width: 50, height: 50)) button.setImage(img, for: .normal) button.addTarget(self, action: #selector(play), for: .touchUpInside) return button }() private var _player: AVPlayer? var player: AVPlayer?{ get{ if let inPlayer = _player{ return inPlayer }else{ _player = AVPlayer(playerItem: playerItem) return _player } } set{ _player = newValue } } private var _playerItem: AVPlayerItem? var playerItem: AVPlayerItem?{ get{ if let inPlayerItem = _playerItem{ return inPlayerItem }else{ if let url = self.playerUrl{ _playerItem = AVPlayerItem(url: url) _playerItem?.addObserver(self, forKeyPath: self.statuKey, options: [.new, .old], context: nil) _playerItem?.addObserver(self, forKeyPath: self.keepUpKey, options: [.new, .old], context: nil) _playerItem?.addObserver(self, forKeyPath: self.bufferEmptyKey, options: [.new, .old], context: nil) _playerItem?.addObserver(self, forKeyPath: self.bufferFullKey, options: [.new, .old], context: nil) _playerItem?.addObserver(self, forKeyPath: self.presentationSizeKey, options: [.new, .old], context: nil) return _playerItem }else{ return nil } } } set{ if newValue == nil{ _playerItem?.removeObserver(self, forKeyPath: statuKey) _playerItem?.removeObserver(self, forKeyPath: keepUpKey) _playerItem?.removeObserver(self, forKeyPath: bufferEmptyKey) _playerItem?.removeObserver(self, forKeyPath: bufferFullKey) _playerItem?.removeObserver(self, forKeyPath: presentationSizeKey) } _playerItem = newValue } } override var frame: CGRect{ set{ super.frame = newValue scrollView.frame = super.bounds startButton.frame = CGRect(x: self.bounds.size.width/2 - 25, y:self.bounds.size.height/2 - 25, width: 50, height: 50) updateUI() } get{ return super.frame } } deinit { player?.pause() player = nil playerItem = nil NotificationCenter.default.removeObserver(self) } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(startButton) NotificationCenter.default.addObserver(self, selector: #selector(willInBackground), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(didInforeground), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } func setVideoUrlStr(url: URL, palceHolder: UIImage?) { image = palceHolder playerUrl = url } var progress: MBProgressHUD? func play() { playerLayer.player = player playerLayer.frame = self.imageView.bounds imageView.layer.addSublayer(playerLayer) progress = MBProgressHUD.showAdded(to: self, animated: true) progress?.removeFromSuperViewOnHide = false progress?.mode = .indeterminate progress?.show(animated: true) startButton.isHidden = true player?.play() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let inKeyPath = keyPath, let item = playerItem else { return } switch inKeyPath { case statuKey: LRLDLog("statuKey") switch item.status { case .readyToPlay: LRLDLog("readyToPlay") case .failed: fallthrough case .unknown: progress?.hide(animated: true) let errorAlert = MBProgressHUD.showAdded(to: self, animated: true) errorAlert.mode = .text errorAlert.label.text = "播放失败" errorAlert.hide(animated: true, afterDelay: 1.0) LRLDLog("unknown || error") } case keepUpKey: LRLDLog("keepUpKey") if item.isPlaybackLikelyToKeepUp { progress?.hide(animated: true) } case bufferEmptyKey: LRLDLog("bufferEmptyKey") progress?.show(animated: true) case bufferFullKey: LRLDLog("bufferFullKey") progress?.hide(animated: true) case presentationSizeKey: LRLDLog("presentationSizeKey") self.videoSize = item.presentationSize UIView.animate(withDuration: 0.3, animations: { self.updateUI() }) default: break } } override func endDisplay() { if zooming{ outZoom() } progress?.hide(animated: true) startButton.isHidden = false player?.pause() playerLayer.player = nil player = nil playerItem = nil } override func updateUI() { if self.videoSize == nil{ guard image != nil && self.bounds.size.width > 0 && self.bounds.size.height > 0 else { return } } switch self.contentMode { case .scaleToFill: self.updateToScaleToFill() case .scaleAspectFit: if let inVideoSize = videoSize{ updateToScaleAspectFit(showSize: inVideoSize, scale: 1.0) }else{ updateToScaleAspectFit(showSize: image!.size, scale: image!.scale) } case .scaleAspectFill: if let inVideoSize = videoSize{ updateToScaleAspectFill(showSize: inVideoSize, scale: 1.0) }else{ updateToScaleAspectFill(showSize: image!.size, scale: image!.scale) } default: break } playerLayer.frame = self.imageView.bounds if imageView.bounds.height < scrollView.bounds.height/2{ scrollView.maximumZoomScale = scrollView.bounds.height/imageView.bounds.height }else{ if scrollView.bounds.width < scrollView.bounds.width { scrollView.maximumZoomScale = scrollView.bounds.width/imageView.bounds.width }else{ scrollView.maximumZoomScale = 2.0 } } } func willInBackground() { player?.pause() } func didInforeground() { player?.play() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
7f63425bb9f9310178293089a2d30957
34.306306
161
0.571319
4.838272
false
false
false
false
hironytic/Kiretan0
Kiretan0Tests/Mock/Model/Utility/MockDataStore.swift
1
11505
// // MockDataStore.swift // Kiretan0Tests // // Copyright (c) 2018 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import XCTest import RxSwift @testable import Kiretan0 class MockDataStore: DataStore { class MockFunctionsForObserveDocument { var typeMap = [String: Any]() func install<E: Entity>(_ mockFunction: MockFunction<(DocumentPath) -> Observable<E?>>) { let typeString = String(describing: E.self) typeMap[typeString] = mockFunction } } class MockFunctionsForObserveCollection { var typeMap = [String: Any]() func install<E: Entity>(_ mockFunction: MockFunction<(DataStoreQuery) -> Observable<CollectionChange<E>>>) { let typeString = String(describing: E.self) typeMap[typeString] = mockFunction } } class Mock { var deletePlaceholder = MockFunction<() -> Any>("MockDataStore.deletePlaceholder") var serverTimestampPlaceholder = MockFunction<() -> Any>("MockDataStore.serverTimestampPlaceholder") var collection = MockFunction<(String) -> CollectionPath>("MockDataStore.collection") var observeDocument = MockFunctionsForObserveDocument() var observeCollection = MockFunctionsForObserveCollection() var write = MockFunction<(@escaping (DocumentWriter) throws -> Void) -> Completable>("MockDataStore.write") init() { deletePlaceholder.setup { return MockDataStorePlaceholder.deletePlaceholder } serverTimestampPlaceholder.setup { return MockDataStorePlaceholder.serverTimestampPlaceholder } collection.setup { return MockCollectionPath(path: "/\($0)")} } } let mock = Mock() var deletePlaceholder: Any { return mock.deletePlaceholder.call() } var serverTimestampPlaceholder: Any { return mock.serverTimestampPlaceholder.call() } func collection(_ collectionID: String) -> CollectionPath { return mock.collection.call(collectionID) } func observeDocument<E: Entity>(at documentPath: DocumentPath) -> Observable<E?> { let typeString = String(describing: E.self) guard let mockFunction = mock.observeDocument.typeMap[typeString] as? MockFunction<(DocumentPath) -> Observable<E?>> else { XCTFail("mock for observeDocument is not installed") fatalError() } return mockFunction.call(documentPath) } func observeCollection<E: Entity>(matches query: DataStoreQuery) -> Observable<CollectionChange<E>> { let typeString = String(describing: E.self) guard let mockFunction = mock.observeCollection.typeMap[typeString] as? MockFunction<(DataStoreQuery) -> Observable<CollectionChange<E>>> else { XCTFail("mock for observeCollection is not installed") fatalError() } return mockFunction.call(query) } func write(block: @escaping (DocumentWriter) throws -> Void) -> Completable { return mock.write.call(block) } } enum MockDataStorePlaceholder { case deletePlaceholder case serverTimestampPlaceholder } class MockDataStoreQuery: DataStoreQuery { class Mock { var whereFieldIsEqualTo = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsEqualTo") var whereFieldIsLessThan = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsLessThan") var whereFieldIsLessThanOrEqualTo = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsLessThanOrEqualTo") var whereFieldIsGreaterThan = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsGreaterThan") var whereFieldIsGreaterThanOrEqualTo = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsGreaterThanOrEqualTo") var orderBy = MockFunction<(String) -> DataStoreQuery>("MockDataStoreQuery.orderBy") var orderByDescending = MockFunction<(String, Bool) -> DataStoreQuery>("MockDataStoreQuery.orderByDescending") init(path: String) { whereFieldIsEqualTo.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)=={\(value)}") } whereFieldIsLessThan.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)<{\(value)}") } whereFieldIsLessThanOrEqualTo.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)<={\(value)}") } whereFieldIsGreaterThan.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)>{\(value)}") } whereFieldIsGreaterThanOrEqualTo.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)>={\(value)}") } orderBy.setup { (field) in return MockDataStoreQuery(path: path + "@\(field):asc") } orderByDescending.setup { (field, isDescending) in let direction = isDescending ? "desc" : "asc" return MockDataStoreQuery(path: path + "@\(field):\(direction)") } } } let mock: Mock let path: String init(path: String = "") { mock = Mock(path: path) self.path = path } func whereField(_ field: String, isEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsEqualTo.call(field, value) } func whereField(_ field: String, isLessThan value: Any) -> DataStoreQuery { return mock.whereFieldIsLessThan.call(field, value) } func whereField(_ field: String, isLessThanOrEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsLessThanOrEqualTo.call(field, value) } func whereField(_ field: String, isGreaterThan value: Any) -> DataStoreQuery { return mock.whereFieldIsGreaterThan.call(field, value) } func whereField(_ field: String, isGreaterThanOrEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsGreaterThanOrEqualTo.call(field, value) } func order(by field: String) -> DataStoreQuery { return mock.orderBy.call(field) } func order(by field: String, descending: Bool) -> DataStoreQuery { return mock.orderByDescending.call(field, descending) } } class MockCollectionPath: CollectionPath { class Mock: MockDataStoreQuery.Mock { var collectionID = MockFunction<() -> String>("MockCollectionPath.collectionID") var document = MockFunction<() -> DocumentPath>("MockCollectionPath.document") var documentForID = MockFunction<(String) -> DocumentPath>("MockCollectionPath.documentForID") override init(path: String) { collectionID.setup { return String(path.split(separator: "/", omittingEmptySubsequences: false).last!) } document.setup { return MockDocumentPath(path: path + "/\(UUID().uuidString)") } documentForID.setup { return MockDocumentPath(path: path + "/\($0)") } super.init(path: path) } } let mock: Mock let path: String init(path: String) { mock = Mock(path: path) self.path = path } func whereField(_ field: String, isEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsEqualTo.call(field, value) } func whereField(_ field: String, isLessThan value: Any) -> DataStoreQuery { return mock.whereFieldIsLessThan.call(field, value) } func whereField(_ field: String, isLessThanOrEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsLessThanOrEqualTo.call(field, value) } func whereField(_ field: String, isGreaterThan value: Any) -> DataStoreQuery { return mock.whereFieldIsGreaterThan.call(field, value) } func whereField(_ field: String, isGreaterThanOrEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsGreaterThanOrEqualTo.call(field, value) } func order(by field: String) -> DataStoreQuery { return mock.orderBy.call(field) } func order(by field: String, descending: Bool) -> DataStoreQuery { return mock.orderByDescending.call(field, descending) } var collectionID: String { return mock.collectionID.call() } func document() -> DocumentPath { return mock.document.call() } func document(_ documentID: String) -> DocumentPath { return mock.documentForID.call(documentID) } } class MockDocumentPath: DocumentPath { class Mock { var documentID = MockFunction<() -> String>("MockDocumentPath.documentID") var collection = MockFunction<(String) -> CollectionPath>("MockDocumentPath.collection") init(path: String) { documentID.setup { return String(path.split(separator: "/", omittingEmptySubsequences: false).last!) } collection.setup { return MockCollectionPath(path: path + "/\($0)") } } } let mock: Mock let path: String init(path: String) { mock = Mock(path: path) self.path = path } var documentID: String { return mock.documentID.call() } func collection(_ collectionID: String) -> CollectionPath { return mock.collection.call(collectionID) } } class MockDocumentWriter: DocumentWriter { class Mock { var setDocumentData = MockFunction<([String: Any], DocumentPath) -> Void>("MockDocumentWriter.setDocumentData") var updateDocumentData = MockFunction<([String: Any], DocumentPath) -> Void>("MockDocumentWriter.updateDocumentData") var mergeDocumentData = MockFunction<([String: Any], DocumentPath) -> Void>("MockDocumentWriter.mergeDocumentData") var deleteDocument = MockFunction<(DocumentPath) -> Void>("MockDocumentWriter.deleteDocument") } let mock = Mock() func setDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { mock.setDocumentData.call(documentData, documentPath) } func updateDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { mock.updateDocumentData.call(documentData, documentPath) } func mergeDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { mock.mergeDocumentData.call(documentData, documentPath) } func deleteDocument(at documentPath: DocumentPath) { mock.deleteDocument.call(documentPath) } }
mit
b6b996ca66ff2d754ebefe7c0dce4d8e
43.593023
152
0.68292
4.570918
false
false
false
false
tjw/swift
stdlib/public/core/ContiguousArrayBuffer.swift
1
23648
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. /// Because it's statically referenced, it requires non-lazy realization /// by the Objective-C runtime. @_fixed_layout @usableFromInline @_objc_non_lazy_realization internal final class _EmptyArrayStorage : _ContiguousArrayStorageBase { @inlinable @nonobjc internal init(_doNotCallMe: ()) { _sanityCheckFailure("creating instance of _EmptyArrayStorage") } #if _runtime(_ObjC) @inlinable override internal func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { return try body(UnsafeBufferPointer(start: nil, count: 0)) } @inlinable @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { return 0 } @inlinable override internal func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> { return _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, 0, 0) } #endif @inlinable override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool { return false } /// A type that every element in the array is. @inlinable override internal var staticElementType: Any.Type { return Void.self } } /// The empty array prototype. We use the same object for all empty /// `[Native]Array<Element>`s. @inlinable internal var _emptyArrayStorage : _EmptyArrayStorage { return Builtin.bridgeFromRawPointer( Builtin.addressof(&_swiftEmptyArrayStorage)) } // The class that implements the storage for a ContiguousArray<Element> @_fixed_layout // FIXME(sil-serialize-all) @usableFromInline internal final class _ContiguousArrayStorage< Element > : _ContiguousArrayStorageBase { @inlinable // FIXME(sil-serialize-all) deinit { _elementPointer.deinitialize(count: countAndCapacity.count) _fixLifetime(self) } #if _runtime(_ObjC) /// If the `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. @inlinable internal final override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { var result: R? try self._withVerbatimBridgedUnsafeBufferImpl { result = try body($0) } return result } /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. @inlinable internal final func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } try body(UnsafeBufferPointer(start: elements, count: count)) } } /// Returns the number of elements in the array. /// /// - Precondition: `Element` is bridged non-verbatim. @inlinable @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") return countAndCapacity.count } /// Bridge array elements and return a new buffer that owns them. /// /// - Precondition: `Element` is bridged non-verbatim. @inlinable override internal func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") let count = countAndCapacity.count let result = _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, count, count) let resultPtr = result.baseAddress let p = _elementPointer for i in 0..<count { (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i])) } _fixLifetime(self) return result } #endif /// Returns `true` if the `proposedElementType` is `Element` or a subclass of /// `Element`. We can't store anything else without violating type /// safety; for example, the destructor has static knowledge that /// all of the elements can be destroyed as `Element`. @inlinable internal override func canStoreElements( ofDynamicType proposedElementType: Any.Type ) -> Bool { #if _runtime(_ObjC) return proposedElementType is Element.Type #else // FIXME: Dynamic casts don't currently work without objc. // rdar://problem/18801510 return false #endif } /// A type that every element in the array is. @inlinable internal override var staticElementType: Any.Type { return Element.self } @inlinable internal final var _elementPointer : UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } } @usableFromInline @_fixed_layout internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol { /// Make a buffer with uninitialized elements. After using this /// method, you must either initialize the `count` elements at the /// result's `.firstElementAddress` or set the result's `.count` /// to zero. @inlinable internal init( _uninitializedCount uninitializedCount: Int, minimumCapacity: Int ) { let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity) if realMinimumCapacity == 0 { self = _ContiguousArrayBuffer<Element>() } else { _storage = Builtin.allocWithTailElems_1( _ContiguousArrayStorage<Element>.self, realMinimumCapacity._builtinWordValue, Element.self) let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage)) let endAddr = storageAddr + _stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress _initStorageHeader( count: uninitializedCount, capacity: realCapacity) } } /// Initialize using the given uninitialized `storage`. /// The storage is assumed to be uninitialized. The returned buffer has the /// body part of the storage initialized, but not the elements. /// /// - Warning: The result has uninitialized elements. /// /// - Warning: storage may have been stack-allocated, so it's /// crucial not to call, e.g., `malloc_size` on it. @inlinable internal init(count: Int, storage: _ContiguousArrayStorage<Element>) { _storage = storage _initStorageHeader(count: count, capacity: count) } @inlinable internal init(_ storage: _ContiguousArrayStorageBase) { _storage = storage } /// Initialize the body part of our storage. /// /// - Warning: does not initialize elements @inlinable internal func _initStorageHeader(count: Int, capacity: Int) { #if _runtime(_ObjC) let verbatim = _isBridgedVerbatimToObjectiveC(Element.self) #else let verbatim = false #endif // We can initialize by assignment because _ArrayBody is a trivial type, // i.e. contains no references. _storage.countAndCapacity = _ArrayBody( count: count, capacity: capacity, elementTypeIsBridgedVerbatim: verbatim) } /// True, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return true } /// A pointer to the first element. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(_storage, Element.self)) } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } //===--- _ArrayBufferProtocol conformance -----------------------------------===// /// Create an empty buffer. @inlinable internal init() { _storage = _emptyArrayStorage } @inlinable internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") self = buffer } @inlinable internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? { if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) { return self } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } @inlinable internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { return self } @inlinable @inline(__always) internal func getElement(_ i: Int) -> Element { _sanityCheck(i >= 0 && i < count, "Array index out of range") return firstElementAddress[i] } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { @inline(__always) get { return getElement(i) } @inline(__always) nonmutating set { _sanityCheck(i >= 0 && i < count, "Array index out of range") // FIXME: Manually swap because it makes the ARC optimizer happy. See // <rdar://problem/16831852> check retain/release order // firstElementAddress[i] = newValue var nv = newValue let tmp = nv nv = firstElementAddress[i] firstElementAddress[i] = tmp } } /// The number of elements the buffer stores. @inlinable internal var count: Int { get { return _storage.countAndCapacity.count } nonmutating set { _sanityCheck(newValue >= 0) _sanityCheck( newValue <= capacity, "Can't grow an array buffer past its capacity") _storage.countAndCapacity.count = newValue } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkValidSubscript(_ index : Int) { _precondition( (index >= 0) && (index < count), "Index out of range" ) } /// The number of elements the buffer can store without reallocation. @inlinable internal var capacity: Int { return _storage.countAndCapacity.capacity } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _sanityCheck(bounds.lowerBound >= 0) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= count) let initializedCount = bounds.upperBound - bounds.lowerBound target.initialize( from: firstElementAddress + bounds.lowerBound, count: initializedCount) _fixLifetime(owner) return target + initializedCount } /// Returns a `_SliceBuffer` containing the given `bounds` of values /// from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { return _SliceBuffer( owner: _storage, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: true) } set { fatalError("not implemented") } } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// - Note: This does not mean the buffer is mutable. Other factors /// may need to be considered, such as whether the buffer could be /// some immutable Cocoa container. @inlinable internal mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } /// Returns `true` iff this buffer's storage is either /// uniquely-referenced or pinned. NOTE: this does not mean /// the buffer is mutable; see the comment on isUniquelyReferenced. @inlinable internal mutating func isUniquelyReferencedOrPinned() -> Bool { return _isUniqueOrPinned(&_storage) } #if _runtime(_ObjC) /// Convert to an NSArray. /// /// - Precondition: `Element` is bridged to Objective-C. /// /// - Complexity: O(1). @inlinable internal func _asCocoaArray() -> _NSArrayCore { if count == 0 { return _emptyArrayStorage } if _isBridgedVerbatimToObjectiveC(Element.self) { return _storage } return _SwiftDeferredNSArray(_nativeStorage: _storage) } #endif /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _storage } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var nativeOwner: AnyObject { return _storage } /// A value that identifies the storage used by the buffer. /// /// Two buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// Returns `true` iff we have storage for elements of the given /// `proposedElementType`. If not, we'll be treated as immutable. @inlinable func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool { return _storage.canStoreElements(ofDynamicType: proposedElementType) } /// Returns `true` if the buffer stores only elements of type `U`. /// /// - Precondition: `U` is a class or `@objc` existential. /// /// - Complexity: O(*n*) @inlinable internal func storesOnlyElementsOfType<U>( _: U.Type ) -> Bool { _sanityCheck(_isClassOrObjCExistential(U.self)) if _fastPath(_storage.staticElementType is U.Type) { // Done in O(1) return true } // Check the elements for x in self { if !(x is U) { return false } } return true } @usableFromInline internal var _storage: _ContiguousArrayStorageBase } /// Append the elements of `rhs` to `lhs`. @inlinable internal func += <Element, C : Collection>( lhs: inout _ContiguousArrayBuffer<Element>, rhs: C ) where C.Element == Element { let oldCount = lhs.count let newCount = oldCount + numericCast(rhs.count) let buf: UnsafeMutableBufferPointer<Element> if _fastPath(newCount <= lhs.capacity) { buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) lhs.count = newCount } else { var newLHS = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCount, minimumCapacity: _growArrayCapacity(lhs.capacity)) newLHS.firstElementAddress.moveInitialize( from: lhs.firstElementAddress, count: oldCount) lhs.count = 0 (lhs, newLHS) = (newLHS, lhs) buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) } var (remainders,writtenUpTo) = buf.initialize(from: rhs) // ensure that exactly rhs.count elements were written _precondition(remainders.next() == nil, "rhs underreported its count") _precondition(writtenUpTo == buf.endIndex, "rhs overreported its count") } extension _ContiguousArrayBuffer : RandomAccessCollection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable internal var endIndex: Int { return count } internal typealias Indices = Range<Int> } extension Sequence { @inlinable public func _copyToContiguousArray() -> ContiguousArray<Element> { return _copySequenceToContiguousArray(self) } } @inlinable internal func _copySequenceToContiguousArray< S : Sequence >(_ source: S) -> ContiguousArray<S.Element> { let initialCapacity = source.underestimatedCount var builder = _UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>( initialCapacity: initialCapacity) var iterator = source.makeIterator() // FIXME(performance): use _copyContents(initializing:). // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { builder.addWithExistingCapacity(iterator.next()!) } // Add remaining elements, if any. while let element = iterator.next() { builder.add(element) } return builder.finish() } extension Collection { @inlinable public func _copyToContiguousArray() -> ContiguousArray<Element> { return _copyCollectionToContiguousArray(self) } } extension _ContiguousArrayBuffer { @inlinable internal func _copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(_buffer: self) } } /// This is a fast implementation of _copyToContiguousArray() for collections. /// /// It avoids the extra retain, release overhead from storing the /// ContiguousArrayBuffer into /// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support /// ARC loops, the extra retain, release overhead cannot be eliminated which /// makes assigning ranges very slow. Once this has been implemented, this code /// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer. @inlinable internal func _copyCollectionToContiguousArray< C : Collection >(_ source: C) -> ContiguousArray<C.Element> { let count: Int = numericCast(source.count) if count == 0 { return ContiguousArray() } let result = _ContiguousArrayBuffer<C.Element>( _uninitializedCount: count, minimumCapacity: 0) var p = result.firstElementAddress var i = source.startIndex for _ in 0..<count { // FIXME(performance): use _copyContents(initializing:). p.initialize(to: source[i]) source.formIndex(after: &i) p += 1 } _expectEnd(of: source, is: i) return ContiguousArray(_buffer: result) } /// A "builder" interface for initializing array buffers. /// /// This presents a "builder" interface for initializing an array buffer /// element-by-element. The type is unsafe because it cannot be deinitialized /// until the buffer has been finalized by a call to `finish`. @usableFromInline @_fixed_layout internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> { @usableFromInline internal var result: _ContiguousArrayBuffer<Element> @usableFromInline internal var p: UnsafeMutablePointer<Element> @usableFromInline internal var remainingCapacity: Int /// Initialize the buffer with an initial size of `initialCapacity` /// elements. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal init(initialCapacity: Int) { if initialCapacity == 0 { result = _ContiguousArrayBuffer() } else { result = _ContiguousArrayBuffer( _uninitializedCount: initialCapacity, minimumCapacity: 0) } p = result.firstElementAddress remainingCapacity = result.capacity } /// Add an element to the buffer, reallocating if necessary. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func add(_ element: Element) { if remainingCapacity == 0 { // Reallocate. let newCapacity = max(_growArrayCapacity(result.capacity), 1) var newResult = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCapacity, minimumCapacity: 0) p = newResult.firstElementAddress + result.capacity remainingCapacity = newResult.capacity - result.capacity if !result.isEmpty { // This check prevents a data race writting to _swiftEmptyArrayStorage // Since count is always 0 there, this code does nothing anyway newResult.firstElementAddress.moveInitialize( from: result.firstElementAddress, count: result.capacity) result.count = 0 } (result, newResult) = (newResult, result) } addWithExistingCapacity(element) } /// Add an element to the buffer, which must have remaining capacity. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func addWithExistingCapacity(_ element: Element) { _sanityCheck(remainingCapacity > 0, "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity") remainingCapacity -= 1 p.initialize(to: element) p += 1 } /// Finish initializing the buffer, adjusting its count to the final /// number of elements. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func finish() -> ContiguousArray<Element> { // Adjust the initialized count of the buffer. result.count = result.capacity - remainingCapacity return finishWithOriginalCount() } /// Finish initializing the buffer, assuming that the number of elements /// exactly matches the `initialCount` for which the initialization was /// started. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> { _sanityCheck(remainingCapacity == result.capacity - result.count, "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count") var finalResult = _ContiguousArrayBuffer<Element>() (finalResult, result) = (result, finalResult) remainingCapacity = 0 return ContiguousArray(_buffer: finalResult) } }
apache-2.0
a62a529c40787582218e1e6b42eb1930
30.360743
110
0.696397
4.748193
false
false
false
false
tjw/swift
test/Driver/linker.swift
2
14966
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt // RUN: %FileCheck %s < %t.simple.txt // RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -static-stdlib %s 2>&1 > %t.simple.txt // RUN: %FileCheck -check-prefix SIMPLE_STATIC -implicit-check-not -rpath %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 > %t.simple.txt // RUN: %FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-tvos9.0 %s 2>&1 > %t.simple.txt // RUN: %FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target i386-apple-watchos2.0 %s 2>&1 > %t.simple.txt // RUN: %FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: %FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -target armv6-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: %FileCheck -check-prefix LINUX-armv6 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: %FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -target thumbv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: %FileCheck -check-prefix LINUX-thumbv7 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -target armv7-none-linux-androideabi -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.android.txt // RUN: %FileCheck -check-prefix ANDROID-armv7 %s < %t.android.txt // RUN: %FileCheck -check-prefix ANDROID-armv7-NEGATIVE %s < %t.android.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.cygwin.txt // RUN: %FileCheck -check-prefix CYGWIN-x86_64 %s < %t.cygwin.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.windows.txt // RUN: %FileCheck -check-prefix WINDOWS-x86_64 %s < %t.windows.txt // RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-unknown-linux-gnu %s -Lbar -o dynlib.out 2>&1 > %t.linux.dynlib.txt // RUN: %FileCheck -check-prefix LINUX_DYNLIB-x86_64 %s < %t.linux.dynlib.txt // RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Fsystem car -F cdr -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt // RUN: %FileCheck %s < %t.complex.txt // RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | %FileCheck -check-prefix DEBUG %s // RUN: %empty-directory(%t) // RUN: touch %t/a.o // RUN: touch %t/a.swiftmodule // RUN: touch %t/b.o // RUN: touch %t/b.swiftmodule // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o %t/a.swiftmodule %t/b.o %t/b.swiftmodule -o linker | %FileCheck -check-prefix LINK-SWIFTMODULES %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.10 %s > %t.simple-macosx10.10.txt // RUN: %FileCheck %s < %t.simple-macosx10.10.txt // RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple-macosx10.10.txt // RUN: %empty-directory(%t) // RUN: touch %t/a.o // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -o linker 2>&1 | %FileCheck -check-prefix COMPILE_AND_LINK %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -driver-filelist-threshold=0 -o linker 2>&1 | %FileCheck -check-prefix FILELIST %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_DARWIN %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_LINUX %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WINDOWS %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WINDOWS %s // Here we specify an output file name using '-o'. For ease of writing these // tests, we happen to specify the same file name as is inferred in the // INFERRED_NAMED_DARWIN tests above: 'libLINKER.dylib'. // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | %FileCheck -check-prefix INFERRED_NAME_DARWIN %s // There are more RUN lines further down in the file. // CHECK: swift // CHECK: -o [[OBJECTFILE:.*]] // CHECK-NEXT: bin/ld{{"? }} // CHECK-DAG: [[OBJECTFILE]] // CHECK-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift/macosx]] // CHECK-DAG: -rpath [[STDLIB_PATH]] // CHECK-DAG: -lSystem // CHECK-DAG: -arch x86_64 // CHECK: -o {{[^ ]+}} // SIMPLE: bin/ld{{"? }} // SIMPLE-NOT: -syslibroot // SIMPLE-DAG: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}} // SIMPLE-NOT: -syslibroot // SIMPLE: -o linker // SIMPLE_STATIC: swift // SIMPLE_STATIC: -o [[OBJECTFILE:.*]] // SIMPLE_STATIC-NEXT: bin/ld{{"? }} // SIMPLE_STATIC: [[OBJECTFILE]] // SIMPLE_STATIC: -lobjc // SIMPLE_STATIC: -lSystem // SIMPLE_STATIC: -arch x86_64 // SIMPLE_STATIC: -L [[STDLIB_PATH:[^ ]+/lib/swift_static/macosx]] // SIMPLE_STATIC: -lc++ // SIMPLE_STATIC: -framework Foundation // SIMPLE_STATIC: -force_load_swift_libs // SIMPLE_STATIC: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}} // SIMPLE_STATIC: -no_objc_category_merging // SIMPLE_STATIC: -o linker // IOS_SIMPLE: swift // IOS_SIMPLE: -o [[OBJECTFILE:.*]] // IOS_SIMPLE: bin/ld{{"? }} // IOS_SIMPLE-DAG: [[OBJECTFILE]] // IOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/iphonesimulator}} // IOS_SIMPLE-DAG: -lSystem // IOS_SIMPLE-DAG: -arch x86_64 // IOS_SIMPLE-DAG: -ios_simulator_version_min 7.1.{{[0-9]+}} // IOS_SIMPLE: -o linker // tvOS_SIMPLE: swift // tvOS_SIMPLE: -o [[OBJECTFILE:.*]] // tvOS_SIMPLE: bin/ld{{"? }} // tvOS_SIMPLE-DAG: [[OBJECTFILE]] // tvOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/appletvsimulator}} // tvOS_SIMPLE-DAG: -lSystem // tvOS_SIMPLE-DAG: -arch x86_64 // tvOS_SIMPLE-DAG: -tvos_simulator_version_min 9.0.{{[0-9]+}} // tvOS_SIMPLE: -o linker // watchOS_SIMPLE: swift // watchOS_SIMPLE: -o [[OBJECTFILE:.*]] // watchOS_SIMPLE: bin/ld{{"? }} // watchOS_SIMPLE-DAG: [[OBJECTFILE]] // watchOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/watchsimulator}} // watchOS_SIMPLE-DAG: -lSystem // watchOS_SIMPLE-DAG: -arch i386 // watchOS_SIMPLE-DAG: -watchos_simulator_version_min 2.0.{{[0-9]+}} // watchOS_SIMPLE: -o linker // LINUX-x86_64: swift // LINUX-x86_64: -o [[OBJECTFILE:.*]] // LINUX-x86_64: clang++{{"? }} // LINUX-x86_64-DAG: -pie // LINUX-x86_64-DAG: [[OBJECTFILE]] // LINUX-x86_64-DAG: -lswiftCore // LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-x86_64-DAG: -F foo -iframework car -F cdr // LINUX-x86_64-DAG: -framework bar // LINUX-x86_64-DAG: -L baz // LINUX-x86_64-DAG: -lboo // LINUX-x86_64-DAG: -Xlinker -undefined // LINUX-x86_64: -o linker // LINUX-armv6: swift // LINUX-armv6: -o [[OBJECTFILE:.*]] // LINUX-armv6: clang++{{"? }} // LINUX-armv6-DAG: -pie // LINUX-armv6-DAG: [[OBJECTFILE]] // LINUX-armv6-DAG: -lswiftCore // LINUX-armv6-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-armv6-DAG: -target armv6-unknown-linux-gnueabihf // LINUX-armv6-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-armv6-DAG: -F foo -iframework car -F cdr // LINUX-armv6-DAG: -framework bar // LINUX-armv6-DAG: -L baz // LINUX-armv6-DAG: -lboo // LINUX-armv6-DAG: -Xlinker -undefined // LINUX-armv6: -o linker // LINUX-armv7: swift // LINUX-armv7: -o [[OBJECTFILE:.*]] // LINUX-armv7: clang++{{"? }} // LINUX-armv7-DAG: -pie // LINUX-armv7-DAG: [[OBJECTFILE]] // LINUX-armv7-DAG: -lswiftCore // LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-armv7-DAG: -target armv7-unknown-linux-gnueabihf // LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-armv7-DAG: -F foo -iframework car -F cdr // LINUX-armv7-DAG: -framework bar // LINUX-armv7-DAG: -L baz // LINUX-armv7-DAG: -lboo // LINUX-armv7-DAG: -Xlinker -undefined // LINUX-armv7: -o linker // LINUX-thumbv7: swift // LINUX-thumbv7: -o [[OBJECTFILE:.*]] // LINUX-thumbv7: clang++{{"? }} // LINUX-thumbv7-DAG: -pie // LINUX-thumbv7-DAG: [[OBJECTFILE]] // LINUX-thumbv7-DAG: -lswiftCore // LINUX-thumbv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-thumbv7-DAG: -target thumbv7-unknown-linux-gnueabihf // LINUX-thumbv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-thumbv7-DAG: -F foo -iframework car -F cdr // LINUX-thumbv7-DAG: -framework bar // LINUX-thumbv7-DAG: -L baz // LINUX-thumbv7-DAG: -lboo // LINUX-thumbv7-DAG: -Xlinker -undefined // LINUX-thumbv7: -o linker // ANDROID-armv7: swift // ANDROID-armv7: -o [[OBJECTFILE:.*]] // ANDROID-armv7: clang++{{"? }} // ANDROID-armv7-DAG: -pie // ANDROID-armv7-DAG: [[OBJECTFILE]] // ANDROID-armv7-DAG: -lswiftCore // ANDROID-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // ANDROID-armv7-DAG: -target armv7-none-linux-androideabi // ANDROID-armv7-DAG: -F foo -iframework car -F cdr // ANDROID-armv7-DAG: -framework bar // ANDROID-armv7-DAG: -L baz // ANDROID-armv7-DAG: -lboo // ANDROID-armv7-DAG: -Xlinker -undefined // ANDROID-armv7: -o linker // ANDROID-armv7-NEGATIVE-NOT: -Xlinker -rpath // CYGWIN-x86_64: swift // CYGWIN-x86_64: -o [[OBJECTFILE:.*]] // CYGWIN-x86_64: clang++{{"? }} // CYGWIN-x86_64-DAG: [[OBJECTFILE]] // CYGWIN-x86_64-DAG: -lswiftCore // CYGWIN-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // CYGWIN-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // CYGWIN-x86_64-DAG: -F foo -iframework car -F cdr // CYGWIN-x86_64-DAG: -framework bar // CYGWIN-x86_64-DAG: -L baz // CYGWIN-x86_64-DAG: -lboo // CYGWIN-x86_64-DAG: -Xlinker -undefined // CYGWIN-x86_64: -o linker // WINDOWS-x86_64: swift // WINDOWS-x86_64: -o [[OBJECTFILE:.*]] // WINDOWS-x86_64: clang++{{"? }} // WINDOWS-x86_64-DAG: [[OBJECTFILE]] // WINDOWS-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift/windows/x86_64]] // WINDOWS-x86_64-DAG: -F foo -iframework car -F cdr // WINDOWS-x86_64-DAG: -framework bar // WINDOWS-x86_64-DAG: -L baz // WINDOWS-x86_64-DAG: -lboo // WINDOWS-x86_64-DAG: -Xlinker -undefined // WINDOWS-x86_64: -o linker // COMPLEX: bin/ld{{"? }} // COMPLEX-DAG: -dylib // COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk // COMPLEX-DAG: -lfoo // COMPLEX-DAG: -framework bar // COMPLEX-DAG: -L baz // COMPLEX-DAG: -F garply -F car -F cdr // COMPLEX-DAG: -undefined dynamic_lookup // COMPLEX-DAG: -macosx_version_min 10.9.1 // COMPLEX: -o sdk.out // LINUX_DYNLIB-x86_64: swift // LINUX_DYNLIB-x86_64: -o [[OBJECTFILE:.*]] // LINUX_DYNLIB-x86_64: -o [[AUTOLINKFILE:.*]] // LINUX_DYNLIB-x86_64: clang++{{"? }} // LINUX_DYNLIB-x86_64-DAG: -shared // LINUX_DYNLIB-x86_64-DAG: -fuse-ld=gold // LINUX_DYNLIB-x86_64-NOT: -pie // LINUX_DYNLIB-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH:[^ ]+/lib/swift/linux]] // LINUX_DYNLIB-x86_64: [[STDLIB_PATH]]/x86_64/swiftrt.o // LINUX_DYNLIB-x86_64-DAG: [[OBJECTFILE]] // LINUX_DYNLIB-x86_64-DAG: @[[AUTOLINKFILE]] // LINUX_DYNLIB-x86_64-DAG: [[STDLIB_PATH]] // LINUX_DYNLIB-x86_64-DAG: -lswiftCore // LINUX_DYNLIB-x86_64-DAG: -L bar // LINUX_DYNLIB-x86_64: -o dynlib.out // DEBUG: bin/swift // DEBUG-NEXT: bin/swift // DEBUG-NEXT: bin/ld{{"? }} // DEBUG: -add_ast_path {{.*}}/{{[^/]+}}.swiftmodule // DEBUG: -o linker // DEBUG-NEXT: {{^|bin/}}dsymutil // DEBUG: linker // DEBUG: -o linker.dSYM // LINK-SWIFTMODULES: bin/swift // LINK-SWIFTMODULES-NEXT: bin/ld{{"? }} // LINK-SWIFTMODULES-SAME: -add_ast_path {{.*}}/a.swiftmodule // LINK-SWIFTMODULES-SAME: -add_ast_path {{.*}}/b.swiftmodule // LINK-SWIFTMODULES-SAME: -o linker // COMPILE_AND_LINK: bin/swift // COMPILE_AND_LINK-NOT: /a.o // COMPILE_AND_LINK: linker.swift // COMPILE_AND_LINK-NOT: /a.o // COMPILE_AND_LINK-NEXT: bin/ld{{"? }} // COMPILE_AND_LINK-DAG: /a.o // COMPILE_AND_LINK-DAG: .o // COMPILE_AND_LINK: -o linker // FILELIST: bin/ld{{"? }} // FILELIST-NOT: .o // FILELIST: -filelist {{"?[^-]}} // FILELIST-NOT: .o // FILELIST: /a.o // FILELIST-NOT: .o // FILELIST: -o linker // INFERRED_NAME_DARWIN: bin/swift // INFERRED_NAME_DARWIN: -module-name LINKER // INFERRED_NAME_DARWIN: bin/ld{{"? }} // INFERRED_NAME_DARWIN: -o libLINKER.dylib // INFERRED_NAME_LINUX: -o libLINKER.so // INFERRED_NAME_WINDOWS: -o LINKER.dll // Test ld detection. We use hard links to make sure // the Swift driver really thinks it's been moved. // RUN: rm -rf %t // RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/bin) // RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld // RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld // RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftc) // RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE-LINKER %s // RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/swift // RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/ld // RELATIVE-LINKER: -o {{[^ ]+}} // Also test arclite detection. This uses xcrun to find arclite when it's not // next to Swift. // RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/bin) // RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc) // RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun // RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=XCRUN_ARCLITE %s // XCRUN_ARCLITE: bin/ld{{"? }} // XCRUN_ARCLITE: /ANOTHER-DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a // XCRUN_ARCLITE: -o {{[^ ]+}} // RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/lib/arc) // RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE_ARCLITE %s // RELATIVE_ARCLITE: bin/ld{{"? }} // RELATIVE_ARCLITE: /DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a // RELATIVE_ARCLITE: -o {{[^ ]+}} // Clean up the test executable because hard links are expensive. // RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
apache-2.0
2db38f44f1d25c9936c77e5dd046a190
39.558266
262
0.676199
2.821112
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/TimelineCells/Styles/Bubble/Cells/BubbleIncomingRoomCellProtocol.swift
1
2009
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation protocol BubbleIncomingRoomCellProtocol: BubbleRoomCellProtocol { } extension BubbleIncomingRoomCellProtocol { // MARK: - Public func setupBubbleDecorations() { self.roomCellContentView?.decorationViewsAlignment = .left self.setupDecorationConstraints() } // MARK: - Private private func setupDecorationConstraints() { self.setupURLPreviewContentViewContraints() self.setupReactionsContentViewContraints() self.setupThreadSummaryViewContentViewContraints() } private func setupReactionsContentViewContraints() { self.roomCellContentView?.reactionsContentViewTrailingConstraint.constant = BubbleRoomCellLayoutConstants.incomingBubbleBackgroundMargins.right } private func setupThreadSummaryViewContentViewContraints() { self.roomCellContentView?.threadSummaryContentViewTrailingConstraint.constant = BubbleRoomCellLayoutConstants.incomingBubbleBackgroundMargins.right self.roomCellContentView?.threadSummaryContentViewBottomConstraint.constant = BubbleRoomCellLayoutConstants.threadSummaryViewMargins.bottom } private func setupURLPreviewContentViewContraints() { self.roomCellContentView?.urlPreviewContentViewTrailingConstraint.constant = BubbleRoomCellLayoutConstants.incomingBubbleBackgroundMargins.right } }
apache-2.0
76c9906923fd96e0b86be16c4f51e1bb
36.203704
155
0.762071
5.343085
false
false
false
false
warren-gavin/OBehave
OBehaveExamples/OBehaveExamples/EmptyTableViewController.swift
1
2761
// // EmptyTableViewController.swift // OBehaveExamples // // Created by Warren Gavin on 20/06/2018. // Copyright © 2018 Apokrupto. All rights reserved. // import UIKit import OBehave class EmptyTableViewController: UITableViewController { // Set in the dock in the storyboard in this example @IBOutlet var emptyStateView: UIView! private var muppets: [Muppet] = [] override func viewDidLoad() { super.viewDidLoad() let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addMuppet(_:))) navigationItem.rightBarButtonItem = addButton } @objc private func addMuppet(_ sender: UIBarButtonItem) { muppets.append(Muppet.randomMuppet) tableView.beginUpdates() tableView.insertRows(at: [IndexPath(row: muppets.count - 1, section: 0)], with: .automatic) tableView.endUpdates() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return muppets.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "muppetCell")! let muppet = muppets[indexPath.row] cell.textLabel?.text = muppet.name cell.detailTextLabel?.text = muppet.comment return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete else { return } muppets.remove(at: indexPath.row) tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: .automatic) tableView.endUpdates() } } // MARK: - OBEmptyStateBehaviorDataSource extension EmptyTableViewController: OBEmptyStateBehaviorDataSource { func viewToDisplayOnEmpty(for behavior: OBEmptyStateBehavior?) -> UIView? { return emptyStateView } } // MARK: - Model private struct Muppet { let name: String let comment: String } private extension Muppet { static let rowlf = Muppet(name: "Rowlf", comment: "Quiet genius") static let animal = Muppet(name: "Animal", comment: "Do not feed") static let sam = Muppet(name: "Sam", comment: "The AMERICAN eagle") static let beaker = Muppet(name: "Beaker", comment: "Meep") static let chef = Muppet(name: "Chef", comment: "Bork!") static var randomMuppet: Muppet { let allMuppets = [rowlf, animal, sam, beaker, chef] let index = Int(arc4random_uniform(UInt32(allMuppets.count - 1))) return allMuppets[index] } }
mit
74a514281a8748de933ba941bc445398
30.724138
137
0.664493
4.188164
false
false
false
false
eigengo/best-intentions
ios/BestIntentionsFramework/MarkovChain.swift
1
6445
/* * Best Intentions * Copyright (C) 2016 Jan Machacek * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ import Foundation /// /// A simple implementation of the markov chain that holds transitions from /// state1 -> state2, where state1 is a non-empty sequence of individual states /// /// Imagine a session that repeats 5 times: /// /// * biceps-curl /// * triceps-extension /// * lateral-raise /// * X /// /// It can be represented as transitions /// /// * [biceps-curl] -> triceps-extension /// * [biceps-curl, triceps-extension] -> lateral-raise, [triceps-extension] -> lateral-raise /// * [biceps-curl, triceps-extension, lateral-raise] -> X, [triceps-extension, lateral-raise] -> X, [lateral-raise] -> X /// ... /// /// struct MarkovChain<State> where State : Hashable { private(set) internal var transitionMap: [StateChain<State> : MarkovTransitionSet<State>] = [:] /// /// Convenience method that adds a transition [previous] -> next /// - parameter previous: the prior state /// - parameter next: the next state /// mutating func addTransition(previous: State, next: State) { addTransition(previous: StateChain(state: previous), next: next) } /// /// Adds a transition [previous] -> next /// - parameter previous: the prior state chain /// - parameter next: the next state /// mutating func addTransition(previous: StateChain<State>, next: State) { for p in previous.slices { var transitions = transitionMap[p] ?? MarkovTransitionSet() transitionMap[p] = transitions.addTransition(state: next) } } /// /// Computes probability of transition from state1 to state2 /// - parameter state1: the from state /// - parameter state2: the to state /// - returns: the probability 0..1 /// func transitionProbability(state1: State, state2: State) -> Double { return transitionProbability(state1: StateChain(state: state1), state2: state2) } /// /// Computes probability of transition from slices of state1 to state2 /// - parameter state1: the from state /// - parameter state2: the to state /// - returns: the probability 0..1 /// func transitionProbability(state1: StateChain<State>, state2: State) -> Double { return transitionMap[state1].map { $0.probabilityFor(state: state2) } ?? 0 } /// /// Computes pairs of (state, probability) of transitions from ``from`` to the next /// state. If favours longer slices of ``from``. /// - parameter from: the completed state chain /// - returns: non-ordered array of (state -> score) /// func transitionProbabilities(from: StateChain<State>) -> [(State, Double)] { let states = Array(Set(transitionMap.keys.flatMap { $0.states })) return from.slices.flatMap { fromSlice in return states.map { to in return (to, self.transitionProbability(state1: fromSlice, state2: to) * Double(fromSlice.count)) } } } } /// /// State chain that holds a sequence of states /// struct StateChain<State> : Hashable where State : Hashable { private(set) internal var states: [State] /// /// Empty chain /// init() { self.states = [] } /// /// Chain with a single entry /// - parameter state: the state /// init(state: State) { self.states = [state] } /// /// Chain with many states /// - parameter states: the states /// init(states: [State]) { self.states = states } /// /// Trims this chain by keeping the last ``maximumCount`` entries /// - parameter maximumCount: the maximum number of entries to keep /// mutating func trim(maximumCount: Int) { if states.count > maximumCount { states.removeSubrange(0..<states.count - maximumCount) } } /// /// Adds a new state /// - parameter state: the next state /// mutating func addState(state: State) { states.append(state) } /// /// The number of states /// var count: Int { return states.count } /// /// Slices of the states from the longest one to the shortest one /// var slices: [StateChain<State>] { // "a", "b", "c", "d" // [a, b, c, d] // [ b, c, d] // [ c, d] // [ d] return (0..<states.count).map { i in return StateChain(states: Array(self.states[i..<states.count])) } } /// the hash value var hashValue: Int { return self.states.reduce(0) { r, s in return Int.addWithOverflow(r, s.hashValue).0 } } } /// /// Implementation of ``Equatable`` for ``StateChain<S where S : Equatable>`` /// func ==<State>(lhs: StateChain<State>, rhs: StateChain<State>) -> Bool where State : Equatable { if lhs.states.count != rhs.states.count { return false } for (i, ls) in lhs.states.enumerated() { if rhs.states[i] != ls { return false } } return true } /// /// The transition set /// struct MarkovTransitionSet<State> where State : Hashable { private(set) internal var transitionCounter: [State : Int] = [:] func countFor(state: State) -> Int { return transitionCounter[state] ?? 0 } var totalCount: Int { return transitionCounter.values.reduce(0) { $0 + $1 } } func probabilityFor(state: State) -> Double { return Double(countFor(state: state)) / Double(totalCount) } mutating func addTransition(state: State) -> MarkovTransitionSet<State> { transitionCounter[state] = countFor(state: state) + 1 return self } }
gpl-3.0
6f584abfd2bef219648706749fbed6f8
28.976744
121
0.60512
4.028125
false
false
false
false
Rahulclaritaz/rahul
ixprez/ixprez/UINavigationBar+Alpha.swift
1
2868
// // UINavigationBar+Alpha.swift // StretchyHeaderView // // Created by sunlubo on 16/8/1. // Copyright © 2016年 sunlubo. All rights reserved. // import Foundation import UIKit private func image(with rect: CGRect, color: UIColor) -> UIImage { UIGraphicsBeginImageContext(rect.size) defer { UIGraphicsEndImageContext() } let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) return UIGraphicsGetImageFromCurrentImageContext()! } extension UINavigationBar { private struct AssociatedKeys { static var kScrollView = "scrollView" static var kBarColor = "barColor" } public var barColor: UIColor? { set { objc_setAssociatedObject(self, &AssociatedKeys.kBarColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(self, &AssociatedKeys.kBarColor) as? UIColor } } private var scrollView: UIScrollView? { set { objc_setAssociatedObject(self, &AssociatedKeys.kScrollView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(self, &AssociatedKeys.kScrollView) as? UIScrollView } } private var distance: CGFloat { return scrollView!.contentInset.top } private func updateAlpha(_ alpha: CGFloat = 0.0) { let color = (barColor ?? tintColor).withAlphaComponent(alpha) setBackgroundImage(image(with: CGRect(x: 0, y: 0, width: 1, height: 1), color: color.withAlphaComponent(alpha)), for: .default) } public func attachToScrollView(_ scrollView: UIScrollView) { self.scrollView = scrollView self.shadowImage = UIImage() self.tintColor = UIColor.white self.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] scrollView.addObserver(self, forKeyPath: kContentOffset, options: .new, context: nil) } public func reset() { self.scrollView?.removeObserver(self, forKeyPath: kContentOffset) self.scrollView = nil self.shadowImage = nil self.tintColor = nil self.titleTextAttributes = nil self.setBackgroundImage(nil, for: .default) } open override func observeValue(forKeyPath _: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) { guard let scrollView = scrollView else { return } let offsetY = scrollView.contentOffset.y if offsetY > -distance { let alpha = min(1, 1 - ((-distance + 120 - offsetY) / 64)) updateAlpha(alpha) } else { updateAlpha(0) } } }
mit
ca90f62ee116d4b90186bc0242d4009e
28.84375
148
0.626876
4.931153
false
false
false
false
KazmaStudio/Feeding
CODE/iOS/Feeding/Feeding/MineTableViewController.swift
1
3149
// // MineTableViewController.swift // Feeding // // Created by ZHAOCHENJUN on 2017/5/3. // Copyright © 2017年 com.kazmastudio. All rights reserved. // import UIKit class MineTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
7990e69b0ab7761c3216472a11b64a35
32.115789
136
0.668786
5.26087
false
false
false
false
tranhieutt/BrightFutures
BrightFutures/AsyncType.swift
1
3144
// // Async.swift // BrightFutures // // Created by Thomas Visser on 09/07/15. // Copyright © 2015 Thomas Visser. All rights reserved. // import Foundation public protocol AsyncType { typealias Value var result: Value? { get } init() init(result: Value) init(result: Value, delay: NSTimeInterval) init<A: AsyncType where A.Value == Value>(other: A) init(@noescape resolver: (result: Value throws -> Void) -> Void) func onComplete(context: ExecutionContext, callback: Value -> Void) -> Self } public extension AsyncType { /// `true` if the future completed (either `isSuccess` or `isFailure` will be `true`) public var isCompleted: Bool { return result != nil } /// Blocks the current thread until the future is completed and then returns the result public func forced() -> Value? { return forced(TimeInterval.Forever) } /// See `forced(timeout: TimeInterval) -> Value?` public func forced(timeout: NSTimeInterval) -> Value? { return forced(.In(timeout)) } /// Blocks the current thread until the future is completed, but no longer than the given timeout /// If the future did not complete before the timeout, `nil` is returned, otherwise the result of the future is returned public func forced(timeout: TimeInterval) -> Value? { if let result = result { return result } else { let sema = Semaphore(value: 0) var res: Value? = nil onComplete(Queue.global.context) { res = $0 sema.signal() } sema.wait(timeout) return res } } /// Alias of delay(queue:interval:) /// Will pass the main queue if we are currently on the main thread, or the /// global queue otherwise public func delay(interval: NSTimeInterval) -> Self { if NSThread.isMainThread() { return delay(Queue.main, interval: interval) } return delay(Queue.global, interval: interval) } /// Returns an Async that will complete with the result that this Async completes with /// after waiting for the given interval /// The delay is implemented using dispatch_after. The given queue is passed to that function. /// If you want a delay of 0 to mean 'delay until next runloop', you will want to pass the main /// queue. public func delay(queue: Queue, interval: NSTimeInterval) -> Self { return Self { complete in queue.after(.In(interval)) { onComplete(ImmediateExecutionContext) { try! complete($0) } } } } } public extension AsyncType where Value: AsyncType { public func flatten() -> Self.Value { return Self.Value { complete in self.onComplete(ImmediateExecutionContext) { value in value.onComplete(ImmediateExecutionContext) { innerValue in try! complete(innerValue) } } } } }
mit
ea5e0148c410966cc5ff3136e970662e
31.071429
124
0.597836
4.80581
false
false
false
false
SergeyStaroletov/Patterns17
ZayvyPolomoshnovSergeevPI42/src/WelcomeViewController.swift
1
1017
import UIKit class WelcomeViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var skipButton: UIButton! var index = 0 var imageName = "" override func viewDidLoad() { super.viewDidLoad() imageView.image = UIImage(named: imageName) pageControl.numberOfPages = 7 pageControl.pageIndicatorTintColor = #colorLiteral(red: 0.6657042861, green: 0.8280222483, blue: 1, alpha: 1) pageControl.currentPageIndicatorTintColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1) pageControl.currentPage = index } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func skipClicked(_ sender: Any) { let userDefaults = UserDefaults.standard userDefaults.set(false, forKey: "isFirstOpen") dismiss(animated: true, completion: nil) } }
mit
d9610abc820a702e90610f42f1d595aa
31.806452
135
0.683382
4.730233
false
false
false
false
MTTHWBSH/Short-Daily-Devotions
Short Daily Devotions/Controllers/PostViewController.swift
1
2315
// // PostViewController.swift // Short Daily Devotions // // Created by Matt Bush on 11/22/16. // Copyright © 2016 Matt Bush. All rights reserved. // import UIKit import PureLayout class PostViewController: UITableViewController { let refreshEnabled: Bool var viewModel: PostViewModel? init(refreshEnabled: Bool) { self.refreshEnabled = refreshEnabled super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() viewModel?.render = { [weak self] in self?.render() } setupTableView() if refreshEnabled { setupRefreshControl() } } private func render() { tableView.reloadData() } private func setupTableView() { registerCells() tableView.separatorStyle = .none tableView.allowsSelection = false tableView.backgroundColor = Style.grayLight tableView.estimatedRowHeight = tableView.frame.height tableView.rowHeight = UITableViewAutomaticDimension } private func setupRefreshControl() { refreshControl = UIRefreshControl() refreshControl?.tintColor = Style.blue refreshControl?.addTarget(self, action: #selector(refresh), for: UIControlEvents.valueChanged) tableView.refreshControl = refreshControl } @objc private func refresh() { refreshControl?.beginRefreshing() viewModel?.refreshPost(completion: { [weak self] _ in self?.refreshControl?.endRefreshing() }) } private func registerCells() { tableView.register(PostDetailsCell.self, forCellReuseIdentifier: PostDetailsCell.kReuseIdentifier) tableView.register(PostContentCell.self, forCellReuseIdentifier: PostContentCell.kReuseIdentifier) } } extension PostViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return viewModel?.cell(forIndexPath: indexPath) ?? UITableViewCell() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel?.postSections() ?? 0 } }
mit
6c2ad255e74048563de39994709f0d0b
30.27027
109
0.675454
5.356481
false
false
false
false
Quick/Spry
Tests/Test+beIdenticalToObject.swift
1
837
// // Test+beIdenticalToObject.swift // Spry // // Created by Shahpour Benkau on 23/02/2017. // // import XCTest import Spry class Test_beIdenticalToObject: XCTestCase { private class BeIdenticalToObjectTester {} private let testObjectA = BeIdenticalToObjectTester() private let testObjectB = BeIdenticalToObjectTester() func testBeIdenticalToPositive() { XCTAssert(expect(self.testObjectA).to(beIdenticalTo(testObjectA)).expectationResult) } func testBeIdenticalToNegative() { XCTAssert(expect(self.testObjectA).toNot(beIdenticalTo(testObjectB)).expectationResult) } func testOperators() { XCTAssert((expect(self.testObjectA) === testObjectA).expectationResult) XCTAssert((expect(self.testObjectA) !== testObjectB).expectationResult) } }
apache-2.0
5ab4785ac322ed98a6b9970e242044a7
26
95
0.709677
4.524324
false
true
false
false
WSDOT/wsdot-ios-app
wsdot/TollRateTableStore.swift
2
9007
// // TollRateTableStore.swift // WSDOT // // Copyright (c) 2018 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation import Alamofire import SwiftyJSON import RealmSwift class TollRateTableStore { typealias getTollRateTablesCompletion = (_ error: Error?) -> () static func getAllTollRateTables() -> [TollRateTableItem] { let realm = try! Realm() let tollTableItems = realm.objects(TollRateTableItem.self).filter("delete == false") return Array(tollTableItems) } static func getTollRateTableByRoute(route: Int) -> TollRateTableItem? { let realm = try! Realm() let tollTableItem = realm.objects(TollRateTableItem.self).filter( "delete == false").filter("route == \(route)").first return tollTableItem } static func updateTollRateTables(_ force: Bool, completion: @escaping getTollRateTablesCompletion) { var delta = CachesStore.staticTollUpdateTime let deltaUpdated = (Calendar.current as NSCalendar).components(.second, from: CachesStore.getUpdatedTime(CachedData.staticTollRates), to: Date(), options: []).second if let deltaValue = deltaUpdated { delta = deltaValue } if ((delta > CachesStore.updateTime) || force) { AF.request("https://data.wsdot.wa.gov/mobile/StaticTollRates.js").validate().responseJSON { response in switch response.result { case .success: if let value = response.data { DispatchQueue.global().async { let json = JSON(value) do { try saveTollRateTables(json) CachesStore.updateTime(CachedData.tollRates, updated: Date()) } catch { completion(nil) } completion(nil) } } case .failure(let error): print(error) completion(error) } } } else { completion(nil) } } fileprivate static func saveTollRateTables(_ json: JSON) throws { let realm = try! Realm() let newTolls = List<TollRateTableItem>() for (_, tollJson):(String, JSON) in json["TollRates"] { let tollRate = TollRateTableItem() tollRate.route = tollJson["route"].intValue tollRate.message = tollJson["message"].stringValue tollRate.numCol = tollJson["numCol"].intValue for (_, rowJson):(String, JSON) in tollJson["tollTable"] { let tollRow = TollRateRowItem() tollRow.header = rowJson["header"].boolValue for (_, rows):(String, JSON) in rowJson["rows"] { tollRow.rows.append(rows.stringValue) } if rowJson["start_time"].exists() && rowJson["end_time"].exists() { tollRow.startHourString = rowJson["start_time"].stringValue tollRow.endHourString = rowJson["end_time"].stringValue } if rowJson["weekday"].exists() { tollRow.weekday = rowJson["weekday"].boolValue } tollRate.tollTable.append(tollRow) } newTolls.append(tollRate) } let oldTolls = getAllTollRateTables() do { try realm.write{ for toll in oldTolls { toll.delete = true } realm.add(newTolls, update: .all) } } catch { print("TollRateTableStore.saveTollRateTables: Realm write error") } } static func flushOldData() { let realm = try! Realm() let tolls = realm.objects(TollRateTableItem.self).filter("delete == true") do { try realm.write{ realm.delete(tolls) } } catch { print("TollRateTableStore.flushOldData: Realm write error") } } static func isTollActive(startHour: String, endHour: String) -> Bool { let start_time_array = startHour.split(separator: ":") if start_time_array.count != 2 { return false } guard let start_hour = Int( start_time_array[0] ) else { return false } guard let start_min = Int( start_time_array[1] ) else { return false } let end_time_array = endHour.split(separator: ":") if end_time_array.count != 2 { return false } guard let end_hour = Int( end_time_array[0] ) else { return false } guard let end_min = Int( end_time_array[1] ) else { return false } let calendar = Calendar.current let now = Date() let toll_start = calendar.date( bySettingHour: start_hour, minute: start_min, second: 0, of: now)! let toll_end = calendar.date( bySettingHour: end_hour, minute: end_min, second: 0, of: now)! if now >= toll_start && now <= toll_end { return true } return false } } struct FourColItem{ let colOne: String let colTwo: String let colThree: String let colFour: String let header: Bool } struct ThreeColItem{ let colOne: String let colTwo: String let colThree: String let header: Bool } extension Date { var isWeekend: Bool { let calendar = Calendar(identifier: .gregorian) let components = calendar.dateComponents([.weekday], from: self) if (components.weekday == 1) || (components.weekday == 0) { return true } else { return false } } var is_WAC_468_270_071_Holiday: Bool { let components = Calendar.current.dateComponents([.year, .month, .day, .weekday, .weekdayOrdinal], from: self) guard let year = components.year, let month = components.month, let day = components.day, let weekday = components.weekday, let weekdayOrdinal = components.weekdayOrdinal else { return false } let memorialDay = Date.dateComponentsForMemorialDay(year: year)?.day ?? -1 // weekday is Sunday==1 ... Saturday==7 // weekdayOrdinal is nth instance of weekday in month switch (month, day, weekday, weekdayOrdinal) { case (1, 1, _, _): return true // Happy New Years case (5, memorialDay, _, _): return true // Memorial Day case (7, 4, _, _): return true // Independence Day case (9, _, 2, 1): return true // Labor Day - 1st Mon in Sept case (11, _, 5, 4): return true // Happy Thanksgiving - 4th Thurs in Nov case (12, 25, _, _): return true // Happy Holidays default: return false } } static func dateComponentsForMemorialDay(year: Int) -> DateComponents? { guard let memorialDay = Date.memorialDay(year: year) else { return nil } return NSCalendar.current.dateComponents([.year, .month, .day, .weekday, .weekdayOrdinal], from: memorialDay) } static func memorialDay(year: Int) -> Date? { let calendar = Calendar.current var firstMondayJune = DateComponents() firstMondayJune.month = 6 firstMondayJune.weekdayOrdinal = 1 // 1st in month firstMondayJune.weekday = 2 // Monday firstMondayJune.year = year guard let refDate = calendar.date(from: firstMondayJune) else { return nil } var timeMachine = DateComponents() timeMachine.weekOfMonth = -1 return calendar.date(byAdding: timeMachine, to: refDate) } }
gpl-3.0
f79a7dbaa5358e395656e313e7a26977
32.860902
173
0.544576
4.65478
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
CustomViewTransitions/CustomViewTransitions/TransAnimateManager.swift
1
3420
// // TransAnimateManager.swift // CustomViewTransitions // // Created by Edward Salter on 9/6/14. // Copyright (c) 2014 Edward Salter. All rights reserved. // import UIKit class TransAnimateManager: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { private var presenting = true func animateTransition(transitionContext: UIViewControllerContextTransitioning) { //MARK: Set Transition Constants //Get reference to fromView, toView, & container view where transition occurs let container = transitionContext.containerView() let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! let Pi : CGFloat = 3.14159265359 let offScreenRight = CGAffineTransformMakeRotation(-Pi/2) let offScreenLeft = CGAffineTransformMakeRotation(Pi/2) //MARK: Mechanics of Sliding Views Horizontally // let offScreenRight = CGAffineTransformMakeTranslation(container.frame.width, 0) // let offScreenLeft = CGAffineTransformMakeTranslation(-container.frame.width, 0) // start the toView to the right of the screen // toView.transform = offScreenRight // if self.presenting { // fromView.transform = offScreenLeft // } else { // fromView.transform = offScreenRight // } //MARK: Mechanics of Rotating View About Anchor toView.transform = self.presenting ? offScreenRight : offScreenLeft //MARK: Anchor //Provides axis of rotation for view transiton toView.layer.anchorPoint = CGPoint(x:0, y:0) fromView.layer.anchorPoint = CGPoint(x:0, y:0) //MARK: Center Reset //Moving center position point to allow rotation transformation about top left corner toView.layer.position = CGPoint(x:0, y:0) fromView.layer.position = CGPoint(x:0, y:0) //Add both views to viewController container.addSubview(toView) container.addSubview(fromView) //Get duration of animation let duration = self.transitionDuration(transitionContext) //MARK: Perform Animation //Perform animation UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: nil, animations: { fromView.transform = self.presenting ? offScreenLeft : offScreenRight //fromView.transform = offScreenLeft toView.transform = CGAffineTransformIdentity }, completion: { finished in transitionContext.completeTransition(true) }) } //MARK: Transition Timing func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.75 } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } }
gpl-2.0
5e96a8cd8c6e006be8d23fe62ba0d913
40.707317
217
0.68655
5.606557
false
false
false
false
DianQK/TransitionTreasury
TransitionAnimation/DefaultPercentDrivenInteractiveTransition.swift
1
3899
// // DefaultPercentDrivenInteractiveTransition.swift // DefaultPercentDrivenInteractiveTransition // // Created by John_LS on 2016/12/22. // Copyright © 2016年 John_LS. All rights reserved. // import UIKit class DefaultPercentDrivenInteractiveTransition: UIPercentDrivenInteractiveTransition { ///以下是自定义交互控制器 var transitionContext : UIViewControllerContextTransitioning! var formView : UIView! var toView : UIView! let x_to : CGFloat = -100.0 ///toview起始x坐标 /// 以下----自定义交互控制器 override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let fromViewController = transitionContext.viewController(forKey: .from), let toViewController = transitionContext.viewController(forKey: .to) else { ///预防rootviewcontroller触发 return } self.transitionContext = transitionContext containerView.insertSubview((toViewController.view)!, belowSubview: (fromViewController.view)!) /// 加点阴影 fromViewController.view.layer.shadowOpacity = 0.8 fromViewController.view.layer.shadowColor = UIColor.black.cgColor fromViewController.view.layer.shadowOffset = CGSize(width: 3, height: 3) fromViewController.view.layer.shadowRadius = 3 self.formView = fromViewController.view self.toView = toViewController.view self.toView.frame = CGRect(x:x_to,y:0,width:self.toView.frame.width,height:self.toView.frame.height) } override func update(_ percentComplete: CGFloat) { if transitionContext == nil { ///预防rootviewcontroller触发 return } self.formView?.frame = CGRect(x:(self.formView?.frame.width)!*percentComplete, y:0, width:(self.formView?.frame.width)! , height: (self.formView?.frame.height)!) self.toView?.frame = CGRect(x:self.x_to+CGFloat(fabsf(Float(self.x_to*percentComplete))), y:0, width:(self.toView?.frame.width)! , height: (self.toView?.frame.height)!) transitionContext?.updateInteractiveTransition(percentComplete) } func finishBy(cancelled: Bool) { if self.transitionContext == nil { ///预防rootviewcontroller触发 return } if cancelled { UIView.animate(withDuration: 0.2, animations: { self.formView?.frame = CGRect(x:0, y:0, width:(self.formView?.frame.width)! , height: (self.formView?.frame.height)!) self.toView?.frame = CGRect(x:self.x_to, y:0, width:(self.toView?.frame.width)! , height: (self.toView?.frame.height)!) }, completion: {completed in self.transitionContext!.cancelInteractiveTransition() self.transitionContext!.completeTransition(false) self.transitionContext = nil self.toView = nil self.formView = nil }) } else { UIView.animate(withDuration: 0.2, animations: { self.formView?.frame = CGRect(x:(self.formView?.frame.width)!, y:0, width:(self.formView?.frame.width)! , height: (self.formView?.frame.height)!) self.toView?.frame = CGRect(x:0, y:0, width:(self.toView?.frame.width)! , height: (self.toView?.frame.height)!) }, completion: {completed in self.transitionContext!.finishInteractiveTransition() self.transitionContext!.completeTransition(true) self.transitionContext = nil self.toView = nil self.formView = nil }) } } }
mit
d0851438bf7a2eda3dbededd0959f6e0
38.729167
176
0.621133
4.914948
false
false
false
false
davidahouse/FierceCoder
FierceCoderTests/FierceCoderChildObjectTests.swift
1
3893
// // FierceCoderChildObjectTests.swift // FierceCoder // // Created by David House on 7/27/15. // Copyright © 2015 David House. All rights reserved. // import XCTest struct ChildStructTest : FierceEncodeable { let name:String let age:Int private enum EncoderKeys : String { case Name case Age } init(name:String,age:Int) { self.name = name self.age = age } init(decoder:FierceDecoder) { if let name = decoder.decodeObject(EncoderKeys.Name.rawValue) as? String { self.name = name } else { self.name = "" } if let age = decoder.decodeObject(EncoderKeys.Age.rawValue) as? Int { self.age = age } else { self.age = 0 } } func encode(encoder: FierceEncoder) { encoder.encodeObject(self.name, key: EncoderKeys.Name.rawValue) encoder.encodeObject(self.age, key: EncoderKeys.Age.rawValue) } } struct ParentStructTest : FierceEncodeable { let name:String let child:ChildStructTest private enum EncoderKeys : String { case Name case Child } init(name:String,childName:String,childAge:Int) { self.name = name self.child = ChildStructTest(name: childName, age: childAge) } init(decoder:FierceDecoder) { self.name = decoder.decodeObject(EncoderKeys.Name.rawValue) as! String self.child = ChildStructTest(decoder: decoder.decode(EncoderKeys.Child.rawValue)) } func encode(encoder: FierceEncoder) { encoder.encodeObject(self.name, key: EncoderKeys.Name.rawValue) encoder.encode(self.child, key: EncoderKeys.Child.rawValue) } } struct ParentWithChildArray : FierceEncodeable { var children = [ChildStructTest]() init(children:[ChildStructTest]) { self.children = children } init(decoder: FierceDecoder) { self.children = [ChildStructTest]() let encodedChildren = decoder.decodeArray("children") for encodedChild in encodedChildren { self.children.append(ChildStructTest(decoder: encodedChild)) } } func encode(encoder: FierceEncoder) { encoder.encodeArray(self.children.map{ $0 as FierceEncodeable }, key: "children") } } class FierceCoderChildObjectTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testWithChild() { let parent = ParentStructTest(name: "Fred", childName: "Pebbles", childAge: 10) let encoder = FierceEncoder() parent.encode(encoder) let rawData = encoder.encodedData() XCTAssertNotNil(rawData) XCTAssertTrue(rawData.length > 0) let decoder = FierceDecoder(data:rawData) let decodedParent = ParentStructTest(decoder: decoder) XCTAssertTrue(parent.name == decodedParent.name) } func testParentWithChildArray() { let children = [ChildStructTest(name: "fred", age: 12),ChildStructTest(name: "barney", age: 21)] let parent = ParentWithChildArray(children: children) let encoder = FierceEncoder() parent.encode(encoder) let rawData = encoder.encodedData() XCTAssertNotNil(rawData) XCTAssertTrue(rawData.length > 0) let decoder = FierceDecoder(data: rawData) let decodedParent = ParentWithChildArray(decoder: decoder) XCTAssertTrue(children.count == decodedParent.children.count) } }
mit
42ae7e78fa64932a14a946a4fc1b6e26
27.408759
111
0.627955
4.281628
false
true
false
false
sync/NearbyTrams
NearbyTramsStorageKit/Source/Stop.swift
1
3096
// // Copyright (c) 2014 Dblechoc. All rights reserved. // import CoreData public class Stop: NSManagedObject, InsertAndFetchManagedObject, RESTManagedObject { @NSManaged public var uniqueIdentifier: String? @NSManaged public var stopDescription: String? @NSManaged public var latitude: NSNumber? // Why when Double it crashes @NSManaged public var longitude: NSNumber? // Why when Double it crashes @NSManaged public var name: String? @NSManaged public var stopNo: NSNumber? // Why when Int it crashes @NSManaged public var suburb: String? @NSManaged public var isUpStop: Bool @NSManaged public var cityDirection: String? @NSManaged public var zones: String? @NSManaged public var routes: NSMutableSet @NSManaged public var schedules: NSMutableSet public class var entityName: String { get { return "Stop" } } public class var primaryKey: String { get { return "uniqueIdentifier" } } public class func primaryKeyValueFromRest(dictionary: NSDictionary) -> String? { if let intValue = dictionary["StopNo"] as? Int { return String(intValue) } return nil } public func configureWithDictionaryFromRest(dictionary: NSDictionary) -> Void { stopDescription = dictionary["Description"] as? String latitude = dictionary["Latitude"] as? Double longitude = dictionary["Longitude"] as? Double name = dictionary["StopName"] as? String stopNo = dictionary["StopNo"] as? Int suburb = dictionary["SuburbName"] as? String if let tmp = dictionary["UpStop"] as? Bool { isUpStop = tmp } } public func configureWithPartialDictionaryFromRest(dictionary: NSDictionary) -> Void { cityDirection = dictionary["CityDirection"] as? String zones = dictionary["Zones"] as? String } } public extension Stop { public var routesNo: [String] { if let currentRoutes = routes.allObjects as? [Route] { return currentRoutes.map { route -> String in return route.routeNo! } } return [] } } public extension Stop { public var nextScheduledArrivalDates: [NSDate]? { if let identifier = self.uniqueIdentifier { let fetchRequest = NSFetchRequest(entityName: Schedule.entityName) fetchRequest.fetchLimit = 3 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "predictedArrivalDateTime", ascending: true)] fetchRequest.predicate = NSPredicate(format:"stop.uniqueIdentifier == %@ AND predictedArrivalDateTime >= %@", identifier, NSDate()) let arrivalDates = self.managedObjectContext.executeFetchRequest(fetchRequest, error: nil).map { schedule -> NSDate in return (schedule as Schedule).predictedArrivalDateTime! } return arrivalDates } return nil } }
mit
7aec2cdfcc868f342644a54b91d70e39
29.352941
139
0.632106
5.07541
false
false
false
false
presence-insights/pi-clientsdk-ios
IBMPIGeofenceSample/IBMPIGeofenceSample/AppDelegate.swift
1
8407
/** * IBMPIGeofenceSample * AppDelegate.swift * * Performs all communication to the PI Rest API. * * © Copyright 2016 IBM Corp. * * Licensed under the Presence Insights Client iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import UIKit import IBMPIGeofence import CoreLocation var piGeofencingManager: PIGeofencingManager? @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private let locationManager = CLLocationManager() private static let dateFormatter:NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .MediumStyle dateFormatter.timeStyle = .MediumStyle return dateFormatter }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. PIGeofencingManager.enableLogging(true) let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) let tenantCode = "xf504jy" let orgCode = "rpcwyjy" let baseURL = "http://pi-outdoor-proxy.mybluemix.net" let username = "a6su7f" let password = "8xdr5vfh" piGeofencingManager = PIGeofencingManager( tenantCode: tenantCode, orgCode: orgCode, baseURL: baseURL, username: username, password: password) piGeofencingManager?.delegate = self //self.seeding() self.manageAuthorizations() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { let state = UIApplication .sharedApplication().applicationState if state == .Active { let title = NSLocalizedString("Alert.LocalNotification.Title",comment:"") let message = notification.alertBody ?? NSLocalizedString("Alert.LocalNotification.MissingBody",comment:"") self.showAlert(title, message: message) } } func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) { piGeofencingManager?.handleEventsForBackgroundURLSession(identifier, completionHandler: completionHandler) } } extension AppDelegate { private func manageAuthorizations() { if !CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion) { dispatch_async(dispatch_get_main_queue()) { let title = NSLocalizedString("Alert.NoMonitoring.Title",comment:"") let message = NSLocalizedString("Alert.NoMonitoring.Message",comment:"") self.showAlert(title, message: message) } } else { switch CLLocationManager.authorizationStatus() { case .NotDetermined: locationManager.requestAlwaysAuthorization() case .AuthorizedAlways: fallthrough case .AuthorizedWhenInUse: break case .Restricted, .Denied: let alertController = UIAlertController( title: NSLocalizedString("Alert.Monitoring.Title",comment:""), message: NSLocalizedString("Alert.Monitoring.Message",comment:""), preferredStyle: .Alert) let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel",comment:""), style: .Cancel){ (action) in } alertController.addAction(cancelAction) let openAction = UIAlertAction(title: NSLocalizedString("Alert.Monitoring.OpenAction",comment:""), style: .Default) { (action) in if let url = NSURL(string:UIApplicationOpenSettingsURLString) { UIApplication.sharedApplication().openURL(url) } } alertController.addAction(openAction) dispatch_async(dispatch_get_main_queue()) { self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) } } } let refreshStatus = UIApplication.sharedApplication().backgroundRefreshStatus switch refreshStatus { case .Restricted: fallthrough case .Denied: let alertController = UIAlertController( title: NSLocalizedString("Alert.BackgroundRefresh.Title",comment:""), message: NSLocalizedString("Alert.BackgroundRefresh.Message",comment:""), preferredStyle: .Alert) let okAction = UIAlertAction(title: NSLocalizedString("OK",comment:""), style: .Default){ (action) in } alertController.addAction(okAction) dispatch_async(dispatch_get_main_queue()) { self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) } case .Available: break } } } extension AppDelegate:PIGeofencingManagerDelegate { // MARK: - PIGeofencingManagerDelegate func geofencingManager(manager: PIGeofencingManager, didEnterGeofence geofence: PIGeofence? ) { let geofenceName = geofence?.name ?? "Error,unknown fence" let notification = UILocalNotification() notification.alertBody = String(format:NSLocalizedString("Region.Notification.Enter %@", comment: ""),geofenceName) notification.soundName = UILocalNotificationDefaultSoundName if let geofence = geofence { notification.userInfo = ["geofence.code":geofence.code] } UIApplication.sharedApplication().presentLocalNotificationNow(notification) } func geofencingManager(manager: PIGeofencingManager, didExitGeofence geofence: PIGeofence? ) { let geofenceName = geofence?.name ?? "Error,unknown fence" let notification = UILocalNotification() notification.alertBody = String(format:NSLocalizedString("Region.Notification.Exit %@", comment: ""),geofenceName) notification.soundName = UILocalNotificationDefaultSoundName if let geofence = geofence { notification.userInfo = ["geofence.code":geofence.code] } UIApplication.sharedApplication().presentLocalNotificationNow(notification) } } extension AppDelegate { func showAlert(title:String,message:String) { if let _ = self.window?.rootViewController?.presentedViewController { self.window?.rootViewController?.dismissViewControllerAnimated(true, completion: nil) } let alertController = UIAlertController( title: NSLocalizedString(title,comment:""), message: NSLocalizedString(message,comment:""), preferredStyle: .Alert) let okAction = UIAlertAction(title: NSLocalizedString("OK",comment:""), style: .Default){ (action) in } alertController.addAction(okAction) self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) } }
epl-1.0
6b84006f1c12c58e3fc8a7691fce903a
32.624
279
0.767904
4.588428
false
false
false
false
HLoveMe/HSomeFunctions-swift-
HScrollView/HScrollView/ViewController.swift
1
1683
// // ViewController.swift // HScrollView // // Created by 朱子豪 on 16/3/8. // Copyright © 2016年 朱子豪. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let array:[imageAbleConversion] = ["http://e.hiphotos.bdimg.com/imgad/pic/item/500fd9f9d72a6059a1f411202f34349b033bba20.jpg","http://c.hiphotos.bdimg.com/imgad/pic/item/00e93901213fb80ec98291ed31d12f2eb93894bd.jpg","http://f.hiphotos.baidu.com/image/pic/item/e1fe9925bc315c60d916f9d58ab1cb134954770d.jpg"] let one = HScrollView.scrollView(CGRectMake(0, 0,view.width,view.height-100), source:array,title:["000000","111111","2222222"]) one.center = self.view.center one.delegate = self let center = self.view.center let page = HPageControl(frame:CGRectMake(center.x - 50, center.y * 2 - 40, 100, 20)) page.currentPageIndicatorTintColor = UIColor.redColor() page.pageIndicatorTintColor = UIColor.blackColor() // one.replacePageControl(page) one.autoScrollTime = 4 self.view.addSubview(one) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { UIImageCache.deleteAllCache() } } extension ViewController:HScrollViewDelegate{ func HScrollViewDidTouchUp(scrollView: HScrollView, indexPath: NSIndexPath) { print("\(indexPath)"+"Touch") } func HScrollViewWillShowCell(scrollView: HScrollView, indexPath: NSIndexPath) { print("\(indexPath)"+"Will") } }
apache-2.0
4747c6db2225787df8f6d772470045c4
35.26087
313
0.693046
3.61039
false
false
false
false
FAU-Inf2/kwikshop-ios
Kwik Shop/LanguageSelectionViewController.swift
1
4139
// // LanguageSelectionViewController.swift // Kwik Shop // // Created by Adrian Kretschmer on 02.09.15. // Copyright (c) 2015 FAU-Inf2. All rights reserved. // import UIKit class LanguageSelectionViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var languagesTableView: UITableView! private var selectedLanguageIndex : Int { get { return languageHelper.selectedLanguageIndex } set { languageHelper.selectedLanguageIndex = newValue languagesTableView.reloadData() } } private let languageHelper = LanguageHelper.instance private var languageStrings : [String] { return languageHelper.languageStrings } override var hidesBottomBarWhenPushed : Bool { get { return true } set { } } override func viewDidLoad() { super.viewDidLoad() self.title = "settings_language".localized languagesTableView.delegate = self languagesTableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return languageStrings.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("languageCell", forIndexPath: indexPath) // Configure the cell... cell.textLabel?.text = languageStrings[indexPath.row] if indexPath.row == selectedLanguageIndex { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { languagesTableView.deselectRowAtIndexPath(indexPath, animated: false) let row = indexPath.row if row == selectedLanguageIndex { return } let message = "alert_box_change_language_confirmation_beginning".localized + languageStrings[row] + "alert_box_change_language_confirmation_end".localized + "?" let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.ActionSheet) let confirmationYesTitle = "alert_box_change_language_confirmation_yes_beginning".localized + languageStrings[row] + "alert_box_change_language_confirmation_yes_end".localized alert.addAction(UIAlertAction(title: confirmationYesTitle, style: .Default, handler: { [unowned self] (action: UIAlertAction!) in self.selectedLanguageIndex = row self.performSegueWithIdentifier("unwindToSettings", sender: self) })) alert.addAction(UIAlertAction(title: "alert_box_cancel".localized, style: .Cancel, handler: nil)) alert.popoverPresentationController?.sourceRect = tableView.cellForRowAtIndexPath(indexPath)!.bounds alert.popoverPresentationController?.sourceView = tableView.cellForRowAtIndexPath(indexPath)! alert.popoverPresentationController?.permittedArrowDirections = [UIPopoverArrowDirection.Down, UIPopoverArrowDirection.Up] presentViewController(alert, animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
25f968a0ce836cfe1653e895380f582a
34.681034
183
0.666345
5.563172
false
false
false
false
DayLogger/ADVOperation
Source/RemoteNotificationCondition.swift
1
4441
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ #if os(iOS) import UIKit private let RemoteNotificationQueue = OperationQueue() private let RemoteNotificationName = "RemoteNotificationPermissionNotification" private enum RemoteRegistrationResult { case Token(NSData) case Error(NSError) } /// A condition for verifying that the app has the ability to receive push notifications. public struct RemoteNotificationCondition: OperationCondition { public static let name = "RemoteNotification" public static let isMutuallyExclusive = false public static func didReceiveNotificationToken(token: NSData) { NSNotificationCenter.defaultCenter().postNotificationName(RemoteNotificationName, object: nil, userInfo: [ "token": token ]) } public static func didFailToRegister(error: NSError) { NSNotificationCenter.defaultCenter().postNotificationName(RemoteNotificationName, object: nil, userInfo: [ "error": error ]) } let application: UIApplication public init(application: UIApplication) { self.application = application } public func dependencyForOperation(operation: Operation) -> NSOperation? { return RemoteNotificationPermissionOperation(application: application, handler: { _ in }) } public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { /* Since evaluation requires executing an operation, use a private operation queue. */ RemoteNotificationQueue.addOperation(RemoteNotificationPermissionOperation(application: application) { result in switch result { case .Token(_): completion(.Satisfied) case .Error(let underlyingError): let error = NSError(code: .ConditionFailed, userInfo: [ OperationConditionKey: self.dynamicType.name, NSUnderlyingErrorKey: underlyingError ]) completion(.Failed(error)) } }) } } /** A private `Operation` to request a push notification token from the `UIApplication`. - note: This operation is used for *both* the generated dependency **and** condition evaluation, since there is no "easy" way to retrieve the push notification token other than to ask for it. - note: This operation requires you to call either `RemoteNotificationCondition.didReceiveNotificationToken(_:)` or `RemoteNotificationCondition.didFailToRegister(_:)` in the appropriate `UIApplicationDelegate` method, as shown in the `AppDelegate.swift` file. */ private class RemoteNotificationPermissionOperation: Operation { let application: UIApplication private let handler: RemoteRegistrationResult -> Void private init(application: UIApplication, handler: RemoteRegistrationResult -> Void) { self.application = application self.handler = handler super.init() /* This operation cannot run at the same time as any other remote notification permission operation. */ addCondition(MutuallyExclusive<RemoteNotificationPermissionOperation>()) } override func execute() { dispatch_async(dispatch_get_main_queue()) { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "didReceiveResponse:", name: RemoteNotificationName, object: nil) self.application.registerForRemoteNotifications() } } @objc func didReceiveResponse(notification: NSNotification) { NSNotificationCenter.defaultCenter().removeObserver(self) let userInfo = notification.userInfo if let token = userInfo?["token"] as? NSData { handler(.Token(token)) } else if let error = userInfo?["error"] as? NSError { handler(.Error(error)) } else { fatalError("Received a notification without a token and without an error.") } finish() } } #endif
unlicense
1eaeb095780e04c00c43ae5ee95b0552
33.952756
124
0.662311
5.87947
false
false
false
false
mozilla-mobile/firefox-ios
Tests/ClientTests/TestingHelperClasses/URLProtocolStub.swift
2
1391
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation class URLProtocolStub: URLProtocol { private struct Stub { let data: Data? let response: URLResponse? let error: Error? } private static var stub: Stub? static func stub(data: Data?, response: URLResponse?, error: Error?) { stub = Stub(data: data, response: response, error: error) } static func removeStub() { stub = nil } override class func canInit(with request: URLRequest) -> Bool { return true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } override func startLoading() { guard let stub = URLProtocolStub.stub else { return } if let data = stub.data { client?.urlProtocol(self, didLoad: data) } if let response = stub.response { client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } if let error = stub.error { client?.urlProtocol(self, didFailWithError: error) } else { client?.urlProtocolDidFinishLoading(self) } } override func stopLoading() {} }
mpl-2.0
be0616e43f3adc904d4f7762c7ce07e8
25.75
92
0.621855
4.621262
false
false
false
false
benlangmuir/swift
test/SILOptimizer/access_enforcement_noescape.swift
7
21536
// RUN: %target-swift-frontend -enable-copy-propagation=requested-passes-only -enable-lexical-lifetimes=false -module-name access_enforcement_noescape -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -parse-as-library %s | %FileCheck %s // This tests SILGen and AccessEnforcementSelection as a single set of tests. // (Some static/dynamic enforcement selection is done in SILGen, and some is // deferred. That may change over time but we want the outcome to be the same). // // These tests attempt to fully cover the possibilities of reads and // modifications to captures along with `inout` arguments on both the caller and // callee side. // // Tests that result in a compile-time error have been commented out // here so we can FileCheck this output. Instead, copies of these // tests are compiled access_enforcement_noescape_error.swift to check // the compiler diagnostics. // Helper func doOne(_ f: () -> ()) { f() } // Helper func doTwo(_: ()->(), _: ()->()) {} // Helper func doOneInout(_: ()->(), _: inout Int) {} // Error: Cannot capture nonescaping closure. // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func reentrantCapturedNoescape(fn: (() -> ()) -> ()) { // let c = { fn {} } // fn(c) // } // Helper struct Frob { mutating func outerMut() { doOne { innerMut() } } mutating func innerMut() {} } // Allow nested mutable access via closures. func nestedNoEscape(f: inout Frob) { doOne { f.outerMut() } } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF : $@convention(thin) (@inout Frob) -> () { // CHECK-NOT: begin_access // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF' // closure #1 in nestedNoEscape(f:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Frob) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Frob // CHECK: %{{.*}} = apply %{{.*}}([[ACCESS]]) : $@convention(method) (@inout Frob) -> () // CHECK: end_access [[ACCESS]] : $*Frob // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyyXEfU_' // Allow aliased noescape reads. func readRead() { var x = 3 // Inside each closure: [read] [static] doTwo({ _ = x }, { _ = x }) x = 42 } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape8readReadyyF : $@convention(thin) () -> () { // CHECK: [[ALLOC:%.*]] = alloc_stack $Int, var, name "x" // CHECK-NOT: begin_access // CHECK: apply // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyF' // closure #1 in readRead() // CHECK-LABEL: sil private @$s27access_enforcement_noescape8readReadyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyFyyXEfU_' // closure #2 in readRead() // CHECK-LABEL: sil private @$s27access_enforcement_noescape8readReadyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyFyyXEfU0_' // Allow aliased noescape reads of an `inout` arg. func inoutReadRead(x: inout Int) { // Inside each closure: [read] [static] doTwo({ _ = x }, { _ = x }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape09inoutReadE01xySiz_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tF' // closure #1 in inoutReadRead(x:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU_' // closure #2 in inoutReadRead(x:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU0_' // Allow aliased noescape read + boxed read. func readBoxRead() { var x = 3 let c = { _ = x } // Inside may-escape closure `c`: [read] [dynamic] // Inside never-escape closure: [read] [dynamic] doTwo(c, { _ = x }) x = 42 } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape11readBoxReadyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[CVT1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyF' // closure #1 in readBoxRead() // CHECK-LABEL: sil private @$s27access_enforcement_noescape11readBoxReadyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyFyycfU_' // closure #2 in readBoxRead() // CHECK-LABEL: sil private @$s27access_enforcement_noescape11readBoxReadyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyFyyXEfU0_' // Error: cannout capture inout. // // func inoutReadReadBox(x: inout Int) { // let c = { _ = x } // doTwo({ _ = x }, c) // } // Allow aliased noescape read + write. func readWrite() { var x = 3 // Inside closure 1: [read] [static] // Inside closure 2: [modify] [static] doTwo({ _ = x }, { x = 42 }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape9readWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyF' // closure #1 in readWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape9readWriteyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyFyyXEfU_' // closure #2 in readWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape9readWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyFyyXEfU0_' // Allow aliased noescape read + write of an `inout` arg. func inoutReadWrite(x: inout Int) { // Inside closure 1: [read] [static] // Inside closure 2: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doTwo({ _ = x }, { x = 3 }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14inoutReadWrite1xySiz_tF : $@convention(thin) (@inout Int) -> () { func readBoxWrite() { var x = 3 let c = { _ = x } // Inside may-escape closure `c`: [read] [dynamic] // Inside never-escape closure: [modify] [dynamic] doTwo(c, { x = 42 }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape12readBoxWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[CVT1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyF' // closure #1 in readBoxWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape12readBoxWriteyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyFyycfU_' // closure #2 in readBoxWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape12readBoxWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyFyyXEfU0_' // Error: cannout capture inout. // func inoutReadBoxWrite(x: inout Int) { // let c = { _ = x } // doTwo({ x = 42 }, c) // } func readWriteBox() { var x = 3 let c = { x = 42 } // Inside may-escape closure `c`: [modify] [dynamic] // Inside never-escape closure: [read] [dynamic] doTwo({ _ = x }, c) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape12readWriteBoxyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA2]], [[CVT1]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyF' // closure #1 in readWriteBox() // CHECK-LABEL: sil private @$s27access_enforcement_noescape12readWriteBoxyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyFyycfU_' // closure #2 in readWriteBox() // CHECK-LABEL: sil private @$s27access_enforcement_noescape12readWriteBoxyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyFyyXEfU0_' // Error: cannout capture inout. // func inoutReadWriteBox(x: inout Int) { // let c = { x = 42 } // doTwo({ _ = x }, c) // } // Error: noescape read + write inout. func readWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doOneInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14readWriteInoutyyF : $@convention(thin) () -> () { // Error: noescape read + write inout of an inout. func inoutReadWriteInout(x: inout Int) { // Around the call: [modify] [static] // Inside closure: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doOneInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape19inoutReadWriteInout1xySiz_tF : $@convention(thin) (@inout Int) -> () { // Traps on boxed read + write inout. // Covered by Interpreter/enforce_exclusive_access.swift. func readBoxWriteInout() { var x = 3 let c = { _ = x } // Around the call: [modify] [dynamic] // Inside closure: [read] [dynamic] doOneInout(c, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape17readBoxWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int // CHECK: apply %{{.*}}([[CVT]], [[ACCESS]]) // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape17readBoxWriteInoutyyF' // closure #1 in readBoxWriteInout() // CHECK-LABEL: sil private @$s27access_enforcement_noescape17readBoxWriteInoutyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape17readBoxWriteInoutyyFyycfU_' // Error: inout cannot be captured. // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func inoutReadBoxWriteInout(x: inout Int) { // let c = { _ = x } // doOneInout(c, &x) // } // Allow aliased noescape write + write. func writeWrite() { var x = 3 // Inside closure 1: [modify] [static] // Inside closure 2: [modify] [static] doTwo({ x = 42 }, { x = 87 }) _ = x } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape10writeWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyF' // closure #1 in writeWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape10writeWriteyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyFyyXEfU_' // closure #2 in writeWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape10writeWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyFyyXEfU0_' // Allow aliased noescape write + write of an `inout` arg. func inoutWriteWrite(x: inout Int) { // Inside closure 1: [modify] [static] // Inside closure 2: [modify] [static] doTwo({ x = 42}, { x = 87 }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape010inoutWriteE01xySiz_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tF' // closure #1 in inoutWriteWrite(x:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU_' // closure #2 in inoutWriteWrite(x:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU0_' // Traps on aliased boxed write + noescape write. // Covered by Interpreter/enforce_exclusive_access.swift. func writeWriteBox() { var x = 3 let c = { x = 87 } // Inside may-escape closure `c`: [modify] [dynamic] // Inside never-escape closure: [modify] [dynamic] doTwo({ x = 42 }, c) _ = x } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape13writeWriteBoxyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA2]], [[CVT1]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyF' // closure #1 in writeWriteBox() // CHECK-LABEL: sil private @$s27access_enforcement_noescape13writeWriteBoxyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyFyycfU_' // closure #2 in writeWriteBox() // CHECK-LABEL: sil private @$s27access_enforcement_noescape13writeWriteBoxyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyFyyXEfU0_' // Error: inout cannot be captured. // func inoutWriteWriteBox(x: inout Int) { // let c = { x = 87 } // doTwo({ x = 42 }, c) // } // Error: on noescape write + write inout. func writeWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doOneInout({ x = 42 }, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape15writeWriteInoutyyF : $@convention(thin) () -> () { // Error: on noescape write + write inout. func inoutWriteWriteInout(x: inout Int) { // Around the call: [modify] [static] // Inside closure: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doOneInout({ x = 42 }, &x) } // inoutWriteWriteInout(x:) // Traps on boxed write + write inout. // Covered by Interpreter/enforce_exclusive_access.swift. func writeBoxWriteInout() { var x = 3 let c = { x = 42 } // Around the call: [modify] [dynamic] // Inside closure: [modify] [dynamic] doOneInout(c, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape18writeBoxWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int // CHECK: apply %{{.*}}([[CVT]], [[ACCESS]]) // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape18writeBoxWriteInoutyyF' // closure #1 in writeBoxWriteInout() // CHECK-LABEL: sil private @$s27access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_' // Error: Cannot capture inout // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func inoutWriteBoxWriteInout(x: inout Int) { // let c = { x = 42 } // doOneInout(c, &x) // } // Helper func doBlockInout(_: @convention(block) ()->(), _: inout Int) {} func readBlockWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [read] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doBlockInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape19readBlockWriteInoutyyF : $@convention(thin) () -> () { // Test AccessSummaryAnalysis. // // The captured @inout_aliasable argument to `doOne` is re-partially applied, // then stored is a box before passing it to doBlockInout. func noEscapeBlock() { var x = 3 doOne { // Compile time error: see access_enforcement_noescape_error.swift. // doBlockInout({ _ = x }, &x) } } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape13noEscapeBlockyyF : $@convention(thin) () -> () {
apache-2.0
2ee044424b1df5db814c1e328ce8c9d5
44.338947
250
0.662751
3.294478
false
false
false
false
codepgq/LearningSwift
TableViewCellEdit/TableViewCellEdit/ViewController.swift
1
4839
// // ViewController.swift // TableViewCellEdit // // Created by ios on 16/9/28. // Copyright © 2016年 ios. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate { static private let cellIdentifier = "cellIdentifier" /// DataSource private var dataSource = TBDataSource.cellIdentifierWith(cellIdentifier, data: ViewController.cellsData, style: TBSectionStyle.Section_Single) { (cell, item) in let newCell = cell as! TableViewCell newCell.updateWithItem(item as! cellModel) } /// tableView @IBOutlet weak var tableView: UITableView! /// 展示数据源 static private var cellsData : NSArray = [ cellModel(image: "1", name: "老吴") , cellModel(image: "2", name: "老李") , cellModel(image: "3", name: "老赵") , cellModel(image: "4", name: "老王") , cellModel(image: "5", name: "老杨") , cellModel(image: "6", name: "老鸟") , cellModel(image: "7", name: "老头") , cellModel(image: "8", name: "老人") ] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = dataSource tableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { //创建选项 let delete = UITableViewRowAction(style: .Normal, title: "🗑\n删除") { action, index in print("Delete button tapped") //刷新页面 self.tableView.reloadRowsAtIndexPaths([index], withRowAnimation: UITableViewRowAnimation.Fade) } delete.backgroundColor = UIColor.grayColor() //创建选项 let share = UITableViewRowAction(style: .Normal, title: "🤗\n分享") { (action: UITableViewRowAction!, indexPath: NSIndexPath) -> Void in //创建一个分享页面 let activityViewController = UIActivityViewController(activityItems: ["老师","老司机"], applicationActivities: [PQCustomActivity()]) //加载分享页面 self.presentViewController(activityViewController, animated: true, completion: nil) //刷新页面 self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) } share.backgroundColor = UIColor.redColor() //创建选项 let download = UITableViewRowAction(style: .Normal, title: "⬇️\n下载") { action, index in print("Download button tapped") //刷新页面 self.tableView.reloadRowsAtIndexPaths([index], withRowAnimation: UITableViewRowAnimation.Fade) } download.backgroundColor = UIColor.blueColor() return [download, share, delete] } } /** * 介绍UIActivityViewController 展示重点: 官方文档:When presenting the view controller, you must do so using the appropriate means for the current device. On iPad, you must present the view controller in a popover. On iPhone and iPod touch, you must present it modally 中文翻译(大概意思):当展示这个ViewController的时候需要根据当前的设备类型进行判断,在iPad上面使用popover,在其他的设备上面使用present excludedActivityTypes - 忽略类型 NSString *const UIActivityTypePostToFacebook; NSString *const UIActivityTypePostToTwitter; NSString *const UIActivityTypePostToWeibo; NSString *const UIActivityTypeMessage; NSString *const UIActivityTypeMail; NSString *const UIActivityTypePrint; NSString *const UIActivityTypeCopyToPasteboard; NSString *const UIActivityTypeAssignToContact; NSString *const UIActivityTypeSaveToCameraRoll; NSString *const UIActivityTypeAddToReadingList; NSString *const UIActivityTypePostToFlickr; NSString *const UIActivityTypePostToVimeo; NSString *const UIActivityTypePostToTencentWeibo; NSString *const UIActivityTypeAirDrop; UIActivity - 服务 官方文档:This class must be subclassed before it can be used. The job of an activity object is to act on the data provided to it and to provide some meta information that iOS can display to the user. For more complex services, an activity object can also display a custom user interface and use it to gather additional information from the user 中文翻译(大概意思):UIActivity必须通过继承来使用,他主要是操作给用户展示的信息,而且还可以操作展示定制化的界面来获取给多的数据信息 《 详情 》查看 PQCustomActivity 类 */
apache-2.0
f0a4cc367ceb5f2cecf9f12aa4d06773
37.278261
341
0.684007
4.743534
false
false
false
false
brokenseal/iOS-exercises
FaceSnap/FaceSnap/PhotoFilterController.swift
1
1727
// // PhotoFilterController.swift // FaceSnap // // Created by Davide Callegari on 27/06/17. // Copyright © 2017 Davide Callegari. All rights reserved. // import UIKit class PhotoFilterController: UIViewController { private var mainImage: UIImage private let photoImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() private lazy var filterHeaderLabel: UILabel = { let label = UILabel() label.text = "Select a filter" label.textAlignment = .center return label }() lazy var filtersCollectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal return flowLayout }() init(image: UIImage) { self.mainImage = image self.photoImageView.image = image super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("BWAHAHAHA") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
014034d9cbb53333daf4acd405b07d98
25.151515
106
0.644844
5.136905
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/Content/ConversationContentViewController+ConversationMessageCellDelegate.swift
1
3814
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireDataModel extension UIView { func targetView(for message: ZMConversationMessage!, dataSource: ConversationTableViewDataSource) -> UIView { /// if the view is a tableView, search for a visible cell that contains the message and the cell is a SelectableView guard let tableView: UITableView = self as? UITableView else { return self } var actionView: UIView = tableView let section = dataSource.section(for: message) for cell in tableView.visibleCells { let indexPath = tableView.indexPath(for: cell) if indexPath?.section == section, cell is SelectableView { actionView = cell break } } return actionView } } extension ConversationContentViewController: ConversationMessageCellDelegate { // MARK: - MessageActionResponder func perform(action: MessageAction, for message: ZMConversationMessage!, view: UIView) { let actionView = view.targetView(for: message, dataSource: dataSource) /// Do not dismiss Modal for forward since share VC is present in a popover let shouldDismissModal = action != .delete && action != .copy && !(action == .forward && isIPadRegular()) if messagePresenter.modalTargetController?.presentedViewController != nil && shouldDismissModal { messagePresenter.modalTargetController?.dismiss(animated: true) { self.messageAction(actionId: action, for: message, view: actionView) } } else { messageAction(actionId: action, for: message, view: actionView) } } func conversationMessageWantsToOpenUserDetails(_ cell: UIView, user: UserType, sourceView: UIView, frame: CGRect) { delegate?.didTap(onUserAvatar: user, view: sourceView, frame: frame) } func conversationMessageShouldBecomeFirstResponderWhenShowingMenuForCell(_ cell: UIView) -> Bool { return delegate?.conversationContentViewController(self, shouldBecomeFirstResponderWhenShowMenuFromCell: cell) ?? false } func conversationMessageWantsToOpenMessageDetails(_ cell: UIView, messageDetailsViewController: MessageDetailsViewController) { parent?.present(messageDetailsViewController, animated: true) } func conversationMessageWantsToOpenGuestOptionsFromView(_ cell: UIView, sourceView: UIView) { delegate?.conversationContentViewController(self, presentGuestOptionsFrom: sourceView) } func conversationMessageWantsToOpenParticipantsDetails(_ cell: UIView, selectedUsers: [UserType], sourceView: UIView) { delegate?.conversationContentViewController(self, presentParticipantsDetailsWithSelectedUsers: selectedUsers, from: sourceView) } func conversationMessageShouldUpdate() { dataSource.loadMessages(forceRecalculate: true) } }
gpl-3.0
f15867197ab644130006a33cba05877d
37.918367
135
0.679339
5.334266
false
false
false
false
entotsu/TKSwarmAlert
TKSwarmAlert/Classes/FallingAnimationView.swift
1
11079
// // FallingAnimationView.swift // dinamicTest // // Created by Takuya Okamoto on 2015/08/14. // Copyright (c) 2015年 Uniface. All rights reserved. // //http://stackoverflow.com/questions/21325057/implement-uikitdynamics-for-dragging-view-off-screen /* TODO: * ✔ 落ちながら登場する感じ * ✔ Viewを渡したら落ちてくるような感じにしたいな * ✔ UIViewのクラスにする? * ✔ 連続登場 * ✔ 落としたあとに戻ってくる SHOULD FIX: * なんか登場時ギザギザしてる WANNA FIX: * ドラッグ時に震えるの何とかしたい * 凄く早く連続で落とすと残る WANNA DO: * ジャイロパララックス * タップすると震える */ import UIKit /* Usage */ class FallingAnimationView: UIView { var willDissmissAllViews: Closure? var didDissmissAllViews: Closure? let gravityMagnitude:CGFloat = 3 let snapBackDistance:CGFloat = 30 let fieldMargin:CGFloat = 300 var animator: UIDynamicAnimator var animationView: UIView var attachmentBehavior: UIAttachmentBehavior? var startPoints: [CGPoint] = [] var currentAnimationViewTags: [Int] = [] var nextViewsList: [[UIView]] = [] var enableToTapSuperView: Bool = true var allViews: [UIView] { get { return animationView.subviews.filter({ (view: AnyObject) -> Bool in return view is UIView }) } } var animatedViews:[UIView] { get { return allViews.filter({ (view:UIView) -> Bool in view.tag >= 0 }) } } var staticViews:[UIView] { get { return allViews.filter({ (view:UIView) -> Bool in view.tag < 0 }) } } var currentAnimationViews: [UIView] { get { return animatedViews.filter(isCurrentView) } } var unCurrentAnimationViews: [UIView] { get { return animatedViews.filter(isUnCurrentView) } } func isCurrentView(view:UIView) -> Bool { for currentTag in self.currentAnimationViewTags { if currentTag == view.tag { return true } } return false } func isUnCurrentView(view:UIView) -> Bool { for currentTag in self.currentAnimationViewTags { if currentTag == view.tag { return false } } return true } func fadeOutStaticViews(duration:TimeInterval) { for v in self.staticViews { UIView.animate(withDuration: duration) { v.alpha = 0 } } } override init(frame:CGRect) { self.animationView = UIView() self.animator = UIDynamicAnimator(referenceView: animationView) super.init(frame:frame) animationView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width + fieldMargin*2, height: self.frame.size.height + fieldMargin*2) animationView.center = self.center self.addSubview(animationView) enableTapGesture() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ func spawn(views:[UIView]) { //refresh currentAnimationViewTags = [] animator.removeAllBehaviors() fallAndRemove(views: animatedViews) //fixMargin for v in views { v.frame.x = v.frame.x + fieldMargin v.frame.y = v.frame.y + fieldMargin } // make it draggable for v in views { // dev_makeLine(v: v) v.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(FallingAnimationView.didDrag))) v.tag = startPoints.count startPoints.append(v.center) currentAnimationViewTags.append(v.tag) } // lift up let upDist:CGFloat = calcHideUpDistance(views: views) for v in views { v.frame.y = v.frame.y - upDist animationView.addSubview(v) } //drop collisionAll() snap(views: views) } func spawnNextViews() { let views = nextViewsList.remove(at: 0) spawn(views: views) } @objc func didDrag(gesture: UIPanGestureRecognizer) { let gestureView = gesture.view! if gesture.state == UIGestureRecognizer.State.began { self.animator.removeAllBehaviors() collisionAll() snapAll() fallAndRemove(views: unCurrentAnimationViews) // drag start let gripPoint: CGPoint = gesture.location(in: gestureView) let offsetFromCenter: UIOffset = UIOffset.init( horizontal: gripPoint.x - gestureView.bounds.size.width / 2.0, vertical: gripPoint.y - gestureView.bounds.size.height / 2.0 ) let anchorPoint: CGPoint = gesture.location(in: gestureView.superview) attachmentBehavior = UIAttachmentBehavior(item: gestureView, offsetFromCenter: offsetFromCenter, attachedToAnchor: anchorPoint) self.animator.addBehavior(attachmentBehavior!) } else if gesture.state == UIGestureRecognizer.State.changed { // drag move let touchPoint: CGPoint = gesture.location(in: gestureView.superview) attachmentBehavior?.anchorPoint = touchPoint } else if gesture.state == UIGestureRecognizer.State.ended { disableTapGesture() self.animator.removeAllBehaviors() collisionAll() // judge if fall let touchPoint: CGPoint = gesture.location(in: gestureView.superview) let movedDistance = distance(from: startPoints[gestureView.tag], to: touchPoint) if movedDistance < snapBackDistance {// not fall let snap = UISnapBehavior(item: gestureView, snapTo: startPoints[gestureView.tag]) self.animator.addBehavior(snap) } else { if nextViewsList.count != 0 {//next spawnNextViews() } else {// fall // velocity let pushBehavior = UIPushBehavior(items: [gestureView], mode: UIPushBehavior.Mode.instantaneous) let velocity: CGPoint = gesture.velocity(in: gestureView.superview) // not sure if I can really just convert it to CGVector though pushBehavior.pushDirection = CGVector(dx: (velocity.x / 900), dy: (velocity.y / 900)) self.animator.addBehavior(pushBehavior) disableDragGesture() fallAndRemoveAll() } } } } @objc func onTapSuperView() { if (enableToTapSuperView) { animator.removeAllBehaviors() disableTapGesture() if nextViewsList.count != 0 {//next spawnNextViews() } else { disableDragGesture() fallAndRemoveAll() } } } func fallAndRemoveAll() { fallAndRemove(views: animatedViews) if nextViewsList.count == 0 { //ここでフェードアウト disableTapGesture() self.willDissmissAllViews?() } } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MARK: behaviors func collisionAll() { let collisionBehavior = UICollisionBehavior(items: animatedViews) collisionBehavior.translatesReferenceBoundsIntoBoundary = true//❓ self.animator.addBehavior(collisionBehavior) } func snapAll() { snap(views: currentAnimationViews) } func snap(views:[UIView]) { for v in views { let snap = UISnapBehavior(item: v, snapTo: startPoints[v.tag]) self.animator.addBehavior(snap) } } func fallAndRemove(views:[UIView]) { let gravity = UIGravityBehavior(items: views) gravity.magnitude = gravityMagnitude gravity.action = { [weak self] in if self != nil { if self!.animatedViews.count == 0 { self!.animator.removeAllBehaviors() self!.didDissmissAllViews?() } else { for v in views { if v.superview != nil { if v.frame.top >= (v.superview!.bounds.bottom - self!.fieldMargin) { v.removeFromSuperview() } else if v.frame.right <= (v.superview!.bounds.left + self!.fieldMargin) { v.removeFromSuperview() } else if v.frame.left >= (v.superview!.bounds.right - self!.fieldMargin) { v.removeFromSuperview() } } } } } } self.animator.addBehavior(gravity) } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MARK: Util func disableDragGesture() { // remove event for v in allViews { if let recognizers = v.gestureRecognizers { for recognizer in recognizers { v.removeGestureRecognizer(recognizer) } } } } func enableTapGesture() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FallingAnimationView.onTapSuperView)) self.addGestureRecognizer(tapGesture) } func disableTapGesture() { if let recognizers = self.gestureRecognizers { for recognizer in recognizers { self.removeGestureRecognizer(recognizer) } } Timer.schedule(delay: 0.5) { [weak self] (timer) in self?.enableTapGesture() } } func dev_makeLine(v: UIView) { let lineView = UIView(frame: v.frame) lineView.backgroundColor = UIColor.clear lineView.layer.borderColor = UIColor.blue.withAlphaComponent(0.2).cgColor lineView.layer.borderWidth = 1 lineView.tag = -1 animationView.addSubview(lineView) } func calcHideUpDistance(views:[UIView])->CGFloat { var minimumTop:CGFloat = CGFloat(HUGE) for view in views { if view.frame.y < minimumTop { minimumTop = view.frame.y } } return minimumTop } func distance(from:CGPoint, to:CGPoint) -> CGFloat { let xDist = (to.x - from.x) let yDist = (to.y - from.y) return sqrt((xDist * xDist) + (yDist * yDist)) } }
mit
34e749a477a294b534e457b3d8a1ba50
29.894286
142
0.546194
4.624893
false
false
false
false
groovelab/SwiftBBS
SwiftBBS/SwiftBBS Server/BbsHandler.swift
1
9787
// // BbsHandler.swift // SwiftBBS // // Created by Takeo Namba on 2016/01/16. // Copyright GrooveLab // import PerfectLib class BbsHandler: BaseRequestHandler { // MARK: repositories lazy var bbsRepository: BbsRepository = BbsRepository(db: self.db) lazy var bbsCommentRepository: BbsCommentRepository = BbsCommentRepository(db: self.db) lazy var imageRepository: ImageRepository = ImageRepository(db: self.db) // MARK: forms class AddForm : FormType { var title: String! var comment: String! var image: MimeReader.BodySpec? var validationRules: ValidatorManager.ValidationKeyAndRules { return [ "title": [ ValidationType.Required, ValidationType.Length(min: 1, max: 100) ], "comment": [ ValidationType.Required, ValidationType.Length(min: 1, max: 1000) ], "image": [ ValidationType.Image(fileSize: Config.uploadImageFileSize, fileExtensions: Config.uploadImageFileExtensions) ] ] } subscript (key: String) -> Any? { get { return nil } // not use set { switch key { case "title": title = newValue! as! String case "comment": comment = newValue! as! String case "image": image = newValue as? MimeReader.BodySpec default: break } } } } class AddCommentForm : FormType { var bbsId: UInt! var comment: String! var validationRules: ValidatorManager.ValidationKeyAndRules { return [ "bbs_id": [ ValidationType.Required, ValidationType.UInteger(min: 1, max: nil) ], "comment": [ ValidationType.Required, ValidationType.Length(min: 1, max: 1000) ], ] } subscript (key: String) -> Any? { get { return nil } // not use set { switch key { case "bbs_id": bbsId = newValue! as! UInt case "comment": comment = newValue! as! String default: break } } } } // MARK: life cycle override init() { super.init() // define action acl needLoginActions = ["add", "addcomment"] redirectUrlIfNotLogin = "/user/login" // noNeedLoginActions = [] // redirectUrlIfLogin = "/" } override func dispatchAction(action: String) throws -> ActionResponse { switch request.action { case "add" where request.requestMethod() == "POST": return try addAction() case "addcomment" where request.requestMethod() == "POST": return try addcommentAction() case "detail": return try detailAction() default: return try listAction() } } // MARK: actions func listAction() throws -> ActionResponse { let keyword = request.param("keyword") let bbsEntities = try bbsRepository.selectByKeyword(keyword, selectOption: selectOption) var values = [String: Any]() values["keyword"] = keyword ?? "" if request.acceptJson { values["bbsList"] = bbsEntities.map({ (bbsEntity) -> [String: Any] in return bbsEntity.toDictionary() }) as [Any] } else { values["bbsList"] = bbsEntities.map({ (bbsEntity) -> [String: Any] in var dictionary = bbsEntity.toDictionary() if !request.acceptJson { dictionary["comment"] = (dictionary["comment"] as! String).stringByEncodingHTML.htmlBrString } return dictionary }) } let totalCount = try bbsRepository.countByKeyword(keyword) values["pager"] = Pager(totalCount: totalCount, selectOption: selectOption).toDictionary(request.acceptJson) return .Output(templatePath: "bbs_list.mustache", values: values) } func addAction() throws -> ActionResponse { var form = AddForm() do { try form.validate(request) } catch let error as FormError { return .Error(status: 500, message: "invalidate request parameter. " + error.description) } // insert TODO: begin transaction let entity = BbsEntity(id: nil, title: form.title, comment: form.comment, userId: try self.userIdInSession()!, createdAt: nil, updatedAt: nil) let bbsId = try bbsRepository.insert(entity) // add image if let image = form.image { let imageService = ImageService( uploadedImage: image, uploadDirPath: request.docRoot + Config.uploadDirPath, repository: imageRepository ) imageService.parent = .Bbs imageService.parentId = bbsId imageService.userId = try self.userIdInSession()! try imageService.save() // TODO: delete file if catch exception } if request.acceptJson { var values = [String: Any]() values["bbsId"] = bbsId return .Output(templatePath: nil, values: values) } else { return .Redirect(url: "/bbs/detail/\(bbsId)") } } func detailAction() throws -> ActionResponse { guard let bbsIdString = request.urlVariables["id"], let bbsId = UInt(bbsIdString) else { return .Error(status: 500, message: "invalidate request parameter") } var values = [String: Any]() // bbs guard let bbsEntity = try bbsRepository.findById(bbsId) else { return .Error(status: 404, message: "not found bbs") } var dictionary = bbsEntity.toDictionary() if !request.acceptJson { dictionary["comment"] = (dictionary["comment"] as! String).stringByEncodingHTML.htmlBrString } values["bbs"] = dictionary // bbs image let imageEntities = try imageRepository.selectBelongTo(parent:.Bbs, parentId: bbsEntity.id) if let imageEntity = imageEntities.first { var dictionary = imageEntity.toDictionary() dictionary["url"] = "/" + Config.uploadDirPath + (dictionary["path"] as! String) values["image"] = dictionary } // bbs post let bbsCommentEntities = try bbsCommentRepository.selectByBbsId(bbsId) if request.acceptJson { values["comments"] = bbsCommentEntities.map({ (entity) -> [String: Any] in return entity.toDictionary() }) as [Any] } else { values["comments"] = bbsCommentEntities.map({ (entity) -> [String: Any] in var dictionary = entity.toDictionary() if !request.acceptJson { dictionary["comment"] = (dictionary["comment"] as! String).stringByEncodingHTML.htmlBrString } return dictionary }) } return .Output(templatePath: "bbs_detail.mustache", values: values) } func addcommentAction() throws -> ActionResponse { var form = AddCommentForm() do { try form.validate(request) } catch let error as FormError { return .Error(status: 500, message: "invalidate request parameter. " + error.description) } // TODO: if bbs exists // insert let entity = BbsCommentEntity(id: nil, bbsId: form.bbsId, comment: form.comment, userId: try userIdInSession()!, createdAt: nil, updatedAt: nil) let commentId = try bbsCommentRepository.insert(entity) // notify try notifyBbsCommented(entity.bbsId, exceptUserId: entity.userId) if request.acceptJson { var values = [String: Any]() values["commentId"] = commentId return .Output(templatePath: nil, values: values) } else { return .Redirect(url: "/bbs/detail/\(entity.bbsId)") } } private func notifyBbsCommented(bbsId: UInt, exceptUserId: UInt) throws { guard let bbs = try bbsRepository.findById(bbsId) where Config.apnsEnabled else { return } var userIds = Set([bbs.userId]) let comments = try bbsCommentRepository.selectByBbsId(bbsId) comments.forEach { (entity) -> () in userIds.insert(entity.userId) } userIds.remove(exceptUserId) let userEntities = try userRepository.selectByIds(userIds) let deviceTokens = userEntities.map { $0.apnsDeviceToken }.flatMap { $0 } print("device tokens:", deviceTokens) let notificationItems = [ IOSNotificationItem.AlertBody("New Comment!!"), IOSNotificationItem.Sound("default") ] let pusher = NotificationPusher() pusher.apnsTopic = Config.apnsTopic pusher.pushIOS(Config.apnsConfigurationName, deviceTokens: deviceTokens, expiration: 0, priority: 10, notificationItems: notificationItems) { responses in responses.forEach({ response in print("NotificationResponse: \(response.code) \(response.stringBody)") }) } } }
mit
2ebc99e73cbd34adaecf610cd6109ea3
35.248148
152
0.552978
4.723456
false
false
false
false
LeaderQiu/SwiftWeibo
HMWeibo04/HMWeibo04/Classes/UI/Main/MainTabBar.swift
1
2704
// // MainTabBar.swift // HMWeibo04 // // Created by apple on 15/3/5. // Copyright (c) 2015年 heima. All rights reserved. // import UIKit class MainTabBar: UITabBar { /// 点击撰写微博按钮回调(闭包) -> (括号内部是闭包函数的类型 (参数)->(返回值)) var composedButtonClicked: (()->())? override func awakeFromNib() { self.addSubview(composeBtn!) } override func layoutSubviews() { super.layoutSubviews() setButtonsFrame() } /// 设置按钮的位置,水平均分显示"五"个按钮 func setButtonsFrame() { // 1. 计算基本属性 let w = self.bounds.size.width / CGFloat(buttonCount) let h = self.bounds.size.height var index = 0 // 2. 遍历子视图,提示:UITabBarButton属于私有API,在程序中如果直接使用私有 API,通常不能上架 // ** 在 swift 中遍历子视图一定要指定子视图的类型 // ** 所有的基本数字类型在计算时,类型一定要匹配! for view in self.subviews as! [UIView] { // 判断子视图是否是控件,UITabBarButton是继承自 UIControl if view is UIControl && !(view is UIButton) { let r = CGRectMake(CGFloat(index) * w, 0, w, h) view.frame = r index++ if index == 2 { index++ } } } // 3. 设置加号按钮的位置 composeBtn!.frame = CGRectMake(0, 0, w, h) composeBtn!.center = CGPointMake(self.center.x, h * 0.5) } /// 按钮总数 let buttonCount = 5 /// 创建撰写微博按钮 lazy var composeBtn: UIButton? = { let btn = UIButton() btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) // 添加按钮的监听方法 btn.addTarget(self, action: "clickCompose", forControlEvents: .TouchUpInside) return btn }() func clickCompose() { println("come here") // 判断闭包是否被设置数值 if composedButtonClicked != nil { // 执行回调方法 composedButtonClicked!() } } }
mit
f381cb8499eafbc20334822ba79a55d9
27.716049
121
0.55761
4.13879
false
false
false
false
Wolox/wolmo-core-ios
WolmoCoreTests/Extensions/UIKit/UITableViewSpec.swift
1
6433
// // UITableViewSpec.swift // WolmoCore // // Created by Daniela Riesgo on 4/19/17. // Copyright © 2017 Wolox. All rights reserved. // import Foundation import Quick import Nimble import WolmoCore public class UITableViewSpec: QuickSpec, UITableViewDataSource, UITableViewDelegate { public func numberOfSections(in tableView: UITableView) -> Int { return 5 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return UITableViewHeaderFooterView() } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UITableViewHeaderFooterView() } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 50 } override public func spec() { var tableView: UITableView! beforeEach { tableView = NibLoadableUITableView.loadFromNib()! tableView.dataSource = self tableView.delegate = self tableView.reloadData() } describe("#register(cell:) and #dequeue(cell:for:)") { context("when dequeing an already registered cell") { it("should return the loaded cell") { tableView.register(cell: NibLoadableTableCell.self) let cell = tableView.dequeue(cell: NibLoadableTableCell.self, for: IndexPath(row: 0, section: 0)) expect(cell).toNot(beNil()) } } context("when dequeing a not before registered cell") { it("should return .none") { expect(tableView.dequeue(cell: NibLoadableTableCell.self, for: IndexPath(row: 0, section: 0))) .to(raiseException(named: "NSInternalInconsistencyException")) } } } describe("#register(cell:) and #dequeue(cell:)") { context("when dequeing an already registered cell") { it("should return the loaded cell") { tableView.register(cell: NibLoadableTableCell.self) let cell = tableView.dequeue(cell: NibLoadableTableCell.self) expect(cell).toNot(beNil()) } } context("when dequeing a not before registered cell") { it("should return .none") { let cell = tableView.dequeue(cell: NibLoadableTableCell.self) expect(cell).to(beNil()) } } } //Test failing because of `dequeueReusableHeaderFooterView(withIdentifier: headerType.identifier)` always returns nil. //But don't know why. /* describe("#register(header:) and #dequeue(header:for:)") { context("when dequeing an already registered header") { it("should return the loaded view") { //Test failing because of error: "NSInternalInconsistencyException", //"request for layout attributes for supplementary view UICollectionElementKindSectionHeader in section 0 when there are only 0 sections in the collection view" //But don't know why. tableView.register(header: NibLoadableTableView.self) let view = tableView.dequeue(header: NibLoadableTableView.self) expect(view).toNot(beNil()) } } context("when dequeing a view registered for footer") { it("should return the loaded view since footer and header are interchangeable in table views") { tableView.register(footer: NibLoadableTableView.self) let view = tableView.dequeue(header: NibLoadableTableView.self) expect(view).toNot(beNil()) } } context("when dequeing a not before registered view") { it("should return .none") { let view = tableView.dequeue(header: NibLoadableTableView.self) expect(view).to(beNil()) } } } describe("#register(footer:) and #dequeue(footer:for:)") { context("when dequeing an already registered footer") { it("should return the loaded view") { //Test failing because of error: "NSInternalInconsistencyException", //"request for layout attributes for supplementary view UICollectionElementKindSectionHeader in section 0 when there are only 0 sections in the collection view" //But don't know why. tableView.register(footer: NibLoadableTableView.self) let view = tableView.dequeue(footer: NibLoadableTableView.self) expect(view).toNot(beNil()) } } context("when dequeing a view registered for header") { it("should return the loaded view since footer and header are interchangeable in table views") { tableView.register(header: NibLoadableTableView.self) let view = tableView.dequeue(footer: NibLoadableTableView.self) expect(view).toNot(beNil()) } } context("when dequeing a not before registered view") { it("should return .none") { let view = tableView.dequeue(footer: NibLoadableTableView.self) expect(view).to(beNil()) } } } */ } }
mit
d413ab8f8686fb6050a85bcb42fb9b7f
38.703704
180
0.550062
5.955556
false
false
false
false
SwiftKit/Lipstick
LipstickTests/NSAttributedString+AttributeTest.swift
1
1418
// // NSAttributedString+AttributeTest.swift // Lipstick // // Created by Filip Dolnik on 18.10.16. // Copyright © 2016 Brightify. All rights reserved. // import Quick import Nimble import Lipstick class NSAttributedStringAttributeTest: QuickSpec { override func spec() { describe("AttributedString + AttributedString") { it("sums") { expect(NSAttributedString(string: "A") + NSAttributedString(string: "B")) == NSAttributedString(string: "AB") } } describe("String + AttributedString") { it("sums") { expect("A" + NSAttributedString(string: "B")) == NSAttributedString(string: "AB") } } describe("AttributedString + String") { it("sums") { expect(NSAttributedString(string: "A") + "B") == NSAttributedString(string: "AB") } } describe("attributed") { it("creates AttributedString") { let attributes = [Attribute.baselineOffset(1), Attribute.expansion(1)] let attributedString = NSAttributedString(string: "A", attributes: attributes.toDictionary()) expect("A".attributed(attributes)) == attributedString expect("A".attributed(Attribute.baselineOffset(1), Attribute.expansion(1))) == attributedString } } } }
mit
315cfaa0a33b68c567d8df7c465c5cf9
33.560976
125
0.577982
4.97193
false
false
false
false
loganSims/wsdot-ios-app
wsdot/ThemeManager.swift
1
5077
// // File.swift // WSDOT // // Created by Logan Sims on 2/2/18. // Copyright © 2018 WSDOT. All rights reserved. // import Foundation struct Colors { static let wsdotPrimary = UIColor.init(red: 0.0/255.0, green: 123.0/255.0, blue: 95.0/255.0, alpha: 1) static let wsdotPrimaryDark = UIColor.init(red: 0.0/255.0, green: 81.0/255.0, blue: 81.0/255.0, alpha: 1) static let wsdotOrange = UIColor.init(red: 255.0/255.0, green: 108.0/255.0, blue: 12.0/255.0, alpha: 1) static let wsdotDarkOrange = UIColor.init(red: 196.0/255.0, green: 59.0/255.0, blue: 0.0/255.0, alpha: 1) static let wsdotBlue = UIColor.init(red: 0.0/255.0, green: 123.0/255.0, blue: 154.0/255.0, alpha: 1) static let customColor = UIColor.init(red: 0.0/255.0, green: 63.0/255.0, blue: 135.0/255.0, alpha: 1) static let tintColor = UIColor.init(red: 0.0/255.0, green: 174.0/255.0, blue: 65.0/255.0, alpha: 1) static let yellow = UIColor.init(red: 255.0/255.0, green: 235.0/255.0, blue: 59.0/255.0, alpha: 1) static let lightGreen = UIColor.init(red: 204.0/255.0, green: 239.0/255.0, blue: 184.0/255.0, alpha: 1) static let lightGrey = UIColor.init(red: 242.0/255.0, green: 242.0/255.0, blue: 242.0/255.0, alpha: 1) static let paleGrey = UIColor.init(red: 209.0/255.0, green: 213.0/255.0, blue: 219.0/255.0, alpha: 1) } enum Theme: Int { case defaultTheme = 0, orangeTheme = 1, blueTheme = 2, customTheme = 3 var mainColor: UIColor { switch self { case .defaultTheme: if #available(iOS 13, *) { return UIColor.init { (trait) -> UIColor in return trait.userInterfaceStyle == .dark ? Colors.wsdotPrimaryDark : Colors.wsdotPrimary } } return Colors.wsdotPrimary case .orangeTheme: return Colors.wsdotOrange case .blueTheme: return Colors.wsdotBlue case .customTheme: return Colors.customColor } } //Customizing the Navigation Bar var barStyle: UIBarStyle { switch self { case .defaultTheme: return .default case .orangeTheme: return .default case .blueTheme: return .default case .customTheme: return .default } } var darkColor: UIColor { switch self { case .defaultTheme: return Colors.wsdotPrimary case .orangeTheme: return Colors.wsdotDarkOrange case .blueTheme: return Colors.wsdotPrimary case .customTheme: return Colors.wsdotPrimary } } var secondaryColor: UIColor { switch self { case .defaultTheme: return UIColor.white case .orangeTheme: return UIColor.white case .blueTheme: return UIColor.white case .customTheme: return UIColor.white } } var titleTextColor: UIColor { switch self { case .defaultTheme: return UIColor.white case .orangeTheme: return UIColor.white case .blueTheme: return UIColor.white case .customTheme: return UIColor.white } } } // Enum declaration let SelectedThemeKey = "SelectedTheme" // This will let you use a theme in the app. class ThemeManager { // ThemeManager static func currentTheme() -> Theme { if let storedTheme = (UserDefaults.standard.value(forKey: SelectedThemeKey) as AnyObject).integerValue { return Theme(rawValue: storedTheme)! } else { return .defaultTheme } } static func applyTheme(theme: Theme) { UserDefaults.standard.setValue(theme.rawValue, forKey: SelectedThemeKey) UserDefaults.standard.synchronize() let sharedApplication = UIApplication.shared sharedApplication.delegate?.window??.tintColor = theme.mainColor UIToolbar.appearance().tintColor = theme.darkColor UITabBar.appearance().tintColor = theme.darkColor UIProgressView.appearance().tintColor = theme.mainColor UIPageControl.appearance().pageIndicatorTintColor = UIColor.gray UIPageControl.appearance().currentPageIndicatorTintColor = theme.mainColor UINavigationBar.appearance().barStyle = theme.barStyle UINavigationBar.appearance().barTintColor = theme.mainColor UINavigationBar.appearance().tintColor = theme.secondaryColor UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : theme.titleTextColor] UIPopoverBackgroundView.appearance().tintColor = theme.mainColor UITabBar.appearance().barStyle = theme.barStyle UISwitch.appearance().onTintColor = theme.mainColor.withAlphaComponent(0.8) UISegmentedControl.appearance().tintColor = theme.mainColor } }
gpl-3.0
487ad60a47946237da10541043ede19c
31.126582
122
0.615839
4.198511
false
false
false
false
serp1412/LazyTransitions
LazyTransitions.playground/Pages/Bouncy ScrollView animation.xcplaygroundpage/Contents.swift
1
3682
/*: # How to add a bouncy effect to scroll view transitions */ import LazyTransitions import UIKit import PlaygroundSupport class LazyViewController: UIViewController { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) override func viewDidLoad() { super.viewDidLoad() /* 1. Become lazy for your transition type */ becomeLazy(for: .dismiss) /* 2. Add transition for your scroll view. Bouncy effect will be applied automatically */ addTransition(forScrollView: collectionView) } } /* 3. Run the playground and flick the collection view to the very top or bottom to see how it bounces. **NOTE** to opt out of the bouncy effect just call `addTransition(forScrollView: collectionView, bouncyEdges: false)` instead */ //: [NEXT: Multiple Scroll Views](Multiple%20scroll%20views) [PREVIOUS: Limit Transition Orientations](Limit%20transition%20orientations) /* Oh hey there, didn't expect you to scroll down here. You won't find anything special here, just some setup code ☺️ */ let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0) let itemsPerRow: CGFloat = 3 extension LazyViewController: UICollectionViewDelegateFlowLayout { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "PhotoCell") view.addSubview(collectionView) collectionView.bindFrameToSuperviewBounds() collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = .white } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let paddingSpace = sectionInsets.left * (itemsPerRow + 1) let availableWidth = view.frame.width - paddingSpace let widthPerItem = availableWidth / itemsPerRow return CGSize(width: widthPerItem, height: widthPerItem) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.left } } // MARK: - UICollectionViewDataSource extension LazyViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 27 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoCell.identifier, for: indexPath) as! PhotoCell cell.backgroundColor = UIColor.white cell.imageView.image = UIImage(named: "\(indexPath.row)") return cell } } let backVC = BackgroundViewController.instantiate(with: LazyViewController.self, action: { presented, presenting in presenting.present(presented, animated: true, completion: nil) }) backVC.view.frame = .iphone6 PlaygroundPage.current.liveView = backVC.view
bsd-2-clause
75e4e4f413526ce7abb96c3db28389f0
25.652174
170
0.686514
5.632466
false
false
false
false
BGDigital/mckuai2.0
mckuai/mckuai/community/FollowTalk.swift
1
14349
// // FollowTalk.swift // mckuai // // Created by 陈强 on 15/5/6. // Copyright (c) 2015年 XingfuQiu. All rights reserved. // import Foundation import UIKit class FollowTalk: UIViewController,UITextViewDelegate,UzysAssetsPickerControllerDelegate, UIGestureRecognizerDelegate { var manager = AFHTTPRequestOperationManager() var progress = MBProgressHUD() var params = [String: String]() var fromViewController:UIViewController! var textView:KMPlaceholderTextView! var pic_wight:CGFloat! var addPic:UIButton! var image_array = [UIImage]() var image_button = [UIButton]() var image_button_tag:Int = 0 var sendButton:UIBarButtonItem! var content:String! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 0.933, green: 0.941, blue: 0.949, alpha: 1.00) self.pic_wight = (self.view.frame.width-6*10)/5 sendButton = UIBarButtonItem() sendButton.title = "发送" sendButton.target = self sendButton.action = Selector("send") self.navigationItem.rightBarButtonItem = sendButton initTextView() initimage() self.edgesForExtendedLayout = UIRectEdge.None // Do any additional setup after loading the view. } func initTextView() { self.textView = KMPlaceholderTextView(frame: CGRectMake(0, 0,self.view.frame.width, self.view.frame.height-pic_wight-5-260)) self.textView.delegate = self textView.userInteractionEnabled = true; textView.font = UIFont.systemFontOfSize(14) textView.scrollEnabled = true; textView.autoresizingMask = UIViewAutoresizing.FlexibleHeight textView.textAlignment = NSTextAlignment.Left textView.placeholder = "内容..." textView.textColor = UIColor.lightGrayColor() var tapDismiss = UITapGestureRecognizer(target: self, action: "dismissKeyboard") self.view.addGestureRecognizer(tapDismiss) self.view.addSubview(self.textView) self.textView.becomeFirstResponder() } func textViewDidChange(textView: UITextView) { self.textView.scrollRangeToVisible(self.textView.selectedRange) } func dismissKeyboard(){ self.textView.resignFirstResponder() } func initimage() { addPic = UIButton(frame: CGRectMake(10, self.textView.frame.origin.y+self.textView.frame.size.height-60, pic_wight, pic_wight)) addPic.setImage(UIImage(named: "addImage"), forState: UIControlState.Normal) addPic.addTarget(self, action: "addPicAction", forControlEvents: UIControlEvents.TouchUpInside) image_button += [addPic] self.view.addSubview(addPic) } func removeImg(sender:UIButton) { var selected_index:Int = 0 println(sender.tag) for(var i=0;i<self.image_button.count;i++) { if(sender.tag == self.image_button[i].tag){ selected_index = i break } } for(var i=0;i<self.image_button.count;i++){ if(self.image_button[i].frame.origin.x>sender.frame.origin.x){ self.image_button[i].frame.origin.x -= (self.pic_wight+10) } } sender.hidden = true self.image_button.removeAtIndex(selected_index) self.image_array.removeAtIndex(selected_index) } func addPicAction() { MobClick.event("followTalkPage", attributes: ["type":"addpic","result":"all"]) if(self.image_button.count >= 5){ MCUtils.showCustomHUD("最多同时支持四张图片上传", aType: .Warning) }else{ var appearanceConfig = UzysAppearanceConfig() appearanceConfig.finishSelectionButtonColor = UIColor.greenColor() UzysAssetsPickerController.setUpAppearanceConfig(appearanceConfig) var picker = UzysAssetsPickerController() picker.delegate = self picker.maximumNumberOfSelectionVideo = 0; picker.maximumNumberOfSelectionPhoto = 4-self.image_array.count; self.presentViewController(picker, animated: true, completion: nil) } } func uzysAssetsPickerController(picker: UzysAssetsPickerController!, didFinishPickingAssets assets: [AnyObject]!) { if(assets.count != 0){ var assets_array = assets as NSArray assets_array.enumerateObjectsUsingBlock({ obj, index, stop in println(index) var representation:ALAsset = obj as! ALAsset var returnImg = UIImage(CGImage: representation.defaultRepresentation().fullScreenImage().takeUnretainedValue(), scale:CGFloat(representation.defaultRepresentation().scale()), orientation:UIImageOrientation(rawValue: representation.defaultRepresentation().orientation().rawValue)!) var image_x = CGFloat(self.image_button.count-1)*(self.pic_wight+10)+10 var img_btn = UIButton(frame: CGRectMake(image_x, self.addPic.frame.origin.y , self.pic_wight, self.pic_wight)) img_btn.setImage(returnImg, forState: UIControlState.Normal) img_btn.addTarget(self, action: "removeImg:", forControlEvents: UIControlEvents.TouchUpInside) img_btn.tag = self.image_button_tag++ self.image_button.insert(img_btn, atIndex: self.image_button.count-1) self.image_array += [returnImg!] self.image_button.last!.frame.origin.x = self.image_button.last!.frame.origin.x+self.pic_wight+10 self.view.addSubview(img_btn) }) } // if(assets[0].valueForProperty(ALAssetPropertyType).isEqualToString(ALAssetTypePhoto)){ // [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { // ALAsset *representation = obj; // // UIImage *img = [UIImage imageWithCGImage:representation.defaultRepresentation.fullResolutionImage // scale:representation.defaultRepresentation.scale // orientation:(UIImageOrientation)representation.defaultRepresentation.orientation]; // // }]; // } } func uzysAssetsPickerControllerDidExceedMaximumNumberOfSelection(picker: UzysAssetsPickerController!) { MCUtils.showCustomHUD("你传的图片已达到上限", aType: .Warning) } // func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){ // println("choose--------->>") // println(info) // // var image_x = CGFloat(image_button.count-1)*(self.pic_wight+10)+10 // // var img_btn = UIButton(frame: CGRectMake(image_x, self.addPic.frame.origin.y // , self.pic_wight, self.pic_wight)) // // var img = info[UIImagePickerControllerEditedImage] as! UIImage // img_btn.setImage(img, forState: UIControlState.Normal) // img_btn.addTarget(self, action: "removeImg:", forControlEvents: UIControlEvents.TouchUpInside) // img_btn.tag = self.image_button_tag++ // // image_button.insert(img_btn, atIndex: image_button.count-1) // // image_array += [ImageUtil.thumbnailWithImageWithoutScale(img, asize: CGSize(width: 620, height: 350))] // image_array += [img] // image_button.last!.frame.origin.x = image_button.last!.frame.origin.x+self.pic_wight+10 // self.view.addSubview(img_btn) // picker.dismissViewControllerAnimated(true, completion: nil) // // // } // func imagePickerControllerDidCancel(picker: UIImagePickerController){ // // // println("cancel--------->>") // // // // picker.dismissViewControllerAnimated(true, completion: nil) // // // } func send() { MobClick.event("followTalkPage", attributes: ["type":"send","result":"all"]) self.sendButton.enabled = false content = self.textView.text if(content == nil || content.isEmpty || content == "内容..."){ MCUtils.showCustomHUD("跟贴的内容不能为空", aType: .Error) self.sendButton.enabled = true return } if(self.params.count != 0) { progress = MBProgressHUD.showHUDAddedTo(view, animated: true) progress.labelText = "正在发送" if(self.image_array.count != 0){ manager.POST(upload_url, parameters:nil, constructingBodyWithBlock: { (formData:AFMultipartFormData!) in for(var i=0;i<self.image_array.count;i++){ var key = "file"+String(i) var value = "fileName"+String(i)+".jpg" var imageData = UIImageJPEGRepresentation(self.image_array[i], 0.0) formData.appendPartWithFileData(imageData, name: key, fileName: value, mimeType: "image/jpeg") } }, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in var json = JSON(responseObject) if "ok" == json["state"].stringValue { println(json["msg"]) self.content! += json["msg"].stringValue self.postTalkToServer() MobClick.event("followTalkPage", attributes: ["type":"addpic","result":"success"]) }else{ self.sendButton?.enabled = true self.progress.removeFromSuperview() MCUtils.showCustomHUD("图片上传失败,请稍候再试", aType: .Error) MobClick.event("followTalkPage", attributes: ["type":"addpic","result":"error"]) } }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in println("Error: " + error.localizedDescription) self.progress.removeFromSuperview() MCUtils.showCustomHUD("图片上传失败,请稍候再试", aType: .Error) MobClick.event("followTalkPage", attributes: ["type":"addpic","result":"error"]) }) }else{ self.postTalkToServer() } } } func postTalkToServer() { self.params["content"] = content self.params["device"] = "ios" self.params["userId"] = String(stringInterpolationSegment: appUserIdSave) manager.POST(followTalk_url, parameters: self.params, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in var json = JSON(responseObject) if "ok" == json["state"].stringValue { self.progress.labelText = "发送成功" NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "returnPage", userInfo: nil, repeats: false) MobClick.event("followTalkPage", attributes: ["type":"send","result":"success"]) }else{ self.sendButton?.enabled = true self.progress.removeFromSuperview() MCUtils.showCustomHUD("跟贴失败,请稍候再试", aType: .Error) MobClick.event("followTalkPage", attributes: ["type":"send","result":"error"]) } }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in println("Error: " + error.localizedDescription) self.sendButton?.enabled = true self.progress.removeFromSuperview() MCUtils.showCustomHUD("跟贴失败,请稍候再试", aType: .Error) MobClick.event("followTalkPage", attributes: ["type":"send","result":"error"]) }) } func returnPage() { if self.params["isOver"] == "yes" { (self.fromViewController as! TalkDetail).afterReply() } self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } class func showFollowTalkView(ctl:UINavigationController?,dict: [String: String]!,viewController:UIViewController){ var followTalkView = UIStoryboard(name: "FollowTalk", bundle: nil).instantiateViewControllerWithIdentifier("followTalk") as! FollowTalk followTalkView.params = dict followTalkView.fromViewController = viewController if (ctl != nil) { ctl?.pushViewController(followTalkView, animated: true) } else { ctl?.presentViewController(followTalkView, animated: true, completion: nil) } } override func viewWillAppear(animated: Bool) { MobClick.beginLogPageView("followTalk") } override func viewDidAppear(animated: Bool) { self.tabBarController?.tabBar.hidden = true } override func viewWillDisappear(animated: Bool) { MobClick.endLogPageView("followTalk") } }
mit
13b40e2ac2b56fb474a0e511c8f616c2
38.046832
297
0.566429
4.946946
false
false
false
false
maxoumime/emoji-data-ios
emojidataios/Classes/EmojiParser.swift
1
6871
// // EmojiParser.swift // Pods // // Created by Maxime Bertheau on 4/12/17. // // import Foundation open class EmojiParser { fileprivate static var loading = false fileprivate static var _emojiManager: EmojiManager? fileprivate static var emojiManager: EmojiManager { get { if _emojiManager == nil { _emojiManager = EmojiManager() } return _emojiManager! } } fileprivate static var _aliasMatchingRegex: NSRegularExpression? fileprivate static var aliasMatchingRegex: NSRegularExpression { if _aliasMatchingRegex == nil { do { _aliasMatchingRegex = try NSRegularExpression(pattern: ":([\\w_+-]+)(?:(?:\\||::)((type_|skin-tone-\\d+)[\\w_]*))*:", options: .caseInsensitive) } catch { } } return _aliasMatchingRegex! } fileprivate static var _aliasMatchingRegexOptionalColon: NSRegularExpression? fileprivate static var aliasMatchingRegexOptionalColon: NSRegularExpression { if _aliasMatchingRegexOptionalColon == nil { do { _aliasMatchingRegexOptionalColon = try NSRegularExpression(pattern: ":?([\\w_+-]+)(?:(?:\\||::)((type_|skin-tone-\\d+)[\\w_]*))*:?", options: .caseInsensitive) } catch { } } return _aliasMatchingRegexOptionalColon! } public static func prepare() { if loading || _emojiManager != nil { return } loading = true DispatchQueue.global(qos: .background).async { let emojiManager = EmojiManager() DispatchQueue.main.async { loading = false if self._emojiManager == nil { self._emojiManager = emojiManager } } } } public static func getAliasesFromUnicode(_ unicode: String) -> [String] { let escapedUnicode = unicode.unicodeScalars.map { $0.escaped(asASCII: true) } .map { (escaped: String) -> String? in if (!escaped.hasPrefix("\\u{")) { return escaped.unicodeScalars.map { (unicode: Unicode.Scalar) -> String in var hexValue = String(unicode.value, radix: 16).uppercased() while(hexValue.count < 4) { hexValue = "0" + hexValue } return hexValue }.reduce("", +) } // Cleaning // format \u{XXXXX} var cleaned = escaped.dropFirst(3).dropLast() // removing unecessary 0s while (cleaned.hasPrefix("0") && cleaned.count > 4) { cleaned = cleaned.dropFirst() } return String(cleaned) } if escapedUnicode.contains(where: { $0 == nil }) { return [] } let unified = (escapedUnicode as! [String]).joined(separator: "-") return emojiManager.emojiForUnified[unified]?.map { $0.shortName } ?? [] } public static func getUnicodeFromAlias(_ alias: String) -> String? { let input = alias as NSString let matches = aliasMatchingRegexOptionalColon.matches(in: alias, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: alias.count)) if(matches.count == 0) { return nil } let match = matches[0] let aliasMatch = match.range(at: 1) let alias = input.substring(with: aliasMatch) let skinVariationsString = input.substring(from: aliasMatch.upperBound) .split(separator: ":") .map { $0.trimmingCharacters(in: [":"]) } .filter { !$0.isEmpty } guard let emojiObject = getEmojiFromAlias(alias) else { return nil } let emoji: String let skinVariations = skinVariationsString.compactMap { SkinVariationTypes(rawValue: $0.uppercased()) ?? SkinVariationTypes.getFromAlias($0.lowercased()) } emoji = emojiObject.getEmojiWithSkinVariations(skinVariations) return emoji } public static func getEmojiFromUnified(_ unified: String) -> String { Emoji(shortName: "", unified: unified).emoji } static func getEmojiFromAlias(_ alias: String) -> Emoji? { guard let emoji = emojiManager.shortNameForUnified[alias] else { return nil } return emoji.first } public static func parseUnicode(_ input: String) -> String { return input .map { ($0, $0.unicodeScalars.map { $0.escaped(asASCII: true) }) } .reduce("") { result, mapped in let fallback = mapped.0 let unicode = mapped.1 let maybeEmojiAlias = unicode.map { (escaped: String) -> String in if (!escaped.hasPrefix("\\u{")) { return escaped } // Cleaning // format \u{XXXXX} var cleaned = escaped.dropFirst(3).dropLast() // removing unecessary 0s while (cleaned.hasPrefix("0")) { cleaned = cleaned.dropFirst() } return String(cleaned) }.joined(separator: "-") let toDisplay: String if let emoji = emojiManager.emojiForUnified[maybeEmojiAlias]?.first { toDisplay = ":\(emoji.shortName):" } else { toDisplay = String(fallback) } return "\(result)\(toDisplay)" } } public static func parseAliases(_ input: String) -> String { var result = input getUnicodesForAliases(input).forEach { alias, emoji in if let emoji = emoji { result = result.replacingOccurrences(of: alias, with: emoji) } } return result } public static func getUnicodesForAliases(_ input: String) -> [(key: String, value: String?)] { let matches = aliasMatchingRegex.matches(in: input, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: input.count)) if(matches.count == 0) { return [] } let nsInput = input as NSString var uniqueMatches: [String:String?] = [:] matches.forEach { let fullAlias = nsInput.substring(with: $0.range(at: 0)) if uniqueMatches.index(forKey: fullAlias) == nil { uniqueMatches[fullAlias] = getUnicodeFromAlias(fullAlias) } } return uniqueMatches.sorted(by: { $0.key.count > $1.key.count // Execute the longer first so emojis with skin variations are executed before the ones without }) } public static var emojisByCategory: [EmojiCategory: [Emoji]]{ return emojiManager.emojisForCategory } public static var emojisByUnicode: [String: Emoji] { return emojiManager.emojiForUnicode } public static func getEmojisForCategory(_ category: EmojiCategory) -> [String] { let emojis = emojiManager.getEmojisForCategory(category) ?? [] return emojis.map { $0.emoji } } }
mit
3de5edcd0a256e472c6c07a0d9712c12
27.27572
167
0.590307
4.52635
false
false
false
false