repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
PokemonGoSucks/pgoapi-swift
PGoApi/Classes/protos/Pogoprotos.Data.Capture.PogoprotosDataCapture.proto.swift
1
40528
// Generated by the Protocol Buffers 3.0 compiler. DO NOT EDIT! // Source file "POGOProtos.Data.Capture.proto" // Syntax "Proto3" import Foundation import ProtocolBuffers public func == (lhs: Pogoprotos.Data.Capture.CaptureAward, rhs: Pogoprotos.Data.Capture.CaptureAward) -> Bool { if (lhs === rhs) { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) fieldCheck = fieldCheck && (lhs.activityType == rhs.activityType) fieldCheck = fieldCheck && (lhs.xp == rhs.xp) fieldCheck = fieldCheck && (lhs.candy == rhs.candy) fieldCheck = fieldCheck && (lhs.stardust == rhs.stardust) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } public func == (lhs: Pogoprotos.Data.Capture.CaptureProbability, rhs: Pogoprotos.Data.Capture.CaptureProbability) -> Bool { if (lhs === rhs) { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) fieldCheck = fieldCheck && (lhs.pokeballType == rhs.pokeballType) fieldCheck = fieldCheck && (lhs.captureProbability == rhs.captureProbability) fieldCheck = fieldCheck && (lhs.hasReticleDifficultyScale == rhs.hasReticleDifficultyScale) && (!lhs.hasReticleDifficultyScale || lhs.reticleDifficultyScale == rhs.reticleDifficultyScale) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } public extension Pogoprotos.Data.Capture { public struct PogoprotosDataCaptureRoot { public static var sharedInstance : PogoprotosDataCaptureRoot { struct Static { static let instance : PogoprotosDataCaptureRoot = PogoprotosDataCaptureRoot() } return Static.instance } public var extensionRegistry:ExtensionRegistry init() { extensionRegistry = ExtensionRegistry() registerAllExtensions(registry: extensionRegistry) Pogoprotos.Enums.PogoprotosEnumsRoot.sharedInstance.registerAllExtensions(registry: extensionRegistry) Pogoprotos.Inventory.Item.PogoprotosInventoryItemRoot.sharedInstance.registerAllExtensions(registry: extensionRegistry) } public func registerAllExtensions(registry: ExtensionRegistry) { } } final public class CaptureAward : GeneratedMessage { private var activityTypeMemoizedSerializedSize:Int32 = 0 public fileprivate(set) var activityType:Array<Pogoprotos.Enums.ActivityType> = Array<Pogoprotos.Enums.ActivityType>() public fileprivate(set) var xp:Array<Int32> = Array<Int32>() private var xpMemoizedSerializedSize:Int32 = -1 public fileprivate(set) var candy:Array<Int32> = Array<Int32>() private var candyMemoizedSerializedSize:Int32 = -1 public fileprivate(set) var stardust:Array<Int32> = Array<Int32>() private var stardustMemoizedSerializedSize:Int32 = -1 required public init() { super.init() } override public func isInitialized() -> Bool { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { if !activityType.isEmpty { try codedOutputStream.writeRawVarint32(value: 10) try codedOutputStream.writeRawVarint32(value: activityTypeMemoizedSerializedSize) } for oneValueOfactivityType in activityType { try codedOutputStream.writeEnumNoTag(value: oneValueOfactivityType.rawValue) } if !xp.isEmpty { try codedOutputStream.writeRawVarint32(value: 18) try codedOutputStream.writeRawVarint32(value: xpMemoizedSerializedSize) for oneValuexp in xp { try codedOutputStream.writeInt32NoTag(value: oneValuexp) } } if !candy.isEmpty { try codedOutputStream.writeRawVarint32(value: 26) try codedOutputStream.writeRawVarint32(value: candyMemoizedSerializedSize) for oneValuecandy in candy { try codedOutputStream.writeInt32NoTag(value: oneValuecandy) } } if !stardust.isEmpty { try codedOutputStream.writeRawVarint32(value: 34) try codedOutputStream.writeRawVarint32(value: stardustMemoizedSerializedSize) for oneValuestardust in stardust { try codedOutputStream.writeInt32NoTag(value: oneValuestardust) } } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } override public func serializedSize() -> Int32 { var serialize_size:Int32 = memoizedSerializedSize if serialize_size != -1 { return serialize_size } serialize_size = 0 var dataSizeactivityType:Int32 = 0 for oneValueOfactivityType in activityType { dataSizeactivityType += oneValueOfactivityType.rawValue.computeEnumSizeNoTag() } serialize_size += dataSizeactivityType if !activityType.isEmpty { serialize_size += 1 serialize_size += dataSizeactivityType.computeRawVarint32Size() } activityTypeMemoizedSerializedSize = dataSizeactivityType var dataSizeXp:Int32 = 0 for oneValuexp in xp { dataSizeXp += oneValuexp.computeInt32SizeNoTag() } serialize_size += dataSizeXp if !xp.isEmpty { serialize_size += 1 serialize_size += dataSizeXp.computeInt32SizeNoTag() } xpMemoizedSerializedSize = dataSizeXp var dataSizeCandy:Int32 = 0 for oneValuecandy in candy { dataSizeCandy += oneValuecandy.computeInt32SizeNoTag() } serialize_size += dataSizeCandy if !candy.isEmpty { serialize_size += 1 serialize_size += dataSizeCandy.computeInt32SizeNoTag() } candyMemoizedSerializedSize = dataSizeCandy var dataSizeStardust:Int32 = 0 for oneValuestardust in stardust { dataSizeStardust += oneValuestardust.computeInt32SizeNoTag() } serialize_size += dataSizeStardust if !stardust.isEmpty { serialize_size += 1 serialize_size += dataSizeStardust.computeInt32SizeNoTag() } stardustMemoizedSerializedSize = dataSizeStardust serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } public class func getBuilder() -> Pogoprotos.Data.Capture.CaptureAward.Builder { return Pogoprotos.Data.Capture.CaptureAward.classBuilder() as! Pogoprotos.Data.Capture.CaptureAward.Builder } public func getBuilder() -> Pogoprotos.Data.Capture.CaptureAward.Builder { return classBuilder() as! Pogoprotos.Data.Capture.CaptureAward.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { return Pogoprotos.Data.Capture.CaptureAward.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { return Pogoprotos.Data.Capture.CaptureAward.Builder() } public func toBuilder() throws -> Pogoprotos.Data.Capture.CaptureAward.Builder { return try Pogoprotos.Data.Capture.CaptureAward.builderWithPrototype(prototype:self) } public class func builderWithPrototype(prototype:Pogoprotos.Data.Capture.CaptureAward) throws -> Pogoprotos.Data.Capture.CaptureAward.Builder { return try Pogoprotos.Data.Capture.CaptureAward.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary<String,Any> { guard isInitialized() else { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } var jsonMap:Dictionary<String,Any> = Dictionary<String,Any>() if !activityType.isEmpty { var jsonArrayActivityType:Array<String> = [] for oneValueActivityType in activityType { jsonArrayActivityType.append(oneValueActivityType.toString()) } jsonMap["activityType"] = jsonArrayActivityType } if !xp.isEmpty { var jsonArrayXp:Array<NSNumber> = [] for oneValueXp in xp { jsonArrayXp.append(NSNumber(value:oneValueXp)) } jsonMap["xp"] = jsonArrayXp } if !candy.isEmpty { var jsonArrayCandy:Array<NSNumber> = [] for oneValueCandy in candy { jsonArrayCandy.append(NSNumber(value:oneValueCandy)) } jsonMap["candy"] = jsonArrayCandy } if !stardust.isEmpty { var jsonArrayStardust:Array<NSNumber> = [] for oneValueStardust in stardust { jsonArrayStardust.append(NSNumber(value:oneValueStardust)) } jsonMap["stardust"] = jsonArrayStardust } return jsonMap } override class public func decode(jsonMap:Dictionary<String,Any>) throws -> Pogoprotos.Data.Capture.CaptureAward { return try Pogoprotos.Data.Capture.CaptureAward.Builder.decodeToBuilder(jsonMap:jsonMap).build() } override class public func fromJSON(data:Data) throws -> Pogoprotos.Data.Capture.CaptureAward { return try Pogoprotos.Data.Capture.CaptureAward.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" var activityTypeElementIndex:Int = 0 for oneValueOfactivityType in activityType { output += "\(indent) activityType[\(activityTypeElementIndex)]: \(oneValueOfactivityType.description)\n" activityTypeElementIndex += 1 } var xpElementIndex:Int = 0 for oneValueXp in xp { output += "\(indent) xp[\(xpElementIndex)]: \(oneValueXp)\n" xpElementIndex += 1 } var candyElementIndex:Int = 0 for oneValueCandy in candy { output += "\(indent) candy[\(candyElementIndex)]: \(oneValueCandy)\n" candyElementIndex += 1 } var stardustElementIndex:Int = 0 for oneValueStardust in stardust { output += "\(indent) stardust[\(stardustElementIndex)]: \(oneValueStardust)\n" stardustElementIndex += 1 } output += unknownFields.getDescription(indent: indent) return output } override public var hashValue:Int { get { var hashCode:Int = 7 for oneValueOfactivityType in activityType { hashCode = (hashCode &* 31) &+ Int(oneValueOfactivityType.rawValue) } for oneValueXp in xp { hashCode = (hashCode &* 31) &+ oneValueXp.hashValue } for oneValueCandy in candy { hashCode = (hashCode &* 31) &+ oneValueCandy.hashValue } for oneValueStardust in stardust { hashCode = (hashCode &* 31) &+ oneValueStardust.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } } //Meta information declaration start override public class func className() -> String { return "Pogoprotos.Data.Capture.CaptureAward" } override public func className() -> String { return "Pogoprotos.Data.Capture.CaptureAward" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { fileprivate var builderResult:Pogoprotos.Data.Capture.CaptureAward = Pogoprotos.Data.Capture.CaptureAward() public func getMessage() -> Pogoprotos.Data.Capture.CaptureAward { return builderResult } required override public init () { super.init() } public var activityType:Array<Pogoprotos.Enums.ActivityType> { get { return builderResult.activityType } set (value) { builderResult.activityType = value } } public func setActivityType(_ value:Array<Pogoprotos.Enums.ActivityType>) -> Pogoprotos.Data.Capture.CaptureAward.Builder { self.activityType = value return self } public func clearActivityType() -> Pogoprotos.Data.Capture.CaptureAward.Builder { builderResult.activityType.removeAll(keepingCapacity: false) return self } public var xp:Array<Int32> { get { return builderResult.xp } set (array) { builderResult.xp = array } } public func setXp(_ value:Array<Int32>) -> Pogoprotos.Data.Capture.CaptureAward.Builder { self.xp = value return self } public func clearXp() -> Pogoprotos.Data.Capture.CaptureAward.Builder { builderResult.xp.removeAll(keepingCapacity: false) return self } public var candy:Array<Int32> { get { return builderResult.candy } set (array) { builderResult.candy = array } } public func setCandy(_ value:Array<Int32>) -> Pogoprotos.Data.Capture.CaptureAward.Builder { self.candy = value return self } public func clearCandy() -> Pogoprotos.Data.Capture.CaptureAward.Builder { builderResult.candy.removeAll(keepingCapacity: false) return self } public var stardust:Array<Int32> { get { return builderResult.stardust } set (array) { builderResult.stardust = array } } public func setStardust(_ value:Array<Int32>) -> Pogoprotos.Data.Capture.CaptureAward.Builder { self.stardust = value return self } public func clearStardust() -> Pogoprotos.Data.Capture.CaptureAward.Builder { builderResult.stardust.removeAll(keepingCapacity: false) return self } override public var internalGetResult:GeneratedMessage { get { return builderResult } } override public func clear() -> Pogoprotos.Data.Capture.CaptureAward.Builder { builderResult = Pogoprotos.Data.Capture.CaptureAward() return self } override public func clone() throws -> Pogoprotos.Data.Capture.CaptureAward.Builder { return try Pogoprotos.Data.Capture.CaptureAward.builderWithPrototype(prototype:builderResult) } override public func build() throws -> Pogoprotos.Data.Capture.CaptureAward { try checkInitialized() return buildPartial() } public func buildPartial() -> Pogoprotos.Data.Capture.CaptureAward { let returnMe:Pogoprotos.Data.Capture.CaptureAward = builderResult return returnMe } public func mergeFrom(other:Pogoprotos.Data.Capture.CaptureAward) throws -> Pogoprotos.Data.Capture.CaptureAward.Builder { if other == Pogoprotos.Data.Capture.CaptureAward() { return self } if !other.activityType.isEmpty { builderResult.activityType += other.activityType } if !other.xp.isEmpty { builderResult.xp += other.xp } if !other.candy.isEmpty { builderResult.candy += other.candy } if !other.stardust.isEmpty { builderResult.stardust += other.stardust } _ = try merge(unknownField: other.unknownFields) return self } override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Pogoprotos.Data.Capture.CaptureAward.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Data.Capture.CaptureAward.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() switch protobufTag { case 0: self.unknownFields = try unknownFieldsBuilder.build() return self case 10: let length = Int(try codedInputStream.readRawVarint32()) let oldLimit = try codedInputStream.pushLimit(byteLimit: length) while codedInputStream.bytesUntilLimit() > 0 { let valueIntactivityType = try codedInputStream.readEnum() if let enumsactivityType = Pogoprotos.Enums.ActivityType(rawValue:valueIntactivityType) { builderResult.activityType.append(enumsactivityType) } else { _ = try unknownFieldsBuilder.mergeVarintField(fieldNumber: 1, value:Int64(valueIntactivityType)) } } codedInputStream.popLimit(oldLimit: oldLimit) case 18: let length = Int(try codedInputStream.readRawVarint32()) let limit = try codedInputStream.pushLimit(byteLimit: length) while (codedInputStream.bytesUntilLimit() > 0) { builderResult.xp.append(try codedInputStream.readInt32()) } codedInputStream.popLimit(oldLimit: limit) case 26: let length = Int(try codedInputStream.readRawVarint32()) let limit = try codedInputStream.pushLimit(byteLimit: length) while (codedInputStream.bytesUntilLimit() > 0) { builderResult.candy.append(try codedInputStream.readInt32()) } codedInputStream.popLimit(oldLimit: limit) case 34: let length = Int(try codedInputStream.readRawVarint32()) let limit = try codedInputStream.pushLimit(byteLimit: length) while (codedInputStream.bytesUntilLimit() > 0) { builderResult.stardust.append(try codedInputStream.readInt32()) } codedInputStream.popLimit(oldLimit: limit) default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { unknownFields = try unknownFieldsBuilder.build() return self } } } } class public func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> Pogoprotos.Data.Capture.CaptureAward.Builder { let resultDecodedBuilder = Pogoprotos.Data.Capture.CaptureAward.Builder() if let jsonValueActivityType = jsonMap["activityType"] as? Array<String> { var jsonArrayActivityType:Array<Pogoprotos.Enums.ActivityType> = [] for oneValueActivityType in jsonValueActivityType { let enumFromStringActivityType = try Pogoprotos.Enums.ActivityType.fromString(str: oneValueActivityType) jsonArrayActivityType.append(enumFromStringActivityType) } resultDecodedBuilder.activityType = jsonArrayActivityType } if let jsonValueXp = jsonMap["xp"] as? Array<NSNumber> { var jsonArrayXp:Array<Int32> = [] for oneValueXp in jsonValueXp { jsonArrayXp.append(oneValueXp.int32Value) } resultDecodedBuilder.xp = jsonArrayXp } if let jsonValueCandy = jsonMap["candy"] as? Array<NSNumber> { var jsonArrayCandy:Array<Int32> = [] for oneValueCandy in jsonValueCandy { jsonArrayCandy.append(oneValueCandy.int32Value) } resultDecodedBuilder.candy = jsonArrayCandy } if let jsonValueStardust = jsonMap["stardust"] as? Array<NSNumber> { var jsonArrayStardust:Array<Int32> = [] for oneValueStardust in jsonValueStardust { jsonArrayStardust.append(oneValueStardust.int32Value) } resultDecodedBuilder.stardust = jsonArrayStardust } return resultDecodedBuilder } override class public func fromJSONToBuilder(data:Data) throws -> Pogoprotos.Data.Capture.CaptureAward.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary<String,Any> else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } return try Pogoprotos.Data.Capture.CaptureAward.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } final public class CaptureProbability : GeneratedMessage { private var pokeballTypeMemoizedSerializedSize:Int32 = 0 public fileprivate(set) var pokeballType:Array<Pogoprotos.Inventory.Item.ItemId> = Array<Pogoprotos.Inventory.Item.ItemId>() public fileprivate(set) var captureProbability:Array<Float> = Array<Float>() private var captureProbabilityMemoizedSerializedSize:Int32 = -1 public fileprivate(set) var reticleDifficultyScale:Double = Double(0) public fileprivate(set) var hasReticleDifficultyScale:Bool = false required public init() { super.init() } override public func isInitialized() -> Bool { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { if !pokeballType.isEmpty { try codedOutputStream.writeRawVarint32(value: 10) try codedOutputStream.writeRawVarint32(value: pokeballTypeMemoizedSerializedSize) } for oneValueOfpokeballType in pokeballType { try codedOutputStream.writeEnumNoTag(value: oneValueOfpokeballType.rawValue) } if !captureProbability.isEmpty { try codedOutputStream.writeRawVarint32(value: 18) try codedOutputStream.writeRawVarint32(value: captureProbabilityMemoizedSerializedSize) for oneValuecaptureProbability in captureProbability { try codedOutputStream.writeFloatNoTag(value: oneValuecaptureProbability) } } if hasReticleDifficultyScale { try codedOutputStream.writeDouble(fieldNumber: 12, value:reticleDifficultyScale) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } override public func serializedSize() -> Int32 { var serialize_size:Int32 = memoizedSerializedSize if serialize_size != -1 { return serialize_size } serialize_size = 0 var dataSizepokeballType:Int32 = 0 for oneValueOfpokeballType in pokeballType { dataSizepokeballType += oneValueOfpokeballType.rawValue.computeEnumSizeNoTag() } serialize_size += dataSizepokeballType if !pokeballType.isEmpty { serialize_size += 1 serialize_size += dataSizepokeballType.computeRawVarint32Size() } pokeballTypeMemoizedSerializedSize = dataSizepokeballType var dataSizeCaptureProbability:Int32 = 0 dataSizeCaptureProbability = 4 * Int32(captureProbability.count) serialize_size += dataSizeCaptureProbability if !captureProbability.isEmpty { serialize_size += 1 serialize_size += dataSizeCaptureProbability.computeInt32SizeNoTag() } captureProbabilityMemoizedSerializedSize = dataSizeCaptureProbability if hasReticleDifficultyScale { serialize_size += reticleDifficultyScale.computeDoubleSize(fieldNumber: 12) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } public class func getBuilder() -> Pogoprotos.Data.Capture.CaptureProbability.Builder { return Pogoprotos.Data.Capture.CaptureProbability.classBuilder() as! Pogoprotos.Data.Capture.CaptureProbability.Builder } public func getBuilder() -> Pogoprotos.Data.Capture.CaptureProbability.Builder { return classBuilder() as! Pogoprotos.Data.Capture.CaptureProbability.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { return Pogoprotos.Data.Capture.CaptureProbability.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { return Pogoprotos.Data.Capture.CaptureProbability.Builder() } public func toBuilder() throws -> Pogoprotos.Data.Capture.CaptureProbability.Builder { return try Pogoprotos.Data.Capture.CaptureProbability.builderWithPrototype(prototype:self) } public class func builderWithPrototype(prototype:Pogoprotos.Data.Capture.CaptureProbability) throws -> Pogoprotos.Data.Capture.CaptureProbability.Builder { return try Pogoprotos.Data.Capture.CaptureProbability.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary<String,Any> { guard isInitialized() else { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } var jsonMap:Dictionary<String,Any> = Dictionary<String,Any>() if !pokeballType.isEmpty { var jsonArrayPokeballType:Array<String> = [] for oneValuePokeballType in pokeballType { jsonArrayPokeballType.append(oneValuePokeballType.toString()) } jsonMap["pokeballType"] = jsonArrayPokeballType } if !captureProbability.isEmpty { var jsonArrayCaptureProbability:Array<NSNumber> = [] for oneValueCaptureProbability in captureProbability { jsonArrayCaptureProbability.append(NSNumber(value:oneValueCaptureProbability)) } jsonMap["captureProbability"] = jsonArrayCaptureProbability } if hasReticleDifficultyScale { jsonMap["reticleDifficultyScale"] = NSNumber(value:reticleDifficultyScale) } return jsonMap } override class public func decode(jsonMap:Dictionary<String,Any>) throws -> Pogoprotos.Data.Capture.CaptureProbability { return try Pogoprotos.Data.Capture.CaptureProbability.Builder.decodeToBuilder(jsonMap:jsonMap).build() } override class public func fromJSON(data:Data) throws -> Pogoprotos.Data.Capture.CaptureProbability { return try Pogoprotos.Data.Capture.CaptureProbability.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" var pokeballTypeElementIndex:Int = 0 for oneValueOfpokeballType in pokeballType { output += "\(indent) pokeballType[\(pokeballTypeElementIndex)]: \(oneValueOfpokeballType.description)\n" pokeballTypeElementIndex += 1 } var captureProbabilityElementIndex:Int = 0 for oneValueCaptureProbability in captureProbability { output += "\(indent) captureProbability[\(captureProbabilityElementIndex)]: \(oneValueCaptureProbability)\n" captureProbabilityElementIndex += 1 } if hasReticleDifficultyScale { output += "\(indent) reticleDifficultyScale: \(reticleDifficultyScale) \n" } output += unknownFields.getDescription(indent: indent) return output } override public var hashValue:Int { get { var hashCode:Int = 7 for oneValueOfpokeballType in pokeballType { hashCode = (hashCode &* 31) &+ Int(oneValueOfpokeballType.rawValue) } for oneValueCaptureProbability in captureProbability { hashCode = (hashCode &* 31) &+ oneValueCaptureProbability.hashValue } if hasReticleDifficultyScale { hashCode = (hashCode &* 31) &+ reticleDifficultyScale.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } } //Meta information declaration start override public class func className() -> String { return "Pogoprotos.Data.Capture.CaptureProbability" } override public func className() -> String { return "Pogoprotos.Data.Capture.CaptureProbability" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { fileprivate var builderResult:Pogoprotos.Data.Capture.CaptureProbability = Pogoprotos.Data.Capture.CaptureProbability() public func getMessage() -> Pogoprotos.Data.Capture.CaptureProbability { return builderResult } required override public init () { super.init() } public var pokeballType:Array<Pogoprotos.Inventory.Item.ItemId> { get { return builderResult.pokeballType } set (value) { builderResult.pokeballType = value } } public func setPokeballType(_ value:Array<Pogoprotos.Inventory.Item.ItemId>) -> Pogoprotos.Data.Capture.CaptureProbability.Builder { self.pokeballType = value return self } public func clearPokeballType() -> Pogoprotos.Data.Capture.CaptureProbability.Builder { builderResult.pokeballType.removeAll(keepingCapacity: false) return self } public var captureProbability:Array<Float> { get { return builderResult.captureProbability } set (array) { builderResult.captureProbability = array } } public func setCaptureProbability(_ value:Array<Float>) -> Pogoprotos.Data.Capture.CaptureProbability.Builder { self.captureProbability = value return self } public func clearCaptureProbability() -> Pogoprotos.Data.Capture.CaptureProbability.Builder { builderResult.captureProbability.removeAll(keepingCapacity: false) return self } public var hasReticleDifficultyScale:Bool { get { return builderResult.hasReticleDifficultyScale } } public var reticleDifficultyScale:Double { get { return builderResult.reticleDifficultyScale } set (value) { builderResult.hasReticleDifficultyScale = true builderResult.reticleDifficultyScale = value } } public func setReticleDifficultyScale(_ value:Double) -> Pogoprotos.Data.Capture.CaptureProbability.Builder { self.reticleDifficultyScale = value return self } public func clearReticleDifficultyScale() -> Pogoprotos.Data.Capture.CaptureProbability.Builder{ builderResult.hasReticleDifficultyScale = false builderResult.reticleDifficultyScale = Double(0) return self } override public var internalGetResult:GeneratedMessage { get { return builderResult } } override public func clear() -> Pogoprotos.Data.Capture.CaptureProbability.Builder { builderResult = Pogoprotos.Data.Capture.CaptureProbability() return self } override public func clone() throws -> Pogoprotos.Data.Capture.CaptureProbability.Builder { return try Pogoprotos.Data.Capture.CaptureProbability.builderWithPrototype(prototype:builderResult) } override public func build() throws -> Pogoprotos.Data.Capture.CaptureProbability { try checkInitialized() return buildPartial() } public func buildPartial() -> Pogoprotos.Data.Capture.CaptureProbability { let returnMe:Pogoprotos.Data.Capture.CaptureProbability = builderResult return returnMe } public func mergeFrom(other:Pogoprotos.Data.Capture.CaptureProbability) throws -> Pogoprotos.Data.Capture.CaptureProbability.Builder { if other == Pogoprotos.Data.Capture.CaptureProbability() { return self } if !other.pokeballType.isEmpty { builderResult.pokeballType += other.pokeballType } if !other.captureProbability.isEmpty { builderResult.captureProbability += other.captureProbability } if other.hasReticleDifficultyScale { reticleDifficultyScale = other.reticleDifficultyScale } _ = try merge(unknownField: other.unknownFields) return self } override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Pogoprotos.Data.Capture.CaptureProbability.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Data.Capture.CaptureProbability.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() switch protobufTag { case 0: self.unknownFields = try unknownFieldsBuilder.build() return self case 10: let length = Int(try codedInputStream.readRawVarint32()) let oldLimit = try codedInputStream.pushLimit(byteLimit: length) while codedInputStream.bytesUntilLimit() > 0 { let valueIntpokeballType = try codedInputStream.readEnum() if let enumspokeballType = Pogoprotos.Inventory.Item.ItemId(rawValue:valueIntpokeballType) { builderResult.pokeballType.append(enumspokeballType) } else { _ = try unknownFieldsBuilder.mergeVarintField(fieldNumber: 1, value:Int64(valueIntpokeballType)) } } codedInputStream.popLimit(oldLimit: oldLimit) case 18: let length = Int(try codedInputStream.readRawVarint32()) let limit = try codedInputStream.pushLimit(byteLimit: length) while (codedInputStream.bytesUntilLimit() > 0) { builderResult.captureProbability.append(try codedInputStream.readFloat()) } codedInputStream.popLimit(oldLimit: limit) case 97: reticleDifficultyScale = try codedInputStream.readDouble() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { unknownFields = try unknownFieldsBuilder.build() return self } } } } class public func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> Pogoprotos.Data.Capture.CaptureProbability.Builder { let resultDecodedBuilder = Pogoprotos.Data.Capture.CaptureProbability.Builder() if let jsonValuePokeballType = jsonMap["pokeballType"] as? Array<String> { var jsonArrayPokeballType:Array<Pogoprotos.Inventory.Item.ItemId> = [] for oneValuePokeballType in jsonValuePokeballType { let enumFromStringPokeballType = try Pogoprotos.Inventory.Item.ItemId.fromString(str: oneValuePokeballType) jsonArrayPokeballType.append(enumFromStringPokeballType) } resultDecodedBuilder.pokeballType = jsonArrayPokeballType } if let jsonValueCaptureProbability = jsonMap["captureProbability"] as? Array<NSNumber> { var jsonArrayCaptureProbability:Array<Float> = [] for oneValueCaptureProbability in jsonValueCaptureProbability { jsonArrayCaptureProbability.append(oneValueCaptureProbability.floatValue) } resultDecodedBuilder.captureProbability = jsonArrayCaptureProbability } if let jsonValueReticleDifficultyScale = jsonMap["reticleDifficultyScale"] as? NSNumber { resultDecodedBuilder.reticleDifficultyScale = jsonValueReticleDifficultyScale.doubleValue } return resultDecodedBuilder } override class public func fromJSONToBuilder(data:Data) throws -> Pogoprotos.Data.Capture.CaptureProbability.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary<String,Any> else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } return try Pogoprotos.Data.Capture.CaptureProbability.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } } extension Pogoprotos.Data.Capture.CaptureAward: GeneratedMessageProtocol { public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array<Pogoprotos.Data.Capture.CaptureAward> { var mergedArray = Array<Pogoprotos.Data.Capture.CaptureAward>() while let value = try parseDelimitedFrom(inputStream: inputStream) { mergedArray.append(value) } return mergedArray } public class func parseDelimitedFrom(inputStream: InputStream) throws -> Pogoprotos.Data.Capture.CaptureAward? { return try Pogoprotos.Data.Capture.CaptureAward.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build() } public class func parseFrom(data: Data) throws -> Pogoprotos.Data.Capture.CaptureAward { return try Pogoprotos.Data.Capture.CaptureAward.Builder().mergeFrom(data: data, extensionRegistry:Pogoprotos.Data.Capture.PogoprotosDataCaptureRoot.sharedInstance.extensionRegistry).build() } public class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Data.Capture.CaptureAward { return try Pogoprotos.Data.Capture.CaptureAward.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build() } public class func parseFrom(inputStream: InputStream) throws -> Pogoprotos.Data.Capture.CaptureAward { return try Pogoprotos.Data.Capture.CaptureAward.Builder().mergeFrom(inputStream: inputStream).build() } public class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Data.Capture.CaptureAward { return try Pogoprotos.Data.Capture.CaptureAward.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build() } public class func parseFrom(codedInputStream: CodedInputStream) throws -> Pogoprotos.Data.Capture.CaptureAward { return try Pogoprotos.Data.Capture.CaptureAward.Builder().mergeFrom(codedInputStream: codedInputStream).build() } public class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Data.Capture.CaptureAward { return try Pogoprotos.Data.Capture.CaptureAward.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build() } } extension Pogoprotos.Data.Capture.CaptureProbability: GeneratedMessageProtocol { public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array<Pogoprotos.Data.Capture.CaptureProbability> { var mergedArray = Array<Pogoprotos.Data.Capture.CaptureProbability>() while let value = try parseDelimitedFrom(inputStream: inputStream) { mergedArray.append(value) } return mergedArray } public class func parseDelimitedFrom(inputStream: InputStream) throws -> Pogoprotos.Data.Capture.CaptureProbability? { return try Pogoprotos.Data.Capture.CaptureProbability.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build() } public class func parseFrom(data: Data) throws -> Pogoprotos.Data.Capture.CaptureProbability { return try Pogoprotos.Data.Capture.CaptureProbability.Builder().mergeFrom(data: data, extensionRegistry:Pogoprotos.Data.Capture.PogoprotosDataCaptureRoot.sharedInstance.extensionRegistry).build() } public class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Data.Capture.CaptureProbability { return try Pogoprotos.Data.Capture.CaptureProbability.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build() } public class func parseFrom(inputStream: InputStream) throws -> Pogoprotos.Data.Capture.CaptureProbability { return try Pogoprotos.Data.Capture.CaptureProbability.Builder().mergeFrom(inputStream: inputStream).build() } public class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Data.Capture.CaptureProbability { return try Pogoprotos.Data.Capture.CaptureProbability.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build() } public class func parseFrom(codedInputStream: CodedInputStream) throws -> Pogoprotos.Data.Capture.CaptureProbability { return try Pogoprotos.Data.Capture.CaptureProbability.Builder().mergeFrom(codedInputStream: codedInputStream).build() } public class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Data.Capture.CaptureProbability { return try Pogoprotos.Data.Capture.CaptureProbability.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build() } } // @@protoc_insertion_point(global_scope)
mit
Yoloabdo/CS-193P
Phsychoic/Phsychoic/MainViewController.swift
1
1280
// // ViewController.swift // Phsychoic // // Created by abdelrahman mohamed on 2/5/16. // Copyright © 2016 Abdulrhman dev. All rights reserved. // import UIKit class MainViewController: UIViewController { struct segues { static let happiness = "happy" static let sadness = "sad" static let meh = "meh" static let fourth = "nothing" } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destination = segue.destinationViewController if let navcon = destination as? UINavigationController { destination = navcon.visibleViewController! } if let hvc = destination as? HappinessViewController{ if let identfier = segue.identifier{ switch identfier{ case segues.happiness: hvc.happiness = 100 case segues.sadness: hvc.happiness = 0 case segues.fourth: hvc.happiness = 20 default: hvc.happiness = 50 } } } } @IBAction func movenoth(sender: UIButton) { performSegueWithIdentifier(segues.fourth, sender: nil) } }
mit
peaks-cc/iOS11_samplecode
chapter_03/samplecode/iOS/RecChar/RecChar/ViewController.swift
1
6131
// // ViewController.swift // hogee // // Created by sonson on 2017/07/26. // Copyright © 2017年 sonson. All rights reserved. // import UIKit import CoreML extension MLMultiArray { var maxIndex: Int { var max: Double = 0 var index = -1 for j in 0..<self.count { let x = self[[NSNumber(value: j)]] if max < x.doubleValue { max = x.doubleValue index = j } } return index } func imageAsString(width: Int, height: Int) -> String { var buffer = "" for x in 0..<width { for y in 0..<height { let xx = NSNumber(value: x) let yy = NSNumber(value: y) buffer = buffer.appendingFormat("%02x", Int(self[[0, xx, yy]].doubleValue*255)) } buffer = buffer.appendingFormat("\n") } return buffer } } class ViewController: UIViewController { let model = KerasMNIST() static let width: Int = 28 static let height: Int = 28 @IBOutlet var imageView: UIImageView! @IBOutlet var textLabel: UILabel! var pixelBuffer32bit: [CUnsignedChar] = [CUnsignedChar](repeating: 0, count: ViewController.width * ViewController.height * 4) private func creatCGImage(pointer: UnsafeMutableRawPointer?, width: Int, height: Int, bytesPerRow: Int) -> CGImage? { let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) .union(CGBitmapInfo.byteOrder32Little) guard let context = CGContext(data: pointer, width: (width), height: (height), bitsPerComponent: 8, bytesPerRow: (bytesPerRow), space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return nil } return context.makeImage() } func updateImage() { guard let cgImage = creatCGImage(pointer: &pixelBuffer32bit, width: ViewController.width, height: ViewController.height, bytesPerRow: 4 * ViewController.width) else { return } imageView.image = UIImage(cgImage: cgImage) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let location = touch.location(in: self.view) if imageView.frame.contains(location) { let locationInImageView = imageView.convert(location, from: self.view) let x = locationInImageView.x / imageView.frame.size.width let y = locationInImageView.y / imageView.frame.size.height let ix = Int(x * CGFloat(ViewController.width)) let iy = Int(y * CGFloat(ViewController.height)) let w = 1 let l = ix - w > 0 ? ix - w : 0 let r = ix + w < ViewController.width ? ix + w : ViewController.width - 1 let t = iy - w > 0 ? iy - w : 0 let b = iy + w < ViewController.height ? iy + w : ViewController.height - 1 for xx in l..<r { for yy in t..<b { pixelBuffer32bit[4 * xx + 4 * yy * ViewController.width + 0] = 255 pixelBuffer32bit[4 * xx + 4 * yy * ViewController.width + 1] = 255 pixelBuffer32bit[4 * xx + 4 * yy * ViewController.width + 2] = 255 pixelBuffer32bit[4 * xx + 4 * yy * ViewController.width + 3] = 255 } } updateImage() } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { do { let input = try MLMultiArray(shape: [1, NSNumber(value: ViewController.width), NSNumber(value: ViewController.height)], dataType: .double) for x in 0..<ViewController.width { for y in 0..<ViewController.height { let xx = NSNumber(value: x) let yy = NSNumber(value: y) input[[0, xx, yy]] = NSNumber(value: Double(pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 1]) / 255 ) } } print(input.imageAsString(width: ViewController.width, height: ViewController.height)) let result = try model.prediction(image: input) let index = result.digit.maxIndex textLabel.text = "\(index)" } catch { print(error) } for x in 0..<ViewController.width { for y in 0..<ViewController.height { pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 0] = 255 pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 1] = 0 pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 2] = 0 pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 3] = 0 } } updateImage() } func testMNIST() { do { let count = 1000 var trueCount = 0 for i in 0..<count { let label = try loadLabel(index: i) let image = try loadImage(index: i) let result = try model.prediction(image: image) if label == result.digit.maxIndex { trueCount += 1 } } print("\(Double(trueCount) / Double(count) * 100)") } catch { print(error) } } override func viewDidLoad() { super.viewDidLoad() //testMNIST() for x in 0..<ViewController.width { for y in 0..<ViewController.height { pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 0] = 255 pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 1] = 0 pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 2] = 0 pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 3] = 0 } } updateImage() } }
mit
rcach/Tasks
TODO/UserStoryListViewController.swift
1
2258
import Cocoa class UserStoryListViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate { @IBOutlet weak var tableView: NSTableView! // TODO: Make this an unowned reference once you can specify memory management on Swift protocol object references. var navigatorOptional: Navigator? var userStories = [UserStory]() override func viewDidLoad() { reload() } func reload() { clearSelection() userStories.removeAll(keepCapacity: true) tableView.reloadData() loadDataFromJIRA() } func clearSelection() { tableView.deselectAll(self) } func disableList() { tableView.enabled = false } func enableList() { tableView.enabled = true } func loadDataFromJIRA() { navigatorOptional?.disableNavigation() disableList() getUserStories() { result in // TODO: Handle this better. if self.view.superview == nil { return } self.navigatorOptional?.enableNavigation() self.enableList() switch result { case let .Error(error): // TODO: Indicate error to user. println(error) case let .Value(userStories): self.userStories = userStories self.tableView.reloadData() } } } } extension UserStoryListViewController { // MARK: NSTableViewDataSource func numberOfRowsInTableView(tableView: NSTableView!) -> Int { return userStories.count } // MARK: NSTableViewDelegate func tableView(tableView: NSTableView!, viewForTableColumn tableColumn: NSTableColumn!, row: Int) -> NSView! { if let reusableCellView = tableView.makeViewWithIdentifier(tableColumn.identifier, owner: self) as? NSTableCellView { var titleTextField = reusableCellView.textField titleTextField.stringValue = userStories[row].summary return reusableCellView } return nil } func tableView(tableView: NSTableView!, selectionIndexesForProposedSelection proposedSelectionIndexes: NSIndexSet!) -> NSIndexSet! { if let navigator = navigatorOptional { if proposedSelectionIndexes.count > 0 { navigator.navigateToUserStoryTaskList(userStories[proposedSelectionIndexes.firstIndex]) } } return proposedSelectionIndexes } }
apache-2.0
KatagiriSo/CoreDataUtil
CoreDataUtilTests/CoreDataUtilTests.swift
1
921
// // CoreDataUtilTests.swift // CoreDataUtilTests // // Created by 片桐奏羽 on 2015/10/02. // Copyright (c) 2015年 SoKatagiri. All rights reserved. // import UIKit import XCTest class CoreDataUtilTests: 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
josherick/DailySpend
DailySpend/Expense+CoreDataClass.swift
1
11366
// // Expense+CoreDataClass.swift // DailySpend // // Created by Josh Sherick on 3/22/17. // Copyright © 2017 Josh Sherick. All rights reserved. // import Foundation import CoreData @objc(Expense) class Expense: NSManagedObject { func json(jsonIds: [NSManagedObjectID: Int]) -> [String: Any]? { var jsonObj = [String: Any]() if let amount = amount { let num = amount as NSNumber jsonObj["amount"] = num } else { Logger.debug("couldn't unwrap amount in Expense") return nil } if let shortDescription = shortDescription { jsonObj["shortDescription"] = shortDescription } else { Logger.debug("couldn't unwrap shortDescription in Expense") return nil } if let notes = notes { jsonObj["notes"] = notes } if let transactionDay = transactionDay { let num = transactionDay.start.gmtDate.timeIntervalSince1970 as NSNumber jsonObj["transactionDate"] = num } else { Logger.debug("couldn't unwrap transactionDate in Expense") return nil } if let dateCreated = dateCreated { let num = dateCreated.timeIntervalSince1970 as NSNumber jsonObj["dateCreated"] = num } else { Logger.debug("couldn't unwrap dateCreated in Expense") return nil } if let imgs = sortedImages { var jsonImgs = [[String: Any]]() for image in imgs { if let jsonImg = image.json() { jsonImgs.append(jsonImg) } else { Logger.debug("couldn't unwrap jsonImg in Expense") return nil } } jsonObj["images"] = jsonImgs } if let goal = goal { var goalJsonIds = [Int]() if let jsonId = jsonIds[goal.objectID] { goalJsonIds.append(jsonId) } else { Logger.debug("a goal didn't have an associated jsonId in Expense") return nil } jsonObj["goal"] = goalJsonIds } else { Logger.debug("couldn't unwrap goal in Expense") return nil } return jsonObj } func serialize(jsonIds: [NSManagedObjectID: Int]) -> Data? { if let jsonObj = self.json(jsonIds: jsonIds) { let serialization = try? JSONSerialization.data(withJSONObject: jsonObj) return serialization } return nil } class func create(context: NSManagedObjectContext, json: [String: Any], jsonIds: [Int: NSManagedObjectID]) -> Expense? { let expense = Expense(context: context) if let amount = json["amount"] as? NSNumber { let decimal = Decimal(amount.doubleValue) if decimal <= 0 { Logger.debug("amount less than 0 in Expense") return nil } expense.amount = decimal } else { Logger.debug("couldn't unwrap amount in Expense") return nil } if let shortDescription = json["shortDescription"] as? String { if shortDescription.count == 0 { Logger.debug("shortDescription empty in Expense") return nil } expense.shortDescription = shortDescription } else { Logger.debug("couldn't unwrap shortDescription in Expense") return nil } if let notes = json["notes"] as? String { expense.notes = notes } if let jsonImgs = json["images"] as? [[String: Any]] { for jsonImg in jsonImgs { if let image = Image.create(context: context, json: jsonImg) { image.expense = expense } else { Logger.debug("couldn't create image in Expense") return nil } } } if let transactionDate = json["transactionDate"] as? NSNumber { let date = Date(timeIntervalSince1970: transactionDate.doubleValue) let calDay = CalendarDay(dateInDay: GMTDate(date)); if date != calDay.start.gmtDate { Logger.debug("transactionDate after today in Expense") return nil } expense.transactionDay = calDay } else { Logger.debug("coulnd't unwrap transactionDate in Expense") return nil } if let dateCreated = json["dateCreated"] as? NSNumber { let date = Date(timeIntervalSince1970: dateCreated.doubleValue) if date > Date() { Logger.debug("dateCreated after today in Expense") return nil } expense.dateCreated = date } else { Logger.debug("couldn't unwrap dateCreated in Expense") return nil } if let goalJsonIds = json["goals"] as? Array<Int> { if goalJsonIds.count > 1 { Logger.debug("there were multiple goals associated with an Expense") return nil } for goalJsonId in goalJsonIds { if let objectID = jsonIds[goalJsonId], let goal = context.object(with: objectID) as? Goal { expense.goal = goal } else { Logger.debug("a goal didn't have an associated objectID in Expense") return nil } } } else { Logger.debug("couldn't unwrap goals in Expense") return nil } return expense } /** * Accepts all members of Expense. If the passed variables, attached to * corresponding variables on an Expense object, will form a valid * object, this function will assign the passed variables to this object * and return `(valid: true, problem: nil)`. Otherwise, this function will * return `(valid: false, problem: ...)` with problem set to a user * readable string describing why this adjustment wouldn't be valid. */ func propose( amount: Decimal?? = nil, shortDescription: String?? = nil, transactionDay: CalendarDay?? = nil, notes: String?? = nil, dateCreated: Date?? = nil, goal: Goal? = nil ) -> (valid: Bool, problem: String?) { let _amount = amount ?? self.amount let _shortDescription = shortDescription ?? self.shortDescription let _transactionDay = transactionDay ?? self.transactionDay let _notes = notes ?? self.notes let _dateCreated = dateCreated ?? self.dateCreated let _goal = goal ?? self.goal if _amount == nil || _amount! == 0 { return (false, "This expense must have an amount specified.") } if _transactionDay == nil { return (false, "This expense must have a transaction date.") } if _dateCreated == nil { return (false, "The expense must have a date created.") } if _goal == nil { return (false, "This expense must be associated with a goal.") } if _goal!.start != nil && _transactionDay!.start.gmtDate < _goal!.start!.gmtDate { return (false, "This expense must be after it's associated goal's start date.") } if _goal!.exclusiveEnd != nil && _transactionDay!.start.gmtDate < _goal!.exclusiveEnd!.gmtDate { return (false, "This expense must be before it's associated goal's end date.") } if _goal!.isRecurring { let mostRecentPeriodEnd = _goal!.mostRecentPeriod()?.end?.gmtDate if mostRecentPeriodEnd == nil || _transactionDay!.start.gmtDate > mostRecentPeriodEnd! { return (false, "This expense must be created no later than end the most recent period for this goal.") } } self.amount = _amount self.shortDescription = _shortDescription self.transactionDay = _transactionDay self.notes = _notes self.dateCreated = _dateCreated self.goal = _goal return (true, nil) } class func get(context: NSManagedObjectContext, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, fetchLimit: Int = 0) -> [Expense]? { let fetchRequest: NSFetchRequest<Expense> = Expense.fetchRequest() fetchRequest.predicate = predicate fetchRequest.sortDescriptors = sortDescriptors fetchRequest.fetchLimit = fetchLimit let expenseResults = try? context.fetch(fetchRequest) return expenseResults } // Accessor functions (for Swift 3 classes) var amount: Decimal? { get { return amount_ as Decimal? } set { if newValue != nil { amount_ = NSDecimalNumber(decimal: newValue!) } else { amount_ = nil } } } var transactionDay: CalendarDay? { get { if let date = transactionDate_ { return CalendarDay(dateInDay: GMTDate(date as Date)) } else { return nil } } set { if newValue != nil { transactionDate_ = newValue!.start.gmtDate as NSDate } else { transactionDate_ = nil } } } var dateCreated: Date? { get { return dateCreated_ as Date? } set { if newValue != nil { dateCreated_ = newValue! as NSDate } else { dateCreated_ = nil } } } var shortDescription: String? { get { return shortDescription_ } set { shortDescription_ = newValue } } var notes: String? { get { return notes_ } set { notes_ = newValue } } /** * Expenses can currently only be associated with one goal. This is that * goal, if it exists. */ var goal: Goal? { get { return goal_ } set { goal_ = newValue } } /** * `images` sorted in a deterministic way. */ var sortedImages: [Image]? { if let img = images { return img.sorted(by: { $0.dateCreated! < $1.dateCreated! }) } else { return nil } } var images: Set<Image>? { get { return images_ as! Set? } set { if newValue != nil { images_ = NSSet(set: newValue!) } else { images_ = nil } } } }
mit
austinzheng/swift
test/Interpreter/ClosureLeak.swift
42
659
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest struct Large { var a : LifetimeTracked = LifetimeTracked(0) var b : LifetimeTracked = LifetimeTracked(0) var c : LifetimeTracked = LifetimeTracked(0) var d : LifetimeTracked = LifetimeTracked(0) var e : LifetimeTracked = LifetimeTracked(0) var f : LifetimeTracked = LifetimeTracked(0) } func doit( action: () -> ()) { action() } func foo(_ s: Large) { doit { let _ = s } } var Tests = TestSuite("ClosureLeak") Tests.test("dontLeak") { do { let s = Large() foo(s) } expectEqual(0, LifetimeTracked.instances) } runAllTests()
apache-2.0
335g/FingerTree
Example1.playground/Contents.swift
1
2522
import FingerTree // // Example(1) Priority Queue // reference (https://hackage.haskell.org/package/fingertree-0.1.1.0/docs/Data-PriorityQueue-FingerTree.html) // enum Ent<V: Equatable>: Equatable { case Entry(UInt, V) } func == <V: Equatable> (lhs: Ent<V>, rhs: Ent<V>) -> Bool { switch (lhs, rhs) { case let (.Entry(p1, v1), .Entry(p2, v2)): return p1 == p2 && v1 == v2 } } enum Prio<V: Equatable>: Equatable { case NoPriority case Priority(UInt, V) } func == <V: Equatable> (lhs: Prio<V>, rhs: Prio<V>) -> Bool { switch (lhs, rhs) { case (.NoPriority, .NoPriority): return true case let (.Priority(p1, v1), .Priority(p2, v2)): return p1 == p2 && v1 == v2 default: return false } } extension Prio: Monoid { static var mempty: Prio { return .NoPriority } func mappend(other: Prio) -> Prio { switch (self, other) { case (.NoPriority, .NoPriority): return .NoPriority case (.NoPriority, .Priority(_)): return other case (.Priority(_), .NoPriority): return self case let (.Priority(x, _), .Priority(y, _)): if x <= y { return self }else { return other } } } } extension Ent: Measurable { typealias MeasuredValue = Prio<V> func measure() -> Prio<V> { switch self { case let .Entry(p, v): return .Priority(p, v) } } } class PriorityQueue<V: Equatable> { var tree: FingerTree<Prio<V>, Ent<V>> init(_ ent: Ent<V>){ self.tree = FingerTree.single(ent) } func add(ent: Ent<V>) { self.tree = tree |> ent } var highestPriorityEntry: Ent<V>? { switch self.measure() { case .NoPriority: return nil case let .Priority(p, v): return .Entry(p, v) } } // var minView: (V, PriorityQueue)? { // // } var minViewWithKey: ((UInt, V), PriorityQueue)? { switch tree { case .Empty: return nil default: let prio = tree.measure() switch prio { case let .Priority(k, v): switch tree.split({ p in switch p { case .NoPriority: return false case let .Priority(k_, _): return k_ <= k } }) } } } } extension PriorityQueue: Measurable { typealias MeasuredValue = Prio<V> func measure() -> Prio<V> { return tree.measure() } } let queue = PriorityQueue(.Entry(100, "a")) queue.add(.Entry(120, "b")) queue.add(.Entry(140, "c")) queue.highestPriorityEntry queue.add(.Entry(80, "d")) queue.add(.Entry(90, "e")) queue.highestPriorityEntry switch queue.tree { case let .Deep(_, pre, m, suf): pre m suf default: () } //queue.pull() queue.highestPriorityEntry
mit
KoheiKanagu/ImageDownloader
ImageDownloaderTests/ImageDownloaderTests.swift
1
924
// // ImageDownloaderTests.swift // ImageDownloaderTests // // Created by Kohei on 2014/11/18. // Copyright (c) 2014年 KoheiKanagu. All rights reserved. // import Cocoa import XCTest class ImageDownloaderTests: 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
mozilla-mobile/firefox-ios
Client/Frontend/Home/Wallpapers/v1/UI/WallpaperSelectorViewModel.swift
2
8419
// 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 private struct WallpaperSelectorItem { let wallpaper: Wallpaper let collection: WallpaperCollection } public enum WallpaperSelectorError: Error { case itemNotFound } class WallpaperSelectorViewModel { enum WallpaperSelectorLayout: Equatable { case compact case regular // The maximum number of items to display in the whole section var maxItemsToDisplay: Int { switch self { case .compact: return 6 case .regular: return 8 } } // The maximum number of items to display per row var itemsPerRow: Int { switch self { case .compact: return 3 case .regular: return 4 } } // The maximum number of seasonal items to display var maxNumberOfSeasonalItems: Int { switch self { case .compact: return 3 case .regular: return 5 } } } private var wallpaperManager: WallpaperManagerInterface private var availableCollections: [WallpaperCollection] private var wallpaperItems = [WallpaperSelectorItem]() var openSettingsAction: (() -> Void) var sectionLayout: WallpaperSelectorLayout = .compact // We use the compact layout as default var selectedIndexPath: IndexPath? var numberOfWallpapers: Int { return wallpaperItems.count } init(wallpaperManager: WallpaperManagerInterface = WallpaperManager(), openSettingsAction: @escaping (() -> Void)) { self.wallpaperManager = wallpaperManager self.availableCollections = wallpaperManager.availableCollections self.openSettingsAction = openSettingsAction setupWallpapers() selectedIndexPath = initialSelectedIndexPath } func updateSectionLayout(for traitCollection: UITraitCollection) { if traitCollection.horizontalSizeClass == .compact { sectionLayout = .compact } else { sectionLayout = .regular } setupWallpapers() } func cellViewModel(for indexPath: IndexPath) -> WallpaperCellViewModel? { guard let wallpaperItem = wallpaperItems[safe: indexPath.row] else { return nil } return cellViewModel(for: wallpaperItem.wallpaper, collectionType: wallpaperItem.collection.type, number: indexPath.row) } func downloadAndSetWallpaper(at indexPath: IndexPath, completion: @escaping (Result<Void, Error>) -> Void) { guard let wallpaperItem = wallpaperItems[safe: indexPath.row] else { completion(.failure(WallpaperSelectorError.itemNotFound)) return } let wallpaper = wallpaperItem.wallpaper let setWallpaperBlock = { [weak self] in self?.updateCurrentWallpaper(for: wallpaperItem) { result in if case .success = result { self?.selectedIndexPath = indexPath } completion(result) } } if wallpaper.needsToFetchResources { wallpaperManager.fetchAssetsFor(wallpaper) { result in switch result { case .success: setWallpaperBlock() case .failure: completion(result) } } } else { setWallpaperBlock() } } func sendImpressionTelemetry() { TelemetryWrapper.recordEvent(category: .action, method: .view, object: .onboardingWallpaperSelector, value: nil, extras: nil) } func sendDismissImpressionTelemetry() { TelemetryWrapper.recordEvent(category: .action, method: .close, object: .onboardingWallpaperSelector, value: nil, extras: nil) } func removeAssetsOnDismiss() { wallpaperManager.removeUnusedAssets() } } private extension WallpaperSelectorViewModel { var initialSelectedIndexPath: IndexPath? { if let index = wallpaperItems.firstIndex(where: {$0.wallpaper == wallpaperManager.currentWallpaper}) { return IndexPath(row: index, section: 0) } return nil } func setupWallpapers() { wallpaperItems = [] let classicCollection = availableCollections.first { $0.type == .classic } let seasonalCollection = availableCollections.first { $0.type == .limitedEdition } let seasonalItems = collectWallpaperItems(for: seasonalCollection, maxNumber: sectionLayout.maxNumberOfSeasonalItems) let maxNumberOfClassic = sectionLayout.maxItemsToDisplay - seasonalItems.count let classicItems = collectWallpaperItems(for: classicCollection, maxNumber: maxNumberOfClassic) wallpaperItems.append(contentsOf: classicItems) wallpaperItems.append(contentsOf: seasonalItems) } func collectWallpaperItems(for collection: WallpaperCollection?, maxNumber: Int) -> [WallpaperSelectorItem] { guard let collection = collection else { return [] } var wallpapers = [WallpaperSelectorItem]() for wallpaper in collection.wallpapers { if wallpapers.count < maxNumber { wallpapers.append(WallpaperSelectorItem(wallpaper: wallpaper, collection: collection)) } else { break } } return wallpapers } func cellViewModel(for wallpaper: Wallpaper, collectionType: WallpaperCollectionType, number: Int ) -> WallpaperCellViewModel { let a11yId = "\(AccessibilityIdentifiers.Onboarding.Wallpaper.card)_\(number)" var a11yLabel: String switch collectionType { case .classic: a11yLabel = "\(String.Onboarding.ClassicWallpaper) \(number + 1)" case .limitedEdition: a11yLabel = "\(String.Onboarding.LimitedEditionWallpaper) \(number + 1)" } let cellViewModel = WallpaperCellViewModel(image: wallpaper.thumbnail, a11yId: a11yId, a11yLabel: a11yLabel) return cellViewModel } func updateCurrentWallpaper(for wallpaperItem: WallpaperSelectorItem, completion: @escaping (Result<Void, Error>) -> Void) { wallpaperManager.setCurrentWallpaper(to: wallpaperItem.wallpaper) { [weak self] result in guard let extra = self?.telemetryMetadata(for: wallpaperItem) else { completion(result) return } TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .onboardingWallpaperSelector, value: .wallpaperSelected, extras: extra) completion(result) } } func telemetryMetadata(for item: WallpaperSelectorItem) -> [String: String] { var metadata = [String: String]() metadata[TelemetryWrapper.EventExtraKey.wallpaperName.rawValue] = item.wallpaper.id let wallpaperTypeKey = TelemetryWrapper.EventExtraKey.wallpaperType.rawValue switch item.wallpaper.type { case .defaultWallpaper: metadata[wallpaperTypeKey] = "default" case .other: switch item.collection.type { case .classic: metadata[wallpaperTypeKey] = item.collection.type.rawValue case .limitedEdition: metadata[wallpaperTypeKey] = item.collection.id } } return metadata } }
mpl-2.0
sammyd/VT_InAppPurchase
prototyping/GreenGrocer/GreenGrocer/ShoppingListViewController.swift
13
3476
/* * Copyright (c) 2015 Razeware LLC * * 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 ShoppingListViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var nameLabel: MultilineLabelThatWorks! @IBOutlet weak var dateLabel: MultilineLabelThatWorks! @IBOutlet weak var totalCostLabel: UILabel! var dataStore : DataStore? var shoppingList : ShoppingList? { didSet { updateViewForShoppingList() } } private static var dateFormatter : NSDateFormatter = { let df = NSDateFormatter() df.dateStyle = .ShortStyle return df }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. configureTableView(tableView) updateViewForShoppingList() } } extension ShoppingListViewController { private func updateViewForShoppingList() { if let shoppingList = shoppingList { nameLabel?.text = shoppingList.name dateLabel?.text = self.dynamicType.dateFormatter.stringFromDate(shoppingList.date) totalCostLabel?.text = "$\(shoppingList.products.reduce(0){ $0 + $1.price })" } tableView?.reloadData() } private func configureTableView(tableView: UITableView) { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 tableView.dataSource = self tableView.backgroundColor = UIColor.clearColor() tableView.backgroundView?.backgroundColor = UIColor.clearColor() tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 49, right: 0) tableView.separatorStyle = .None } } extension ShoppingListViewController : UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shoppingList?.products.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell", forIndexPath: indexPath) if let cell = cell as? ProductTableViewCell { cell.product = shoppingList?.products[indexPath.row] } cell.backgroundView?.backgroundColor = UIColor.clearColor() cell.backgroundColor = UIColor.clearColor() cell.contentView.backgroundColor = UIColor.clearColor() return cell } }
mit
MatrixHero/FlowSlideMenu
FlowSlideMenuCore/LLFlowSlideMenuVC.swift
1
20670
// // LLFlowSlideMenuVC // // Created by LL on 15/10/31. // Copyright © 2015 LL. All rights reserved. // import UIKit import QuartzCore public class LLFlowSlideMenuVC : UIViewController, UIGestureRecognizerDelegate ,LLFlowCurveViewDelegate { public enum SlideAction { case Open case Close } struct PanInfo { var action: SlideAction var shouldBounce: Bool var velocity: CGFloat } // MARK: - // MARK: parms public var leftViewController: UIViewController? public var mainViewController: UIViewController? public var opacityView = UIView() public var mainContainerView = UIView() public var leftContainerView = LLFlowCurveView() public var leftPanGesture: UIPanGestureRecognizer? public var leftTapGetsture: UITapGestureRecognizer? private var curContext = 0 // MARK: - // MARK: lifecycle public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public convenience init(mainViewController: UIViewController,leftViewController: UIViewController) { self.init() self.mainViewController = mainViewController self.leftViewController = leftViewController initView() self.leftContainerView.addObserver(self, forKeyPath: "frame", options: .New, context: &curContext) } override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &curContext { if let newValue : CGRect = change?[NSKeyValueChangeNewKey]?.CGRectValue{ self.leftContainerView.updatePointKVO(self.leftContainerView.frame.size.width + newValue.origin.x, orientation: Orientation.Left) } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) leftContainerView.hidden = true coordinator.animateAlongsideTransition(nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.closeLeftNonAnimation() self.leftContainerView.hidden = false if self.leftPanGesture != nil && self.leftPanGesture != nil { self.removeLeftGestures() self.addLeftGestures() } }) } public override func viewWillLayoutSubviews() { setUpViewController(mainContainerView, targetViewController: mainViewController) setUpViewController(leftContainerView, targetViewController: leftViewController,slideview: true) } deinit { self.leftContainerView.removeObserver(self, forKeyPath: "frame", context: &curContext) } // MARK: - // MARK: private funs func initView() { mainContainerView = UIView(frame: view.bounds) mainContainerView.backgroundColor = UIColor.clearColor() mainContainerView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] view.insertSubview(mainContainerView, atIndex: 0) var opacityframe: CGRect = view.bounds let opacityOffset: CGFloat = 0 opacityframe.origin.y = opacityframe.origin.y + opacityOffset opacityframe.size.height = opacityframe.size.height - opacityOffset opacityView = UIView(frame: opacityframe) opacityView.backgroundColor = FlowSlideMenuOptions.opacityViewBackgroundColor opacityView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] opacityView.layer.opacity = 0.0 view.insertSubview(opacityView, atIndex: 1) var leftFrame: CGRect = view.bounds leftFrame.size.width = FlowSlideMenuOptions.leftViewWidth + FlowCurveOptions.waveMargin leftFrame.origin.x = leftMinOrigin(); let leftOffset: CGFloat = 0 leftFrame.origin.y = leftFrame.origin.y + leftOffset leftFrame.size.height = leftFrame.size.height - leftOffset leftContainerView = LLFlowCurveView(frame: leftFrame) leftContainerView.backgroundColor = UIColor.clearColor() leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight leftContainerView.delegate = self view.insertSubview(leftContainerView, atIndex: 2) addLeftGestures() } private func setUpViewController(targetView: UIView, targetViewController: UIViewController?) { if let viewController = targetViewController { addChildViewController(viewController) viewController.view.frame = targetView.bounds targetView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) } } private func setUpViewController(targetView: UIView, targetViewController: UIViewController?, slideview:Bool) { if let viewController = targetViewController { addChildViewController(viewController) if(slideview) { viewController.view.frame = CGRectMake(0,0,slideViewWidth(),targetView.bounds.height) }else { viewController.view.frame = targetView.bounds } targetView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) } } private func removeViewController(viewController: UIViewController?) { if let _viewController = viewController { _viewController.willMoveToParentViewController(nil) _viewController.view.removeFromSuperview() _viewController.removeFromParentViewController() } } private func leftMinOrigin() -> CGFloat { return -FlowSlideMenuOptions.leftViewWidth - FlowCurveOptions.waveMargin } private func slideViewWidth() -> CGFloat { return FlowSlideMenuOptions.leftViewWidth } private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool{ var leftBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero let bezelWidth: CGFloat = FlowSlideMenuOptions.leftBezelWidth CGRectDivide(view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(leftBezelRect, point) } private func addLeftGestures() { if (leftViewController != nil) { if leftPanGesture == nil { leftPanGesture = UIPanGestureRecognizer(target: self, action: "handleLeftPanGesture:") leftPanGesture!.delegate = self view.addGestureRecognizer(leftPanGesture!) } } } private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo { let thresholdVelocity: CGFloat = 1000.0 let pointOfNoReturn: CGFloat = CGFloat(floor(leftMinOrigin())) + FlowSlideMenuOptions.pointOfNoReturnWidth let leftOrigin: CGFloat = leftContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open; if velocity.x >= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if velocity.x <= (-1.0 * thresholdVelocity) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } public func isTagetViewController() -> Bool { // Function to determine the target ViewController // Please to override it if necessary return true } private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool{ return isLeftOpen() || FlowSlideMenuOptions.panFromBezel && isLeftPointContainedWithinBezelRect(point) } private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool { return CGRectContainsPoint(leftContainerView.frame, point) } private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x let minOrigin: CGFloat = leftMinOrigin() let maxOrigin: CGFloat = 0.0 var newFrame: CGRect = toFrame if newOrigin < minOrigin { newOrigin = minOrigin } else if newOrigin > maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func setOpenWindowLevel() { if (FlowSlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelStatusBar + 1 } }) } } private func setCloseWindowLebel() { if (FlowSlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelNormal } }) } } public func isLeftOpen() -> Bool { return leftContainerView.frame.origin.x == 0.0 } public func isLeftHidden() -> Bool { return leftContainerView.frame.origin.x <= leftMinOrigin() } public func closeLeftWithVelocity(velocity: CGFloat) { leftContainerView.close() let xOrigin: CGFloat = leftContainerView.frame.origin.x let finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(FlowSlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.enableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() strongSelf.leftViewController?.view.alpha = 0 } } } public override func openLeft (){ setOpenWindowLevel() leftViewController?.beginAppearanceTransition(isLeftHidden(), animated:false) openLeftFakeAnimation() self.leftContainerView.openAll() } public func updatePointTimer() { print(self.leftContainerView.frame.origin.x) } public override func closeLeft (){ leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) closeLeftWithVelocity(0.0) setCloseWindowLebel() } public func openLeftFakeAnimation() { var frame = leftContainerView.frame; frame.origin.x = 0; self.leftContainerView.frame = frame self.opacityView.layer.opacity = Float(FlowSlideMenuOptions.contentViewOpacity) let duration: NSTimeInterval = Double(FlowSlideMenuOptions.animationDuration) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(FlowSlideMenuOptions.contentViewScale, FlowSlideMenuOptions.contentViewScale) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() } } } public func openLeftWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = leftContainerView.frame.origin.x let finalXOrigin: CGFloat = 0.0 var frame = leftContainerView.frame; frame.origin.x = finalXOrigin; var duration: NSTimeInterval = Double(FlowSlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(FlowSlideMenuOptions.contentViewOpacity) strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(FlowSlideMenuOptions.contentViewScale, FlowSlideMenuOptions.contentViewScale) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() } } self.leftContainerView.open() } private func applyLeftContentViewScale() { let openedLeftRatio: CGFloat = getOpenedLeftRatio() let scale: CGFloat = 1.0 - ((1.0 - FlowSlideMenuOptions.contentViewScale) * openedLeftRatio); mainContainerView.transform = CGAffineTransformMakeScale(scale, scale) } private func getOpenedLeftRatio() -> CGFloat { let width: CGFloat = leftContainerView.frame.size.width let currentPosition: CGFloat = leftContainerView.frame.origin.x - leftMinOrigin() return currentPosition / width } // MARK: - // MARK: public funs public func removeLeftGestures() { if leftPanGesture != nil { view.removeGestureRecognizer(leftPanGesture!) leftPanGesture = nil } } public func closeLeftNonAnimation(){ setCloseWindowLebel() let finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin leftContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) enableContentInteraction() self.leftContainerView.animating = false } private func disableContentInteraction() { mainContainerView.userInteractionEnabled = false } private func enableContentInteraction() { mainContainerView.userInteractionEnabled = true } // MARK: - // MARK: handleLeftPanGesture funs struct LeftPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false } func handleLeftPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } switch panGesture.state { case UIGestureRecognizerState.Began: LeftPanState.wasHiddenAtStartOfPan = isLeftHidden() LeftPanState.wasOpenAtStartOfPan = isLeftOpen() self.leftContainerView.start() LeftPanState.frameAtStartOfPan = leftContainerView.frame LeftPanState.startPointOfPan = panGesture.locationInView(self.view) leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true) setOpenWindowLevel() case UIGestureRecognizerState.Changed: let translation: CGPoint = panGesture.translationInView(panGesture.view) leftContainerView.updatePoint(CGPointMake(translation.x, translation.y + LeftPanState.startPointOfPan.y), orientation: Orientation.Left) leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan) applyLeftContentViewScale() case UIGestureRecognizerState.Ended: let velocity:CGPoint = panGesture.velocityInView(panGesture.view) let panInfo: PanInfo = panLeftResultInfoForVelocity(velocity) if panInfo.action == .Open { if !LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(true, animated: true) } openLeftWithVelocity(panInfo.velocity) } else { if LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(false, animated: true) } closeLeftWithVelocity(panInfo.velocity) setCloseWindowLebel() } default: break } } // MARK: - // MARK: UIGestureRecognizerDelegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { let point: CGPoint = touch.locationInView(view) if gestureRecognizer == leftPanGesture { return slideLeftForGestureRecognizer(gestureRecognizer, point: point) } else if gestureRecognizer == leftTapGetsture { return isLeftOpen() && !isPointContainedWithinLeftRect(point) } return true } // MARK: - // MARK: LLFlowCurveViewDelegate public func flowViewStartAnimation(flow:LLFlowCurveView) { leftViewController?.view.alpha = 0.0 } public func flowViewEndAnimation(flow:LLFlowCurveView) { UIView.animateWithDuration(0.3) { () -> Void in self.leftViewController?.view.alpha = 1 } } } // MARK: - // MARK: UIViewController extension extension UIViewController { public func slideMenuController() -> LLFlowSlideMenuVC? { var viewController: UIViewController? = self while viewController != nil { if viewController is LLFlowSlideMenuVC { return viewController as? LLFlowSlideMenuVC } viewController = viewController?.parentViewController } return nil; } public func addLeftBarButtonWithImage(buttonImage: UIImage) { let leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleLeft") navigationItem.leftBarButtonItem = leftButton; } public func openLeft() { slideMenuController()?.openLeft() } public func closeLeft() { slideMenuController()?.closeLeft() } // Please specify if you want menu gesuture give priority to than targetScrollView public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) { guard let slideController = slideMenuController(), let recognizers = slideController.view.gestureRecognizers else { return } for recognizer in recognizers where recognizer is UIPanGestureRecognizer { targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer) } } }
mit
twobitlabs/Nimble
Sources/Nimble/Matchers/PostNotification.swift
27
2520
import Foundation internal class NotificationCollector { private(set) var observedNotifications: [Notification] private let notificationCenter: NotificationCenter #if canImport(Darwin) private var token: AnyObject? #else private var token: NSObjectProtocol? #endif required init(notificationCenter: NotificationCenter) { self.notificationCenter = notificationCenter self.observedNotifications = [] } func startObserving() { // swiftlint:disable:next line_length self.token = self.notificationCenter.addObserver(forName: nil, object: nil, queue: nil) { [weak self] notification in // linux-swift gets confused by .append(n) self?.observedNotifications.append(notification) } } deinit { #if canImport(Darwin) if let token = self.token { self.notificationCenter.removeObserver(token) } #else if let token = self.token as? AnyObject { self.notificationCenter.removeObserver(token) } #endif } } private let mainThread = pthread_self() public func postNotifications<T>( _ notificationsMatcher: T, fromNotificationCenter center: NotificationCenter = .default) -> Predicate<Any> where T: Matcher, T.ValueType == [Notification] { _ = mainThread // Force lazy-loading of this value let collector = NotificationCollector(notificationCenter: center) collector.startObserving() var once: Bool = false return Predicate { actualExpression in let collectorNotificationsExpression = Expression(memoizedExpression: { _ in return collector.observedNotifications }, location: actualExpression.location, withoutCaching: true) assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.") if !once { once = true _ = try actualExpression.evaluate() } let failureMessage = FailureMessage() let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage) if collector.observedNotifications.isEmpty { failureMessage.actualValue = "no notifications" } else { failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>" } return PredicateResult(bool: match, message: failureMessage.toExpectationMessage()) } }
apache-2.0
nvzqz/Sage
Benchmark/main.swift
1
1449
import Foundation extension Int { static func random(from value: Int) -> Int { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) return Int(arc4random_uniform(UInt32(value))) #elseif os(Linux) srand(.init(time(nil))) return Int(rand() % .init(value)) #else fatalError("Unknown OS") #endif } } extension Array { var random: Element? { return !self.isEmpty ? self[.random(from: count)] : nil } } var info = [(time: Double, count: Double)]() for _ in 1...20 { var count = 0.0 let game = Game() #if swift(>=3) let start = Date() #else let start = NSDate() #endif do { while let move = game.availableMoves().random { count += 1 try game.execute(uncheckedMove: move) } } catch { print(error) break } #if swift(>=3) let time = Date().timeIntervalSince(start) #else let time = NSDate().timeIntervalSinceDate(start) #endif info.append((time, count)) } let perSec = info.map(/) let averageSecs = perSec.reduce(0) { $0 + $1 } / Double(info.count) let averageMoves = info.reduce(0) { $0 + $1.1 } / Double(info.count) let multiplier = 1 / (info.reduce(0) { $0 + $1.0 } / Double(info.count)) print("Benchmark: 1 move in \(averageSecs) seconds") print("Benchmark: \(averageMoves * multiplier) moves in 1 seconds")
apache-2.0
hectr/swift-idioms
Tests/IdiomsTests/StringRemovingTests.swift
1
1759
// Copyright (c) 2019 Hèctor Marquès Ranea // // 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 Idioms final class StringRemovingTests: XCTestCase { func testRemovingSuffix() { XCTAssertEqual("lorem".removingSuffix("orem"), "l") } func testRemovingPrefix() { XCTAssertEqual("lorem".removingPrefix("lore"), "m") } func testRemovingCharacters() { XCTAssertEqual("lorem ipsum".removingCharacters(from: .whitespaces), "loremipsum") } static var allTests = [ ("testRemovingSuffix", testRemovingSuffix), ("testRemovingPrefix", testRemovingPrefix), ("testRemovingCharacters", testRemovingCharacters), ] }
mit
techmehra/AJCountryPicker
AJCountryPicker/Source/CallingCodes.swift
1
27825
import Foundation struct CountryProvider { static let callingCodes: [[String: String]] = [ [ "name": "Afghanistan", "dialCode": "+93", "code": "AF" ], [ "name": "Aland Islands", "dialCode": "+358", "code": "AX" ], [ "name": "Albania", "dialCode": "+355", "code": "AL" ], [ "name": "Algeria", "dialCode": "+213", "code": "DZ" ], [ "name": "AmericanSamoa", "dialCode": "+1684", "code": "AS" ], [ "name": "Andorra", "dialCode": "+376", "code": "AD" ], [ "name": "Angola", "dialCode": "+244", "code": "AO" ], [ "name": "Anguilla", "dialCode": "+1264", "code": "AI" ], [ "name": "Antarctica", "dialCode": "+672", "code": "AQ" ], [ "name": "Antigua and Barbuda", "dialCode": "+1268", "code": "AG" ], [ "name": "Argentina", "dialCode": "+54", "code": "AR" ], [ "name": "Armenia", "dialCode": "+374", "code": "AM" ], [ "name": "Aruba", "dialCode": "+297", "code": "AW" ], [ "name": "Australia", "dialCode": "+61", "code": "AU" ], [ "name": "Austria", "dialCode": "+43", "code": "AT" ], [ "name": "Azerbaijan", "dialCode": "+994", "code": "AZ" ], [ "name": "Bahamas", "dialCode": "+1242", "code": "BS" ], [ "name": "Bahrain", "dialCode": "+973", "code": "BH" ], [ "name": "Bangladesh", "dialCode": "+880", "code": "BD" ], [ "name": "Barbados", "dialCode": "+1246", "code": "BB" ], [ "name": "Belarus", "dialCode": "+375", "code": "BY" ], [ "name": "Belgium", "dialCode": "+32", "code": "BE" ], [ "name": "Belize", "dialCode": "+501", "code": "BZ" ], [ "name": "Benin", "dialCode": "+229", "code": "BJ" ], [ "name": "Bermuda", "dialCode": "+1441", "code": "BM" ], [ "name": "Bhutan", "dialCode": "+975", "code": "BT" ], [ "name": "Bolivia, Plurinational State of", "dialCode": "+591", "code": "BO" ], [ "name": "Bosnia and Herzegovina", "dialCode": "+387", "code": "BA" ], [ "name": "Botswana", "dialCode": "+267", "code": "BW" ], [ "name": "Brazil", "dialCode": "+55", "code": "BR" ], [ "name": "British Indian Ocean Territory", "dialCode": "+246", "code": "IO" ], [ "name": "Brunei Darussalam", "dialCode": "+673", "code": "BN" ], [ "name": "Bulgaria", "dialCode": "+359", "code": "BG" ], [ "name": "Burkina Faso", "dialCode": "+226", "code": "BF" ], [ "name": "Burundi", "dialCode": "+257", "code": "BI" ], [ "name": "Cambodia", "dialCode": "+855", "code": "KH" ], [ "name": "Cameroon", "dialCode": "+237", "code": "CM" ], [ "name": "Canada", "dialCode": "+1", "code": "CA" ], [ "name": "Cape Verde", "dialCode": "+238", "code": "CV" ], [ "name": "Cayman Islands", "dialCode": "+ 345", "code": "KY" ], [ "name": "Central African Republic", "dialCode": "+236", "code": "CF" ], [ "name": "Chad", "dialCode": "+235", "code": "TD" ], [ "name": "Chile", "dialCode": "+56", "code": "CL" ], [ "name": "China", "dialCode": "+86", "code": "CN" ], [ "name": "Christmas Island", "dialCode": "+61", "code": "CX" ], [ "name": "Cocos (Keeling) Islands", "dialCode": "+61", "code": "CC" ], [ "name": "Colombia", "dialCode": "+57", "code": "CO" ], [ "name": "Comoros", "dialCode": "+269", "code": "KM" ], [ "name": "Congo", "dialCode": "+242", "code": "CG" ], [ "name": "Congo, The Democratic Republic of the Congo", "dialCode": "+243", "code": "CD" ], [ "name": "Cook Islands", "dialCode": "+682", "code": "CK" ], [ "name": "Costa Rica", "dialCode": "+506", "code": "CR" ], [ "name": "Cote d'Ivoire", "dialCode": "+225", "code": "CI" ], [ "name": "Croatia", "dialCode": "+385", "code": "HR" ], [ "name": "Cuba", "dialCode": "+53", "code": "CU" ], [ "name": "Cyprus", "dialCode": "+357", "code": "CY" ], [ "name": "Czech Republic", "dialCode": "+420", "code": "CZ" ], [ "name": "Denmark", "dialCode": "+45", "code": "DK" ], [ "name": "Djibouti", "dialCode": "+253", "code": "DJ" ], [ "name": "Dominica", "dialCode": "+1767", "code": "DM" ], [ "name": "Dominican Republic", "dialCode": "+1849", "code": "DO" ], [ "name": "Ecuador", "dialCode": "+593", "code": "EC" ], [ "name": "Egypt", "dialCode": "+20", "code": "EG" ], [ "name": "El Salvador", "dialCode": "+503", "code": "SV" ], [ "name": "Equatorial Guinea", "dialCode": "+240", "code": "GQ" ], [ "name": "Eritrea", "dialCode": "+291", "code": "ER" ], [ "name": "Estonia", "dialCode": "+372", "code": "EE" ], [ "name": "Ethiopia", "dialCode": "+251", "code": "ET" ], [ "name": "Falkland Islands (Malvinas)", "dialCode": "+500", "code": "FK" ], [ "name": "Faroe Islands", "dialCode": "+298", "code": "FO" ], [ "name": "Fiji", "dialCode": "+679", "code": "FJ" ], [ "name": "Finland", "dialCode": "+358", "code": "FI" ], [ "name": "France", "dialCode": "+33", "code": "FR" ], [ "name": "French Guiana", "dialCode": "+594", "code": "GF" ], [ "name": "French Polynesia", "dialCode": "+689", "code": "PF" ], [ "name": "Gabon", "dialCode": "+241", "code": "GA" ], [ "name": "Gambia", "dialCode": "+220", "code": "GM" ], [ "name": "Georgia", "dialCode": "+995", "code": "GE" ], [ "name": "Germany", "dialCode": "+49", "code": "DE" ], [ "name": "Ghana", "dialCode": "+233", "code": "GH" ], [ "name": "Gibraltar", "dialCode": "+350", "code": "GI" ], [ "name": "Greece", "dialCode": "+30", "code": "GR" ], [ "name": "Greenland", "dialCode": "+299", "code": "GL" ], [ "name": "Grenada", "dialCode": "+1473", "code": "GD" ], [ "name": "Guadeloupe", "dialCode": "+590", "code": "GP" ], [ "name": "Guam", "dialCode": "+1671", "code": "GU" ], [ "name": "Guatemala", "dialCode": "+502", "code": "GT" ], [ "name": "Guernsey", "dialCode": "+44", "code": "GG" ], [ "name": "Guinea", "dialCode": "+224", "code": "GN" ], [ "name": "Guinea-Bissau", "dialCode": "+245", "code": "GW" ], [ "name": "Guyana", "dialCode": "+595", "code": "GY" ], [ "name": "Haiti", "dialCode": "+509", "code": "HT" ], [ "name": "Holy See (Vatican City State)", "dialCode": "+379", "code": "VA" ], [ "name": "Honduras", "dialCode": "+504", "code": "HN" ], [ "name": "Hong Kong", "dialCode": "+852", "code": "HK" ], [ "name": "Hungary", "dialCode": "+36", "code": "HU" ], [ "name": "Iceland", "dialCode": "+354", "code": "IS" ], [ "name": "India", "dialCode": "+91", "code": "IN" ], [ "name": "Indonesia", "dialCode": "+62", "code": "ID" ], [ "name": "Iran, Islamic Republic of Persian Gulf", "dialCode": "+98", "code": "IR" ], [ "name": "Iraq", "dialCode": "+964", "code": "IQ" ], [ "name": "Ireland", "dialCode": "+353", "code": "IE" ], [ "name": "Isle of Man", "dialCode": "+44", "code": "IM" ], [ "name": "Israel", "dialCode": "+972", "code": "IL" ], [ "name": "Italy", "dialCode": "+39", "code": "IT" ], [ "name": "Jamaica", "dialCode": "+1876", "code": "JM" ], [ "name": "Japan", "dialCode": "+81", "code": "JP" ], [ "name": "Jersey", "dialCode": "+44", "code": "JE" ], [ "name": "Jordan", "dialCode": "+962", "code": "JO" ], [ "name": "Kazakhstan", "dialCode": "+77", "code": "KZ" ], [ "name": "Kenya", "dialCode": "+254", "code": "KE" ], [ "name": "Kiribati", "dialCode": "+686", "code": "KI" ], [ "name": "Korea, Democratic People's Republic of Korea", "dialCode": "+850", "code": "KP" ], [ "name": "Korea, Republic of South Korea", "dialCode": "+82", "code": "KR" ], [ "name": "Kuwait", "dialCode": "+965", "code": "KW" ], [ "name": "Kyrgyzstan", "dialCode": "+996", "code": "KG" ], [ "name": "Laos", "dialCode": "+856", "code": "LA" ], [ "name": "Latvia", "dialCode": "+371", "code": "LV" ], [ "name": "Lebanon", "dialCode": "+961", "code": "LB" ], [ "name": "Lesotho", "dialCode": "+266", "code": "LS" ], [ "name": "Liberia", "dialCode": "+231", "code": "LR" ], [ "name": "Libyan Arab Jamahiriya", "dialCode": "+218", "code": "LY" ], [ "name": "Liechtenstein", "dialCode": "+423", "code": "LI" ], [ "name": "Lithuania", "dialCode": "+370", "code": "LT" ], [ "name": "Luxembourg", "dialCode": "+352", "code": "LU" ], [ "name": "Macao", "dialCode": "+853", "code": "MO" ], [ "name": "Macedonia", "dialCode": "+389", "code": "MK" ], [ "name": "Madagascar", "dialCode": "+261", "code": "MG" ], [ "name": "Malawi", "dialCode": "+265", "code": "MW" ], [ "name": "Malaysia", "dialCode": "+60", "code": "MY" ], [ "name": "Maldives", "dialCode": "+960", "code": "MV" ], [ "name": "Mali", "dialCode": "+223", "code": "ML" ], [ "name": "Malta", "dialCode": "+356", "code": "MT" ], [ "name": "Marshall Islands", "dialCode": "+692", "code": "MH" ], [ "name": "Martinique", "dialCode": "+596", "code": "MQ" ], [ "name": "Mauritania", "dialCode": "+222", "code": "MR" ], [ "name": "Mauritius", "dialCode": "+230", "code": "MU" ], [ "name": "Mayotte", "dialCode": "+262", "code": "YT" ], [ "name": "Mexico", "dialCode": "+52", "code": "MX" ], [ "name": "Micronesia, Federated States of Micronesia", "dialCode": "+691", "code": "FM" ], [ "name": "Moldova", "dialCode": "+373", "code": "MD" ], [ "name": "Monaco", "dialCode": "+377", "code": "MC" ], [ "name": "Mongolia", "dialCode": "+976", "code": "MN" ], [ "name": "Montenegro", "dialCode": "+382", "code": "ME" ], [ "name": "Montserrat", "dialCode": "+1664", "code": "MS" ], [ "name": "Morocco", "dialCode": "+212", "code": "MA" ], [ "name": "Mozambique", "dialCode": "+258", "code": "MZ" ], [ "name": "Myanmar", "dialCode": "+95", "code": "MM" ], [ "name": "Namibia", "dialCode": "+264", "code": "NA" ], [ "name": "Nauru", "dialCode": "+674", "code": "NR" ], [ "name": "Nepal", "dialCode": "+977", "code": "NP" ], [ "name": "Netherlands", "dialCode": "+31", "code": "NL" ], [ "name": "Netherlands Antilles", "dialCode": "+599", "code": "AN" ], [ "name": "New Caledonia", "dialCode": "+687", "code": "NC" ], [ "name": "New Zealand", "dialCode": "+64", "code": "NZ" ], [ "name": "Nicaragua", "dialCode": "+505", "code": "NI" ], [ "name": "Niger", "dialCode": "+227", "code": "NE" ], [ "name": "Nigeria", "dialCode": "+234", "code": "NG" ], [ "name": "Niue", "dialCode": "+683", "code": "NU" ], [ "name": "Norfolk Island", "dialCode": "+672", "code": "NF" ], [ "name": "Northern Mariana Islands", "dialCode": "+1670", "code": "MP" ], [ "name": "Norway", "dialCode": "+47", "code": "NO" ], [ "name": "Oman", "dialCode": "+968", "code": "OM" ], [ "name": "Pakistan", "dialCode": "+92", "code": "PK" ], [ "name": "Palau", "dialCode": "+680", "code": "PW" ], [ "name": "Palestinian Territory, Occupied", "dialCode": "+970", "code": "PS" ], [ "name": "Panama", "dialCode": "+507", "code": "PA" ], [ "name": "Papua New Guinea", "dialCode": "+675", "code": "PG" ], [ "name": "Paraguay", "dialCode": "+595", "code": "PY" ], [ "name": "Peru", "dialCode": "+51", "code": "PE" ], [ "name": "Philippines", "dialCode": "+63", "code": "PH" ], [ "name": "Pitcairn", "dialCode": "+872", "code": "PN" ], [ "name": "Poland", "dialCode": "+48", "code": "PL" ], [ "name": "Portugal", "dialCode": "+351", "code": "PT" ], [ "name": "Puerto Rico", "dialCode": "+1939", "code": "PR" ], [ "name": "Qatar", "dialCode": "+974", "code": "QA" ], [ "name": "Romania", "dialCode": "+40", "code": "RO" ], [ "name": "Russia", "dialCode": "+7", "code": "RU" ], [ "name": "Rwanda", "dialCode": "+250", "code": "RW" ], [ "name": "Reunion", "dialCode": "+262", "code": "RE" ], [ "name": "Saint Barthelemy", "dialCode": "+590", "code": "BL" ], [ "name": "Saint Helena, Ascension and Tristan Da Cunha", "dialCode": "+290", "code": "SH" ], [ "name": "Saint Kitts and Nevis", "dialCode": "+1869", "code": "KN" ], [ "name": "Saint Lucia", "dialCode": "+1758", "code": "LC" ], [ "name": "Saint Martin", "dialCode": "+590", "code": "MF" ], [ "name": "Saint Pierre and Miquelon", "dialCode": "+508", "code": "PM" ], [ "name": "Saint Vincent and the Grenadines", "dialCode": "+1784", "code": "VC" ], [ "name": "Samoa", "dialCode": "+685", "code": "WS" ], [ "name": "San Marino", "dialCode": "+378", "code": "SM" ], [ "name": "Sao Tome and Principe", "dialCode": "+239", "code": "ST" ], [ "name": "Saudi Arabia", "dialCode": "+966", "code": "SA" ], [ "name": "Senegal", "dialCode": "+221", "code": "SN" ], [ "name": "Serbia", "dialCode": "+381", "code": "RS" ], [ "name": "Seychelles", "dialCode": "+248", "code": "SC" ], [ "name": "Sierra Leone", "dialCode": "+232", "code": "SL" ], [ "name": "Singapore", "dialCode": "+65", "code": "SG" ], [ "name": "Slovakia", "dialCode": "+421", "code": "SK" ], [ "name": "Slovenia", "dialCode": "+386", "code": "SI" ], [ "name": "Solomon Islands", "dialCode": "+677", "code": "SB" ], [ "name": "Somalia", "dialCode": "+252", "code": "SO" ], [ "name": "South Africa", "dialCode": "+27", "code": "ZA" ], [ "name": "South Sudan", "dialCode": "+211", "code": "SS" ], [ "name": "South Georgia and the South Sandwich Islands", "dialCode": "+500", "code": "GS" ], [ "name": "Spain", "dialCode": "+34", "code": "ES" ], [ "name": "Sri Lanka", "dialCode": "+94", "code": "LK" ], [ "name": "Sudan", "dialCode": "+249", "code": "SD" ], [ "name": "Suriname", "dialCode": "+597", "code": "SR" ], [ "name": "Svalbard and Jan Mayen", "dialCode": "+47", "code": "SJ" ], [ "name": "Swaziland", "dialCode": "+268", "code": "SZ" ], [ "name": "Sweden", "dialCode": "+46", "code": "SE" ], [ "name": "Switzerland", "dialCode": "+41", "code": "CH" ], [ "name": "Syrian Arab Republic", "dialCode": "+963", "code": "SY" ], [ "name": "Taiwan", "dialCode": "+886", "code": "TW" ], [ "name": "Tajikistan", "dialCode": "+992", "code": "TJ" ], [ "name": "Tanzania, United Republic of Tanzania", "dialCode": "+255", "code": "TZ" ], [ "name": "Thailand", "dialCode": "+66", "code": "TH" ], [ "name": "Timor-Leste", "dialCode": "+670", "code": "TL" ], [ "name": "Togo", "dialCode": "+228", "code": "TG" ], [ "name": "Tokelau", "dialCode": "+690", "code": "TK" ], [ "name": "Tonga", "dialCode": "+676", "code": "TO" ], [ "name": "Trinidad and Tobago", "dialCode": "+1868", "code": "TT" ], [ "name": "Tunisia", "dialCode": "+216", "code": "TN" ], [ "name": "Turkey", "dialCode": "+90", "code": "TR" ], [ "name": "Turkmenistan", "dialCode": "+993", "code": "TM" ], [ "name": "Turks and Caicos Islands", "dialCode": "+1649", "code": "TC" ], [ "name": "Tuvalu", "dialCode": "+688", "code": "TV" ], [ "name": "Uganda", "dialCode": "+256", "code": "UG" ], [ "name": "Ukraine", "dialCode": "+380", "code": "UA" ], [ "name": "United Arab Emirates", "dialCode": "+971", "code": "AE" ], [ "name": "United Kingdom", "dialCode": "+44", "code": "GB" ], [ "name": "United States", "dialCode": "+1", "code": "US" ], [ "name": "Uruguay", "dialCode": "+598", "code": "UY" ], [ "name": "Uzbekistan", "dialCode": "+998", "code": "UZ" ], [ "name": "Vanuatu", "dialCode": "+678", "code": "VU" ], [ "name": "Venezuela, Bolivarian Republic of Venezuela", "dialCode": "+58", "code": "VE" ], [ "name": "Vietnam", "dialCode": "+84", "code": "VN" ], [ "name": "Virgin Islands, British", "dialCode": "+1284", "code": "VG" ], [ "name": "Virgin Islands, U.S.", "dialCode": "+1340", "code": "VI" ], [ "name": "Wallis and Futuna", "dialCode": "+681", "code": "WF" ], [ "name": "Yemen", "dialCode": "+967", "code": "YE" ], [ "name": "Zambia", "dialCode": "+260", "code": "ZM" ], [ "name": "Zimbabwe", "dialCode": "+263", "code": "ZW" ] ] } extension CountryProvider { static func countries(customCountriesCode: [String]? = nil) -> [Country] { if let codes = customCountriesCode { return CountryProvider.countries().filter{codes.contains($0.ISOCode)} } return CountryProvider.callingCodes.compactMap({ (dict) -> Country in Country(name: dict["name"]!, ISOCode: dict["code"]!, callingCode: dict["dialCode"]!) }) } }
mit
krevis/MIDIApps
Applications/SysExLibrarian/RecordController.swift
1
3844
/* Copyright (c) 2002-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Cocoa class RecordController: NSObject { init(mainWindowController: MainWindowController, midiController: MIDIController) { self.mainWindowController = mainWindowController self.midiController = midiController super.init() } deinit { NotificationCenter.default.removeObserver(self) } // MARK: API for main window controller func beginRecording() { guard let window = mainWindowController?.window else { return } if topLevelObjects == nil { guard Bundle.main.loadNibNamed(self.nibName, owner: self, topLevelObjects: &topLevelObjects) else { fatalError("couldn't load nib") } } progressIndicator.startAnimation(nil) updateIndicators(status: MIDIController.MessageListenStatus(messageCount: 0, bytesRead: 0, totalBytesRead: 0)) window.beginSheet(sheetWindow, completionHandler: nil) observeMIDIController() tellMIDIControllerToStartRecording() } // MARK: Actions @IBAction func cancelRecording(_ sender: Any?) { midiController?.cancelMessageListen() stopObservingMIDIController() progressIndicator.stopAnimation(nil) mainWindowController?.window?.endSheet(sheetWindow) } // MARK: To be implemented in subclasses var nibName: String { fatalError("must override in subclass") } func tellMIDIControllerToStartRecording() { fatalError("must override in subclass") } func updateIndicators(status: MIDIController.MessageListenStatus) { fatalError("must override in subclass") } // MARK: May be overridden in subclasses func observeMIDIController() { NotificationCenter.default.addObserver(self, selector: #selector(readStatusChanged(_:)), name: .readStatusChanged, object: midiController) } func stopObservingMIDIController() { NotificationCenter.default.removeObserver(self, name: .readStatusChanged, object: midiController) } // MARK: To be used by subclasses weak var mainWindowController: MainWindowController? weak var midiController: MIDIController? @IBOutlet var sheetWindow: NSPanel! @IBOutlet var progressIndicator: NSProgressIndicator! @IBOutlet var progressMessageField: NSTextField! @IBOutlet var progressBytesField: NSTextField! lazy var waitingForSysexMessage = NSLocalizedString("Waiting for SysEx message…", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "message when waiting for sysex") lazy var receivingSysexMessage = NSLocalizedString("Receiving SysEx message…", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "message when receiving sysex") func updateIndicatorsImmediatelyIfScheduled() { if scheduledProgressUpdate { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.privateUpdateIndicators), object: nil) scheduledProgressUpdate = false privateUpdateIndicators() } } // MARK: Private private var topLevelObjects: NSArray? private var scheduledProgressUpdate = false @objc private func privateUpdateIndicators() { guard let status = midiController?.messageListenStatus else { return } updateIndicators(status: status) scheduledProgressUpdate = false } @objc private func readStatusChanged(_ notification: Notification) { if !scheduledProgressUpdate { self.perform(#selector(self.privateUpdateIndicators), with: nil, afterDelay: 5.0 / 60.0) scheduledProgressUpdate = true } } }
bsd-3-clause
crashoverride777/SwiftyRate
Package.swift
1
429
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription private let packageName = "SwiftyRate" let package = Package( name: packageName, platforms: [.iOS(.v9)], products: [.library(name: packageName, targets: [packageName])], targets: [.target(name: packageName, path: "Source")], swiftLanguageVersions: [.v5] )
mit
rxwei/cuda-swift
Sources/NVRTC/Error.swift
1
1691
// // Error.swift // CUDA // // Created by Richard Wei on 10/16/16. // // import CNVRTC public struct CompilerError : Error { public enum Kind : UInt32 { case outOfMemory = 1 case programCreationFailure = 2 case invalidInput = 3 case invalidProgram = 4 case invalidOption = 5 case compilationError = 6 case builtinOperationFailure = 7 case noNameExpressionsAfterCompilation = 8 case noLoweredNamesBeforeCompilation = 9 case nameExpressionNotValid = 10 case internalError = 11 /// Invalid text encoding of input /// - Note: Not part of CUDA libraries case invalidEncoding init(_ nvrtcError: nvrtcResult) { self.init(rawValue: nvrtcError.rawValue)! } } public let kind: Kind public let log: String? public init(kind: Kind, log: String? = nil) { self.kind = kind self.log = log } init(result: nvrtcResult, log: String? = nil) { self.kind = Kind(result) self.log = log } } extension CompilerError : CustomStringConvertible { public var description: String { return log ?? String(describing: kind) } } @inline(__always) func ensureSuccess(_ result: nvrtcResult) throws { guard result == NVRTC_SUCCESS else { throw CompilerError(kind: .init(result)) } } @inline(__always) func forceSuccess(_ result: nvrtcResult) { guard result == NVRTC_SUCCESS else { fatalError(String(describing: CompilerError(kind: .init(result)))) } } prefix operator !! @inline(__always) prefix func !!(result: nvrtcResult) { forceSuccess(result) }
mit
AugustRush/Stellar
Sources/UIView+AnimateBehavior.swift
1
27197
// // UIView+AnimateBehavior.swift // StellarDemo // // Created by AugustRush on 6/21/16. // Copyright © 2016 August. All rights reserved. // import UIKit extension UIView: DriveAnimateBehaviors { func behavior(forType type: AnimationType, step: AnimationStep) -> UIDynamicBehavior { let mainType = type.mainType let subType = type.subType return createDynamicBehavior(withStyle: mainType, subType: subType, step: step) } //MARK: Basic fileprivate func createDynamicBehavior(withStyle style: AnimationStyle, subType: AnimationSubType, step: AnimationStep) -> UIDynamicBehavior { var behavior: UIDynamicBehavior! switch subType { case .moveX(let inc): let from = self.center.x let to = from + inc let render = {(f: CGFloat) in self.center.x = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .moveY(let inc): let from = self.center.y let to = from + inc let render = {(f: CGFloat) in self.center.y = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .moveTo(let point): let from = self.center let to = point let render = {(p: CGPoint) in self.center = p } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .color(let color): let from = self.backgroundColor ?? UIColor.clear let to = color let render = {(c: UIColor) in self.backgroundColor = c } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .opacity(let o): let from = self.layer.opacity let to = o let render = {(o: Float) in self.layer.opacity = o } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .alpha(let a): let from = self.alpha let to = a let render = {(f: CGFloat) in self.alpha = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .rotateX(let x): let from: CGFloat = 0.0 let to = x let transform = self.layer.transform let render = {(f: CGFloat) in self.layer.transform = CATransform3DRotate(transform, f, 1, 0, 0) } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .rotateY(let y): let from: CGFloat = 0.0 let to = y let transform = self.layer.transform let render = {(f: CGFloat) in self.layer.transform = CATransform3DRotate(transform, f, 0, 1, 0) } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .rotate(let z): let from: CGFloat = 0.0 let to = z let transform = self.layer.transform let render = {(f: CGFloat) in self.layer.transform = CATransform3DRotate(transform, f, 0, 0, 1) } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .rotateXY(let xy): let from: CGFloat = 0.0 let to = xy let transform = self.layer.transform let render = {(f: CGFloat) in self.layer.transform = CATransform3DRotate(transform, f, 1, 1, 0) } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .width(let w): let from = self.frame.width let to = w let render = {(f: CGFloat) in self.frame.size.width = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .height(let h): let from = self.bounds.height let to = h let render = {(f: CGFloat) in self.bounds.size.height = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .size(let size): let from = self.bounds.size let to = size let render = {(s: CGSize) in self.bounds.size = s } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .frame(let frame): let from = self.frame let to = frame let render = {(f: CGRect) in self.frame = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .bounds(let frame): let from = self.bounds let to = frame let render = {(f: CGRect) in self.bounds = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .scaleX(let x): let from: CGFloat = 1.0 let to = x let transform = self.layer.transform let render = {(f: CGFloat) in self.layer.transform = CATransform3DScale(transform, f, 1, 1) } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .scaleY(let y): let from: CGFloat = 1.0 let to = y let transform = self.layer.transform let render = {(f: CGFloat) in self.layer.transform = CATransform3DScale(transform, 1, y, 1) } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .scaleXY(let x, let y): let from = CGPoint(x: 1, y: 1) let to = CGPoint(x: x, y: y) let transform = self.layer.transform let render = {(p: CGPoint) in self.layer.transform = CATransform3DScale(transform, p.x, p.y, 1) } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .cornerRadius(let r): let from = self.layer.cornerRadius let to = r let render = {(f: CGFloat) in self.layer.cornerRadius = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .borderWidth(let b): let from = self.layer.borderWidth let to = b let render = {(f: CGFloat) in self.layer.borderWidth = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .shadowRadius(let s): let from = self.layer.shadowRadius let to = s let render = {(f: CGFloat) in self.layer.shadowRadius = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .zPosition(let p): let from = self.layer.zPosition let to = p let render = {(f: CGFloat) in self.layer.zPosition = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .anchorPoint(let point): let from = self.layer.anchorPoint let to = point let render = {(p: CGPoint) in self.layer.anchorPoint = p } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .anchorPointZ(let z): let from = self.layer.anchorPointZ let to = z let render = {(f: CGFloat) in self.layer.anchorPointZ = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .shadowOffset(let size): let from = self.layer.shadowOffset let to = size let render = {(s: CGSize) in self.layer.shadowOffset = s } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .shadowColor(let c): let color = self.layer.shadowColor let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear let to = c let render = {(c: UIColor) in self.layer.shadowColor = c.cgColor } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .shadowOpacity(let o): let from = self.layer.shadowOpacity let to = o let render = {(f: Float) in self.layer.shadowOpacity = f } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .tintColor(let color): let from = self.tintColor ?? UIColor.clear let to = color let render = {(c: UIColor) in self.tintColor = c } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case .textColor(let color): switch self { case let label as UILabel: let from = label.textColor ?? UIColor.clear let to = color let render = {(c: UIColor) in label.textColor = c } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } case let textView as UITextView: let from = textView.textColor ?? UIColor.clear let to = color let render = {(c: UIColor) in textView.textColor = c } switch style { case .basic: behavior = basicBehavior(step, from: from, to: to, render: render) case .attachment(let damping, let frequency): behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render) case .gravity(let magnitude): behavior = gravityBehavior(magnitude, from: from, to: to, render: render) case .snap(let damping): behavior = snapBehavior(damping, from: from, to: to, render: render) } default: fatalError("This object has not textColor property!") } default: fatalError("Unsupport this animation type!") } return behavior } //MARK: Private methods fileprivate func basicBehavior<T: Interpolatable>(_ step: AnimationStep,from: T, to: T, render: @escaping ((T) -> Void)) -> UIDynamicBehavior { let item = DynamicItemBasic(from: from, to: to, render: render) let push = item.pushBehavior(.down) item.behavior = push item.duration = step.duration item.timingFunction = step.timing.easing() item.delay = step.delay item.repeatCount = step.repeatCount item.autoreverses = step.autoreverses return push } fileprivate func snapBehavior<T: Vectorial>(_ damping: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior { let item = DynamicItem(from: from, to: to, render: render) let point = CGPoint(x: 0.0, y: item.referenceChangeLength) let snap = item.snapBehavior(point, damping: damping) item.behavior = snap return snap } fileprivate func attachmentBehavior<T: Vectorial>(_ damping: CGFloat, frequency: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior { let item = DynamicItem(from: from, to: to, render: render) let point = CGPoint(x: 0.0, y: item.referenceChangeLength) let attachment = item.attachmentBehavior(point, length: 0.0, damping: damping, frequency: frequency) item.behavior = attachment return attachment } fileprivate func gravityBehavior<T: Interpolatable>(_ magnitude: Double, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior { let item = DynamicItemGravity(from: from, to: to, render: render) let push = item.pushBehavior(.down) item.behavior = push item.magnitude = magnitude return push } }
mit
trafi/SlideOutable
Package.swift
1
977
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SlideOutable", platforms: [ .iOS(.v10), ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "SlideOutable", targets: ["SlideOutable"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "SlideOutable", dependencies: []), ] )
mit
abertelrud/swift-package-manager
Fixtures/Miscellaneous/DependenciesWarnings2/app/app.swift
2
107
import dep1 import dep2 @main struct App { public static func main() { print("hello, world!") } }
apache-2.0
ioswpf/CalendarKit
CalendarKit/CKExtensions.swift
1
1330
// // CKExtensions.swift // demo // // Created by wpf on 2017/3/20. // Copyright © 2017年 wpf. All rights reserved. // import Foundation extension Bundle { class func ckBundle() -> Bundle? { guard let path = Bundle(for: CalendarKit.self).path(forResource: "CalendarKit", ofType: "bundle") , let bundle = Bundle(path: path) else { return nil } return bundle } class func ckLocalizeString(key: String, value: String? = nil) -> String? { guard var language = NSLocale.preferredLanguages.first else { return nil } if language.hasPrefix("en") { language = "en" } else if language.hasPrefix("zh") { if language.range(of: "Hans") != nil { language = "zh-Hans" } else { language = "zh-Hant" } } else { language = "en" } guard let path = Bundle.ckBundle()?.path(forResource: language, ofType: "lproj") , let bundle = Bundle(path: path) else { return nil } let v = bundle.localizedString(forKey: key, value: value, table: nil) return Bundle.main.localizedString(forKey: key, value: v, table: nil) } }
mit
BenziAhamed/Tracery
Playgrounds/Tracery.playground/Pages/Calls.xcplaygroundpage/Contents.swift
1
1600
//: [Previous](@previous) /*: # Calls There is one more type of rule extension, which is a `call`. Unlike modifiers and methods that work with arguments, parameters and are expected to return some string value, calls do not need to do these. Calls have the same syntax as that of a modifier `#rule.call_something#`, except that they do not modify any results. Just to show how calls work, we will create one to track a rule expansion. */ import Tracery var t = Tracery {[ "f": "f" "letter" : ["a", "b", "c", "d", "e", "#f.track#"] ]} t.add(call: "track") { print("rule 'f' was expanded") } t.expand("#letter#") /*: In the code snippet above, the rule letter has 5 candidates, 4 of which are basically string values, but the fifth one is a rule. Yes, rules can be mixed in freely and can appear anywhere at all. So in this case, rule `f` can be expanded to the basic string `f`. Notice we also have added the track call. Now, whenever `letter` choose the rule `f` as a candidate for expansion, `.track` will be called. > Rule extensions can be place on their own inside a pair `#`. For example, if we created a modifier that always adds 'yo' to its input, called it `yo`, and have a rule candidate like `#.yo#`, this evaluates to the string "yo"; the modifier is passed in the empty string as an input parameter since there were no rules to expand. At this point, we have pretty much covered the basics. The following sections cover more advanced topics that involved getting more control over the candidate selection process. */ //: [Advanced](@next)
mit
amnuaym/TiAppBuilder
Day10/PushNotification/MyPushNotiApp/MyPushNotiApp/ViewController.swift
1
503
// // ViewController.swift // MyPushNotiApp // // Created by DrKeng on 10/16/2560 BE. // Copyright © 2560 ANT. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } }
gpl-3.0
Adorkable/seguecode
Example/iOS/Generated/FirstViewController+Main_iPhone.swift
1
1049
// // FirstViewController+Main_iPhone.swift // Example // // Generated by seguecode [http://bit.ly/seguecode] // import UIKit extension FirstViewController { struct StoryboardInstances { static let First = StoryboardInstance(identifier: "First") } struct Segues { static let FirstForwardToUIVC = Segue(identifier: "ForwardToUIVC") static let FirstGoToSecondSecond = Segue(identifier: "GoTo") static let FirstForwardToFirstSecond = Segue(identifier: "ForwardTo") } @IBAction func performFirstForwardToUIVC(sender : AnyObject? = nil) { self.performSegue(FirstViewController.Segues.FirstForwardToUIVC, sender: sender) } @IBAction func performFirstGoToSecondSecond(sender : AnyObject? = nil) { self.performSegue(FirstViewController.Segues.FirstGoToSecondSecond, sender: sender) } @IBAction func performFirstForwardToFirstSecond(sender : AnyObject? = nil) { self.performSegue(FirstViewController.Segues.FirstForwardToFirstSecond, sender: sender) } }
mit
NikolaiRuhe/SwiftDigest
SwiftDigestTests/MD5DigestTests.swift
1
2599
import SwiftDigest import XCTest class MD5Tests: XCTestCase { func testEmpty() { XCTAssertEqual( Data().md5, MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e") ) } func testData() { XCTAssertEqual( MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")?.data, Data([212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126,]) ) } func testBytes() { XCTAssertEqual( "\(MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")!.bytes)", "(212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126)" ) } func testFox1() { let input = "The quick brown fox jumps over the lazy dog" XCTAssertEqual( input.utf8.md5, MD5Digest(rawValue: "9e107d9d372bb6826bd81d3542a419d6") ) } func testFox2() { let input = "The quick brown fox jumps over the lazy dog." XCTAssertEqual( input.utf8.md5, MD5Digest(rawValue: "e4d909c290d0fb1ca068ffaddf22cbd0") ) } func testTwoFooterChunks() { let input = Data(count: 57) XCTAssertEqual( input.md5, MD5Digest(rawValue: "ab9d8ef2ffa9145d6c325cefa41d5d4e") ) } func test4KBytes() { var input = String(repeating: "The quick brown fox jumps over the lazy dog.", count: 100) XCTAssertEqual( input.utf8.md5, MD5Digest(rawValue: "7052292b1c02ae4b0b35fabca4fbd487") ) } func test4MBytes() { var input = String(repeating: "The quick brown fox jumps over the lazy dog.", count: 100000) XCTAssertEqual( input.utf8.md5, MD5Digest(rawValue: "f8a4ffa8b1c902f072338caa1e4482ce") ) } func testRecursive() { XCTAssertEqual( "".utf8.md5.description.utf8.md5.description.utf8.md5.description.utf8.md5, MD5Digest(rawValue: "5a8dccb220de5c6775c873ead6ff2e43") ) } func testEncoding() { let sut = MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")! let json = String(bytes: try! JSONEncoder().encode([sut]), encoding: .utf8)! XCTAssertEqual(json, "[\"\(sut)\"]") } func testDecoding() { let sut = MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")! let json = Data("[\"\(sut)\"]".utf8) let digest = try! JSONDecoder().decode(Array<MD5Digest>.self, from: json).first! XCTAssertEqual(digest, sut) } }
mit
CoderXpert/Weather
Weather/CurrentWeatherForecastViewModel.swift
1
8287
// // CurrentWeatherForecastViewModel.swift // Weather // // Created by Adnan Aftab on 3/8/16. // Copyright © 2016 CX. All rights reserved. // import Foundation import CoreLocation class CurrentWeatherForecastViewModel { //: Private properties private var forecastsItems:[Forecast]? private var forecast:Forecast? private let locationManager = LocationManager() private let forecastClient = ForecastClient() private var location : CLLocation? private var isLoadingCurrentWeatherData : Bool = false private var isLoadingForecastData : Bool = false init() { startLocationService() } // This method will start locationServices and will set delegate method to self private func startLocationService() { locationManager.delegate = self locationManager.requestLocation() } private func postNotification(notif:String){ dispatch_async(dispatch_get_main_queue(), { NSNotificationCenter.defaultCenter().postNotificationName(notif, object: .None) }) } private func getCurrentWeatherData (){ guard isLoadingCurrentWeatherData == false else { return } guard let loc = location else { return } isLoadingCurrentWeatherData = true self.postNotification(ForecastViewModelNotificaitons.StartLoadingCurrentWeatherInfo.rawValue) forecastClient.getCurrentWeatherWithLocation(loc) { (forecast, error) in self.isLoadingCurrentWeatherData = false guard error == .None else { //Post error notification self.postNotification(ForecastViewModelNotificaitons.GotNoCurrentWeatherData.rawValue) return } guard let fc = forecast else { // Post no forecast notification self.postNotification(ForecastViewModelNotificaitons.GotNoCurrentWeatherData.rawValue) return } self.forecast = fc self.postNotification(ForecastViewModelNotificaitons.GotNewCurrentWeatherData.rawValue) } } private func getForecastData() { guard isLoadingForecastData == false else { return } guard let loc = location else { return } isLoadingForecastData = true forecastClient.getForecastsWithLocation(loc) { (forecasts, error) in self.isLoadingForecastData = false guard error == .None else { self.postNotification(ForecastViewModelNotificaitons.GotNoForecasts.rawValue) return } guard let fcs = forecasts else { self.postNotification(ForecastViewModelNotificaitons.GotNoForecasts.rawValue) return } self.isLoadingForecastData = false self.forecastsItems = fcs self.postNotification(ForecastViewModelNotificaitons.GotNewForecastData.rawValue) } } private func getCurrentWeatherAndForecastData() { guard let _ = location else { return } getCurrentWeatherData() getForecastData() } } //: ViewModel protocol implementation extension CurrentWeatherForecastViewModel : CurrentWeatherForecastViewModelType { //: Current Weather var currentLocationName:String{ get{ guard let fc = forecast else { return "" } return fc.location } } var lastUpdateDateAndTimeString:String { get{ guard let fc = forecast else { return "" } let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd MMM yyy MM:HH" return dateFormatter.stringFromDate(fc.date) } } var currentTemperatureString:String { get{ guard let fc = forecast else { return "" } return fc.localizedTemperatureString } } var currentMaxTemperatureString:String { get{ guard let fc = forecast else { return "" } return fc.localizedMaxTemperatureString } } var currentMinTemperatureString:String { get{ guard let fc = forecast else { return "" } return fc.localizedMinTemeratureString } } var currentWeatherConditionIconText:String { get{ guard let fc = forecast else { return "" } return fc.iconText } } var currentWeatherConditionText:String { get{ guard let fc = forecast else { return "" } return fc.weatherConditionText } } //: Forecasts var totalNumberOfTodaysForecasts:Int { get { guard let fcs = forecastsItems else { return 0 } return fcs.forecastForToday().count } } var totalNumberOfFutureForecastsExcludingToday:Int { get { guard let fcs = forecastsItems else { return 0 } return fcs.forecastExcludingToday().count } } func todayForecastTemperatureStringForIndex(index:Int) -> String? { guard index >= 0 else { return .None } guard let fcs = forecastsItems else { return .None } let tfcs = fcs.forecastForToday() guard tfcs.count > 0 && index <= tfcs.count else { return .None } let fc = tfcs[index] return fc.localizedTemperatureString } func todayForecastShortDateTimeStringForIndex(index:Int) -> String? { guard index >= 0 else { return .None } guard let fcs = forecastsItems else { return .None } let tfcs = fcs.forecastForToday() guard tfcs.count > 0 && index <= tfcs.count else { return .None } let fc = tfcs[index] return fc.date.shortTime() } func todayForecastWeatherConditionIconTextForIndex(index:Int) -> String? { guard index >= 0 else { return .None } guard let fcs = forecastsItems else { return .None } let tfcs = fcs.forecastForToday() guard tfcs.count > 0 && index <= tfcs.count else { return .None } let fc = tfcs[index] return fc.iconText } func futureForecastTemperatureStringForIndex(index:Int) -> String? { guard index >= 0 else { return .None } guard let fcs = forecastsItems else { return .None } let tfcs = fcs.forecastExcludingToday() guard tfcs.count > 0 && index <= tfcs.count else { return .None } let fc = tfcs[index] return fc.localizedTemperatureString } func futureForecastShortDateTimeStringForIndex(index:Int) -> String? { guard index >= 0 else { return .None } guard let fcs = forecastsItems else { return .None } let tfcs = fcs.forecastExcludingToday() guard tfcs.count > 0 && index <= tfcs.count else { return .None } let fc = tfcs[index] return "\(fc.date.dayAndMonth())\n\(fc.date.shortTime())" } func futureForecastWeatherConditionIconTextForIndex(index:Int) -> String? { guard index >= 0 else { return .None } guard let fcs = forecastsItems else { return .None } let tfcs = fcs.forecastExcludingToday() guard tfcs.count > 0 && index <= tfcs.count else { return .None } let fc = tfcs[index] return fc.iconText } func updateWeatherData() { getCurrentWeatherAndForecastData() } } //: Extension which will implement LocationManagerDelegate method extension CurrentWeatherForecastViewModel : LocationManagerDelegate { func locationDidUpdate(service: LocationManager, location: CLLocation) { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.location = location self.getCurrentWeatherAndForecastData() } } }
apache-2.0
KeisukeSoma/RSSreader
RSSReader/View10.swift
1
3162
// // View10.swift // RSSReader // // Created by mikilab on 2015/06/19. // Copyright (c) 2015年 susieyy. All rights reserved. // import UIKit class View10: UITableViewController, MWFeedParserDelegate { var items = [MWFeedItem]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) request() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func request() { let URL = NSURL(string: "http://news.livedoor.com/topics/rss/ent.xml") let feedParser = MWFeedParser(feedURL: URL); feedParser.delegate = self feedParser.parse() } func feedParserDidStart(parser: MWFeedParser) { SVProgressHUD.show() self.items = [MWFeedItem]() } func feedParserDidFinish(parser: MWFeedParser) { SVProgressHUD.dismiss() self.tableView.reloadData() } func feedParser(parser: MWFeedParser, didParseFeedInfo info: MWFeedInfo) { print(info) self.title = info.title } func feedParser(parser: MWFeedParser, didParseFeedItem item: MWFeedItem) { print(item) self.items.append(item) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "FeedCell") self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = self.items[indexPath.row] as MWFeedItem let con = KINWebBrowserViewController() let URL = NSURL(string: item.link) con.loadURL(URL) self.navigationController?.pushViewController(con, animated: true) } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let item = self.items[indexPath.row] as MWFeedItem cell.textLabel?.text = item.title cell.textLabel?.font = UIFont.systemFontOfSize(14.0) cell.textLabel?.numberOfLines = 0 let projectURL = item.link.componentsSeparatedByString("?")[0] let imgURL: NSURL? = NSURL(string: projectURL + "/cover_image?style=200x200#") cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit // cell.imageView?.setImageWithURL(imgURL, placeholderImage: UIImage(named: "logo.png")) } }
mit
thiagotmb/TBHourMinutePickerView
TBHourMinutePickerView/NSDateComponents+Manager.swift
1
969
// // NSDateComponents+Manager.swift // TBHourMinutePickerView // // Created by Thiago-Bernardes on 1/26/16. // Copyright © 2016 TMB. All rights reserved. // extension NSDateComponents{ static func dateComponentsFrom(originalDate: NSDate) -> NSDateComponents { let cal: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! cal.locale = NSLocale.currentLocale() let timeZone: NSTimeZone = NSTimeZone.localTimeZone() cal.timeZone = timeZone var convertedDateComponents = NSDateComponents() convertedDateComponents.timeZone = timeZone if !originalDate.isEqual(nil){ convertedDateComponents = cal.components( [.Year, .Month, .Day, .Hour, .Minute], fromDate: originalDate) } else { convertedDateComponents = cal.components( [.Year, .Month, .Day, .Hour, .Minute], fromDate: NSDate()) } return convertedDateComponents } }
mit
itssofluffy/NanoMessage
Sources/NanoMessage/Core/SymbolProperty.swift
1
2708
/* SymbolProperty.swift Copyright (c) 2016, 2017 Stephen Whittle All rights reserved. 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 ISFLibrary import FNVHashValue /// Nanomsg symbol. public struct SymbolProperty { public let namespace: SymbolPropertyNamespace public let name: String public let value: CInt public let type: SymbolPropertyType public let unit: SymbolPropertyUnit public init(namespace: CInt, name: String, value: CInt, type: CInt, unit: CInt) { self.namespace = SymbolPropertyNamespace(rawValue: namespace) self.name = name self.value = value self.type = SymbolPropertyType(rawValue: type) self.unit = SymbolPropertyUnit(rawValue: unit) } } extension SymbolProperty: Hashable { public var hashValue: Int { return fnv1a(typeToBytes(namespace) + typeToBytes(value)) } } extension SymbolProperty: Comparable { public static func <(lhs: SymbolProperty, rhs: SymbolProperty) -> Bool { return ((lhs.namespace.rawValue < rhs.namespace.rawValue) || (lhs.namespace.rawValue == rhs.namespace.rawValue && lhs.value < rhs.value)) } } extension SymbolProperty: Equatable { public static func ==(lhs: SymbolProperty, rhs: SymbolProperty) -> Bool { return (lhs.namespace == rhs.namespace && lhs.value == rhs.value) } } extension SymbolProperty: CustomDebugStringConvertible { public var debugDescription: String { return "namespace: \(namespace), name: \(name), value: \(value), type: \(type), unit: \(unit)" } }
mit
MillmanY/MMPlayerView
MMPlayerView/Classes/Transition/MMPlayerBaseTransition.swift
1
744
// // BaseTransition.swift // Pods // // Created by Millman YANG on 2017/3/27. // // import UIKit public class MMPlayerBasePresentTransition: NSObject { var isPresent = true internal var config: MMPlayerPresentConfig! convenience init(config: MMPlayerPresentConfig , isPresent: Bool) { self.init() self.config = config self.isPresent = isPresent } } public class MMPlayerBaseNavTransition: NSObject { var operation: UINavigationController.Operation = .none internal var config: MMPlayerConfig! convenience init(config: MMPlayerConfig , operation: UINavigationController.Operation) { self.init() self.config = config self.operation = operation } }
mit
TrustWallet/trust-wallet-ios
Trust/Transactions/Types/LocalizedOperationObject.swift
1
2617
// Copyright DApps Platform Inc. All rights reserved. import Foundation import RealmSwift import TrustCore final class LocalizedOperationObject: Object, Decodable { @objc dynamic var from: String = "" @objc dynamic var to: String = "" @objc dynamic var contract: String? = .none @objc dynamic var type: String = "" @objc dynamic var value: String = "" @objc dynamic var name: String? = .none @objc dynamic var symbol: String? = .none @objc dynamic var decimals: Int = 18 convenience init( from: String, to: String, contract: String?, type: String, value: String, symbol: String?, name: String?, decimals: Int ) { self.init() self.from = from self.to = to self.contract = contract self.type = type self.value = value self.symbol = symbol self.name = name self.decimals = decimals } enum LocalizedOperationObjectKeys: String, CodingKey { case from case to case type case value case contract } convenience required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: LocalizedOperationObjectKeys.self) let from = try container.decode(String.self, forKey: .from) let to = try container.decode(String.self, forKey: .to) guard let fromAddress = EthereumAddress(string: from), let toAddress = EthereumAddress(string: to) else { let context = DecodingError.Context(codingPath: [LocalizedOperationObjectKeys.from, LocalizedOperationObjectKeys.to, ], debugDescription: "Address can't be decoded as a TrustKeystore.Address") throw DecodingError.dataCorrupted(context) } let type = try container.decode(OperationType.self, forKey: .type) let value = try container.decode(String.self, forKey: .value) let contract = try container.decode(ERC20Contract.self, forKey: .contract) self.init(from: fromAddress.description, to: toAddress.description, contract: contract.address, type: type.rawValue, value: value, symbol: contract.symbol, name: contract.name, decimals: contract.decimals ) } var operationType: OperationType { return OperationType(string: type) } }
gpl-3.0
daisuke310vvv/TopTabBarView
TopTabBarViewExample/TopTabBarViewExample/ViewController.swift
1
2004
// // ViewController.swift // TopTabBarViewExample // // Created by SatoDaisuke on 7/21/15. // Copyright (c) 2015 com.daisukeSato. All rights reserved. // import UIKit import TopTabBarView class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor.whiteColor() let item1 = TopTabBarItem(title: "Hot", color: UIColor(red: 2/255, green: 174/255, blue: 220/255, alpha: 1)) let item2 = TopTabBarItem(title: "Social", color: UIColor(red: 255/255, green: 212/255, blue: 100/255, alpha: 1)) let item3 = TopTabBarItem(title: "Politics", color: UIColor(red: 18/255, green: 83/255, blue: 164/255, alpha: 1)) let item4 = TopTabBarItem(title: "Business", color: UIColor(red: 47/255, green: 205/255, blue: 180/255, alpha: 1)) let item5 = TopTabBarItem(title: "Entertaiment", color: UIColor(red: 251/255, green: 168/255, blue: 72/255, alpha: 1)) let item6 = TopTabBarItem(title: "Tech", color: UIColor(red: 12/255, green: 85/255, blue: 93/255, alpha: 1)) let item7 = TopTabBarItem(title: "Media", color: UIColor(red: 2/255, green: 150/255, blue: 200/255, alpha: 1)) let item8 = TopTabBarItem(title: "Comedy", color: UIColor(red: 255/255, green: 83/255, blue: 200/255, alpha: 1)) let topTabBarView = TopTabBarView( frame: CGRectMake( 0, UIApplication.sharedApplication().statusBarFrame.height, self.view.frame.width, 44 ), items: [item1,item2,item3,item4,item5,item6,item7,item8] ) topTabBarView.delegate = self self.view.addSubview(topTabBarView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
cliqz-oss/jsengine
jsengine-ios/jsengineTests/CryptoTest.swift
1
1353
// // CryptoTest.swift // jsengine // // Created by Ghadir Eraisha on 1/17/17. // Copyright © 2017 Cliqz GmbH. All rights reserved. // import XCTest import JavaScriptCore @testable import jsengine class CryptoTest: XCTestCase { var jsengine: JSContext? = nil override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. self.jsengine = JSContext() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testMd5() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let crypto = Crypto() crypto.extend(self.jsengine!) let hashedString = self.jsengine?.evaluateScript("crypto._md5Native('test')") XCTAssertNotNil(hashedString) XCTAssertEqual(hashedString?.toString(), "098f6bcd4621d373cade4e832627b4f6") } func testPerformanceExample() { // This is an example of a performance test case. // self.measure { // // Put the code you want to measure the time of here. // } } }
mpl-2.0
LiuChang712/SwiftHelper
SwiftHelper/Foundation/Double+SH.swift
1
546
// // Double+Extension.swift // SwiftHelperDemo // // Created by LiuChang on 16/9/18. // Copyright © 2016年 LiuChang. All rights reserved. // import UIKit public extension Double { var abs: Double { return fabs(self) } func delay(_ closure:@escaping ()->()) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(self * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } } public extension Float { var abs: Float { return fabsf(self) } }
mit
xiabob/WebColor
WebColor/WebColor/AppDelegate.swift
1
2166
// // AppDelegate.swift // WebColor // // Created by xiabob on 16/12/13. // Copyright © 2016年 xiabob. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 invalidate graphics rendering callbacks. 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 active 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:. } }
mit
prolificinteractive/Kumi-iOS
Kumi/Core/Utility/SwiftyJSONHelper.swift
1
455
// // SwiftyJSONHelper.swift // Kumi // // Created by Nattawut Singhchai on 29/11/17. // Copyright © 2017 Prolific Interactive. All rights reserved. // extension JSON { var cgFloat: CGFloat? { if let double = double { return CGFloat(double) } if let int = int { return CGFloat(int) } return nil } var cgFloatValue: CGFloat { return CGFloat(floatValue) } }
mit
byronlai/unicode-encodings
Utf8Encoder.swift
1
861
class Utf8Encoder { private var codeUnits = [Int]() func encode(codePoint: Int) -> [Int] { codeUnits.removeAll(keepCapacity: true) if codePoint <= 0x007f { codeUnits.append(codePoint) } else if codePoint <= 0x07ff { codeUnits.append(codePoint >> 6 | 0xc0) codeUnits.append(codePoint & 0x3f | 0x80) } else if codePoint <= 0xffff { codeUnits.append(codePoint >> 12 | 0xe0) codeUnits.append(codePoint >> 6 & 0x3f | 0x80) codeUnits.append(codePoint & 0x3f | 0x80) } else { codeUnits.append(codePoint >> 18 | 0xf0) codeUnits.append(codePoint >> 12 & 0x3f | 0x80) codeUnits.append(codePoint >> 6 & 0x3f | 0x80) codeUnits.append(codePoint & 0x3f | 0x80) } return codeUnits } }
mit
gtrdp/cs-rug-internship
BTWF/BTWFUITests/BTWFUITests.swift
1
1252
// // BTWFUITests.swift // BTWFUITests // // Created by Guntur Dharma Putra on 20/04/16. // Copyright © 2016 Guntur Dharma Putra. All rights reserved. // import XCTest class BTWFUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
NorthernRealities/ColorSenseRainbow
ColorSenseRainbow/RainbowHexadecimalStringSeeker.swift
1
2725
// // RainbowHexadecimalSeeker.swift // ColorSenseRainbow // // Created by Reid Gravelle on 2015-04-23. // Copyright (c) 2015 Northern Realities Inc. All rights reserved. // import AppKit class RainbowHexadecimalStringSeeker: Seeker { override init () { super.init() var error : NSError? var regex: NSRegularExpression? // Swift let commonSwiftRegex = "(?:NS|UI)Color" + swiftInit + "\\s*\\(\\s*hexString:\\s*\"#?([0-9a-fA-F]{6})\"\\s*" do { regex = try NSRegularExpression ( pattern: commonSwiftRegex + ",\\s*alpha:\\s*" + swiftAlphaConst + "\\s*\\)", options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift Rainbow hexidecimal string with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } do { regex = try NSRegularExpression ( pattern: commonSwiftRegex + "\\)", options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift Rainbow hexidecimal string without alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } } override func processMatch ( match : NSTextCheckingResult, line : String ) -> SearchResult? { if ( ( match.numberOfRanges == 2 ) || ( match.numberOfRanges == 3 ) ) { var alphaValue : CGFloat = 1.0 let matchString = stringFromRange( match.range, line: line ) let hexString = stringFromRange( match.rangeAtIndex( 1 ), line: line ) var capturedStrings = [ matchString, hexString ] if ( match.numberOfRanges == 3 ) { let alphaString = stringFromRange( match.rangeAtIndex( 2 ), line: line ) alphaValue = CGFloat ( (alphaString as NSString).doubleValue ) capturedStrings.append( alphaString ) } var color = NSColor ( hexString: hexString ) if ( alphaValue != 1.0 ) { color = color.colorWithAlphaComponent( alphaValue ) } var searchResult = SearchResult ( color: color, textCheckingResult: match, capturedStrings: capturedStrings ) searchResult.creationType = .RainbowHexString return searchResult } return nil } }
mit
achimk/Cars
CarsApp/Repositories/Cars/Models/CarIdentityModel.swift
1
374
// // CarIdentityModel.swift // CarsApp // // Created by Joachim Kret on 30/07/2017. // Copyright © 2017 Joachim Kret. All rights reserved. // import Foundation struct CarIdentityModel: Equatable { let id: String init(_ id: String) { self.id = id } } func ==(lhs: CarIdentityModel, rhs: CarIdentityModel) -> Bool { return lhs.id == rhs.id }
mit
kopto/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorAnimationBallZigZagDeflect.swift
1
3754
// // KRActivityIndicatorAnimationBallZigZagDeflect.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // 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 Cocoa class KRActivityIndicatorAnimationBallZigZagDeflect: KRActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { let circleSize: CGFloat = size.width / 5 let duration: CFTimeInterval = 0.75 let deltaX = size.width / 2 - circleSize / 2 let deltaY = size.height / 2 - circleSize / 2 let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) // Circle 1 animation let animation = CAKeyframeAnimation(keyPath:"transform") animation.keyTimes = [0.0, 0.33, 0.66, 1.0] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] animation.duration = duration animation.repeatCount = HUGE animation.autoreverses = true animation.isRemovedOnCompletion = false // Draw circle 1 circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) // Circle 2 animation animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] // Draw circle 2 circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) } func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: NSColor, animation: CAAnimation) { let circle = KRActivityIndicatorShape.circle.layerWith(size: size, color: color) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
polkahq/PLKSwift
Sources/polka/utils/PLKEvent.swift
1
785
// // PLKEvent.swift // Pods // // Created by Alvaro Talavera on 7/4/17. // // import UIKit public class PLKEvent { private init() {} static public func addEventListener(object:Any, eventName:String, selector: Selector) { NotificationCenter.default.addObserver(object, selector: selector, name: NSNotification.Name(rawValue: eventName), object: nil) } static public func removeEventListener(object:Any, eventName:String) { NotificationCenter.default.removeObserver(object, name: NSNotification.Name(rawValue: eventName), object: nil) } static public func dispatchEvent(eventName:String, object: Any?) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: eventName), object: object) } }
mit
overtake/TelegramSwift
Telegram-Mac/AddContactModalController.swift
1
7785
// // AddContactModalController.swift // Telegram // // Created by keepcoder on 10/04/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import SwiftSignalKit import Postbox private struct AddContactState : Equatable { let firstName: String let lastName: String let phoneNumber: String let errors: [InputDataIdentifier : InputDataValueError] init(firstName: String, lastName: String, phoneNumber: String, errors: [InputDataIdentifier : InputDataValueError]) { self.firstName = firstName self.lastName = lastName self.phoneNumber = phoneNumber self.errors = errors } func withUpdatedError(_ error: InputDataValueError?, for key: InputDataIdentifier) -> AddContactState { var errors = self.errors if let error = error { errors[key] = error } else { errors.removeValue(forKey: key) } return AddContactState(firstName: self.firstName, lastName: self.lastName, phoneNumber: self.phoneNumber, errors: errors) } func withUpdatedFirstName(_ firstName: String) -> AddContactState { return AddContactState(firstName: firstName, lastName: self.lastName, phoneNumber: self.phoneNumber, errors: self.errors) } func withUpdatedLastName(_ lastName: String) -> AddContactState { return AddContactState(firstName: self.firstName, lastName: lastName, phoneNumber: self.phoneNumber, errors: self.errors) } func withUpdatedPhoneNumber(_ phoneNumber: String) -> AddContactState { return AddContactState(firstName: self.firstName, lastName: self.lastName, phoneNumber: phoneNumber, errors: self.errors) } } private let _id_input_first_name = InputDataIdentifier("_id_input_first_name") private let _id_input_last_name = InputDataIdentifier("_id_input_last_name") private let _id_input_phone_number = InputDataIdentifier("_id_input_phone_number") private func addContactEntries(state: AddContactState) -> [InputDataEntry] { var entries: [InputDataEntry] = [] var sectionId: Int32 = 0 var index: Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(InputDataEntry.input(sectionId: sectionId, index: index, value: .string(state.firstName), error: state.errors[_id_input_first_name], identifier: _id_input_first_name, mode: .plain, data: InputDataRowData(viewType: .firstItem), placeholder: nil, inputPlaceholder: strings().contactsFirstNamePlaceholder, filter: { $0 }, limit: 255)) index += 1 entries.append(InputDataEntry.input(sectionId: sectionId, index: index, value: .string(state.lastName), error: state.errors[_id_input_last_name], identifier: _id_input_last_name, mode: .plain, data: InputDataRowData(viewType: .innerItem), placeholder: nil, inputPlaceholder: strings().contactsLastNamePlaceholder, filter: { $0 }, limit: 255)) index += 1 entries.append(InputDataEntry.input(sectionId: sectionId, index: index, value: .string(state.phoneNumber), error: state.errors[_id_input_phone_number], identifier: _id_input_phone_number, mode: .plain, data: InputDataRowData(viewType: .lastItem), placeholder: nil, inputPlaceholder: strings().contactsPhoneNumberPlaceholder, filter: { text in return text.trimmingCharacters(in: CharacterSet(charactersIn: "0987654321+ ").inverted) }, limit: 30)) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func AddContactModalController(_ context: AccountContext) -> InputDataModalController { let initialState = AddContactState(firstName: "", lastName: "", phoneNumber: "", errors: [:]) let statePromise = ValuePromise(initialState, ignoreRepeated: false) let stateValue = Atomic(value: initialState) let updateState: ((AddContactState) -> AddContactState) -> Void = { f in statePromise.set(stateValue.modify (f)) } let dataSignal = statePromise.get() |> map { state in return addContactEntries(state: state) } var close: (() -> Void)? var shouldMakeNextResponderAfterTransition: InputDataIdentifier? = nil let controller = InputDataController(dataSignal: dataSignal |> map { InputDataSignalValue(entries: $0) }, title: strings().contactsAddContact, validateData: { data in return .fail(.doSomething { f in let state = stateValue.with {$0} var fields: [InputDataIdentifier : InputDataValidationFailAction] = [:] if state.firstName.isEmpty { fields[_id_input_first_name] = .shake shouldMakeNextResponderAfterTransition = _id_input_first_name } if state.phoneNumber.isEmpty { fields[_id_input_phone_number] = .shake if shouldMakeNextResponderAfterTransition == nil { shouldMakeNextResponderAfterTransition = _id_input_phone_number } updateState { $0.withUpdatedError(InputDataValueError(description: strings().contactsPhoneNumberInvalid, target: .data), for: _id_input_phone_number) } } if !fields.isEmpty { f(.fail(.fields(fields))) } else { _ = (showModalProgress(signal: context.engine.contacts.importContact(firstName: state.firstName, lastName: state.lastName, phoneNumber: state.phoneNumber), for: context.window) |> deliverOnMainQueue).start(next: { peerId in if let peerId = peerId { context.bindings.rootNavigation().push(ChatController(context: context, chatLocation: .peer(peerId))) close?() } else { updateState { $0.withUpdatedError(InputDataValueError(description: strings().contactsPhoneNumberNotRegistred, target: .data), for: _id_input_phone_number) } } }) } updateState { $0 } }) }, updateDatas: { data in updateState { state in return state .withUpdatedFirstName(data[_id_input_first_name]?.stringValue ?? "") .withUpdatedLastName(data[_id_input_last_name]?.stringValue ?? "") .withUpdatedPhoneNumber(formatPhoneNumber(data[_id_input_phone_number]?.stringValue ?? "")) .withUpdatedError(nil, for: _id_input_first_name) .withUpdatedError(nil, for: _id_input_last_name) .withUpdatedError(nil, for: _id_input_phone_number) } return .none }, afterDisappear: { }, afterTransaction: { controller in if let identifier = shouldMakeNextResponderAfterTransition { controller.makeFirstResponderIfPossible(for: identifier) } shouldMakeNextResponderAfterTransition = nil }) let modalInteractions = ModalInteractions(acceptTitle: strings().modalOK, accept: { [weak controller] in controller?.validateInputValues() }, drawBorder: true, singleButton: true) let modalController = InputDataModalController(controller, modalInteractions: modalInteractions, size: NSMakeSize(300, 300)) controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in modalController?.close() }) close = { [weak modalController] in modalController?.close() } return modalController }
gpl-2.0
annecruz/MDCSwipeToChoose
Examples/SwiftLikedOrNope/SwiftLikedOrNope/ChoosePersonView.swift
3
4990
// // ChoosePersonView.swift // SwiftLikedOrNope // // Copyright (c) 2014 to present, Richard Burdish @rjburdish // // 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 ChoosePersonView: MDCSwipeToChooseView { let ChoosePersonViewImageLabelWidth:CGFloat = 42.0; var person: Person! var informationView: UIView! var nameLabel: UILabel! var carmeraImageLabelView:ImagelabelView! var interestsImageLabelView: ImagelabelView! var friendsImageLabelView: ImagelabelView! init(frame: CGRect, person: Person, options: MDCSwipeToChooseViewOptions) { super.init(frame: frame, options: options) self.person = person if let image = self.person.Image { self.imageView.image = image } self.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] UIViewAutoresizing.FlexibleBottomMargin self.imageView.autoresizingMask = self.autoresizingMask constructInformationView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } func constructInformationView() -> Void{ let bottomHeight:CGFloat = 60.0 let bottomFrame:CGRect = CGRectMake(0, CGRectGetHeight(self.bounds) - bottomHeight, CGRectGetWidth(self.bounds), bottomHeight); self.informationView = UIView(frame:bottomFrame) self.informationView.backgroundColor = UIColor.whiteColor() self.informationView.clipsToBounds = true self.informationView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleTopMargin] self.addSubview(self.informationView) constructNameLabel() constructCameraImageLabelView() constructInterestsImageLabelView() constructFriendsImageLabelView() } func constructNameLabel() -> Void{ let leftPadding:CGFloat = 12.0 let topPadding:CGFloat = 17.0 let frame:CGRect = CGRectMake(leftPadding, topPadding, floor(CGRectGetWidth(self.informationView.frame)/2), CGRectGetHeight(self.informationView.frame) - topPadding) self.nameLabel = UILabel(frame:frame) self.nameLabel.text = "\(person.Name), \(person.Age)" self.informationView .addSubview(self.nameLabel) } func constructCameraImageLabelView() -> Void{ var rightPadding:CGFloat = 10.0 let image:UIImage = UIImage(named:"camera")! self.carmeraImageLabelView = buildImageLabelViewLeftOf(CGRectGetWidth(self.informationView.bounds), image:image, text:person.NumberOfPhotos.stringValue) self.informationView.addSubview(self.carmeraImageLabelView) } func constructInterestsImageLabelView() -> Void{ let image: UIImage = UIImage(named: "book")! self.interestsImageLabelView = self.buildImageLabelViewLeftOf(CGRectGetMinX(self.carmeraImageLabelView.frame), image: image, text:person.NumberOfPhotos.stringValue) self.informationView.addSubview(self.interestsImageLabelView) } func constructFriendsImageLabelView() -> Void{ let image:UIImage = UIImage(named:"group")! self.friendsImageLabelView = buildImageLabelViewLeftOf(CGRectGetMinX(self.interestsImageLabelView.frame), image:image, text:"No Friends") self.informationView.addSubview(self.friendsImageLabelView) } func buildImageLabelViewLeftOf(x:CGFloat, image:UIImage, text:String) -> ImagelabelView{ let frame:CGRect = CGRect(x:x-ChoosePersonViewImageLabelWidth, y: 0, width: ChoosePersonViewImageLabelWidth, height: CGRectGetHeight(self.informationView.bounds)) let view:ImagelabelView = ImagelabelView(frame:frame, image:image, text:text) view.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin return view } }
mit
Darshanptl7500/GPlaceAPI-Swift
GPlaceAPI/GPPlaceSearchRequest.swift
1
4216
// // GPPlaceSearchRequest.swift // GPlaceAPI-Swift // // Created by Darshan Patel on 7/23/15. // Copyright (c) 2015 Darshan Patel. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Darshan Patel // // 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 CoreLocation import Alamofire class GPPlaceSearchRequest { typealias GooglePlaceSearchHandler = (GPPlaceSearchResponse?, NSError?)->Void var location: CLLocationCoordinate2D! var radius: Int! var rankby: GPRankBy! var keyword: String? var language: String? var minprice: Int? var maxprice: Int? var name: String? var opennow: Bool? var types:[String]? var pagetoken: String? init (location: CLLocationCoordinate2D) { self.location = location; self.radius = 1000 self.minprice = -1 self.maxprice = -1 self.rankby = .GPRankByProminence } func params() -> Dictionary<String, AnyObject> { var dicParams = Dictionary<String, AnyObject>() dicParams["key"] = GPlaceAPISetup.sharedInstance.Api_Key dicParams["location"] = "\(self.location.latitude),\(self.location.longitude)" if let opRadius = self.radius { dicParams["radius"] = "\(self.radius)"; } if let opKeyWord = self.keyword { dicParams["keyword"] = self.keyword; } if self.maxprice != -1 { dicParams["maxprice"] = "\(self.maxprice)"; } if self.minprice != -1 { dicParams["maxprice"] = "\(self.minprice)"; } if let opName = self.name { dicParams["name"] = self.name } if self.opennow == true { dicParams["opennow"] = "\(self.opennow)" } if let language = self.language { dicParams["language"] = language } if let opPageToken = self.pagetoken { dicParams["pagetoken"] = self.pagetoken } dicParams["rankBy"] = self.rankby.rawValue if let opTypes = self.types { if opTypes.count > 0 { dicParams["types"] = join("|", opTypes) } } return dicParams } func doFetchPlaces(handler : GooglePlaceSearchHandler) { Alamofire.request(.GET, "\(GPlaceConstants.kAPI_PLACES_URL)nearbysearch/json", parameters: self.params(), encoding: .URL).responseJSON(options: .AllowFragments) { (request, response, data, error) -> Void in if error == nil { var gpResponse = GPPlaceSearchResponse(attributes: data as! Dictionary) handler(gpResponse, error) }else { handler(nil, error) } } } }
mit
MrSongzj/MSDouYuZB
MSDouYuZB/MSDouYuZB/Classes/Tools/Extension/NSDate(Extension).swift
1
290
// // NSDate(Extension).swift // MSDouYuZB // // Created by jiayuan on 2017/8/3. // Copyright © 2017年 mrsong. All rights reserved. // import Foundation extension NSDate { static var currentTimeInterval: TimeInterval { return NSDate().timeIntervalSince1970 } }
mit
andrewBatutin/SwiftYamp
SwiftYamp/WebSocketServer/WebsocketConnection.swift
1
6176
// // WebsocketConnection.swift // SwiftYamp // // Created by Andrey Batutin on 6/19/17. // Copyright © 2017 Andrey Batutin. All rights reserved. // import Foundation import Starscream import CocoaLumberjack public class WebSocketConnection: YampConnection, YampMessageConnection, YampConnectionCallback, YampDataCallback{ public var onConnect: ((Void)->Void)? public var onClose: ((String, CloseCodeType)->Void)? public var onRedirect: ((Void) -> String)? public var onEvent: ((EventFrame)->Void)? public var onResponse: ((ResponseFrame)->Void)? public var onPong: ((Data?) -> Void)? var onDataReceived: ((Data?) -> Void)? var onDataSend: ((Data?) -> Void)? private var data:Data = Data() public var versionSupported:[UInt16] = [0x01] public private(set) var webSocket:WebSocket? public init?(url: String){ guard let serverUrl = URL(string: url) else { return nil } webSocket = self.setupTransport(url: serverUrl) } private func setupTransport(url: URL) -> WebSocket{ let webSocket = WebSocket(url: url) webSocket.onData = self.incomingDataHandler() webSocket.onConnect = { [unowned self] in let handshakeFrame = HandshakeFrame(version: self.versionSupported.last ?? 0x1) self.sendFrame(frame: handshakeFrame) } webSocket.onDisconnect = {[unowned self] (error)in let c = CloseFrame(closeCode: .Unknown, message: error?.localizedDescription) self.closeReceived(frame: c) } return webSocket } private func incomingDataHandler() -> ((Data) -> Void)?{ self.data = Data() return { [unowned self] (data: Data) in self.data.append(data) do{ let frame:YampTypedFrame = try deserialize(data: self.data) as! YampTypedFrame self.onDataReceived?(self.data) self.handleFrame(frame: frame) self.data = Data() }catch(let exp){ DDLogWarn(exp.localizedDescription) } } } func handleFrame(frame:YampTypedFrame){ switch frame.frameType { case .Handshake: self.handshakeReceived(frame: frame as! HandshakeFrame) case .Close: let closeFrame:CloseFrame = frame as! CloseFrame self.closeReceived(frame: closeFrame) case .Ping: let pingFrame = frame as! PingFrame let pongFrame = PingFrame(ack: true, size:UInt8(pingFrame.payload.characters.count), payload: pingFrame.payload) self.sendFrame(frame: pongFrame) case .Event: self.onEvent?(frame as! EventFrame) case .Response: self.onResponse?(frame as! ResponseFrame) default: DDLogInfo("we've got some unxpected frame \(frame.frameType)") } } func handshakeReceived(frame: HandshakeFrame){ let v = frame.version if let str = self.onRedirect?() { self.cancel(reason: str, closeCode: .Redirect) self.onClose?("Redirect to \(str)", .Redirect) return } if ( self.versionSupported.contains(v) ){ self.onConnect?() } else { self.cancel(reason: "Version Not Supported", closeCode: .VersionNotSupported) self.onClose?("Version Not Supported", .VersionNotSupported) } } func closeReceived(frame: CloseFrame){ self.onClose?(frame.message, frame.closeCode) switch frame.closeCode { case .Timeout: self.disconnect() case .Redirect: self.reconnect(url: frame.message) default: DDLogInfo("close with code \(frame.closeCode)") } } public func reconnect(url: String){ self.disconnect() guard let serverUrl = URL(string: url) else { return } self.webSocket = self.setupTransport(url: serverUrl) self.connect() } private func disconnect(){ self.webSocket?.disconnect() } public func connect() { webSocket?.connect() } public func cancel(reason: String?, closeCode: CloseCodeType) { let closeFrame = CloseFrame(closeCode: closeCode, message: reason) self.sendFrame(frame: closeFrame) } func sendFrame(frame: YampFrame) { do{ let data = try frame.toData() self.onDataSend?(data) webSocket?.write(data: data) }catch(let exp){ DDLogError(exp.localizedDescription) } } public func sendPing(payload: String?){ let size = payload?.characters.count ?? 0 let frame = PingFrame(ack: false, size: UInt8(size), payload: payload) self.sendFrame(frame: frame) } public func sendData(uri: String, data: Data) { let h = UserMessageHeaderFrame(uid: messageUuid(), size: UInt8(uri.characters.count), uri: uri) let b = UserMessageBodyFrame(size: UInt32(data.count), body: data.toByteArray()) let r = RequestFrame(header: h, body: b) self.sendFrame(frame: r) } public func sendEvent(uri: String, message: String){ guard let data = message.data(using: .utf8) else { DDLogError("Error converting string to data") return } let h = UserMessageHeaderFrame(uid: messageUuid(), size: UInt8(uri.characters.count), uri: uri) let b = UserMessageBodyFrame(size: UInt32(data.count), body: data.toByteArray()) let r = EventFrame(header: h, body: b) self.sendFrame(frame: r) } public func sendMessage(uri: String, message: String) { guard let data = message.data(using: .utf8) else { DDLogError("Error converting string to data") return } self.sendData(uri: uri, data: data) } public func timeout(){ self.onClose?("Timeout", .Timeout) self.cancel(reason: "Timeout", closeCode: .Timeout) } }
mit
JakeLin/IBAnimatable
IBAnimatable/IBAnimatableTests/MockProtocols/StringFillDesignable.swift
2
1055
// // StringFillDesignable.swift // IBAnimatable // // Created by Steven on 5/12/17. // Copyright © 2017 IBAnimatable. All rights reserved. // import Foundation @testable import IBAnimatable // MARK: - StringFillDesignable Protocol protocol StringFillDesignable: FillDesignable { var _predefinedColor: String? { get set } } // MARK: - Classes with StringFillDesignable conformance extension AnimatableView: StringFillDesignable {} extension AnimatableScrollView: StringFillDesignable {} extension AnimatableButton: StringFillDesignable {} extension AnimatableCheckBox: StringFillDesignable {} extension AnimatableImageView: StringFillDesignable {} extension AnimatableStackView: StringFillDesignable {} extension AnimatableTableView: StringFillDesignable {} extension AnimatableTableViewCell: StringFillDesignable {} extension AnimatableCollectionViewCell: StringFillDesignable {} extension AnimatableTextView: StringFillDesignable {} extension AnimatableTextField: StringFillDesignable {} extension AnimatableLabel: StringFillDesignable {}
mit
zvonler/PasswordElephant
external/github.com/CryptoSwift/Tests/Tests/DigestTestsPerf.swift
3
2507
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // http://www.di-mgt.com.au/sha_testvectors.html (http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA_All.pdf) // @testable import CryptoSwift import Foundation import XCTest final class DigestTestsPerf: XCTestCase { func testMD5Performance() { measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { let arr = Array<UInt8>(repeating: 200, count: 1024 * 1024) self.startMeasuring() _ = Digest.md5(arr) self.stopMeasuring() } } func testSHA1Performance() { measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { let arr = Array<UInt8>(repeating: 200, count: 1024 * 1024) self.startMeasuring() _ = Digest.sha1(arr) self.stopMeasuring() } } // Keep it to compare /* func testSHA1PerformanceCC() { measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { let arr = Array<UInt8>(repeating: 200, count: 1024 * 1024) self.startMeasuring() var digest = Array<UInt8>(repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) CC_SHA1(arr, CC_LONG(arr.count), &digest) self.stopMeasuring() } } */ } extension DigestTestsPerf { static func allTests() -> [(String, (DigestTestsPerf) -> () -> Void)] { return [ ("testMD5Performance", testMD5Performance), ("testSHA1Performance", testSHA1Performance) ] } }
gpl-3.0
ajmccall/viper_sandbox
FarmDropSearch/domain/repository/ProducerDataSource.swift
1
424
// // ProducerDataSource.swift // FarmDropSearch // // Created by alasdair on 19/03/2017. // Copyright © 2017 alasdair. All rights reserved. // /** * Protocol that represents a Repository for getting Producer related data. */ import Foundation protocol ProducerDataSource { func producerCatalogue(completion: (ProducerCatalogue) -> Void) func getProducer(byId : Int, completion: (Producer?) -> Void) }
apache-2.0
JGiola/swift-package-manager
Fixtures/Miscellaneous/UnreachableTargets/B/Sources/BTarget2/main.swift
4
18
print("BTarget2")
apache-2.0
tamasoszko/sandbox-ios
Jazzy/Jazzy/PlayLists.swift
1
4822
// // PlayListItem.swift // Jazzy // // Created by Oszkó Tamás on 07/11/15. // Copyright © 2015 Oszi. All rights reserved. // import Foundation public class PlayListItem : NSObject { let date : NSDate let title : String let artist : String init(date : NSDate, title : String, artist : String) { self.date = date self.title = title self.artist = artist } override public func isEqual(object: AnyObject?) -> Bool { if let rhs = object as? PlayListItem { return title == rhs.title && artist == rhs.artist } return false } } class PlayListParser { let string : String let dateFormatter = NSDateFormatter() init(data: NSData) { self.string = String(data: data, encoding: NSUTF8StringEncoding)! self.dateFormatter.dateFormat = "HH:mm" self.dateFormatter.defaultDate = NSDate() } func parse() -> [PlayListItem] { let regexp = try! NSRegularExpression(pattern: "<td>(.*)</td>\n *<td>(.*)</td>\n *<td>(.*)</td>", options: NSRegularExpressionOptions.CaseInsensitive) let matches = regexp.matchesInString(string, options: NSMatchingOptions.ReportProgress, range: NSRange(location: 0, length: string.characters.count)) var items = [PlayListItem]() let nsString: NSString = string as NSString for match in matches { if match.numberOfRanges == 4 { let dataStr = nsString.substringWithRange(match.rangeAtIndex(1)) let artist = nsString.substringWithRange(match.rangeAtIndex(2)) let title = nsString.substringWithRange(match.rangeAtIndex(3)) let item = PlayListItem(date: dateFormatter.dateFromString(dataStr)!, title: title, artist: artist) items.append(item) } } return items } } class PlayListDownloader { let url : NSURL var maxCount = 10 init(url: NSURL) { self.url = url } func download(completion : ([PlayListItem]?, NSError?) -> Void) { let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url) { (_data: NSData?, _resp: NSURLResponse?, _error: NSError?) -> Void in if let error = _error { completion(nil, error) return } completion(self.items(_data!), nil) } task.resume() } private func items(data: NSData) -> [PlayListItem] { let parser = PlayListParser(data: data) let allItems = parser.parse().sort ({ $0.date.compare($1.date) == NSComparisonResult.OrderedDescending }) var items = [PlayListItem]() for var i = 0; i < min(self.maxCount, allItems.count); i++ { items.append(allItems[i]) } return items } } public class PlayListUpdater : NSObject { let ItemChangedNotification = "PlayListItemChanged" let updatePeriod = 15.0 var currentPlayListItem : PlayListItem? var timer : NSTimer? let downloader : PlayListDownloader init(url: NSURL) { self.downloader = PlayListDownloader(url: url) } public func startUpdate() { dispatch_async(dispatch_get_main_queue()) { () -> Void in if self.timer == nil { self.timer = NSTimer.scheduledTimerWithTimeInterval(self.updatePeriod, target: self, selector:"onTimer:", userInfo: nil, repeats: false) } } } public func stopUpdate() { if let timer = self.timer { timer.invalidate() self.timer = nil } } private func restartTimer() { if self.timer != nil { self.timer = nil startUpdate() } } func onTimer(timer:NSTimer!) { doUpdate() } private func doUpdate() { downloader.download { (items: [PlayListItem]?, error: NSError?) -> Void in if let error = error { NSLog("Error downloading playlist \(error)") return; } self.processPlayList(items) self.restartTimer() } } private func processPlayList(items: [PlayListItem]?) { let item = valid(items?.first) if currentPlayListItem != item { currentPlayListItem = item NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: ItemChangedNotification, object: currentPlayListItem)) } } private func valid(item: PlayListItem?) -> PlayListItem? { if let item = item { if item.date.timeIntervalSinceNow > -450 { return item } } return nil; } }
apache-2.0
matrix-org/matrix-ios-sdk
MatrixSDK/Background/Crypto/MXBackgroundCryptoV2.swift
1
3489
// // Copyright 2022 The Matrix.org Foundation C.I.C // // 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 #if DEBUG import MatrixSDKCrypto /// An implementation of `MXBackgroundCrypto` which uses [matrix-rust-sdk](https://github.com/matrix-org/matrix-rust-sdk/tree/main/crates/matrix-sdk-crypto) /// under the hood. class MXBackgroundCryptoV2: MXBackgroundCrypto { enum Error: Swift.Error { case missingCredentials } private let machine: MXCryptoMachine private let log = MXNamedLog(name: "MXBackgroundCryptoV2") init(credentials: MXCredentials, restClient: MXRestClient) throws { guard let userId = credentials.userId, let deviceId = credentials.deviceId else { throw Error.missingCredentials } // `MXCryptoMachine` will load the same store as the main application meaning that background and foreground // sync services have access to the same data / keys. Possible race conditions are handled internally. machine = try MXCryptoMachine( userId: userId, deviceId: deviceId, restClient: restClient, getRoomAction: { [log] _ in log.error("The background crypto should not be accessing rooms") return nil } ) } func handleSyncResponse(_ syncResponse: MXSyncResponse) { let toDeviceCount = syncResponse.toDevice?.events.count ?? 0 log.debug("Handling new sync response with \(toDeviceCount) to-device event(s)") do { _ = try machine.handleSyncResponse( toDevice: syncResponse.toDevice, deviceLists: syncResponse.deviceLists, deviceOneTimeKeysCounts: syncResponse.deviceOneTimeKeysCount ?? [:], unusedFallbackKeys: syncResponse.unusedFallbackKeys ) } catch { log.error("Failed handling sync response", context: error) } } func canDecryptEvent(_ event: MXEvent) -> Bool { if !event.isEncrypted { return true } guard let _ = event.content["sender_key"] as? String, let _ = event.content["session_id"] as? String else { return false } do { // Rust-sdk does not expose api to see if we have a given session key yet (will be added in the future) // so for the time being to find out if we can decrypt we simply perform the (more expensive) decryption _ = try machine.decryptRoomEvent(event) return true } catch { return false } } func decryptEvent(_ event: MXEvent) throws { let decrypted = try machine.decryptRoomEvent(event) let result = try MXEventDecryptionResult(event: decrypted) event.setClearData(result) } } #endif
apache-2.0
LiLe2015/DouYuLive
DouYuLive/DouYuLive/Classes/Tools/Extension/NSDate-Extension.swift
1
364
// // NSDate-Extension.swift // DouYuLive // // Created by LiLe on 2016/11/15. // Copyright © 2016年 LiLe. All rights reserved. // import Foundation extension NSDate { class func getCurrentTime() -> String { let nowDate = NSDate() let interval = Int(nowDate.timeIntervalSince1970) return "\(interval)" } }
mit
dev-gao/GYPageViewController
Example/GYPageViewController/ViewController.swift
1
4614
// // ViewController.swift // GYPageViewController // // Created by GaoYu on 16/6/12. // Copyright © 2016年 GaoYu. All rights reserved. // import UIKit class ViewController: UITableViewController ,GYPageViewControllerDataSource, GYPageViewControllerDelegate { @objc var pageControllers:Array<UIViewController>! override func viewDidLoad() { super.viewDidLoad() self.title = "Demo" self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CustomCell") } //MARK: - UITableViewDelegate, UITableViewDataSource override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath as IndexPath) if indexPath.row == 0 { cell.textLabel?.text = "GYTapPageViewController" } else if indexPath.row == 1 { cell.textLabel?.text = "GYPageViewController" } else if indexPath.row == 2 { cell.textLabel?.text = "UIPageViewController" } cell.setSelected(false, animated: false) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 { var titlesArray:Array<String> = Array<String>() var pageControllers:Array<TestChildViewController> = Array<TestChildViewController>() let colorStep:CGFloat = 1/4 for i in 0...20 { titlesArray.append("tab \(i)") let tabVc = TestChildViewController() tabVc.pageIndex = i tabVc.view.backgroundColor = UIColor(red: colorStep * CGFloat((i + 1) % 2), green: colorStep * CGFloat((i + 1) % 3), blue: colorStep * CGFloat((i + 1) % 5), alpha: 1) let label = UILabel(frame: CGRect(x:100,y:100,width:100,height:100)) label.backgroundColor = UIColor.gray label.text = "tab \(i)" label.textAlignment = .center tabVc.view.addSubview(label) pageControllers.append(tabVc) } self.pageControllers = pageControllers let vc = GYTabPageViewController(pageTitles: titlesArray) vc.delegate = self vc.dataSource = self vc.showPageAtIndex(2, animated: false) self.navigationController?.pushViewController(vc, animated: true) } else if indexPath.row == 1 { } else if indexPath.row == 2 { var titlesArray:Array<String> = Array<String>() var pageControllers:Array<TestChildViewController> = Array<TestChildViewController>() let colorStep:CGFloat = 1/4 for i in 0...20 { titlesArray.append("tab \(i)") let tabVc = TestChildViewController() tabVc.pageIndex = i tabVc.view.backgroundColor = UIColor(red: colorStep * CGFloat((i + 1) % 2), green: colorStep * CGFloat((i + 1) % 3), blue: colorStep * CGFloat((i + 1) % 5), alpha: 1) let label = UILabel(frame: CGRect(x:100,y:100,width:100,height:100)) label.backgroundColor = UIColor.gray label.text = "tab \(i)" label.textAlignment = .center tabVc.view.addSubview(label) pageControllers.append(tabVc) } self.pageControllers = pageControllers let vc = TestPageViewController(pageTitles: titlesArray, pageControllers: pageControllers) vc.showPageAtIndex(index: 2, animated: false) self.navigationController?.pushViewController(vc, animated: true) } } //MARK: - GYPageViewControllerDataSource & GYPageViewControllerDelegate @objc func gy_pageViewController(_: GYPageViewController, controllerAtIndex index: Int) -> UIViewController! { return self.pageControllers[index] } @objc func numberOfControllers(_: GYPageViewController) -> Int { return self.pageControllers.count } }
mit
ChrisMyrants/Wires
Sources/Logging.swift
1
558
public enum Preferences { public static var logActive: Bool = false public static var logSeparator: String? = nil } enum Log { static let prefix = "WiresLog" static let separator = "------" static let interfix = " --> " static func with(context: Any, text: String) { guard Preferences.logActive else { return } let preseparator = Preferences.logSeparator.map { $0 + "\n" } ?? "" let postseparator = Preferences.logSeparator.map { "\n" + $0 } ?? "" print(preseparator + prefix + interfix + "\(context)" + interfix + text + postseparator) } }
mit
343max/WorldTime
WorldTime/LocationEditorViewController.swift
1
2731
// Copyright 2014-present Max von Webel. All Rights Reserved. import UIKit protocol LocationEditorDelegate: class { func locationEditorDidEditLocation(index: Int, newLocation: Location) } class LocationEditorViewController: UITableViewController { var index = 0 var location: Location! { didSet { self.delegate?.locationEditorDidEditLocation(index: index, newLocation: location) if isViewLoaded { update(location: location) } } } weak var delegate: LocationEditorDelegate? @IBOutlet weak var locationNameTextField: UITextField! @IBOutlet weak var timeZoneCell: UITableViewCell! static func fromXib(location: Location, index: Int) -> LocationEditorViewController { let storyboard = UIStoryboard(name: "LocationEditorViewController", bundle: nil) guard let viewController = storyboard.instantiateInitialViewController() as? LocationEditorViewController else { fatalError("no LocationEditorViewController") } viewController.location = location viewController.index = index return viewController } override func viewDidLoad() { super.viewDidLoad() locationNameTextField.delegate = self update(location: location) } func update(location: Location) { locationNameTextField.text = location.name timeZoneCell.textLabel?.text = location.timeZone.pseudoLocalizedName timeZoneCell.detailTextLabel?.text = location.timeZone.localizedName(for: .standard, locale: Locale.current) } } extension LocationEditorViewController: TimeZonePickerDelegate { func timeZonePicker(_ timeZonePicker: TimeZonePicker, didSelect timeZone: TimeZone) { location.timeZone = timeZone } } extension LocationEditorViewController: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { if let name = textField.text, !name.isEmpty { self.location.name = name } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } } extension LocationEditorViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath as IndexPath) if cell == timeZoneCell { let timeZonePicker = TimeZonePicker(timeZone: location.timeZone) timeZonePicker.delegate = self let navigationController = UINavigationController(rootViewController: timeZonePicker) self.present(navigationController, animated: true, completion: nil) } } }
mit
robtimp/xswift
exercises/house/Package.swift
2
409
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "House", products: [ .library( name: "House", targets: ["House"]), ], dependencies: [], targets: [ .target( name: "House", dependencies: []), .testTarget( name: "HouseTests", dependencies: ["House"]), ] )
mit
mozilla-mobile/firefox-ios
Shared/RemoteDevices.swift
2
918
// 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 SwiftyJSON public protocol RemoteDevices { func replaceRemoteDevices(_ remoteDevices: [RemoteDevice]) -> Success } open class RemoteDevice { public let id: String? public let name: String public let type: String? public let isCurrentDevice: Bool public let lastAccessTime: Timestamp? public let availableCommands: JSON? public init(id: String?, name: String, type: String?, isCurrentDevice: Bool, lastAccessTime: Timestamp?, availableCommands: JSON?) { self.id = id self.name = name self.type = type self.isCurrentDevice = isCurrentDevice self.lastAccessTime = lastAccessTime self.availableCommands = availableCommands } }
mpl-2.0
benlangmuir/swift
test/Interpreter/vtables_multifile_testable.swift
13
5018
// We test various combinations to make sure that -enable-testing does not // break ABI with or without -enable-library-evolution. //// // RUN: %empty-directory(%t) // 1) -enable-testing OFF / -enable-library-evolution OFF // RUN: %target-build-swift-dylib(%t/%target-library-name(vtables_multifile_testable_helper)) %S/Inputs/vtables_multifile_testable_helper.swift -emit-module -emit-module-path %t/vtables_multifile_testable_helper.swiftmodule // RUN: %target-codesign %t/%target-library-name(vtables_multifile_testable_helper) // RUN: %target-build-swift %s -L %t -I %t -lvtables_multifile_testable_helper -o %t/main %target-rpath(%t) // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) // 2) -enable-testing ON / -enable-library-evolution OFF // ... first without rebuilding the client: // RUN: %target-build-swift-dylib(%t/%target-library-name(vtables_multifile_testable_helper)) %S/Inputs/vtables_multifile_testable_helper.swift -enable-testing -emit-module -emit-module-path %t/vtables_multifile_testable_helper.swiftmodule // RUN: %target-codesign %t/%target-library-name(vtables_multifile_testable_helper) // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) // ... now try to rebuild the client: // RUN: %target-build-swift %s -L %t -I %t -lvtables_multifile_testable_helper -o %t/main %target-rpath(%t) // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) //// // Delete build artifacts // RUN: %empty-directory(%t) // 3) -enable-testing OFF / -enable-library-evolution ON // RUN: %target-build-swift-dylib(%t/%target-library-name(vtables_multifile_testable_helper)) %S/Inputs/vtables_multifile_testable_helper.swift -enable-library-evolution -emit-module -emit-module-path %t/vtables_multifile_testable_helper.swiftmodule // RUN: %target-codesign %t/%target-library-name(vtables_multifile_testable_helper) // RUN: %target-build-swift %s -L %t -I %t -lvtables_multifile_testable_helper -o %t/main %target-rpath(%t) // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) // 4) -enable-testing ON / -enable-library-evolution ON // ... first without rebuilding the client: // RUN: %target-build-swift-dylib(%t/%target-library-name(vtables_multifile_testable_helper)) %S/Inputs/vtables_multifile_testable_helper.swift -enable-testing -enable-library-evolution -emit-module -emit-module-path %t/vtables_multifile_testable_helper.swiftmodule // RUN: %target-codesign %t/%target-library-name(vtables_multifile_testable_helper) // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) // ... now try to rebuild the client: // RUN: %target-build-swift %s -L %t -I %t -lvtables_multifile_testable_helper -o %t/main %target-rpath(%t) // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) //// // Delete build artifacts // RUN: %empty-directory(%t) // 5) -enable-testing OFF / -enable-library-evolution ON / textual interfaces // RUN: %target-build-swift-dylib(%t/%target-library-name(vtables_multifile_testable_helper)) %S/Inputs/vtables_multifile_testable_helper.swift -enable-library-evolution -emit-module-interface -emit-module-interface-path %t/vtables_multifile_testable_helper.swiftinterface // RUN: %target-codesign %t/%target-library-name(vtables_multifile_testable_helper) // RUN: %target-build-swift %s -L %t -I %t -lvtables_multifile_testable_helper -o %t/main %target-rpath(%t) // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) // 6) -enable-testing ON / -enable-library-evolution ON / textual interfaces // ... first without rebuilding the client: // RUN: %target-build-swift-dylib(%t/%target-library-name(vtables_multifile_testable_helper)) %S/Inputs/vtables_multifile_testable_helper.swift -enable-testing -enable-library-evolution -emit-module-interface -emit-module-interface-path %t/vtables_multifile_testable_helper.swiftinterface // RUN: %target-codesign %t/%target-library-name(vtables_multifile_testable_helper) // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) // ... now try to rebuild the client: // RUN: %target-build-swift %s -L %t -I %t -lvtables_multifile_testable_helper -o %t/main %target-rpath(%t) // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/%target-library-name(vtables_multifile_testable_helper) // REQUIRES: executable_test import StdlibUnittest import vtables_multifile_testable_helper var VTableTestSuite = TestSuite("VTable") public class Derived : Middle { public override func method() -> Int { return super.method() + 1 } } VTableTestSuite.test("Derived") { expectEqual(3, callBaseMethod(Derived())) expectEqual(3, callMiddleMethod(Derived())) } runAllTests()
apache-2.0
sambatech/player_sdk_ios_sample_app
SBPlayerSample/Helpers.swift
1
5439
// // Commons.swift // TesteMobileIOS // // Created by Leandro Zanol on 3/8/16. // Copyright © 2016 Sambatech. All rights reserved. // import Foundation import UIKit class Helpers { static let settings = NSDictionary.init(contentsOfFile: Bundle.main.path(forResource: "Configs", ofType: "plist")!)! as! [String:String] static func requestURL<T>(_ url: String, _ callback: ((T?) -> Void)?) { guard let urlObj = URL(string: url) else { print("\(type(of: self)) Error: Invalid URL format: \(url)") return } requestURL(URLRequest(url: urlObj), callback) } static func requestURL(_ url: String) { requestURL(url, nil as ((Data?) -> Void)?) } static func requestURL<T>(_ urlRequest: URLRequest, _ callback: ((T?) -> Void)?) { let requestTask = URLSession.shared.dataTask(with: urlRequest) { data, response, error in let reqText = "\n\(urlRequest.url?.absoluteString ?? "")\nMethod: \(urlRequest.httpMethod ?? "")\nHeader: \(String(describing: urlRequest.allHTTPHeaderFields))" if let error = error { print("\(type(of: self)) Error: \(error.localizedDescription)\(reqText)") callback?(nil) return } guard let response = response as? HTTPURLResponse else { print("\(type(of: self)) Error: No response from server.\(reqText)") callback?(nil) return } guard case 200..<300 = response.statusCode else { print("\(type(of: self)) Error: Invalid server response (\(response)).\(reqText)") callback?(nil) return } guard let data = data else { print("\(type(of: self)) Error: Unable to get data.\(reqText)") callback?(nil) return } switch T.self { case is String.Type: if let text = String(data: data, encoding: String.Encoding.utf8) { callback?(text as? T) } else { print("\(type(of: self)) Error: Unable to get text response.\(reqText)") callback?(nil) } case is Data.Type: callback?(data as? T) default: callback?(nil) } } requestTask.resume() } static func requestURL(_ urlRequest: URLRequest) { requestURL(urlRequest, nil as ((Data?) -> Void)?) } static func requestURLJson(_ url: String, _ callback: @escaping (AnyObject?) -> Void) { requestURL(url) { (data: Data?) in var jsonOpt: AnyObject? do { if let data = data { jsonOpt = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject } else { print("\(type(of: self)) Error getting JSON data.") } } catch { print("\(type(of: self)) Error parsing JSON string.") } callback(jsonOpt) } } } extension UIColor { convenience init(_ rgba: UInt) { let t = rgba > 0xFFFFFF ? 3 : 2 var array = [CGFloat](repeating: 1.0, count: 4) var n: UInt for i in 0...t { n = UInt((t - i)*8) array[i] = CGFloat((rgba & 0xFF << n) >> n)/255.0 } self.init(red: array[0], green: array[1], blue: array[2], alpha: array[3]) } } public extension UIImage { /** Tint, Colorize image with given tint color<br><br> This is similar to Photoshop's "Color" layer blend mode<br><br> This is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved<br><br> white will stay white and black will stay black as the lightness of the image is preserved<br><br> <img src="http://yannickstephan.com/easyhelper/tint1.png" height="70" width="120"/> **To** <img src="http://yannickstephan.com/easyhelper/tint2.png" height="70" width="120"/> - parameter tintColor: UIColor - returns: UIImage */ public func tintPhoto(_ tintColor: UIColor) -> UIImage { return modifiedImage { context, rect in // draw black background - workaround to preserve color of partially transparent pixels context.setBlendMode(.normal) UIColor.black.setFill() context.fill(rect) // draw original image context.setBlendMode(.normal) context.draw(self.cgImage!, in: rect) // tint image (loosing alpha) - the luminosity of the original image is preserved context.setBlendMode(.color) tintColor.setFill() context.fill(rect) // mask by alpha values of original image context.setBlendMode(.destinationIn) context.draw(self.cgImage!, in: rect) } } /** Tint Picto to color - parameter fillColor: UIColor - returns: UIImage */ public func tintPicto(_ fillColor: UIColor) -> UIImage { return modifiedImage { context, rect in // draw tint color context.setBlendMode(.normal) fillColor.setFill() context.fill(rect) // mask by alpha values of original image context.setBlendMode(.destinationIn) context.draw(self.cgImage!, in: rect) } } /** Modified Image Context, apply modification on image - parameter draw: (CGContext, CGRect) -> Void) - returns: UIImage */ fileprivate func modifiedImage(_ draw: (CGContext, CGRect) -> Void) -> UIImage { // using scale correctly preserves retina images UIGraphicsBeginImageContextWithOptions(size, false, scale) let context: CGContext! = UIGraphicsGetCurrentContext() assert(context != nil) // correctly rotate image context.translateBy(x: 0, y: size.height) context.scaleBy(x: 1.0, y: -1.0) let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) draw(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
apache-2.0
bitjammer/swift
test/Sema/Inputs/enum_with_raw_type.swift
61
32
public enum Foo: Int { case A }
apache-2.0
codefellows/sea-d40-iOS
Sample Playgrounds/GenericsDemo.playground/Sources/SupportCode.swift
1
201
// // This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to GenericsDemo.playground. //
mit
vendelal/wave
AudioKit/Instrument.swift
1
2184
// // Instrument.swift // AudioKit // // Created by Matthew Russo on 11/12/15. // Copyright © 2015 AudioKit. All rights reserved. // class FMSynth: AKInstrument { var frequency = AKInstrumentProperty(value: 440, minimum: 150, maximum: 740) var carrierMultiplier = AKInstrumentProperty(value: 0.5, minimum: 0.0, maximum: 1.0) var modulationIndex = AKInstrumentProperty(value: 0.5, minimum: 0.0, maximum: 1.0) var amplitude = AKInstrumentProperty(value: 0.25, minimum: 0.0, maximum: 0.5) override init() { super.init() let fmOscillator = AKFMOscillator() fmOscillator.baseFrequency = frequency fmOscillator.carrierMultiplier = carrierMultiplier fmOscillator.modulationIndex = modulationIndex fmOscillator.amplitude = amplitude setAudioOutput(fmOscillator) } } class touchInstrument: AKInstrument { // INSTRUMENT CONTROLS ===================================================== var frequency = AKInstrumentProperty(value: 440, minimum: 1.0, maximum: 880) var carrierMultiplier = AKInstrumentProperty(value: 1.0, minimum: 0.0, maximum: 2.0) var modulatingMultiplier = AKInstrumentProperty(value: 1, minimum: 0, maximum: 2) var modulationIndex = AKInstrumentProperty(value: 15, minimum: 0, maximum: 30) var amplitude = AKInstrumentProperty(value: 0.1, minimum: 0, maximum: 0.2) // INSTRUMENT DEFINITION =================================================== override init() { super.init() addProperty(frequency) addProperty(amplitude) addProperty(carrierMultiplier) addProperty(modulatingMultiplier) addProperty(modulationIndex) let fmOscillator = AKFMOscillator( waveform: AKTable.standardSineWave(), baseFrequency: frequency, carrierMultiplier: carrierMultiplier, modulatingMultiplier: modulatingMultiplier, modulationIndex: modulationIndex, amplitude: amplitude ) setAudioOutput(fmOscillator) } }
mit
hadibadjian/GAlileo
appstore/AppStore/ViewController.swift
1
277
// Copyright © 2016 HB. All rights reserved. import UIKit class ViewController: UIViewController { @IBOutlet weak var appIcon: UIImageView! override func viewDidLoad() { let layer = appIcon.layer layer.masksToBounds = true layer.cornerRadius = 30.0 } }
mit
jfrowies/iEMI
iEMI/BalanceViewController.swift
1
10505
// // BalanceViewController.swift // iEMI // // Created by Fer Rowies on 2/6/15. // Copyright (c) 2015 Rowies. All rights reserved. // import UIKit class BalanceViewController: NetworkActivityViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var creditBalanceView: CreditBalanceView! private var refreshControl: UIRefreshControl! private var _transactions: [Transaction]? private var transactions : [Transaction] { get { return _transactions ?? [Transaction]() } set { _transactions = newValue for transaction in self.transactions { if transaction.isKindOfClass(Debit) { let debit = transaction as! Debit let parking = Parking(number: debit.number, year: debit.year, serie: debit.serie) parkingInformationService.detail(parking, completion: { [weak self, debit] (result) -> Void in do { let parkingInfo: ParkingGeneral = try result() if let amount = parkingInfo.fareAmount { self?.debitAmounts[debit.number] = Float(amount) } self?.tableView.reloadData() } catch { } }) } } } } private var debitAmounts = [String:Float]() private var parkingSelected: Parking? private var sectionItemCount = [Int]() private var sectionFirstItem = [Int]() private var balance = 0.0 let service: AccountEMIService = AccountEMIService() let parkingInformationService: ParkingInformationEMIService = ParkingInformationEMIService() let licensePlateSotrage = LicensePlate() private let kCreditBalanceHeaderViewNibName = "CreditBalanceHeaderView" private let kCreditBalanceHeaderViewReuseId = "CreditBalanceHeaderViewReuseId" private let kBalanceCellDefaultHeight: CGFloat = 62.0 private let kBalanceHeaderDefaultHeight: CGFloat = 30.0 //MARK: - View controller lifecycle override func viewDidLoad() { super.viewDidLoad() refresh(self) refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(BalanceViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged) refreshControl.tintColor = UIColor.orangeGlobalTintColor() refreshControl.backgroundColor = UIColor.lightGrayBackgroundColor() tableView.addSubview(refreshControl) let nib = UINib(nibName: kCreditBalanceHeaderViewNibName, bundle: nil) tableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: kCreditBalanceHeaderViewReuseId) let tableViewInsets = UIEdgeInsetsMake(0.0, 0.0, (self.tabBarController?.tabBar.frame.size.height)!, 0.0) tableView.contentInset = tableViewInsets tableView.scrollIndicatorInsets = tableViewInsets } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if refreshControl.refreshing { refreshControl.endRefreshing() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: - func reloadData(patente patente: String) { self.reloadTableHeaderData(patente: patente) self.reloadTableData(patente: patente) } func reloadTableData(patente patente: String) { service.balance(licensePlate: patente) { [unowned self] (result) -> Void in do { let transactions = try result() self.transactions = transactions self.tableView.reloadData() self.refreshControl.endRefreshing() if transactions.count == 0 { self.tableView.hidden = true } else { self.tableView.hidden = false } self.hideLoadingView(animated: true) } catch let error{ self.tableView.hidden = false self.showError(error as NSError) } } } private let kCreditBalanceText = NSLocalizedString("Credit balance", comment: "Credit balancen title text") private let kCreditBalanceSeparator = ": " private let kCreditBalanceSign = " $" private let kUnknownCreditBalance = NSLocalizedString("Unknown", comment: "Unknown credit balance") func reloadTableHeaderData(patente licensePlate: String) { service.accountBalance(licensePlate: licensePlate) { [unowned self] (result) -> Void in do { let currentBalance = try result() self.balance = currentBalance let creditBalanceString = String(format: "%.2f", currentBalance) self.creditBalanceView?.creditBalanceLabel.text = self.kCreditBalanceText + self.kCreditBalanceSeparator + creditBalanceString + self.kCreditBalanceSign } catch let error{ self.creditBalanceView?.creditBalanceLabel.text = self.kCreditBalanceText + self.kCreditBalanceSeparator + self.kUnknownCreditBalance self.balance = 0.0 self.showError(error as NSError) } } } private let kErrorText = NSLocalizedString("Error loading balance, please try again later.", comment: "error loading balance text") func showError(error: NSError?) { print("Error: \(error)") self.showErrorView(kErrorText, animated:false) } //MARK: - IBAction private let kLoadingCreditText = NSLocalizedString("Loading balance", comment: "loading credit balance text") @IBAction func refresh(sender:AnyObject) { if let currentLicensePlate = licensePlateSotrage.currentLicensePlate { if !(sender.isEqual(self.refreshControl)) { self.showLoadingView(kLoadingCreditText, animated:false) } self.reloadData(patente:currentLicensePlate) } } //MARK: - UITableViewDelegate implementation func numberOfSectionsInTableView(tableView: UITableView) -> Int { self.sectionItemCount.removeAll(keepCapacity: false) self.sectionFirstItem.removeAll(keepCapacity: false) var sections = 0; var date: String = ""; var index: Int = 0; for mov: Transaction in self.transactions { let timestamp: String = mov.timestamp let subDate = timestamp.substringToIndex(timestamp.startIndex.advancedBy(10)) if (!(date == subDate)) { date = subDate self.sectionItemCount.append(0) self.sectionFirstItem.append(index) sections += 1 } self.sectionItemCount[sections - 1] = self.sectionItemCount[sections - 1] + 1 index += 1 } return sections } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sectionItemCount[section] } private let kCreditCellReuseId = "creditoCell" private let kDebitCellReuseId = "consumoCell" func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let movimiento = self.transactions[self.sectionFirstItem[indexPath.section] + indexPath.row] if movimiento.isKindOfClass(Credit) { let cell = self.tableView.dequeueReusableCellWithIdentifier(kCreditCellReuseId, forIndexPath: indexPath) as! CreditoTableViewCell cell.credito = movimiento as! Credit return cell } if movimiento.isKindOfClass(Debit) { let cell = self.tableView.dequeueReusableCellWithIdentifier(kDebitCellReuseId, forIndexPath: indexPath) as! ConsumoTableViewCell let debit = movimiento as! Debit if let debitAmount = self.debitAmounts[debit.number] { debit.amount = String(format: "%0.2f", debitAmount) } cell.debit = debit return cell } return UITableViewCell() } func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if let debit = self.transactions[self.sectionFirstItem[indexPath.section] + indexPath.row] as? Debit { self.parkingSelected = Parking(number: debit.number, year: debit.year, serie: debit.serie) }else{ return nil } return indexPath } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return kBalanceCellDefaultHeight } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(kCreditBalanceHeaderViewReuseId) as? CreditBalanceHeaderView let mov = self.transactions[self.sectionFirstItem[section]]; let timestamp: String = mov.timestamp let subDate = timestamp.substringToIndex(timestamp.startIndex.advancedBy(10)) let nsDate = NSDate(dateString: subDate) headerView?.sectionTitleLabel.text = nsDate.formattedDateString() return headerView } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return kBalanceHeaderDefaultHeight } // MARK: - Navigation private let kShowParkingInformationSegueId = "showParkingInformation" override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == kShowParkingInformationSegueId { let dvc = segue.destinationViewController as! ParkingInformationViewController dvc.parking = self.parkingSelected } } }
apache-2.0
mohanvydehi/MVCalendar
Example/MVCalendar/AppDelegate.swift
1
450
// // AppDelegate.swift // MVCalendar // // Created by Mohan Reddy on 09/30/2016. // Copyright (c) 2016 Mohan Reddy. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { return true } }
mit
max9631/Piskvorky
Piškvorky/MenuWindow.swift
1
2772
// // MenuWindow.swift // Piškvorky // // Created by Adam Salih on 03/06/15. // Copyright (c) 2015 Adam Salih. All rights reserved. // import UIKit class MenuWindow: UIViewController { @IBOutlet weak var textLabel: UILabel! var currentWindow:WindowManager! override init() { super.init(nibName: "MenuWindow", bundle: nil) } override func viewDidLoad() { self.view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) self.view.backgroundColor = blue self.textLabel.frame.origin.x = (UIScreen.mainScreen().bounds.width / 2) - (textLabel.frame.width / 2) self.textLabel.frame.origin.y = (UIScreen.mainScreen().bounds.height / 4) - (textLabel.frame.height / 2) let notcen = NSNotificationCenter.defaultCenter() notcen.addObserver(self, selector: "segue:", name: "segueToAnotherScreen", object: nil) let mainMenu = MainMenu() notcen.postNotificationName("segueToAnotherScreen", object: mainMenu, userInfo: ["smer":"nahoru"]) } func segue(notification:NSNotification){ UIView.animateWithDuration(0.6, animations: { self.textLabel.alpha = 0 }) let window = notification.object as WindowManager self.view.addSubview(window.getView()) self.currentWindow = window let dic = notification.userInfo as [String:String] if dic["color"] == "white"{ self.view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.9) }else{ UIView.animateWithDuration(0.5, animations: { self.view.backgroundColor = blue }) self.prepareForAppear(windows: window.windowsObjects(), smer: dic["smer"]!) } window.makeAppear(titleLabel: self.textLabel) } func prepareForAppear(#windows:[UIView], smer: String){ if smer == "nahoru"{ for view in windows{ view.frame.origin.y = UIScreen.mainScreen().bounds.height } }else if smer == "dolu"{ for view in windows{ view.frame.origin.y = -(view.frame.height) } }else if smer == "doleva"{ for view in windows{ view.frame.origin.x = UIScreen.mainScreen().bounds.width } }else if smer == "doprava"{ for view in windows{ view.frame.origin.x = -(view.frame.width) } } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } @objc protocol WindowManager { func makeAppear(#titleLabel:UILabel) func windowsObjects() -> [UIView] func getView() -> UIView }
gpl-2.0
spotify/HubFramework
demo/sources/GitHubSearchCustomDataKeys.swift
1
1345
/* * Copyright (c) 2016 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 /// Struct containing keys used for custom data in the GitHub search feature struct GitHubSearchCustomDataKeys { /// Key used to encode a search string into a view model builder's custom data static var searchString: String { return "searchString" } /// Key used to encode a Boolean indicating whether a search is currently in /// progess into a view model builder's custom data static var searchInProgress: String { return "searchInProgress" } }
apache-2.0
lecksfrawen/HeaderDLHamburgerMenuTest
DLHamburguerMenu/DLDemoMenuViewController.swift
1
2081
// // DLDemoMenuViewController.swift // DLHamburguerMenu // // Created by Nacho on 5/3/15. // Copyright (c) 2015 Ignacio Nieto Carvajal. All rights reserved. // import UIKit class DLDemoMenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // outlets @IBOutlet weak var tableView: UITableView! // data let segues = ["Mi Perfil", "Notificaciones", "Valorar", "Más aplicaciones","Acerca de la app", "Cerrar sesión"] override func viewDidLoad() { super.viewDidLoad() print("viewDidLoad desde VC inicial") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UITableViewDelegate&DataSource methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return segues.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MenuCell", forIndexPath: indexPath) cell.textLabel?.text = segues[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let nvc = self.mainNavigationController() if let hamburguerViewController = self.findHamburguerViewController() { hamburguerViewController.hideMenuViewControllerWithCompletion({ () -> Void in nvc.visibleViewController!.performSegueWithIdentifier(self.segues[indexPath.row], sender: nil) hamburguerViewController.contentViewController = nvc }) } } // MARK: - Navigation func mainNavigationController() -> DLHamburguerNavigationController { return self.storyboard?.instantiateViewControllerWithIdentifier("DLDemoNavigationViewController") as! DLHamburguerNavigationController } }
mit
wildthink/BagOfTricks
BagOfTricks/SpeechController.swift
1
4199
// // SpeechController.swift // SpeechRecognition // // Created by Stephen Anthony on 24/11/2016. // Copyright © 2016 Darjeeling Apps. All rights reserved. // import Foundation import Speech /// The class used to control speech recognition sessions. @available(iOS 10.0, *) open class SpeechController { private static let inputNodeBus: AVAudioNodeBus = 0 /// The speech recogniser used by the controller to record the user's speech. private let speechRecogniser = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))! /// The current speech recognition request. Created when the user wants to begin speech recognition. private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? /// The current speech recognition task. Created when the user wants to begin speech recognition. private var recognitionTask: SFSpeechRecognitionTask? /// The audio engine used to record input from the microphone. private let audioEngine = AVAudioEngine() /// The delegate of the receiver. public var delegate: SpeechControllerDelegate? public init () { } /// Begins a new speech recording session. /// /// - Throws: Errors thrown by the creation of the speech recognition session open func startRecording() throws { guard speechRecogniser.isAvailable else { // Speech recognition is unavailable, so do not attempt to start. return } if let recognitionTask = recognitionTask { // We have a recognition task still running, so cancel it before starting a new one. recognitionTask.cancel() self.recognitionTask = nil } guard SFSpeechRecognizer.authorizationStatus() == .authorized else { SFSpeechRecognizer.requestAuthorization({ _ in }) return } let audioSession = AVAudioSession.sharedInstance() try audioSession.setCategory(AVAudioSessionCategoryRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) recognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let inputNode = audioEngine.inputNode, let recognitionRequest = recognitionRequest else { throw SpeechControllerError.noAudioInput } recognitionTask = speechRecogniser.recognitionTask(with: recognitionRequest) { [unowned self] result, error in if let result = result { self.delegate?.speechController(self, didRecogniseText: result.bestTranscription.formattedString) } if result?.isFinal ?? (error != nil) { inputNode.removeTap(onBus: SpeechController.inputNodeBus) } } let recordingFormat = inputNode.outputFormat(forBus: SpeechController.inputNodeBus) inputNode.installTap(onBus: SpeechController.inputNodeBus, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() try audioEngine.start() } /// Ends the current speech recording session. open func stopRecording() { audioEngine.stop() recognitionRequest?.endAudio() } } /// The protocol to conform to for delegates of `SpeechController`. @available(iOS 10.0, *) public protocol SpeechControllerDelegate { /// The message sent when the user's speech has been transcribed. Will be called with partial results of the current recording session. /// /// - Parameters: /// - speechController: The controller sending the message. /// - text: The text transcribed from the user's speech. func speechController(_ speechController: SpeechController, didRecogniseText text: String) } /// The error types vended by `SpeechController` if it cannot create an audio recording session. /// /// - noAudioInput: No audio input connection could be created. public enum SpeechControllerError: Error { case noAudioInput }
mit
KiiPlatform/thing-if-iOSSample
SampleProject/OnBoardViewController.swift
1
2107
// // OnBoardViewController.swift // SampleProject // // Created by Yongping on 8/24/15. // Copyright © 2015 Kii Corporation. All rights reserved. // import UIKit import ThingIFSDK class OnBoardViewController: KiiBaseTableViewController { @IBOutlet weak var thingTypeTextField: UITextField! @IBOutlet weak var vendorThingID: UITextField! @IBOutlet weak var thingPassTextField: UITextField! @IBOutlet weak var thingIDTextField: UITextField! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } @IBAction func tapOnboardWithVendorThingID(sender: AnyObject) { if let vendorThingID = vendorThingID.text, thingPassword = thingPassTextField.text { showActivityView(true) self.iotAPI?.onboard(vendorThingID, thingPassword: thingPassword, thingType: thingTypeTextField.text, thingProperties: nil, completionHandler: { (target, error) -> Void in if target != nil { self.navigationController?.dismissViewControllerAnimated(true, completion: nil) self.showActivityView(false) }else { self.showAlert("Onboard Failed", error: error, completion: { () -> Void in self.showActivityView(false) }) } }) } } @IBAction func tapOnBoardWithThingID(sender: AnyObject) { if let thingID = thingIDTextField.text, thingPassword = thingPassTextField.text { showActivityView(true) self.iotAPI?.onboard(thingID, thingPassword: thingPassword, completionHandler: { (target, error) -> Void in if target != nil { self.navigationController?.dismissViewControllerAnimated(true, completion: nil) self.showActivityView(false) }else { self.showAlert("Onboard Failed", error: error, completion: { () -> Void in self.showActivityView(false) }) } }) } } }
mit
OscarSwanros/swift
test/SILGen/complete_object_init.swift
3
2082
// RUN: %target-swift-frontend %s -emit-silgen -enable-sil-ownership | %FileCheck %s struct X { } class A { // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick A.Type) -> @owned A // CHECK: bb0([[SELF_META:%[0-9]+]] : @trivial $@thick A.Type): // CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A // CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A // CHECK: return [[RESULT]] : $A // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : @owned $A): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var A } // CHECK: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var A } // CHECK: [[PB:%.*]] = project_box [[UNINIT_SELF]] // CHECK: store [[SELF_PARAM]] to [init] [[PB]] : $*A // CHECK: [[SELFP:%[0-9]+]] = load [take] [[PB]] : $*A // CHECK: [[BORROWED_SELFP:%.*]] = begin_borrow [[SELFP]] // CHECK: [[INIT:%[0-9]+]] = class_method [[BORROWED_SELFP]] : $A, #A.init!initializer.1 : (A.Type) -> (X) -> A, $@convention(method) (X, @owned A) -> @owned A // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A // CHECK: store [[INIT_RESULT]] to [init] [[PB]] : $*A // CHECK: [[RESULT:%[0-9]+]] = load [copy] [[PB]] : $*A // CHECK: destroy_value [[UNINIT_SELF]] : ${ var A } // CHECK: return [[RESULT]] : $A convenience init() { self.init(x: X()) } init(x: X) { } }
apache-2.0
OscarSwanros/swift
validation-test/Sema/type_checker_perf/slow/rdar18800950.swift
4
496
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: tools-release,no_asserts // Mixed Float and Double arithmetic func rdar18800950(v: Float) -> Double { let c1: Float = 1.0 let c2 = 2.0 let r = v / c1 let _ = (c2 * 2 * (3 * (1 - c1 / v) - 4) * r + 5) * (c2 * 2 * (3 * (1 - c1 / v) - 4) * r + 5) // expected-error@-1 {{expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions}} }
apache-2.0
nguyenantinhbk77/practice-swift
Views/ProgressBars/ProgressBar Example/ProgressBar Example/AppDelegate.swift
3
236
// // AppDelegate.swift // ProgressBar Example // // Created by Domenico Solazzo on 06/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
mit
LDlalala/LDZBLiving
LDZBLiving/LDZBLiving/Classes/Main/Protocal/Emitterable.swift
1
2225
// // Emitterable.swift // Emittering-粒子运动 // // Created by 李丹 on 17/8/11. // Copyright © 2017年 LD. All rights reserved. // import UIKit protocol Emitterable : class { } // MARK:- 添加协议方法,只要继承自这个协议,那么就可以实现协议 extension Emitterable where Self : UIViewController { // 给一个限制条件 func startEmittering(_ point : CGPoint) { // 创建发射器 let emitter = CAEmitterLayer() // 设置发射器位置 emitter.emitterPosition = point // 开启三维效果 emitter.preservesDepth = true // 创建粒子,并设置栗子相关属性 var cells = [CAEmitterCell]() for i in 0..<10 { let cell = CAEmitterCell() // 设置速度 cell.velocity = 150 cell.velocityRange = 100 // 设置栗子大小 cell.scale = 0.7 cell.scaleRange = 0.3 // 设置栗子方向c cell.emissionLatitude = CGFloat(-M_PI_2) cell.emissionRange = CGFloat(M_PI_2 / 6) // 设置栗子旋转 cell.spin = CGFloat(M_PI_2) cell.spinRange = CGFloat(M_PI_2 / 2) // 设置栗子每秒弹出的个数 cell.birthRate = 2 // 设置生命时间 cell.lifetime = 7 cell.lifetimeRange = 1.5 // 设置内容图片 cell.contents = UIImage(named: "good\(i)_30x30")?.cgImage cells.append(cell) } // 将栗子设置到发射器中 emitter.emitterCells = cells // 将发射器的layer添加到父类的layer中 view.layer.addSublayer(emitter) } func stopEmittering() { view.layer.sublayers?.filter({$0.isKind(of: CAEmitterLayer.self)}).first?.removeFromSuperlayer() /* for layer in view.layer.sublayers! { if layer.isKind(of: CAEmitterLayer.self) { layer.removeFromSuperlayer() } } */ } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/18462-no-stacktrace.swift
11
231
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSData { class A { let : { let f = [ { class case ,
mit
TMTBO/TTARefresher
TTARefresher/Classes/Footer/Auto/TTARefresherAutoStateFooter.swift
1
2093
// // TTARefresherAutoStateFooter.swift // Pods // // Created by TobyoTenma on 11/05/2017. // // import UIKit open class TTARefresherAutoStateFooter: TTARefresherAutoFooter { open lazy var stateLabel: UILabel = { let label = UILabel.TTARefresher.refresherLabel() self.addSubview(label) return label }() var stateTitles = [TTARefresherState: String]() var labelLeftInset = TTARefresherLabelConst.labelLeftInset open override var state: TTARefresherState { didSet { if state == oldValue { return } if stateLabel.isHidden && state == .refreshing { stateLabel.text = nil } else { stateLabel.text = stateTitles[state] } } } } // MARK: - Public Method extension TTARefresherAutoStateFooter { public func set(title: String, for state: TTARefresherState) { stateTitles[state] = title stateLabel.text = stateTitles[self.state] } } // MARK: - Private Methods extension TTARefresherAutoStateFooter { func didClickStateLabel() { guard state == .idle else { return } beginRefreshing() } } // MARK: - Override Methods extension TTARefresherAutoStateFooter { override open func prepare() { super.prepare() labelLeftInset = TTARefresherLabelConst.labelLeftInset set(title: Bundle.TTARefresher.localizedString(for: TTARefresherAutoFooterText.idle), for: .idle) set(title: Bundle.TTARefresher.localizedString(for: TTARefresherAutoFooterText.refreshing), for: .refreshing) set(title: Bundle.TTARefresher.localizedString(for: TTARefresherAutoFooterText.noMoreData), for: .noMoreData) stateLabel.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(didClickStateLabel)) stateLabel.addGestureRecognizer(tap) } override open func placeSubviews() { super.placeSubviews() if stateLabel.constraints.count != 0 { return } stateLabel.frame = bounds } }
mit
jwfriese/FrequentFlyer
FrequentFlyerTests/HTTP/HTTPResponseImplSpec.swift
1
1326
import XCTest import Quick import Nimble @testable import FrequentFlyer class HTTPResponseImplSpec: QuickSpec { override func spec() { describe("HTTPResponseImpl") { describe("isSuccess") { context("When 200-type status code") { it("returns true") { expect(HTTPResponseImpl(body: nil, statusCode: 200).isSuccess).to(beTrue()) expect(HTTPResponseImpl(body: nil, statusCode: 201).isSuccess).to(beTrue()) expect(HTTPResponseImpl(body: nil, statusCode: 210).isSuccess).to(beTrue()) expect(HTTPResponseImpl(body: nil, statusCode: 299).isSuccess).to(beTrue()) } } context("When any other status code") { it("returns false") { expect(HTTPResponseImpl(body: nil, statusCode: 100).isSuccess).to(beFalse()) expect(HTTPResponseImpl(body: nil, statusCode: 300).isSuccess).to(beFalse()) expect(HTTPResponseImpl(body: nil, statusCode: 400).isSuccess).to(beFalse()) expect(HTTPResponseImpl(body: nil, statusCode: 500).isSuccess).to(beFalse()) } } } } } }
apache-2.0
CoderAzreal/AZQrCodeScanController
AZQrCodeScanController/AZQrCodeScanController-Swift/AZSwiftQrCodeScanView.swift
1
4565
// // AZSwiftQrCodeScanView.swift // AZQrCodeScanController // // Created by tianfengyu on 2017/6/13. // Copyright © 2017年 Azreal. All rights reserved. // import UIKit class AZSwiftQrCodeScanView: UIView { var topCoverView = UIView() var leftCoverView = UIView() var rightCoverView = UIView() var bottomCoverView = UIView() fileprivate var scanFrame: CGRect! var scanImageView: UIImageView! // 扫码框 var scanLine: UIImageView! // 扫码线 var introduceLabel: UILabel! // 提示文字label enum AZTimerState { case move case stop } /// 扫码线移动方向 private enum LineMoveDirect { case up case down } var timer: DispatchSourceTimer! var timerState = AZTimerState.move private var lineDirection = LineMoveDirect.down convenience init(scanFrame: CGRect) { self.init(frame: CGRect(x: 0, y: 0, width: AZ_screenWidth, height: AZ_screenHeight)) configCoverView() self.scanFrame = scanFrame resetCoverViewFrame() configScanUI() configTimer() } /// 扫码线移动 private func configTimer() { timer = DispatchSource.makeTimerSource(flags: .strict, queue: .main) timer.scheduleRepeating(deadline: .now(), interval: .milliseconds(10)) weak var wkSelf = self timer.setEventHandler { var lineFrame = wkSelf!.scanLine.frame switch wkSelf!.timerState { case .move: switch wkSelf!.lineDirection { case .up: lineFrame.origin.y -= 1 case .down: lineFrame.origin.y += 1 } case .stop: lineFrame.origin.y = wkSelf!.scanFrame.origin.y } wkSelf?.scanLine.frame = lineFrame if lineFrame.origin.y >= wkSelf!.scanFrame.origin.y + wkSelf!.scanFrame.width - lineFrame.size.height { wkSelf!.lineDirection = .up } else if lineFrame.origin.y <= wkSelf!.scanFrame.origin.y { wkSelf!.lineDirection = .down } } timer.resume() } /// 扫码框/扫码线/介绍文字 private func configScanUI() { let bundlePath = Bundle(for: classForCoder).path(forResource: "AZQrCode", ofType: "bundle")! let captureBundle = Bundle(path: bundlePath)! scanImageView = UIImageView(frame: scanFrame) let bgPath = captureBundle.path(forResource: "scan_bg_pic@2x", ofType: "png")! scanImageView.image = UIImage(contentsOfFile: bgPath) addSubview(scanImageView) scanLine = UIImageView(frame: CGRect(x: scanFrame.origin.x, y: scanFrame.origin.y , width: scanFrame.width, height: 2)) let linePath = captureBundle.path(forResource: "scan_line@2x", ofType: "png")! scanLine.image = UIImage(contentsOfFile: linePath) addSubview(scanLine) introduceLabel = UILabel(frame: CGRect(x: scanFrame.origin.x, y: scanFrame.origin.y+scanFrame.size.height+20, width: scanFrame.width, height: 40)) introduceLabel.numberOfLines = 0 introduceLabel.textAlignment = .center introduceLabel.text = "将二维码/条码放入框内,即可自动扫描。" introduceLabel.textColor = .white introduceLabel.font = UIFont.systemFont(ofSize: 14) addSubview(introduceLabel) } /// 配置coverView private func configCoverView() { for item in [topCoverView, leftCoverView, bottomCoverView, rightCoverView] { item.backgroundColor = UIColor(white: 0, alpha: 0.4) addSubview(item) } } /// 设置遮罩层位置 private func resetCoverViewFrame() { leftCoverView.frame = CGRect(x: 0, y: 0, width: scanFrame.origin.x, height: AZ_screenHeight) topCoverView.frame = CGRect(x: scanFrame.origin.x, y: 0, width: AZ_screenWidth, height: scanFrame.origin.y) rightCoverView.frame = CGRect(x: scanFrame.origin.x, y: scanFrame.height+scanFrame.origin.y, width: AZ_screenWidth, height: AZ_screenHeight) bottomCoverView.frame = CGRect(x: scanFrame.width+scanFrame.origin.x, y: scanFrame.origin.y, width: AZ_screenWidth, height: scanFrame.height) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
taku33/FolioReaderPlus
Source/EPUBCore/FRHighlight.swift
1
6934
// // FRHighlight.swift // FolioReaderKit // // Created by Heberti Almeida on 26/08/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit enum HighlightStyle: Int { case Yellow case Green case Blue case Pink case Underline init () { self = .Yellow } /** Return HighlightStyle for CSS class. */ static func styleForClass(className: String) -> HighlightStyle { switch className { case "highlight-yellow": return .Yellow case "highlight-green": return .Green case "highlight-blue": return .Blue case "highlight-pink": return .Pink case "highlight-underline": return .Underline default: return .Yellow } } /** Return CSS class for HighlightStyle. */ static func classForStyle(style: Int) -> String { switch style { case HighlightStyle.Yellow.rawValue: return "highlight-yellow" case HighlightStyle.Green.rawValue: return "highlight-green" case HighlightStyle.Blue.rawValue: return "highlight-blue" case HighlightStyle.Pink.rawValue: return "highlight-pink" case HighlightStyle.Underline.rawValue: return "highlight-underline" default: return "highlight-yellow" } } /** Return CSS class for HighlightStyle. */ static func colorForStyle(style: Int, nightMode: Bool = false) -> UIColor { switch style { case HighlightStyle.Yellow.rawValue: return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.Green.rawValue: return UIColor(red: 192/255, green: 237/255, blue: 114/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.Blue.rawValue: return UIColor(red: 173/255, green: 216/255, blue: 255/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.Pink.rawValue: return UIColor(red: 255/255, green: 176/255, blue: 202/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.Underline.rawValue: return UIColor(red: 240/255, green: 40/255, blue: 20/255, alpha: nightMode ? 0.6 : 1) default: return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1) } } } class FRHighlight: NSObject { var id: String! var content: String! var contentPre: String! var contentPost: String! var date: NSDate! var page: NSNumber! var bookId: String! var type: HighlightStyle! /** Match a highlight on string. */ static func matchHighlight(text: String!, andId id: String) -> FRHighlight? { let pattern = "<highlight id=\"\(id)\" onclick=\".*?\" class=\"(.*?)\">((.|\\s)*?)</highlight>" let regex = try! NSRegularExpression(pattern: pattern, options: []) let matches = regex.matchesInString(text, options: [], range: NSRange(location: 0, length: text.utf16.count)) let str = (text as NSString) print("patternは\(pattern)") print("regexは\(regex)") print("matchesは\(matches)") print("strは\(str)") let mapped = matches.map { (match) -> FRHighlight in print("matchは\(match)") var contentPre = str.substringWithRange(NSRange(location: match.range.location-kHighlightRange, length: kHighlightRange)) var contentPost = str.substringWithRange(NSRange(location: match.range.location + match.range.length, length: kHighlightRange)) // Normalize string before save if contentPre.rangeOfString(">") != nil { let regex = try! NSRegularExpression(pattern: "((?=[^>]*$)(.|\\s)*$)", options: []) let searchString = regex.firstMatchInString(contentPre, options: .ReportProgress, range: NSRange(location: 0, length: contentPre.characters.count)) if searchString!.range.location != NSNotFound { contentPre = (contentPre as NSString).substringWithRange(searchString!.range) } } if contentPost.rangeOfString("<") != nil { let regex = try! NSRegularExpression(pattern: "^((.|\\s)*?)(?=<)", options: []) let searchString = regex.firstMatchInString(contentPost, options: .ReportProgress, range: NSRange(location: 0, length: contentPost.characters.count)) if searchString!.range.location != NSNotFound { contentPost = (contentPost as NSString).substringWithRange(searchString!.range) } } let highlight = FRHighlight() highlight.id = id //ランダム文字列 highlight.type = HighlightStyle.styleForClass(str.substringWithRange(match.rangeAtIndex(1))) highlight.content = str.substringWithRange(match.rangeAtIndex(2)) print("contentは\(highlight.content)") print("contentPreは\(contentPre)") print("contentPostは\(contentPost)") highlight.contentPre = contentPre highlight.contentPost = contentPost highlight.page = currentPageNumber highlight.bookId = (kBookId as NSString).stringByDeletingPathExtension return highlight } return mapped.first } static func makeBookMarkFRHighlight(id: String) -> FRHighlight? { let highlight = FRHighlight() highlight.id = id //ランダム文字列 highlight.contentPre = FolioReader.sharedInstance.readerCenter.getCurrentChapterName() //これらは章単位でなくページ単位 let currentPage = FolioReader.sharedInstance.readerCenter.pageIndicatorView.currentPage let currentTotalPages = FolioReader.sharedInstance.readerCenter.pageIndicatorView.totalPages highlight.content = "\(currentPage)/\(currentTotalPages)" //4/24など highlight.contentPost = "\(currentPage)/\(currentTotalPages)" //初めて保存する場合なのでcontentと同じ highlight.page = currentPageNumber highlight.bookId = (kBookId as NSString).stringByDeletingPathExtension return highlight } static func removeById(highlightId: String) -> String? { let currentPage = FolioReader.sharedInstance.readerCenter.currentPage if let removedId = currentPage.webView.js("removeHighlightById('\(highlightId)')") { return removedId } else { print("Error removing Higlight from page") return nil } } }
bsd-3-clause
mr-ndrw/PulsingButtons
Pulsing Buttons/PulsingButtonsViewController.swift
1
3753
// // PulsingButtonsViewController.swift // Pulsing Buttons // // Created by Andrew Torski on 24/06/15. // Copyright (c) 2015 Andrew Torski. All rights reserved. // import UIKit class PulsingButtonsViewController: UIViewController { var pulsingButtons2DArray : [[PulsingButtonView]] = [] /// Number of buttons in a row. var numberOfButtonsInRow : Int = 9 /// Number of buttons in a column. var numberOfButtonsInColumn : Int = 4 override func viewDidLoad() { super.viewDidLoad() var pointsMatrix : [CGPoint] = getPointArray( numberOfRows: numberOfButtonsInRow, numberOfColumns: numberOfButtonsInColumn, screenMargin: CGFloat(40.0)) for point in pointsMatrix { var frame = CGRect(center: point, size: CGSize(width: 40.0, height: 40.0)) var currentColor = UIColor(redInt: 255, greenInt: 209, blueInt: 220, alpha: 1.0) var pulsingButton : PulsingButtonView = PulsingButtonView(frame: frame, currentColor: currentColor) self.view.addSubview(pulsingButton) } // Do any additional setup after loading the view. } func getPointArray(#numberOfRows: Int, numberOfColumns: Int, screenMargin: CGFloat) -> [CGPoint]{ // 2. find extremeCornerPoint1 by taking width and height and adding screenMargin to them var extremePointUpperLeftCorner : CGPoint = CGPoint(x: screenMargin, y: screenMargin) // 3. get deMarginalizedHeight by subtracting 2*screenMargin // get deMarginalizedWidth by subtracting let screenHeight : CGFloat = self.view.bounds.height let screenWidth : CGFloat = self.view.bounds.width let demarginalizedHeight : CGFloat = screenHeight - (2 * screenMargin) let demarginalizedWidth : CGFloat = screenWidth - (2 * screenMargin) // 4. get pointXDifference by dividing demarginalizedHeight by numberOfRows - 1 // get pointYDifference by diding demarginalizedWidth by numberOfColumns - 1 /* We're subtracting */ let pointXDifference : CGFloat = demarginalizedWidth / CGFloat(numberOfColumns - 1) let pointYDifference : CGFloat = demarginalizedHeight / CGFloat(numberOfRows - 1) // 5. create an array of points var pointArray : [CGPoint] = [] // 6. populate the array var currentX : CGFloat = extremePointUpperLeftCorner.x var currentY : CGFloat = extremePointUpperLeftCorner.y for rowNumber in 0..<numberOfRows { for columnNumber in 0..<numberOfColumns { var newPoint : CGPoint = CGPoint(x: currentX, y: currentY) pointArray.append(newPoint) currentX += pointXDifference } // default currentX, since we're changing rows and going back to left edge currentX = extremePointUpperLeftCorner.x currentY += pointYDifference } return pointArray } func UIColorFromRGB(rgb: Int, alpha: Float) -> UIColor { let red = CGFloat(Float(((rgb>>16) & 0xFF)) / 255.0) let green = CGFloat(Float(((rgb>>8) & 0xFF)) / 255.0) let blue = CGFloat(Float(((rgb>>0) & 0xFF)) / 255.0) let alpha = CGFloat(alpha) return UIColor(red: red, green: green, blue: blue, alpha: alpha) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
qRoC/Loobee
Sources/Loobee/Library/AssertionConcern/Assertion/GreaterThanAssertions.swift
1
2084
// This file is part of the Loobee package. // // (c) Andrey Savitsky <contact@qroc.pro> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. /// The default message in notifications from `greaterThan` assertions. @usableFromInline internal let kGreaterThanDefaultMessage: StaticString = """ The value is not greater than boundary value. """ /// Determines if the `value` is greater than given limit value. @inlinable public func assert<T: Comparable>( _ value: T, greaterThan boundaryValue: T, orNotification message: @autoclosure () -> String? = nil, file: StaticString = #file, line: UInt = #line ) -> AssertionNotification? { if _slowPath(value <= boundaryValue) { return .create( message: message() ?? kGreaterThanDefaultMessage.description, file: file, line: line ) } return nil } /// Determines if the `value` is greater than given limit value. @inlinable public func assert<T1: BinaryInteger, T2: BinaryInteger>( _ value: T1, greaterThan boundaryValue: T2, orNotification message: @autoclosure () -> String? = nil, file: StaticString = #file, line: UInt = #line ) -> AssertionNotification? { if _slowPath(value <= boundaryValue) { return .create( message: message() ?? kGreaterThanDefaultMessage.description, file: file, line: line ) } return nil } /// Determines if the `value` is greater than given limit value. /// /// - Note: This is ambiguity breaker. @inlinable public func assert<T: BinaryInteger>( _ value: T, greaterThan boundaryValue: T, orNotification message: @autoclosure () -> String? = nil, file: StaticString = #file, line: UInt = #line ) -> AssertionNotification? { if _slowPath(value <= boundaryValue) { return .create( message: message() ?? kGreaterThanDefaultMessage.description, file: file, line: line ) } return nil }
mit
serieuxchat/SwiftySRP
SwiftySRP/SRPConfigurationGenericImpl.swift
1
5337
// // SRPConfigurationGenericImpl.swift // SwiftySRP // // Created by Sergey A. Novitsky on 17/03/2017. // Copyright © 2017 Flock of Files. All rights reserved. // // 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 /// Implementation: configuration for SRP algorithms (see the spec. above for more information about the meaning of parameters). struct SRPConfigurationGenericImpl<BigIntType: SRPBigIntProtocol>: SRPConfiguration { typealias PrivateValueFunc = () -> BigIntType /// A large safe prime per SRP spec. (Also see: https://tools.ietf.org/html/rfc5054#appendix-A) public var modulus: Data { return _N.serialize() } /// A generator modulo N. (Also see: https://tools.ietf.org/html/rfc5054#appendix-A) public var generator: Data { return _g.serialize() } /// A large safe prime per SRP spec. let _N: BigIntType /// A generator modulo N let _g: BigIntType /// Hash function to be used. let digest: DigestFunc /// Function to calculate HMAC let hmac: HMacFunc /// Custom function to generate 'a' let _aFunc: PrivateValueFunc? /// Custom function to generate 'b' let _bFunc: PrivateValueFunc? /// Create a configuration with the given parameters. /// /// - Parameters: /// - N: The modulus (large safe prime) (per SRP spec.) /// - g: The group generator (per SRP spec.) /// - digest: Hash function to be used in intermediate calculations and to derive a single shared key from the shared secret. /// - hmac: HMAC function to be used when deriving multiple shared keys from a single shared secret. /// - aFunc: (ONLY for testing purposes) Custom function to generate the client private value. /// - bFunc: (ONLY for testing purposes) Custom function to generate the server private value. init(N: BigIntType, g: BigIntType, digest: @escaping DigestFunc = CryptoAlgorithm.SHA256.digestFunc(), hmac: @escaping HMacFunc = CryptoAlgorithm.SHA256.hmacFunc(), aFunc: PrivateValueFunc?, bFunc: PrivateValueFunc?) { _N = BigIntType(N) _g = BigIntType(g) self.digest = digest self.hmac = hmac _aFunc = aFunc _bFunc = bFunc } /// Check if configuration is valid. /// Currently only requires the size of the prime to be >= 256 and the g to be greater than 1. /// - Throws: SRPError if invalid. func validate() throws { guard _N.bitWidth >= 256 else { throw SRPError.configurationPrimeTooShort } guard _g > BigIntType(1) else { throw SRPError.configurationGeneratorInvalid } } /// Generate a random private value less than the given value N and at least half the bit size of N /// /// - Parameter N: The value determining the range of the random value to generate. /// - Returns: Randomly generate value. public static func generatePrivateValue(N: BigIntType) -> BigIntType { // Suppose that N is 8 bits wide // Then min bits == 4 let minBits = N.bitWidth / 2 guard minBits > 0 else { return BigIntType.randomInteger(lessThan: BigIntType(2)) } // Smallest number with 4 bits is 2^(4-1) = 8 let minBitsNumber = BigIntType(2).power(minBits - 1) let random = minBitsNumber + BigIntType.randomInteger(lessThan: N - minBitsNumber) return random } /// Function to calculate parameter a (per SRP spec above) func _a() -> BigIntType { if let aFunc = _aFunc { return aFunc() } return type(of: self).generatePrivateValue(N: _N) } /// Function to calculate parameter a (per SRP spec above) func clientPrivateValue() -> Data { return _a().serialize() } /// Function to calculate parameter b (per SRP spec above) func _b() -> BigIntType { if let bFunc = _bFunc { return bFunc() } return type(of: self).generatePrivateValue(N: _N) } /// Function to calculate parameter b (per SRP spec above) func serverPrivateValue() -> Data { return _b().serialize() } }
mit
ivanbruel/SwipeIt
SwipeIt/ViewModels/Link/LinkSwipeViewModel.swift
1
5440
// // SubredditLinkListViewModel.swift // Reddit // // Created by Ivan Bruel on 09/05/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import Foundation import RxSwift // MARK: Properties and initializer class LinkSwipeViewModel { // MARK: Private Properties private let _title: String private let path: String private let subredditOnly: Bool private let user: User private let accessToken: AccessToken private let linkListings: Variable<[LinkListing]> = Variable([]) private let _viewModels: Variable<[LinkItemViewModel]> = Variable([]) private let _listingType: Variable<ListingType> = Variable(.Hot) private var disposeBag = DisposeBag() private let _loadingState = Variable<LoadingState>(.Normal) // MARK: Initializer init(user: User, accessToken: AccessToken, title: String, path: String, subredditOnly: Bool) { self.user = user self.accessToken = accessToken self._title = title self.path = path self.subredditOnly = subredditOnly } convenience init(user: User, accessToken: AccessToken, subreddit: Subreddit) { self.init(user: user, accessToken: accessToken, title: subreddit.displayName, path: subreddit.path, subredditOnly: true) } convenience init(user: User, accessToken: AccessToken, multireddit: Multireddit) { self.init(user: user, accessToken: accessToken, title: multireddit.name, path: multireddit.path, subredditOnly: false) } } // MARK: Private Observables extension LinkSwipeViewModel { private var userObservable: Observable<User> { return .just(user) } private var accessTokenObservable: Observable<AccessToken> { return .just(accessToken) } private var afterObservable: Observable<String?> { return linkListings.asObservable() .map { $0.last?.after } } private var listingTypeObservable: Observable<ListingType> { return _listingType.asObservable() } private var pathObservable: Observable<String> { return .just(path) } private var subredditOnlyObservable: Observable<Bool> { return .just(subredditOnly) } private var request: Observable<LinkListing> { return Observable .combineLatest(listingTypeObservable, afterObservable, accessTokenObservable, pathObservable) { ($0, $1, $2, $3) } .take(1) .doOnNext { [weak self] _ in self?._loadingState.value = .Loading }.flatMap { (listingType: ListingType, after: String?, accessToken: AccessToken, path: String) in Network.request(RedditAPI.LinkListing(token: accessToken.token, path: path, listingPath: listingType.path, listingTypeRange: listingType.range?.rawValue, after: after)) }.observeOn(SerialDispatchQueueScheduler(globalConcurrentQueueQOS: .Background)) .mapObject(LinkListing) .observeOn(MainScheduler.instance) } } // MARK: Public API extension LinkSwipeViewModel { var viewModels: Observable<[LinkItemViewModel]> { return _viewModels.asObservable() } var loadingState: Observable<LoadingState> { return _loadingState.asObservable() } var listingTypeName: Observable<String> { return _listingType.asObservable() .map { $0.name } } func viewModelForIndex(index: Int) -> LinkItemViewModel? { return _viewModels.value.get(index) } func requestLinks() { guard _loadingState.value != .Loading else { return } Observable .combineLatest(request, userObservable, accessTokenObservable, subredditOnlyObservable) { ($0, $1, $2, $3) }.take(1) .subscribe { [weak self] event in guard let `self` = self else { return } switch event { case let .Next(linkListing, user, accessToken, subredditOnly): self.linkListings.value.append(linkListing) let viewModels = LinkSwipeViewModel.viewModelsFromLinkListing(linkListing, user: user, accessToken: accessToken, subredditOnly: subredditOnly) viewModels.forEach { $0.preloadData() } self._loadingState.value = self._viewModels.value.count > 0 ? .Normal : .Empty self._viewModels.value += viewModels if viewModels.count <= 4 { self.requestLinks() } case .Error: self._loadingState.value = .Error default: break } }.addDisposableTo(disposeBag) } func setListingType(listingType: ListingType) { guard listingType != _listingType.value else { return } _listingType.value = listingType refresh() } func refresh() { linkListings.value = [] _viewModels.value = [] disposeBag = DisposeBag() _loadingState.value = .Normal requestLinks() } } // MARK: Helpers extension LinkSwipeViewModel { private static func viewModelsFromLinkListing(linkListing: LinkListing, user: User, accessToken: AccessToken, subredditOnly: Bool) -> [LinkItemViewModel] { return linkListing.links .filter { !$0.stickied } .filter { !Globals.hideVotedPosts || $0.vote == .None } .filter { $0.type == .Image || $0.type == .GIF } .map { LinkItemViewModel.viewModelFromLink($0, user: user, accessToken: accessToken, subredditOnly: subredditOnly) } } } // MARK: TitledViewModel extension LinkSwipeViewModel: TitledViewModel { var title: Observable<String> { return .just(_title) } }
mit
manuelbl/WirekiteMac
Examples/Nunchuck/Nunchuck/AppDelegate.swift
1
512
// // AppDelegate.swift // Nunchuck // // Created by Manuel Bleichenbacher on 12.09.17. // Copyright © 2017 Codecrete. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
mit
rmclea21/Flappy-Santa
FlappyBird/Resources/SKTUtils/SKTAudio.swift
15
2871
/* * Copyright (c) 2013-2014 Razeware LLC * * 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 AVFoundation /** * Audio player that uses AVFoundation to play looping background music and * short sound effects. For when using SKActions just isn't good enough. */ public class SKTAudio { public var backgroundMusicPlayer: AVAudioPlayer? public var soundEffectPlayer: AVAudioPlayer? public class func sharedInstance() -> SKTAudio { return SKTAudioInstance } public func playBackgroundMusic(filename: String) { let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil) if (url == nil) { print("Could not find file: \(filename)") return } //var error: NSError? = nil backgroundMusicPlayer = try? AVAudioPlayer(contentsOfURL: url!) if let player = backgroundMusicPlayer { player.numberOfLoops = -1 player.prepareToPlay() player.play() } else { //print("Could not create audio player: \(error!)") } } public func pauseBackgroundMusic() { if let player = backgroundMusicPlayer { if player.playing { player.pause() } } } public func resumeBackgroundMusic() { if let player = backgroundMusicPlayer { if !player.playing { player.play() } } } public func playSoundEffect(filename: String) { let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil) if (url == nil) { print("Could not find file: \(filename)") return } soundEffectPlayer = try? AVAudioPlayer(contentsOfURL: url!) if let player = soundEffectPlayer { player.numberOfLoops = 0 player.prepareToPlay() player.play() } else { print("Could not create audio player: error") } } } private let SKTAudioInstance = SKTAudio()
mit
yonaskolb/SwagGen
Specs/Petstore/generated/Swift/Sources/Requests/Pets/ListPets.swift
1
4126
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension Petstore.Pets { /** List all pets */ public enum ListPets { public static let service = APIService<Response>(id: "listPets", tag: "pets", method: "GET", path: "/pets", hasBody: false, securityRequirements: []) public final class Request: APIRequest<Response> { public struct Options { /** How many items to return at one time (max 100) */ public var limit: Int? public init(limit: Int? = nil) { self.limit = limit } } public var options: Options public init(options: Options) { self.options = options super.init(service: ListPets.service) } /// convenience initialiser so an Option doesn't have to be created public convenience init(limit: Int? = nil) { let options = Options(limit: limit) self.init(options: options) } public override var queryParameters: [String: Any] { var params: [String: Any] = [:] if let limit = options.limit { params["limit"] = limit } return params } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = [Pet] /** An array of pets */ case status200([Pet]) /** unexpected error */ case defaultResponse(statusCode: Int, ErrorType) public var success: [Pet]? { switch self { case .status200(let response): return response default: return nil } } public var failure: ErrorType? { switch self { case .defaultResponse(_, let response): return response default: return nil } } /// either success or failure value. Success is anything in the 200..<300 status code range public var responseResult: APIResponseResult<[Pet], ErrorType> { if let successValue = success { return .success(successValue) } else if let failureValue = failure { return .failure(failureValue) } else { fatalError("Response does not have success or failure response") } } public var response: Any { switch self { case .status200(let response): return response case .defaultResponse(_, let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 case .defaultResponse(let statusCode, _): return statusCode } } public var successful: Bool { switch self { case .status200: return true case .defaultResponse: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode([Pet].self, from: data)) default: self = try .defaultResponse(statusCode: statusCode, decoder.decode(ErrorType.self, from: data)) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
mit
kingcos/CS193P_2017
Calculator/Calculator/AppDelegate.swift
1
2167
// // AppDelegate.swift // Calculator // // Created by 买明 on 15/02/2017. // Copyright © 2017 买明. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 invalidate graphics rendering callbacks. 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 active 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:. } }
mit
weareopensource/Sample-iOS_Swift_GetStarted
StepOne/APIController.swift
2
3305
// // ViewController.swift // StepOne // // Created by WeAreOpenSource.me on 24/04/2015. // Copyright (c) 2015 WeAreOpenSource.me rights reserved. // // tuto : http://jamesonquave.com/blog/developing-ios-8-apps-using-swift-animations-audio-and-custom-table-view-cells/ import Foundation /**************************************************************************************************/ // Protocol /**************************************************************************************************/ protocol APIControllerProtocol { func didReceiveAPIResults(results: NSArray) } /**************************************************************************************************/ // Class /**************************************************************************************************/ class APIController { /*************************************************/ // Main /*************************************************/ // Var /*************************/ var delegate: APIControllerProtocol // init /*************************/ init(delegate: APIControllerProtocol) { self.delegate = delegate } /*************************************************/ // Functions /*************************************************/ func get(path: String) { let url = NSURL(string: path) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in println("Task completed") if(error != nil) { // If there is an error in the web request, print it to the console println(error.localizedDescription) } var err: NSError? if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary { if(err != nil) { // If there is an error parsing JSON, print it to the console println("JSON Error \(err!.localizedDescription)") } if let results: NSArray = jsonResult["results"] as? NSArray { self.delegate.didReceiveAPIResults(results) } } }) // The task is just an object with all these properties set // In order to actually make the web request, we need to "resume" task.resume() } func searchItunesFor(searchTerm: String) { // The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) // Now escape anything else that isn't URL-friendly if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album" get(urlPath) } } func lookupAlbum(collectionId: Int) { get("https://itunes.apple.com/lookup?id=\(collectionId)&entity=song") } }
mit
hgani/ganiweb-ios
ganiweb/Classes/HtmlForm/GHtmlFormScreen.swift
1
3965
import Eureka import GaniLib open class GHtmlFormScreen: GFormScreen { public private(set) var htmlForm: HtmlForm! private var section: Section! // lazy fileprivate var refresher: GRefreshControl = { // return GRefreshControl().onValueChanged { // self.onRefresh() // } // }() private var autoRefresh = false // This is especially important for detecting if the user is still logged in everytime the form screen // is opened. public func refreshOnAppear() -> Self { self.autoRefresh = true return self } open override func viewDidLoad() { super.viewDidLoad() _ = self.leftBarButton(item: GBarButtonItem() .title("Cancel") .onClick { self.launch.confirm("Changes will be discarded. Are you sure?", title: nil, handler: { // https://stackoverflow.com/questions/39576314/dealloc-a-viewcontroller-warning DispatchQueue.main.async { _ = self.nav.pop() } }) }) // appendRefreshControl() setupForm() } open override func viewWillAppear(_ animated: Bool) { if autoRefresh { onRefresh() } super.viewWillAppear(animated) } private func setupForm() { //self.tableView?.contentInset = UIEdgeInsetsMake(-16, 0, -16, 0) // Eureka-specific requirements self.section = Section() form += [section] setupHeader(height: 0) { _ in // This is just to remove the gap at the top } self.htmlForm = HtmlForm(form: form, onSubmitSucceeded: { result in if self.onSubmitted(result: result) { // TODO: Ideally we should only reset the values, not remove the fields. self.form.allSections.last?.removeAll() } else { if let message = result["message"].string { self.indicator.show(error: message) } else if let message = result["error"].string { // Devise uses "error" key self.indicator.show(error: message) } } }) } // // private func appendRefreshControl() { // tableView?.addSubview(refresher) // // // Eureka-specific requirements // refresher.snp.makeConstraints { (make) -> Void in // make.top.equalTo(4) // make.centerX.equalTo(tableView!) // } // } private func setupHeaderFooter(height: Int, populate: @escaping (GHeaderFooterView) -> Void) -> HeaderFooterView<GHeaderFooterView> { var headerFooter = HeaderFooterView<GHeaderFooterView>(.class) headerFooter.height = { self.htmlForm.rendered ? CGFloat(height) : 0 } headerFooter.onSetupView = { view, section in view.paddings(t: 15, l: 20, b: 15, r: 20).clearViews() populate(view) } return headerFooter } public func setupHeader(height: Int, populate: @escaping (GHeaderFooterView) -> Void) { section.header = setupHeaderFooter(height: height, populate: populate) } public func setupFooter(height: Int, populate: @escaping (GHeaderFooterView) -> Void) { section.footer = setupHeaderFooter(height: height, populate: populate) } public func loadForm(path: String) { htmlForm.load(path, indicator: refresher, onSuccess: { // Allow subclass to populate header/footer, i.e. when htmlForm has been rendered. // E.g. `if !self.htmlForm.rendered { return }` self.section.reload() self.onLoaded() }) } open func onLoaded() { // To be overidden } open func onSubmitted(result: Json) -> Bool { // To be overidden return true } }
mit
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/Preferences/Notifications/NotificationsPreferencesViewController.swift
1
4555
// // NotificationsPreferencesViewController.swift // Rocket.Chat // // Created by Artur Rymarz on 05.03.2018. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit final class NotificationsPreferencesViewController: BaseTableViewController { private let viewModel = NotificationsPreferencesViewModel() var subscription: Subscription? { didSet { guard let subscription = subscription else { return } viewModel.currentPreferences = NotificationPreferences( desktopNotifications: subscription.desktopNotifications, disableNotifications: subscription.disableNotifications, emailNotifications: subscription.emailNotifications, audioNotificationValue: subscription.audioNotificationValue, desktopNotificationDuration: subscription.desktopNotificationDuration, audioNotifications: subscription.audioNotifications, hideUnreadStatus: subscription.hideUnreadStatus, mobilePushNotifications: subscription.mobilePushNotifications ) } } override func viewDidLoad() { super.viewDidLoad() title = viewModel.title viewModel.enableModel.value.bind { [unowned self] _ in let updates = self.viewModel.tableUpdatesAfterStateChange() DispatchQueue.main.async { self.tableView.beginUpdates() self.tableView.insertSections(updates.insertions, with: .fade) self.tableView.deleteSections(updates.deletions, with: .fade) self.tableView.endUpdates() } } viewModel.isSaveButtonEnabled.bindAndFire { enabled in DispatchQueue.main.async { self.navigationItem.rightBarButtonItem?.isEnabled = enabled } } viewModel.updateModel(subscription: subscription) navigationItem.rightBarButtonItem = UIBarButtonItem(title: viewModel.saveButtonTitle, style: .done, target: self, action: #selector(saveSettings)) } @objc private func saveSettings() { guard let subscription = subscription else { Alert(key: "alert.update_notifications_preferences_save_error").present() return } let saveNotificationsRequest = SaveNotificationRequest(rid: subscription.rid, notificationPreferences: viewModel.notificationPreferences) API.current()?.fetch(saveNotificationsRequest) { [weak self] response in guard let self = self else { return } switch response { case .resource: self.viewModel.updateCurrentPreferences() self.alertSuccess(title: self.viewModel.saveSuccessTitle) case .error: Alert(key: "alert.update_notifications_preferences_save_error").present() } } } } extension NotificationsPreferencesViewController { override func numberOfSections(in tableView: UITableView) -> Int { return viewModel.numberOfSections() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfRows(in: section) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return viewModel.titleForHeader(in: section) } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return viewModel.titleForFooter(in: section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let settingModel = viewModel.settingModel(for: indexPath) let cell = tableView.dequeueReusableCell(withIdentifier: settingModel.type.rawValue, for: indexPath) return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let settingModel = viewModel.settingModel(for: indexPath) guard var cell = cell as? NotificationsCellProtocol else { fatalError("Could not dequeue reusable cell with type \(settingModel.type.rawValue)") } cell.cellModel = settingModel } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.beginUpdates() viewModel.openPicker(for: indexPath) tableView.endUpdates() } }
mit
emilstahl/swift
validation-test/compiler_crashers_fixed/2031-llvm-foldingset-swift-boundgenerictype-nodeequals.swift
13
390
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class func e() -> { (i: e? { func b, a() -> Self { } return z: c: a { let f : e: a { } } } protocol C { } protocol a { protocol B { for () { } } } protocol P { func b<T : b :
apache-2.0
RocketChat/Rocket.Chat.iOS
Rocket.ChatTests/API/MockAPI.swift
1
802
// // MockAPI.swift // Rocket.ChatTests // // Created by Matheus Cardoso on 11/28/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import SwiftyJSON @testable import Rocket_Chat class MockAPI: APIFetcher { var nextResult: JSON? var nextError: APIError? @discardableResult func fetch<R: APIRequest>(_ request: R, options: APIRequestOptionSet, sessionDelegate: URLSessionTaskDelegate?, completion: ((_ result: APIResponse<R.APIResourceType>) -> Void)?) -> URLSessionTask? { if let nextResult = nextResult { completion?(.resource(R.APIResourceType(raw: nextResult))) } if let nextError = nextError { completion?(.error(nextError)) } nextResult = nil nextError = nil return nil } }
mit
darrinhenein/firefox-ios
Client/Frontend/Reader/ReaderMode.swift
1
13046
/* 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 WebKit let ReaderModeProfileKeyStyle = "readermode.style" enum ReaderModeMessageType: String { case StateChange = "ReaderModeStateChange" case PageEvent = "ReaderPageEvent" } enum ReaderPageEvent: String { case PageShow = "PageShow" } enum ReaderModeState: String { case Available = "Available" case Unavailable = "Unavailable" case Active = "Active" } enum ReaderModeTheme: String { case Light = "light" case Dark = "dark" case Sepia = "sepia" } enum ReaderModeFontType: String { case Serif = "serif" case SansSerif = "sans-serif" } enum ReaderModeFontSize: Int { case Smallest = 1 case Small case Normal = 3 case Large = 4 case Largest = 5 } struct ReaderModeStyle { var theme: ReaderModeTheme var fontType: ReaderModeFontType var fontSize: ReaderModeFontSize /// Encode the style to a JSON dictionary that can be passed to ReaderMode.js func encode() -> String { return JSON(["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]).toString(pretty: false) } /// Encode the style to a dictionary that can be stored in the profile func encode() -> [String:AnyObject] { return ["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue] } init(theme: ReaderModeTheme, fontType: ReaderModeFontType, fontSize: ReaderModeFontSize) { self.theme = theme self.fontType = fontType self.fontSize = fontSize } /// Initialize the style from a dictionary, taken from the profile. Returns nil if the object cannot be decoded. init?(dict: [String:AnyObject]) { let themeRawValue = dict["theme"] as? String let fontTypeRawValue = dict["fontType"] as? String let fontSizeRawValue = dict["fontSize"] as? Int if themeRawValue == nil || fontTypeRawValue == nil || fontSizeRawValue == nil { return nil } let theme = ReaderModeTheme(rawValue: themeRawValue!) let fontType = ReaderModeFontType(rawValue: fontTypeRawValue!) let fontSize = ReaderModeFontSize(rawValue: fontSizeRawValue!) if theme == nil || fontType == nil || fontSize == nil { return nil } self.theme = theme! self.fontType = fontType! self.fontSize = fontSize! } } let DefaultReaderModeStyle = ReaderModeStyle(theme: .Light, fontType: .SansSerif, fontSize: .Normal) let domainPrefixes = ["www.", "mobile.", "m."] private func simplifyDomain(domain: String) -> String { for prefix in domainPrefixes { if domain.hasPrefix(prefix) { return domain.substringFromIndex(advance(domain.startIndex, countElements(prefix))) } } return domain } /// This struct captures the response from the Readability.js code. struct ReadabilityResult { var domain = "" var url = "" var content = "" var title = "" var credits = "" init?(object: AnyObject?) { if let dict = object as? NSDictionary { if let uri = dict["uri"] as? NSDictionary { if let url = uri["spec"] as? String { self.url = url } if let host = uri["host"] as? String { self.domain = host } } if let content = dict["content"] as? String { self.content = content } if let title = dict["title"] as? String { self.title = title } if let credits = dict["byline"] as? String { self.credits = credits } } else { return nil } } } /// Delegate that contains callbacks that we have added on top of the built-in WKWebViewDelegate protocol ReaderModeDelegate { func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser) func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser) } private let ReaderModeNamespace = "_firefox_ReaderMode" class ReaderMode: BrowserHelper { var delegate: ReaderModeDelegate? private weak var browser: Browser? var state: ReaderModeState = ReaderModeState.Unavailable private var originalURL: NSURL? var activateImmediately: Bool = false class func name() -> String { return "ReaderMode" } required init?(browser: Browser) { self.browser = browser // This is a WKUserScript at the moment because webView.evaluateJavaScript() fails with an unspecified error. Possibly script size related. if let path = NSBundle.mainBundle().pathForResource("Readability", ofType: "js") { if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) { var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true) browser.webView.configuration.userContentController.addUserScript(userScript) } } // This is executed after a page has been loaded. It executes Readability and then fires a script message to let us know if the page is compatible with reader mode. if let path = NSBundle.mainBundle().pathForResource("ReaderMode", ofType: "js") { if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) { var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true) browser.webView.configuration.userContentController.addUserScript(userScript) } } } func scriptMessageHandlerName() -> String? { return "readerModeMessageHandler" } private func handleReaderPageEvent(readerPageEvent: ReaderPageEvent) { switch readerPageEvent { case .PageShow: delegate?.readerMode(self, didDisplayReaderizedContentForBrowser: browser!) } } private func handleReaderModeStateChange(state: ReaderModeState) { self.state = state delegate?.readerMode(self, didChangeReaderModeState: state, forBrowser: browser!) if activateImmediately && state == ReaderModeState.Available { enableReaderMode() activateImmediately = false } } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { println("DEBUG: readerModeMessageHandler message: \(message.body)") if let msg = message.body as? Dictionary<String,String> { if let messageType = ReaderModeMessageType(rawValue: msg["Type"] ?? "") { switch messageType { case .PageEvent: if let readerPageEvent = ReaderPageEvent(rawValue: msg["Value"] ?? "Invalid") { handleReaderPageEvent(readerPageEvent) } break case .StateChange: if let readerModeState = ReaderModeState(rawValue: msg["Value"] ?? "Invalid") { handleReaderModeStateChange(readerModeState) } break } } } } func enableReaderMode() { if state == ReaderModeState.Available { browser!.webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in println("DEBUG: mozReaderize object=\(object != nil) error=\(error)") if error == nil && object != nil { if let readabilityResult = ReadabilityResult(object: object) { if let html = self.generateReaderContent(readabilityResult, initialStyle: self.style) { self.state = ReaderModeState.Active self.originalURL = self.browser!.webView.URL if let readerModeURL = ReaderMode.encodeURL(self.browser!.webView.URL) { self.browser!.webView.loadHTMLString(html, baseURL: readerModeURL) } return } } } // TODO What do we do in case of errors? At this point we actually did show the button, so the user does expect some feedback I think. }) } } func disableReaderMode() { if state == ReaderModeState.Active { state = ReaderModeState.Available self.browser!.webView.loadRequest(NSURLRequest(URL: originalURL!)) originalURL = nil } } var style: ReaderModeStyle = DefaultReaderModeStyle { didSet { if state == ReaderModeState.Active { browser!.webView.evaluateJavaScript("\(ReaderModeNamespace).setStyle(\(style.encode()))", completionHandler: { (object, error) -> Void in return }) } } } private func generateReaderContent(readabilityResult: ReadabilityResult, initialStyle: ReaderModeStyle) -> String? { if let stylePath = NSBundle.mainBundle().pathForResource("Reader", ofType: "css") { if let css = NSString(contentsOfFile: stylePath, encoding: NSUTF8StringEncoding, error: nil) { if let tmplPath = NSBundle.mainBundle().pathForResource("Reader", ofType: "html") { if let tmpl = NSMutableString(contentsOfFile: tmplPath, encoding: NSUTF8StringEncoding, error: nil) { tmpl.replaceOccurrencesOfString("%READER-CSS%", withString: css, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-STYLE%", withString: initialStyle.encode(), options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-DOMAIN%", withString: simplifyDomain(readabilityResult.domain), options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-URL%", withString: readabilityResult.url, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-TITLE%", withString: readabilityResult.title, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-CREDITS%", withString: readabilityResult.credits, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-CONTENT%", withString: readabilityResult.content, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%WEBSERVER-BASE%", withString: WebServer.sharedInstance.base, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) return tmpl } } } } return nil } class func isReaderModeURL(url: NSURL) -> Bool { if let absoluteString = url.absoluteString { return absoluteString.hasPrefix("about:reader?url=") } return false } class func decodeURL(url: NSURL) -> NSURL? { if let absoluteString = url.absoluteString { if absoluteString.hasPrefix("about:reader?url=") { let encodedURL = absoluteString.substringFromIndex(advance(absoluteString.startIndex, 17)) if let decodedURL = encodedURL.stringByRemovingPercentEncoding { return NSURL(string: decodedURL) } } } return nil } class func encodeURL(url: NSURL?) -> NSURL? { if let absoluteString = url?.absoluteString { if let encodedURL = absoluteString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) { if let aboutReaderURL = NSURL(string: "about:reader?url=\(encodedURL)") { return aboutReaderURL } } } return nil } }
mpl-2.0
coodly/SlimTimerAPI
Sources/RemoteModel.swift
1
679
/* * Copyright 2017 Coodly LLC * * 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 import SWXMLHash protocol RemoteModel { init?(xml: XMLIndexer) }
apache-2.0
naoty/AnyQuery
AnyQuery/AnySort.swift
1
1821
// // AnySort.swift // AnyQuery // // Created by Naoto Kaneko on 2/25/16. // Copyright © 2016 Naoto Kaneko. All rights reserved. // import Foundation indirect public enum AnySort { case tree(lhs: AnySort, rhs: AnySort) case ascending(key: String) case descending(key: String) public var sortDescriptors: [NSSortDescriptor] { switch self { case .tree(let lhs, let rhs): return lhs.sortDescriptors + rhs.sortDescriptors case .ascending(let key): return [NSSortDescriptor(key: key, ascending: true)] case .descending(let key): return [NSSortDescriptor(key: key, ascending: false)] } } public var dictionary: [String: [String]] { switch self { case .tree(let lhs, let rhs): return lhs.dictionary.merged(with: rhs.dictionary) case .ascending(let key): return ["sort": [key]] case .descending(let key): return ["sort": ["-\(key)"]] } } public static func >(lhs: AnySort, rhs: AnySort) -> AnySort { return AnySort.tree(lhs: lhs, rhs: rhs) } public static func <(lhs: AnySort, rhs: AnySort) -> AnySort { return AnySort.tree(lhs: rhs, rhs: lhs) } } public func >(lhs: AnySort?, rhs: AnySort?) -> AnySort? { switch (lhs, rhs) { case let (lhs?, rhs?): return lhs > rhs case let (lhs?, nil): return lhs case let (nil, rhs?): return rhs case (nil, nil): return nil } } public func <(lhs: AnySort?, rhs: AnySort?) -> AnySort? { switch (lhs, rhs) { case let (lhs?, rhs?): return lhs < rhs case let (lhs?, nil): return lhs case let (nil, rhs?): return rhs case (nil, nil): return nil } }
mit
OSzhou/MyTestDemo
PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-HTTP.git--6392294032632002019/Sources/Routing.swift
1
17824
// // Routing.swift // PerfectLib // // Created by Kyle Jessup on 2015-12-11. // Copyright © 2015 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectLib /// Function which receives request and response objects and generates content. public typealias RequestHandler = (HTTPRequest, HTTPResponse) -> () /// Object which maps uris to handler. /// RouteNavigators are given to the HTTPServer to control its content generation. public protocol RouteNavigator: CustomStringConvertible { /// Given an array of URI path components and HTTPRequest, return the handler or nil if there was none. func findHandlers(pathComponents components: [String], webRequest: HTTPRequest) -> [RequestHandler]? } public extension RouteNavigator { func findHandler(pathComponents: [String], webRequest: HTTPRequest) -> RequestHandler? { return findHandlers(pathComponents: pathComponents, webRequest: webRequest)?.last } } public extension RouteNavigator { /// Given a URI and HTTPRequest, return the handler or nil if there was none. func findHandler(uri: String, webRequest: HTTPRequest) -> RequestHandler? { return findHandler(pathComponents: uri.routePathComponents, webRequest: webRequest) } /// Given a URI and HTTPRequest, return the handler or nil if there was none. func findHandlers(uri: String, webRequest: HTTPRequest) -> [RequestHandler]? { return findHandlers(pathComponents: uri.routePathComponents, webRequest: webRequest) } } // The url variable key under which the remaining path in a trailing wild card will be placed. public let routeTrailingWildcardKey = "_trailing_wildcard_" /// Combines a method, uri and handler public struct Route { public let methods: [HTTPMethod] public let uri: String public let handler: RequestHandler /// A single method, a uri and handler. public init(method: HTTPMethod, uri: String, handler: @escaping RequestHandler) { self.methods = [method] self.uri = uri self.handler = handler } /// An array of methods, a uri and handler. public init(methods: [HTTPMethod], uri: String, handler: @escaping RequestHandler) { self.methods = methods self.uri = uri self.handler = handler } /// A uri and a handler on any method. public init(uri: String, handler: @escaping RequestHandler) { self.methods = HTTPMethod.allMethods self.uri = uri self.handler = handler } } /// A group of routes. Add one or more routes to this object then call its navigator property to get the RouteNavigator. /// Can be created with a baseUri. All routes which are added will have their URIs prefixed with this value. public struct Routes { var routes = [Route]() var moreRoutes = [Routes]() let baseUri: String let handler: RequestHandler? /// Initialize with no baseUri. public init(handler: RequestHandler? = nil) { self.baseUri = "" self.handler = handler } /// Initialize with a baseUri. public init(baseUri: String, handler: RequestHandler? = nil) { self.baseUri = Routes.sanitizeUri(baseUri) self.handler = handler } /// Initialize with a array of Route. public init(_ routes: [Route]) { self.baseUri = "" self.handler = nil add(routes) } /// Initialize with a baseUri and array of Route. public init(baseUri: String, routes: [Route]) { self.baseUri = Routes.sanitizeUri(baseUri) self.handler = nil add(routes) } /// Add all the routes in the Routes object to this one. public mutating func add(_ routes: Routes) { moreRoutes.append(routes) } /// Add all the routes in the Routes array to this one. public mutating func add(_ routes: [Route]) { for route in routes { add(route) } } /// Add one Route to this object. public mutating func add(_ route: Route, routes vroots: Route...) { routes.append(route) vroots.forEach { add($0) } } /// Add the given method, uri and handler as a route. public mutating func add(method: HTTPMethod, uri: String, handler: @escaping RequestHandler) { add(Route(method: method, uri: uri, handler: handler)) } /// Add the given method, uris and handler as a route. public mutating func add(method: HTTPMethod, uris: [String], handler: @escaping RequestHandler) { uris.forEach { add(method: method, uri: $0, handler: handler) } } /// Add the given uri and handler as a route. /// This will add the route for all standard methods. public mutating func add(uri: String, handler: @escaping RequestHandler) { add(Route(uri: uri, handler: handler)) } /// Add the given method, uris and handler as a route. /// This will add the route for all standard methods. public mutating func add(uris: [String], handler: @escaping RequestHandler) { for uri in uris { add(uri: uri, handler: handler) } } static func sanitizeUri(_ uri: String) -> String { let endSlash = uri.hasSuffix("/") let split = uri.characters.split(separator: "/").map(String.init) let ret = "/" + split.joined(separator: "/") + (endSlash ? "/" : "") return ret } struct Navigator: RouteNavigator { let map: [HTTPMethod:RouteNode] var description: String { var s = "" for (method, root) in self.map { s.append("\n\(method):\n\(root.description)") } return s } func findHandlers(pathComponents components: [String], webRequest: HTTPRequest) -> [RequestHandler]? { let method = webRequest.method guard !components.isEmpty, let root = self.map[method] else { return nil } var g = components.makeIterator() if components[0] == "/" { _ = g.next() } guard let handlers = root.findHandler(currentComponent: "", generator: g, webRequest: webRequest) else { return nil } return handlers.flatMap { $0 } } } private func formatException(route r: String, error: Error) -> String { return "\(error) - \(r)" } } extension Routes { /// Return the RouteNavigator for this object. public var navigator: RouteNavigator { guard let map = try? nodeMap() else { return Navigator(map: [:]) } return Navigator(map: map) } func nodeMap() throws -> [HTTPMethod:RouteNode] { var working = [HTTPMethod:RouteNode]() let paths = self.paths(baseUri: "") for (method, uris) in paths { let root = RouteNode() working[method] = root for path in uris { let uri = Routes.sanitizeUri(path.path) let handler = path.handler let terminal = path.terminal var gen = uri.routePathComponents.makeIterator() if uri.hasPrefix("/") { _ = gen.next() } let node = try root.getNode(gen) node.terminal = terminal node.handler = handler } } return working } struct PathHandler { let path: String let handler: RequestHandler let terminal: Bool } func paths(baseUri: String = "") -> [HTTPMethod:[PathHandler]] { var paths = [HTTPMethod:[PathHandler]]() let newBaseUri = baseUri + self.baseUri moreRoutes.forEach { let newp = $0.paths(baseUri: newBaseUri) paths = merge(newp, into: paths) } routes.forEach { route in let uri = newBaseUri + "/" + route.uri var newpaths = [HTTPMethod:[PathHandler]]() route.methods.forEach { method in newpaths[method] = [PathHandler(path: uri, handler: route.handler, terminal: true)] } paths = merge(newpaths, into: paths) } if let handler = self.handler { for (key, value) in paths { paths[key] = value + [PathHandler(path: newBaseUri, handler: handler, terminal: false)] } } return paths } func merge(_ dict: [HTTPMethod:[PathHandler]], into: [HTTPMethod:[PathHandler]]) -> [HTTPMethod:[PathHandler]] { var ret = into for (key, value) in dict { if var fnd = ret[key] { fnd.append(contentsOf: value) ret[key] = fnd } else { ret[key] = value } } return ret } } extension Routes { // Add all the routes in the Routes object to this one. @available(*, deprecated, message: "Use Routes.add(_:Routes)") public mutating func add(routes: Routes) { for route in routes.routes { self.add(route) } } } extension String { var routePathComponents: [String] { return self.filePathComponents // let components = self.characters.split(separator: "/").map(String.init) // return components } } private enum RouteException: Error { case invalidRoute } private enum RouteItemType { case wildcard, trailingWildcard, variable(String), path, trailingSlash init(_ comp: String) { if comp == "*" { self = .wildcard } else if comp == "**" { self = .trailingWildcard } else if comp == "/" { self = .trailingSlash } else if comp.characters.count >= 3 && comp[comp.startIndex] == "{" && comp[comp.index(before: comp.endIndex)] == "}" { self = .variable(comp[comp.index(after: comp.startIndex)..<comp.index(before: comp.endIndex)]) } else { self = .path } } } class RouteNode { typealias ComponentGenerator = IndexingIterator<[String]> var handler: RouteMap.RequestHandler? var trailingWildCard: RouteNode? var wildCard: RouteNode? var variables = [RouteNode]() var subNodes = [String:RouteNode]() var terminal = true // an end point. not an intermediary func descriptionTabbed(_ tabCount: Int) -> String { var s = "" if let _ = self.handler { s.append("/+h\n") } s.append(self.descriptionTabbedInner(tabCount)) return s } func appendToHandlers(_ handlers: [RouteMap.RequestHandler?]) -> [RouteMap.RequestHandler?] { // terminal handlers are not included in chaining if terminal { return handlers } return [handler] + handlers } func findHandler(currentComponent curComp: String, generator: ComponentGenerator, webRequest: HTTPRequest) -> [RouteMap.RequestHandler?]? { var m = generator if let p = m.next() { // variables for node in self.variables { if let h = node.findHandler(currentComponent: p, generator: m, webRequest: webRequest) { return appendToHandlers(h) } } // paths if let node = self.subNodes[p.lowercased()] { if let h = node.findHandler(currentComponent: p, generator: m, webRequest: webRequest) { return appendToHandlers(h) } } // wildcard if let node = self.wildCard { if let h = node.findHandler(currentComponent: p, generator: m, webRequest: webRequest) { return appendToHandlers(h) } } // trailing wildcard if let node = self.trailingWildCard { if let h = node.findHandler(currentComponent: p, generator: m, webRequest: webRequest) { return appendToHandlers(h) } } } else if let handler = self.handler { if terminal { return [handler] } return nil } else { // wildcards if let node = self.wildCard { if let h = node.findHandler(currentComponent: "", generator: m, webRequest: webRequest) { return appendToHandlers(h) } } // trailing wildcard if let node = self.trailingWildCard { if let h = node.findHandler(currentComponent: "", generator: m, webRequest: webRequest) { return appendToHandlers(h) } } } return nil } func getNode(_ ing: ComponentGenerator) throws -> RouteNode { var g = ing if let comp = g.next() { let routeType = RouteItemType(comp) let node: RouteNode switch routeType { case .wildcard: if wildCard == nil { wildCard = RouteWildCard() } node = wildCard! case .trailingWildcard: guard nil == g.next() else { throw RouteException.invalidRoute } if trailingWildCard == nil { trailingWildCard = RouteTrailingWildCard() } node = trailingWildCard! case .trailingSlash: guard nil == g.next() else { throw RouteException.invalidRoute } node = RouteTrailingSlash() subNodes[comp] = node case .path: let compLower = comp.lowercased() if let existing = subNodes[compLower] { node = existing } else { node = RoutePath(name: compLower) subNodes[compLower] = node } case .variable(let name): let dups = variables.flatMap { $0 as? RouteVariable }.filter { $0.name == name } if dups.isEmpty { let varble = RouteVariable(name: name) variables.append(varble) node = varble } else { node = dups[0] } } return try node.getNode(g) } else { return self } } } extension RouteNode: CustomStringConvertible { var description: String { return self.descriptionTabbed(0) } private func putTabs(_ count: Int) -> String { var s = "" for _ in 0..<count { s.append("\t") } return s } func descriptionTabbedInner(_ tabCount: Int) -> String { var s = "" for (_, node) in self.subNodes { s.append("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))") } for node in self.variables { s.append("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))") } if let node = self.wildCard { s.append("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))") } if let node = self.trailingWildCard { s.append("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))") } return s } } class RoutePath: RouteNode { let name: String init(name: String) { self.name = name } override func descriptionTabbed(_ tabCount: Int) -> String { var s = "/\(self.name)" if let _ = self.handler { s.append("+h\n") } else { s.append("\n") } s.append(self.descriptionTabbedInner(tabCount)) return s } // RoutePaths don't need to perform any special checking. // Their path is validated by the fact that they exist in their parent's `subNodes` dict. } class RouteWildCard: RouteNode { override func descriptionTabbed(_ tabCount: Int) -> String { var s = "/*" if let _ = self.handler { s.append("+h\n") } else { s.append("\n") } s.append(self.descriptionTabbedInner(tabCount)) return s } } class RouteTrailingWildCard: RouteWildCard { override func descriptionTabbed(_ tabCount: Int) -> String { var s = "/**" if let _ = self.handler { s.append("+h\n") } else { s.append("\n") } s.append(self.descriptionTabbedInner(tabCount)) return s } override func findHandler(currentComponent curComp: String, generator: ComponentGenerator, webRequest: HTTPRequest) -> [RouteMap.RequestHandler?]? { let trailingVar = "/\(curComp)" + generator.map { "/" + $0 }.joined(separator: "") webRequest.urlVariables[routeTrailingWildcardKey] = trailingVar if let handler = self.handler { return [handler] } return nil } } class RouteTrailingSlash: RouteNode { override func descriptionTabbed(_ tabCount: Int) -> String { var s = "/" if let _ = self.handler { s.append("+h\n") } else { s.append("\n") } s.append(self.descriptionTabbedInner(tabCount)) return s } override func findHandler(currentComponent curComp: String, generator: ComponentGenerator, webRequest: HTTPRequest) -> [RouteMap.RequestHandler?]? { var m = generator guard curComp == "/", nil == m.next(), let handler = self.handler else { return nil } return [handler] } } class RouteVariable: RouteNode { let name: String init(name: String) { self.name = name } override func descriptionTabbed(_ tabCount: Int) -> String { var s = "/{\(self.name)}" if let _ = self.handler { s.append("+h\n") } else { s.append("\n") } s.append(self.descriptionTabbedInner(tabCount)) return s } override func findHandler(currentComponent curComp: String, generator: ComponentGenerator, webRequest: HTTPRequest) -> [RouteMap.RequestHandler?]? { if let h = super.findHandler(currentComponent: curComp, generator: generator, webRequest: webRequest) { if let decodedComponent = curComp.stringByDecodingURL { webRequest.urlVariables[self.name] = decodedComponent } else { webRequest.urlVariables[self.name] = curComp } return h } return nil } } // -- old -- // ALL code below this is obsolete but remains to provide compatability 1.0 based solutions. // For 1.0 compatability only. public var compatRoutes: Routes? // Holds the registered routes. @available(*, deprecated, message: "Use new Routes API instead") public struct RouteMap: CustomStringConvertible { public typealias RequestHandler = (HTTPRequest, HTTPResponse) -> () public var description: String { return compatRoutes?.navigator.description ?? "no routes" } public subscript(path: String) -> RequestHandler? { get { return nil // Swift does not currently allow set-only subscripts } set { guard let handler = newValue else { return } if nil == compatRoutes { compatRoutes = Routes() } compatRoutes?.add(method: .get, uri: path, handler: handler) } } public subscript(paths: [String]) -> RequestHandler? { get { return nil } set { for path in paths { self[path] = newValue } } } public subscript(method: HTTPMethod, path: String) -> RequestHandler? { get { return nil // Swift does not currently allow set-only subscripts } set { guard let handler = newValue else { return } if nil == compatRoutes { compatRoutes = Routes() } compatRoutes?.add(method: method, uri: path, handler: handler) } } public subscript(method: HTTPMethod, paths: [String]) -> RequestHandler? { get { return nil // Swift does not currently allow set-only subscripts } set { for path in paths { self[method, path] = newValue } } } } @available(*, deprecated, message: "Use new Routes API instead") public struct Routing { static public var Routes = RouteMap() private init() {} }
apache-2.0