repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
iToto/swiftNetworkManager
refs/heads/master
network_connectivity/Managers/Network/Controllers/NetworkManagerViewController.swift
mit
1
// // ViewController.swift // network_connectivity // // Created by Salvatore D'Agostino on 2015-03-01. // Copyright (c) 2015 dressed. All rights reserved. // import UIKit class NetworkManagerViewController: UIViewController { let networkLossNotification = "com.dressed.networkLossNotification" let networkFoundNotification = "com.dressed.networkFoundNotification" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Register observer for network lost NSNotificationCenter.defaultCenter().addObserverForName(self.networkLossNotification,object:nil , queue:nil){ _ in self.displayNoConnectionView() } // Register observer for network found NSNotificationCenter.defaultCenter().addObserverForName(self.networkFoundNotification,object:nil , queue:nil){ _ in self.hideNoConnectionView() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func testConnectivity() { if IJReachability.isConnectedToNetwork() { // Animate fade-in of view self.displayNoConnectionView() } } func displayNoConnectionView() { let screenSize: CGRect = UIScreen.mainScreen().bounds let noConnectionView = NoConnectionView(frame: screenSize) noConnectionView.alpha = 0 // Will animate fade-in of view UIView.animateWithDuration(0.5, delay: 0, options:UIViewAnimationOptions.CurveEaseOut, animations: {() in noConnectionView.alpha = 0.8 }, completion: nil) self.view.addSubview(noConnectionView) } func hideNoConnectionView() { NSLog("Remove no connection view") for view in self.view.subviews { view.removeFromSuperview() } } }
6f96c3c05895b8a9242649358a39b5cf
29.208955
123
0.65168
false
false
false
false
gewill/Feeyue
refs/heads/develop
Feeyue/Main/Twitter/TwitterUser/TwitterUserViewModel.swift
mit
1
// // TwitterUserViewModel.swift // Feeyue // // Created by Will on 2018/7/3. // Copyright © 2018 Will. All rights reserved. // import Foundation import RealmSwift import SwiftyJSON import Moya import RxSwift import Moya_SwiftyJSONMapper import SwifterSwift class TwitterUserViewModel { private var timeline: TwitterTimeline! private var token: NotificationToken? private var userToken: NotificationToken? private var realm: Realm! private var userId: String? private var userName: String? var statuses: Results<TwitterStatus> { return timeline.statuses.sorted(byKeyPath: TwitterStatus.Property.createdAt.rawValue, ascending: false) } var user: TwitterUser? // MARK: - life cycle init(userId: String?, userName: String?, realm: Realm = RealmProvider.twitterInMemory.realm) { self.userId = userId self.userName = userName self.realm = realm timeline = TwitterTimeline.create(idStr: UUID().uuidString, realm: realm) guard let userId = userId else { return } user = TwitterUser.getUser(userId: userId) } deinit { token?.invalidate() userToken?.invalidate() removeCache() } var didUpdate: VoidClosure? = nil { didSet { guard let didUpdate = didUpdate, let timeline = timeline else { token?.invalidate() return } token = timeline.observe({ changes in switch changes { case .change: didUpdate() case .deleted: didUpdate() case .error: break } }) } } var userUpdate: VoidClosure? = nil { didSet { guard let userUpdate = userUpdate, let user = user else { userToken?.invalidate() return } userToken = user.observe({ changes in switch changes { case .change: userUpdate() case .deleted: userUpdate() case .error: break } }) } } func removeCache() { try? self.realm.write { self.realm.delete(self.timeline) } } // MARK: - load data func reloadData() -> Observable<[TwitterStatus]> { return twitterProvider.rx.request(.userTimeline(userId, userName, 200, nil, nil)) //.debug() .map(to: [TwitterStatus.self]) .asObservable() .do(onNext: { response in try! self.realm.write { self.realm.add(response, update: true) self.timeline.statuses.append(objectsIn: response) self.realm.add(self.timeline, update: true) } }) } func moreOldData() -> Observable<[TwitterStatus]> { let maxId = statuses.last?.idStr return twitterProvider.rx.request(.userTimeline(userId, userName, 50, nil, maxId)) //.debug() .map(to: [TwitterStatus.self]) .asObservable() .do(onNext: { response in try! self.realm.write { self.realm.add(response, update: true) self.timeline.statuses.append(objectsIn: response) self.realm.add(self.timeline, update: true) } }) } func moreNewData() -> Observable<[TwitterStatus]> { let sinceId = statuses.first?.idStr return twitterProvider.rx.request(.userTimeline(userId, userName, 50, sinceId, nil)) //.debug() .map(to: [TwitterStatus.self]) .asObservable() .do(onNext: { response in try! self.realm.write { self.realm.add(response, update: true) self.timeline.statuses.append(objectsIn: response) self.realm.add(self.timeline, update: true) } }) } func userInfo() -> Observable<TwitterUser> { return twitterProvider.rx.request(.userInfo(userId, userName)) .debug() .map(to: TwitterUser.self) .asObservable() .do(onNext: { response in TwitterUser.addUser(user: response) self.user = response self.userUpdate?() }) } }
cadda2f4ed1a58d2b0e3e5f3b0e90847
28.649351
111
0.52869
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/Model/Vita/MVitaLinkFactory.swift
mit
1
import Foundation import CocoaAsyncSocket extension MVitaLink { private static let kStatusStrategyMap:[ MVitaPtpLocalStatus: MVitaLinkStrategySendLocalStatus.Type] = [ MVitaPtpLocalStatus.connection: MVitaLinkStrategySendLocalStatusConnection.self, MVitaPtpLocalStatus.connectionEnd: MVitaLinkStrategySendLocalStatusConnectionEnd.self] private static let kCommandQueueLabel:String = "velvetRoom.vitaLink.socketCommand" private static let kEventQueueLabel:String = "velvetRoom.vitaLink.socketEvent" //MARK: private private class func factoryCommandQueue() -> DispatchQueue { let queue = DispatchQueue( label:kCommandQueueLabel, qos:DispatchQoS.background, attributes:DispatchQueue.Attributes(), autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target:DispatchQueue.global( qos:DispatchQoS.QoSClass.background)) return queue } private class func factoryEventQueue() -> DispatchQueue { let queue = DispatchQueue( label:kEventQueueLabel, qos:DispatchQoS.background, attributes:DispatchQueue.Attributes(), autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target:DispatchQueue.global( qos:DispatchQoS.QoSClass.background)) return queue } //MARK: internal class func factorySocketCommand() -> MVitaLinkSocketCommand { let delegate:MVitaLinkSocketCommandDelegate = MVitaLinkSocketCommandDelegate() let queue:DispatchQueue = factoryCommandQueue() let socket:GCDAsyncSocket = GCDAsyncSocket( delegate:delegate, delegateQueue:queue, socketQueue:queue) let linkCommand:MVitaLinkSocketCommand = MVitaLinkSocketCommand( socket:socket, delegate:delegate, queue:queue) delegate.model = linkCommand return linkCommand } class func factorySocketEvent() -> MVitaLinkSocketEvent { let delegate:MVitaLinkSocketEventDelegate = MVitaLinkSocketEventDelegate() let queue:DispatchQueue = factoryEventQueue() let socket:GCDAsyncSocket = GCDAsyncSocket( delegate:delegate, delegateQueue:queue, socketQueue:queue) let linkEvent:MVitaLinkSocketEvent = MVitaLinkSocketEvent( socket:socket, delegate:delegate, queue:queue) delegate.model = linkEvent return linkEvent } class func factoryStrategyStatus( status:MVitaPtpLocalStatus) -> MVitaLinkStrategySendLocalStatus.Type { guard let strategy:MVitaLinkStrategySendLocalStatus.Type = kStatusStrategyMap[ status] else { return MVitaLinkStrategySendLocalStatus.self } return strategy } class func factoryDispatchGroup() -> DispatchGroup { let dispatchGroup:DispatchGroup = DispatchGroup() dispatchGroup.setTarget( queue:DispatchQueue.global( qos:DispatchQoS.QoSClass.background)) return dispatchGroup } }
2c225499bcc6341f24f997db426676c5
30.290909
86
0.631028
false
false
false
false
qinting513/Learning-QT
refs/heads/master
2016 Plan/5月/数据持久化/CoreDataSw/CoreDataSw/ViewController.swift
apache-2.0
1
// // ViewController.swift // CoreDataSw // // Created by Qinting on 16/5/9. // Copyright © 2016年 Qinting. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { var context : NSManagedObjectContext? override func viewDidLoad() { super.viewDidLoad() let context = NSManagedObjectContext.init() let model = NSManagedObjectModel.mergedModelFromBundles(nil) let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last let sqlPath = docPath?.stringByAppendingString("/company.sqlite") let store = NSPersistentStoreCoordinator.init(managedObjectModel: model!) let url = NSURL.fileURLWithPath(sqlPath!) do { try store.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch _ { } context.persistentStoreCoordinator = store self.context = context } @IBAction func insertData(sender: AnyObject) { let emp = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: context!) as! Employee emp.name = "zhangsan" emp.age = 126 do{ try context!.save() print("成功插入") } catch let error as NSError { print(error) } } @IBAction func queryData(sender: AnyObject) { let fetch = NSFetchRequest.init(entityName: "Employee") do { let emps : [AnyObject] = try context!.executeFetchRequest(fetch) for emp in emps as! [Employee] { print("name:\(emp.name!) age: \(emp.age!)") } }catch let error as NSError { print("error:\( error)") } } }
ead38bc28633db0780e9d82f3dfe4e6b
27.169231
128
0.614418
false
false
false
false
weby/PathKit
refs/heads/master
Sources/PathKit.swift
bsd-2-clause
1
// PathKit - Effortless path operations #if os(Linux) import Glibc let system_glob = Glibc.glob #else import Darwin let system_glob = Darwin.glob #endif import Foundation #if !swift(>=3.0) typealias Collection = CollectionType typealias Sequence = SequenceType typealias IteratorProtocol = GeneratorType #endif /// Represents a filesystem path. public struct Path { /// The character used by the OS to separate two path elements public static let separator = "/" /// The underlying string representation internal var path: String #if os(OSX) internal static var fileManager = NSFileManager.default() #else internal static var fileManager = NSFileManager.defaultManager() #endif // MARK: Init public init() { self.path = "" } /// Create a Path from a given String public init(_ path: String) { self.path = path } /// Create a Path by joining multiple path components together #if !swift(>=3.0) public init<S : Collection where S.Generator.Element == String>(components: S) { if components.isEmpty { path = "." } else if components.first == Path.separator && components.count > 1 { let p = components.joinWithSeparator(Path.separator) #if os(Linux) let index = p.startIndex.distanceTo(p.startIndex.successor()) path = NSString(string: p).substringFromIndex(index) #else path = p.substringFromIndex(p.startIndex.successor()) #endif } else { path = components.joinWithSeparator(Path.separator) } } #else public init<S : Collection where S.Iterator.Element == String>(components: S) { if components.isEmpty { path = "." } else if components.first == Path.separator && components.count > 1 { let p = components.joined(separator: Path.separator) path = p.substring(from: p.index(after: p.startIndex)) } else { path = components.joined(separator: Path.separator) } } #endif } // MARK: StringLiteralConvertible extension Path : StringLiteralConvertible { public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = StringLiteralType public init(extendedGraphemeClusterLiteral path: StringLiteralType) { self.init(stringLiteral: path) } public init(unicodeScalarLiteral path: StringLiteralType) { self.init(stringLiteral: path) } public init(stringLiteral value: StringLiteralType) { self.path = value } } // MARK: CustomStringConvertible extension Path : CustomStringConvertible { public var description: String { return self.path } } // MARK: Hashable extension Path : Hashable { public var hashValue: Int { return path.hashValue } } // MARK: Path Info extension Path { /// Test whether a path is absolute. /// /// - Returns: `true` iff the path begings with a slash /// public var isAbsolute: Bool { return path.hasPrefix(Path.separator) } /// Test whether a path is relative. /// /// - Returns: `true` iff a path is relative (not absolute) /// public var isRelative: Bool { return !isAbsolute } /// Concatenates relative paths to the current directory and derives the normalized path /// /// - Returns: the absolute path in the actual filesystem /// public func absolute() -> Path { if isAbsolute { return normalize() } return (Path.current + self).normalize() } /// Normalizes the path, this cleans up redundant ".." and ".", double slashes /// and resolves "~". /// /// - Returns: a new path made by removing extraneous path components from the underlying String /// representation. /// public func normalize() -> Path { #if !swift(>=3.0) return Path(NSString(string: self.path).stringByStandardizingPath) #else #if os(Linux) return Path(NSString(string: self.path).stringByStandardizingPath) #else return Path(NSString(string: self.path).standardizingPath) #endif #endif } /// De-normalizes the path, by replacing the current user home directory with "~". /// /// - Returns: a new path made by removing extraneous path components from the underlying String /// representation. /// public func abbreviate() -> Path { #if os(Linux) // TODO: actually de-normalize the path return self #else #if !swift(>=3.0) return Path(NSString(string: self.path).stringByAbbreviatingWithTildeInPath) #else return Path(NSString(string: self.path).abbreviatingWithTildeInPath) #endif #endif } /// Returns the path of the item pointed to by a symbolic link. /// /// - Returns: the path of directory or file to which the symbolic link refers /// public func symlinkDestination() throws -> Path { let symlinkDestination = try Path.fileManager.destinationOfSymbolicLink(atPath:path) let symlinkPath = Path(symlinkDestination) if symlinkPath.isRelative { return self + ".." + symlinkPath } else { return symlinkPath } } } // MARK: Path Components extension Path { /// The last path component /// /// - Returns: the last path component /// public var lastComponent: String { return NSString(string: path).lastPathComponent } /// The last path component without file extension /// /// - Note: This returns "." for "..". /// /// - Returns: the last path component without file extension /// public var lastComponentWithoutExtension: String { #if !swift(>=3.0) return NSString(string: lastComponent).stringByDeletingPathExtension #else #if os(Linux) return NSString(string: lastComponent).stringByDeletingPathExtension #else return NSString(string: lastComponent).deletingPathExtension #endif #endif } /// Splits the string representation on the directory separator. /// Absolute paths remain the leading slash as first component. /// /// - Returns: all path components /// public var components: [String] { return NSString(string: path).pathComponents } /// The file extension behind the last dot of the last component. /// /// - Returns: the file extension /// public var `extension`: String? { let pathExtension = NSString(string: path).pathExtension if pathExtension.isEmpty { return nil } return pathExtension } } // MARK: File Info extension Path { /// Test whether a file or directory exists at a specified path /// /// - Returns: `false` iff the path doesn't exist on disk or its existence could not be /// determined /// public var exists: Bool { return Path.fileManager.fileExists(atPath:self.path) } /// Test whether a path is a directory. /// /// - Returns: `true` if the path is a directory or a symbolic link that points to a directory; /// `false` if the path is not a directory or the path doesn't exist on disk or its existence /// could not be determined /// public var isDirectory: Bool { var directory = ObjCBool(false) guard Path.fileManager.fileExists(atPath: normalize().path, isDirectory: &directory) else { return false } return directory.boolValue } /// Test whether a path is a regular file. /// /// - Returns: `true` if the path is neither a directory nor a symbolic link that points to a /// directory; `false` if the path is a directory or a symbolic link that points to a /// directory or the path doesn't exist on disk or its existence /// could not be determined /// public var isFile: Bool { var directory = ObjCBool(false) guard Path.fileManager.fileExists(atPath: normalize().path, isDirectory: &directory) else { return false } return !directory.boolValue } /// Test whether a path is a symbolic link. /// /// - Returns: `true` if the path is a symbolic link; `false` if the path doesn't exist on disk /// or its existence could not be determined /// public var isSymlink: Bool { do { let _ = try Path.fileManager.destinationOfSymbolicLink(atPath: path) return true } catch { return false } } /// Test whether a path is readable /// /// - Returns: `true` if the current process has read privileges for the file at path; /// otherwise `false` if the process does not have read privileges or the existence of the /// file could not be determined. /// public var isReadable: Bool { return Path.fileManager.isReadableFile(atPath: self.path) } /// Test whether a path is writeable /// /// - Returns: `true` if the current process has write privileges for the file at path; /// otherwise `false` if the process does not have write privileges or the existence of the /// file could not be determined. /// public var isWritable: Bool { return Path.fileManager.isWritableFile(atPath: self.path) } /// Test whether a path is executable /// /// - Returns: `true` if the current process has execute privileges for the file at path; /// otherwise `false` if the process does not have execute privileges or the existence of the /// file could not be determined. /// public var isExecutable: Bool { return Path.fileManager.isExecutableFile(atPath: self.path) } /// Test whether a path is deletable /// /// - Returns: `true` if the current process has delete privileges for the file at path; /// otherwise `false` if the process does not have delete privileges or the existence of the /// file could not be determined. /// public var isDeletable: Bool { return Path.fileManager.isDeletableFile(atPath: self.path) } } // MARK: File Manipulation extension Path { /// Create the directory. /// /// - Note: This method fails if any of the intermediate parent directories does not exist. /// This method also fails if any of the intermediate path elements corresponds to a file and /// not a directory. /// public func mkdir() throws -> () { try Path.fileManager.createDirectory(atPath: self.path, withIntermediateDirectories: false, attributes: nil) } /// Create the directory and any intermediate parent directories that do not exist. /// /// - Note: This method fails if any of the intermediate path elements corresponds to a file and /// not a directory. /// public func mkpath() throws -> () { try Path.fileManager.createDirectory(atPath: self.path, withIntermediateDirectories: true, attributes: nil) } /// Delete the file or directory. /// /// - Note: If the path specifies a directory, the contents of that directory are recursively /// removed. /// public func delete() throws -> () { try Path.fileManager.removeItem(atPath: self.path) } /// Move the file or directory to a new location synchronously. /// /// - Parameter destination: The new path. This path must include the name of the file or /// directory in its new location. /// public func move(destination: Path) throws -> () { try Path.fileManager.moveItem(atPath: self.path, toPath: destination.path) } /// Copy the file or directory to a new location synchronously. /// /// - Parameter destination: The new path. This path must include the name of the file or /// directory in its new location. /// public func copy(destination: Path) throws -> () { try Path.fileManager.copyItem(atPath: self.path, toPath: destination.path) } /// Creates a hard link at a new destination. /// /// - Parameter destination: The location where the link will be created. /// public func link(destination: Path) throws -> () { try Path.fileManager.linkItem(atPath: self.path, toPath: destination.path) } /// Creates a symbolic link at a new destination. /// /// - Parameter destintation: The location where the link will be created. /// public func symlink(destination: Path) throws -> () { try Path.fileManager.createSymbolicLink(atPath: self.path, withDestinationPath: destination.path) } } // MARK: Current Directory extension Path { /// The current working directory of the process /// /// - Returns: the current working directory of the process /// public static var current: Path { get { return self.init(Path.fileManager.currentDirectoryPath) } set { Path.fileManager.changeCurrentDirectoryPath(newValue.description) } } /// Changes the current working directory of the process to the path during the execution of the /// given block. /// /// - Note: The original working directory is restored when the block returns or throws. /// - Parameter closure: A closure to be executed while the current directory is configured to /// the path. /// public func chdir(closure: @noescape () throws -> ()) rethrows { let previous = Path.current Path.current = self defer { Path.current = previous } try closure() } } // MARK: Temporary extension Path { /// - Returns: the path to either the user’s or application’s home directory, /// depending on the platform. /// public static var home: Path { #if os(Linux) return Path(NSProcessInfo.processInfo().environment["HOME"] ?? "/") #else return Path(NSHomeDirectory()) #endif } /// - Returns: the path of the temporary directory for the current user. /// public static var temporary: Path { #if os(Linux) return Path(NSProcessInfo.processInfo().environment["TMP"] ?? "/tmp") #else return Path(NSTemporaryDirectory()) #endif } /// - Returns: the path of a temporary directory unique for the process. /// - Note: Based on `NSProcessInfo.globallyUniqueString`. /// public static func processUniqueTemporary() throws -> Path { let path = temporary + NSProcessInfo.processInfo().globallyUniqueString if !path.exists { try path.mkdir() } return path } /// - Returns: the path of a temporary directory unique for each call. /// - Note: Based on `NSUUID`. /// public static func uniqueTemporary() throws -> Path { #if !swift(>=3.0) let path = try processUniqueTemporary() + NSUUID().UUIDString #else #if os(Linux) let path = try processUniqueTemporary() + NSUUID().UUIDString #else let path = try processUniqueTemporary() + NSUUID().uuidString #endif #endif try path.mkdir() return path } } // MARK: Contents extension Path { /// Reads the file. /// /// - Returns: the contents of the file at the specified path. /// public func read() throws -> NSData { return try NSData(contentsOfFile: path, options: NSDataReadingOptions(rawValue: 0)) } /// Reads the file contents and encoded its bytes to string applying the given encoding. /// /// - Parameter encoding: the encoding which should be used to decode the data. /// (by default: `NSUTF8StringEncoding`) /// /// - Returns: the contents of the file at the specified path as string. /// public func read(encoding: NSStringEncoding = NSUTF8StringEncoding) throws -> String { return try NSString(contentsOfFile: path, encoding: encoding).substring(from: 0) as String } /// Write a file. /// /// - Note: Works atomically: the data is written to a backup file, and then — assuming no /// errors occur — the backup file is renamed to the name specified by path. /// /// - Parameter data: the contents to write to file. /// public func write(data: NSData) throws { try data.write(toFile:normalize().path, options: .dataWritingAtomic) } /// Reads the file. /// /// - Note: Works atomically: the data is written to a backup file, and then — assuming no /// errors occur — the backup file is renamed to the name specified by path. /// /// - Parameter string: the string to write to file. /// /// - Parameter encoding: the encoding which should be used to represent the string as bytes. /// (by default: `NSUTF8StringEncoding`) /// /// - Returns: the contents of the file at the specified path as string. /// public func write(string: String, encoding: NSStringEncoding = NSUTF8StringEncoding) throws { try NSString(string: string).write(toFile: normalize().path, atomically: true, encoding: encoding) } } // MARK: Traversing extension Path { /// Get the parent directory /// /// - Returns: the normalized path of the parent directory /// public func parent() -> Path { return self + ".." } /// Performs a shallow enumeration in a directory /// /// - Returns: paths to all files, directories and symbolic links contained in the directory /// public func children() throws -> [Path] { return try Path.fileManager.contentsOfDirectory(atPath:path).map { self + Path($0) } } /// Performs a deep enumeration in a directory /// /// - Returns: paths to all files, directories and symbolic links contained in the directory or /// any subdirectory. /// public func recursiveChildren() throws -> [Path] { return try Path.fileManager.subpathsOfDirectory(atPath:path).map { self + Path($0) } } } // MARK: Globbing extension Path { public static func glob(pattern: String) -> [Path] { var gt = glob_t() let cPattern = strdup(pattern) defer { globfree(&gt) free(cPattern) } let flags = GLOB_TILDE | GLOB_BRACE | GLOB_MARK if system_glob(cPattern, flags, nil, &gt) == 0 { #if os(Linux) let matchc = gt.gl_pathc #else let matchc = gt.gl_matchc #endif #if !swift(>=3.0) return (0..<Int(matchc)).flatMap { index in if let path = String.fromCString(gt.gl_pathv[index]) { return Path(path) } return nil } #else return (0..<Int(matchc)).flatMap { index in if let path = String(validatingUTF8: gt.gl_pathv[index]!) { return Path(path) } return nil } #endif } // GLOB_NOMATCH return [] } public func glob(pattern: String) -> [Path] { return Path.glob(pattern: (self + pattern).description) } } // MARK: SequenceType extension Path : Sequence { /// Enumerates the contents of a directory, returning the paths of all files and directories /// contained within that directory. These paths are relative to the directory. public struct DirectoryEnumerator : IteratorProtocol { public typealias Element = Path let path: Path let directoryEnumerator: NSDirectoryEnumerator init(path: Path) { self.path = path self.directoryEnumerator = Path.fileManager.enumerator(atPath:path.path)! } public func next() -> Path? { if let next = directoryEnumerator.nextObject() as! String? { return path + next } return nil } /// Skip recursion into the most recently obtained subdirectory. public func skipDescendants() { directoryEnumerator.skipDescendants() } } /// Perform a deep enumeration of a directory. /// /// - Returns: a directory enumerator that can be used to perform a deep enumeration of the /// directory. /// #if !swift(>=3.0) public func generate() -> DirectoryEnumerator { return DirectoryEnumerator(path: self) } #else public func makeIterator() -> DirectoryEnumerator { return DirectoryEnumerator(path: self) } #endif } // MARK: Equatable extension Path : Equatable {} /// Determines if two paths are identical /// /// - Note: The comparison is string-based. Be aware that two different paths (foo.txt and /// ./foo.txt) can refer to the same file. /// public func ==(lhs: Path, rhs: Path) -> Bool { return lhs.path == rhs.path } // MARK: Pattern Matching /// Implements pattern-matching for paths. /// /// - Returns: `true` iff one of the following conditions is true: /// - the paths are equal (based on `Path`'s `Equatable` implementation) /// - the paths can be normalized to equal Paths. /// public func ~=(lhs: Path, rhs: Path) -> Bool { return lhs == rhs || lhs.normalize() == rhs.normalize() } // MARK: Comparable extension Path : Comparable {} /// Defines a strict total order over Paths based on their underlying string representation. public func <(lhs: Path, rhs: Path) -> Bool { return lhs.path < rhs.path } // MARK: Operators /// Appends a Path fragment to another Path to produce a new Path public func +(lhs: Path, rhs: Path) -> Path { return lhs.path + rhs.path } /// Appends a String fragment to another Path to produce a new Path public func +(lhs: Path, rhs: String) -> Path { return lhs.path + rhs } /// Appends a String fragment to another String to produce a new Path internal func +(lhs: String, rhs: String) -> Path { if rhs.hasPrefix(Path.separator) { // Absolute paths replace relative paths return Path(rhs) } else { var lSlice = NSString(string: lhs).pathComponents.fullSlice var rSlice = NSString(string: rhs).pathComponents.fullSlice // Get rid of trailing "/" at the left side if lSlice.count > 1 && lSlice.last == Path.separator { lSlice.removeLast() } // Advance after the first relevant "." lSlice = lSlice.filter { $0 != "." }.fullSlice rSlice = rSlice.filter { $0 != "." }.fullSlice // Eats up trailing components of the left and leading ".." of the right side while lSlice.last != ".." && rSlice.first == ".." { if (lSlice.count > 1 || lSlice.first != Path.separator) && !lSlice.isEmpty { // A leading "/" is never popped lSlice.removeLast() } if !rSlice.isEmpty { rSlice.removeFirst() } switch (lSlice.isEmpty, rSlice.isEmpty) { case (true, _): break case (_, true): break default: continue } } return Path(components: lSlice + rSlice) } } extension Array { var fullSlice: ArraySlice<Element> { return self[0..<self.endIndex] } }
052719a7bf82c427a36e98555bf32a5e
27.029487
112
0.66656
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
refs/heads/master
Solutions/SolutionsTests/Medium/Medium_064_Minimum_Path_Sum_Test.swift
mit
1
// // Medium_064_Minimum_Path_Sum_Test.swift // Solutions // // Created by Di Wu on 7/10/15. // Copyright © 2015 diwu. All rights reserved. // import XCTest class Medium_064_Minimum_Path_Sum_Test: XCTestCase, SolutionsTestCase { func test_001() { let input: [[Int]] = [ [0,0,0], [0,1,0], [0,0,0] ] let expected: Int = 0 asyncHelper(input: input, expected: expected) } func test_002() { let input: [[Int]] = [ ] let expected: Int = 0 asyncHelper(input: input, expected: expected) } func test_003() { let input: [[Int]] = [ [0,0,2], [0,1,0], [2,0,0] ] let expected: Int = 1 asyncHelper(input: input, expected: expected) } func test_004() { let input: [[Int]] = [ [1,5,2], [4,1,6], [2,0,0], [2,5,0] ] let expected: Int = 6 asyncHelper(input: input, expected: expected) } func test_005() { let input: [[Int]] = [ [1,5,2,3], [4,1,6,1], [2,0,3,0], [2,5,0,3] ] let expected: Int = 12 asyncHelper(input: input, expected: expected) } private func asyncHelper(input: [[Int]], expected: Int) { weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName()) serialQueue().async(execute: { () -> Void in let result = Medium_064_Minimum_Path_Sum.minPathSum(input) assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected) if let unwrapped = expectation { unwrapped.fulfill() } }) waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in if error != nil { assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected) } } } }
3442c219109dcdc977b1f694ae0aa298
28.577465
138
0.510476
false
true
false
false
rdhiggins/PythonMacros
refs/heads/master
PythonMacros/PythonCaptureOutput.swift
mit
1
// // PythonCaptureOutput.swift // MIT License // // Copyright (c) 2016 Spazstik Software, 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 Foundation /// A class that is used to capture the output streams from CPython. It loads /// the capture_output.py script and executes it. This script creates two /// python objects that capture standard out and standard error. /// /// The refreshOutput is called after CPython executes something. The Python /// objects a queryied for any text, which is then appended to the stdOutput or /// stdError buffers. class PythonCaptureOutput { fileprivate let kValueKey = "value" fileprivate let kCaptureScriptName = "capture_output" fileprivate let kPythonStandardOutputName = "standardOutput" fileprivate let kPythonStandardErrorName = "standardError" fileprivate var module: PythonObject? fileprivate var standardOutput: PythonObject? fileprivate var standardError: PythonObject? fileprivate var engine: PythonMacroEngine! /// Property that contains the standard output from CPython var stdOutput: String = String("") /// Property that contains the standard error output from CPython var stdError: String = String("") /// Initialization method that is called by PythonMacroEngine during /// it's initialization process. /// /// - parameter module: A PythonObject reference to the __main__ module. /// - parameter engine: A PythonMacroEngine reference used by the new object /// to monitor. init(module: PythonObject, engine: PythonMacroEngine) { self.engine = engine self.module = module loadCaptureScript() } deinit { module = nil standardOutput = nil standardError = nil } /// Method used to query the Python objects used to capture the streams. func refreshOutput() { refreshChannel(standardOutput!, channel: &stdOutput) refreshChannel(standardError!, channel: &stdError) } /// Method used to clear the stdOutput and stdError buffers func clearBuffers() { stdOutput = "" stdError = "" } /// A private method used to query a Python object for the captured output. /// The PythonObject reference to the particular python channel. The Python /// object's captured output is then cleared. /// /// - parameter object: A PythonObject reference to the python object used /// to capture the stream output. /// - parameter channel: The String buffer to append any new output to. fileprivate func refreshChannel(_ object: PythonObject, channel: inout String) { // This queries the python object for its new content guard let output = object.getAttrString(kValueKey) else { return } // content is appended to the buffer channel += output // This clears the python objects content object.setAttrString(kValueKey, value: "") } /// A private method that performs the setup for capturing the streams /// from CPython. It first loads the capture_python.py script from the /// applications resource bundle and then executes it in the CPython /// runtime. /// /// The two python objects are then looked up and references /// are stored so the the stream output can be queried. fileprivate func loadCaptureScript() { guard let module = self.module, let captureScript = PythonScriptDirectory.sharedInstance.load(kCaptureScriptName, location: .resource) else { print("No module reference") fatalError() } if captureScript.run(engine) { // Get a reference to the python objects used to capture the // output streams. standardOutput = module.getAttr(kPythonStandardOutputName) standardError = module.getAttr(kPythonStandardErrorName) } } } /// Extension used to provide description and debug description string extension PythonCaptureOutput: CustomStringConvertible, CustomDebugStringConvertible { var description: String { return customDescription() } var debugDescription: String { return "PythonCaptureOutput {\n" + " module: \(module.debugDescription)\n" + " std_out: \(standardOutput.debugDescription)\n" + " std_err: \(standardError.debugDescription)\n" + "}" } fileprivate func customDescription() -> String { return "Python StandardOutput: \(stdOutput)\nPython StandardError: \(stdError)\n" } }
91310afd9f795e293943519e3f7d3174
35.433962
121
0.674953
false
false
false
false
lingyijie/DYZB
refs/heads/master
DYZB/DYZB/Class/Home/View/GameRecommendView.swift
mit
1
// // GameRecommendView.swift // DYZB // // Created by ling yijie on 2017/9/15. // Copyright © 2017年 ling yijie. All rights reserved. // import UIKit fileprivate let kCollectionCellID = "kCollectionCellID" fileprivate let kNumberOfSections = 2 fileprivate let kNumberOfItemsInSection = 8 class GameRecommendView: UIView { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! var groups : [AnchorModelGroup]? { didSet { if groups == nil {return} // 移除“热门” groups?.removeFirst() // 添加“更多”图标,一共16组数据 let group : AnchorModelGroup = AnchorModelGroup() group.tag_name = "更多" group.icon_url = "" groups?.append(group) // pageControl.numberOfPages = kNumberOfSections // 展示数据 collectionView.reloadData() } } override func awakeFromNib() { autoresizingMask = UIViewAutoresizing(rawValue: 0) collectionView.register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kCollectionCellID) } } // 快速创建类方法 extension GameRecommendView { class func gameRecommendView() -> GameRecommendView { let gameRecommendView = Bundle.main.loadNibNamed("GameRecommendView", owner: nil, options: nil)?.first as! GameRecommendView return gameRecommendView } } // 遵守collection数据源协议、代理协议 extension GameRecommendView : UICollectionViewDataSource,UICollectionViewDelegate { func numberOfSections(in collectionView: UICollectionView) -> Int { return kNumberOfSections } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return kNumberOfItemsInSection } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCollectionCellID, for: indexPath) as! CollectionViewGameCell cell.group = groups?[indexPath.item + indexPath.section * kNumberOfItemsInSection] return cell } func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x pageControl.currentPage = Int(offsetX / scrollView.bounds.width) } }
8cbea448face75fe7b158dca767c3f1b
32.873239
136
0.686071
false
false
false
false
Roommate-App/roomy
refs/heads/master
roomy/roomy/HomeViewController.swift
mit
1
// // HomeViewController.swift // roomy // // Created by Ryan Liszewski on 4/4/17. // Copyright © 2017 Poojan Dave. All rights reserved. // import UIKit import Parse import ParseLiveQuery import MBProgressHUD import MapKit import UserNotifications import IBAnimatable import QuartzCore class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIViewControllerTransitioningDelegate, RoomySettingsDelegate{ @IBOutlet weak var homeTableView: UITableView! var region: CLCircularRegion! var roomiesHome: [Roomy]? = [] var roomiesNotHome: [Roomy]? = [] var roomies: [Roomy]? = [] var hud = MBProgressHUD() @IBOutlet weak var currentRoomyProfilePoster: AnimatableImageView! @IBOutlet weak var currentRoomynameLabel: UILabel! @IBOutlet weak var currentRoomyStatus: AnimatableLabel! @IBOutlet weak var currentRoomyHomeBadge: AnimatableImageView! var homeTableViewSection: RoomyTableViewCell! var notHomeTableViewSection: RoomyTableViewCell! private var subscription: Subscription<Roomy>! override func viewDidLoad() { super.viewDidLoad() LocationService.shared.setUpHouseFence() LocationService.shared.isRoomyHome() homeTableView.dataSource = self homeTableView.delegate = self homeTableView.sizeToFit() loadCurrentRoomyProfileView() addRoomiesToHome() let roomyQuery = getRoomyQuery() subscription = ParseLiveQuery.Client.shared.subscribe(roomyQuery).handle(Event.updated) { (query, roomy) in if(roomy.username != Roomy.current()?.username){ self.roomyChangedHomeStatus(roomy: roomy) let content = UNMutableNotificationContent() content.title = roomy.username! let roomyIsHome = roomy["is_home"] as! Bool if(roomyIsHome) { content.body = "Came Home!" } else { content.body = "Left Home!" } content.badge = 1 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false) let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger) UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error: Error?) in }) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) print("test") showProgressHud() updateRoomies() loadCurrentRoomyProfileView() } //MARK: Roomy settings delegate. func updateRoomyProfile(userName: String, profileImage: UIImage?){ if(userName != ""){ currentRoomynameLabel.text = userName } currentRoomyProfilePoster.image = profileImage } //MARK: Loads the current roomy's profile view. func loadCurrentRoomyProfileView(){ let roomy = Roomy.current() currentRoomynameLabel.text = roomy?.username //currentRoomyProfilePoster.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720") let pfImage = roomy?["profile_image"] as! PFFile currentRoomyStatus.text = roomy?["status_message"] as? String ?? "" pfImage.getDataInBackground(block: { (image: Data?, error: Error?) in if error == nil { self.currentRoomyProfilePoster.image = UIImage(data: image!) } else { } }) if(checkIfRoomyIsHome(roomy: Roomy.current()!)){ currentRoomyHomeBadge.image = #imageLiteral(resourceName: "home") } else { //currentRoomyHomeStatusLabel.text = "Not Home" currentRoomyHomeBadge.image = #imageLiteral(resourceName: "not-home") } } //MARK: PROGRESSHUD FUNCTIONS func showProgressHud(){ hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = MBProgressHUDMode.indeterminate hud.animationType = .zoomIn } func hideProgressHud(){ hud.hide(animated: true, afterDelay: 1) } //MARK: TABLE VIEW FUNCTIONS func reloadTableView(){ hud.hide(animated: true, afterDelay: 1) homeTableView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return 1 } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: R.Identifier.Cell.homeTableViewCell, for: indexPath) return cell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath){ guard let tableViewCell = cell as? RoomyTableViewCell else { return } if(indexPath.section == 0){ homeTableViewSection = tableViewCell } else { notHomeTableViewSection = tableViewCell } tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.section) } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30)) let homeTextLabel = UILabel(frame: CGRect(x: 20, y: 5, width: 100, height: 30)) homeTextLabel.adjustsFontSizeToFitWidth = true homeTextLabel.font = UIFont (name: "HelveticaNeue-UltraLight", size: 20) let iconImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 20, height: 20)) if(section == 0){ homeTextLabel.text = R.Header.home } else { homeTextLabel.text = R.Header.notHome } headerView.addSubview(homeTextLabel) return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } //MARK: PARSE QUERY TO GET ROOMIES func getRoomyQuery() -> PFQuery<Roomy>{ let query: PFQuery<Roomy> = PFQuery(className: "_User") query.whereKey("house", equalTo: House._currentHouse!) do { let roomies = try query.findObjects() self.roomies = roomies } catch let error as Error? { print(error?.localizedDescription ?? "ERROR") } return query } //MARK: ROOMY HOME FUNCTIONS func addRoomiesToHome() { //addCurrentRoomyToHome() for roomy in self.roomies! { if(roomy.objectId != Roomy.current()?.objectId){ if(self.checkIfRoomyIsHome(roomy: roomy)){ self.roomiesHome?.append(roomy) } else { self.roomiesNotHome?.append(roomy) } } } hideProgressHud() self.homeTableView.reloadData() } func addCurrentRoomyToHome(){ print(Roomy.current()?["is_home"]) if(checkIfRoomyIsHome(roomy: Roomy.current()!)){ roomiesHome?.append(Roomy.current()!) }else { roomiesNotHome?.append(Roomy.current()!) } homeTableView.reloadData() } func checkIfRoomyIsHome(roomy: Roomy) -> Bool{ return roomy["is_home"] as? Bool ?? false } func updateRoomies(){ roomiesHome = [] roomiesNotHome = [] for roomy in self.roomies! { do { try roomy.fetch() } catch let error as Error? { print(error?.localizedDescription ?? "ERROR") } } addRoomiesToHome() } func roomyChangedHomeStatus(roomy: Roomy){ let isRoomyHome = roomy["is_home"] as? Bool ?? false if(isRoomyHome){ roomiesNotHome = roomiesNotHome?.filter({$0.username != roomy.username}) roomiesHome?.append(roomy) notHomeTableViewSection.reloadCollectionViewData() } else { roomiesHome = roomiesHome?.filter({$0.username != roomy.username}) roomiesNotHome?.append(roomy) } //reloadTableView() notHomeTableViewSection.reloadCollectionViewData() homeTableViewSection.reloadCollectionViewData() } //MARK: Displays directions home in Google Maps (If available) or in Maps. @IBAction func onDirectionsHomeButtonTapped(_ sender: Any) { let directionsURL = URL(string: "comgooglemaps://?&daddr=\((House._currentHouse?.latitude)!),\((House._currentHouse?.longitude)!)&zoom=10") UIApplication.shared.open(directionsURL!) { (success: Bool) in if success { } else { let coordinate = CLLocationCoordinate2DMake(Double((House._currentHouse?.latitude)!)!, Double((House._currentHouse?.longitude)!)!) let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate)) mapItem.name = "Home" mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]) } } } //MARK: CHANGES CURRENT ROOMY'S STATUS @IBAction func onChangedStatusButtonTapped(_ sender: Any) { let storyboard = UIStoryboard(name: R.Identifier.Storyboard.Status, bundle: nil) let updateStatusViewController = storyboard.instantiateViewController(withIdentifier: R.Identifier.ViewController.updateStatusViewController) as! UpdateStatusViewController updateStatusViewController.transitioningDelegate = self updateStatusViewController.modalPresentationStyle = .custom let rootViewController = UIApplication.shared.keyWindow?.rootViewController self.present(updateStatusViewController, animated: true, completion: nil) } //MARK: Pop Custom Animation Controller func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PopPresentingAnimationController() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { currentRoomyStatus.text = Roomy.current()?[R.Parse.Key.StatusMessage] as! String currentRoomyStatus.animate() return PopDismissingAnimationController() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if(segue.identifier == R.Identifier.Segue.SettingsSegue){ let navigationController = segue.destination as! UINavigationController let settingsViewController = navigationController.topViewController as! SettingsViewController settingsViewController.settingsDelegate = self } } } extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView.tag == 0 { return (roomiesHome?.count)! } else { return roomiesNotHome!.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: R.Identifier.Cell.homeCollectionViewCell, for: indexPath) as! RoomyCollectionViewCell var statusText = "" if(collectionView.tag == 0) { let roomy = roomiesHome?[indexPath.row] statusText = roomy?["status_message"] as? String ?? "" cell.roomyUserNameLabel.text = roomy?.username cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720") let pfImage = roomy?["profile_image"] as! PFFile pfImage.getDataInBackground(block: { (image: Data?, error: Error?) in if error == nil && image != nil { print(image!) cell.roomyPosterView.image = UIImage(data: image!)! //cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720") } else { print("no image") //cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720") } }) } else { let roomy = roomiesNotHome?[indexPath.row] statusText = roomy?["status_message"] as? String ?? "" cell.roomyUserNameLabel.text = roomy?.username //cell.roomyStatusMessageLabel.text = roomy?["status_message"] as? //String ?? "" let pfImage = roomy?["profile_image"] as! PFFile pfImage.getDataInBackground(block: { (image: Data?, error: Error?) in if error == nil && image != nil{ cell.roomyPosterView.image = UIImage(data: image!)! //print(image!) //cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720") } else { print("no image") //cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720") } }) } if(statusText != ""){ let index = statusText.index((statusText.startIndex), offsetBy: 1) let emoji = statusText.substring(to: index) cell.roomyBadgeView.image = emoji.image() } return cell } //MARK: Draws a badge on an UIImageView func drawImageView(mainImage: UIImage, withBadge badge: UIImage) -> UIImage { UIGraphicsBeginImageContextWithOptions(mainImage.size, false, 0.0) mainImage.draw(in: CGRect(x: 0, y: 0, width: mainImage.size.width, height: mainImage.size.height)) badge.draw(in: CGRect(x: mainImage.size.width - badge.size.width, y: 0, width: badge.size.width, height: badge.size.height)) let resultImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return resultImage } } //MARK: USER NOTIFICATION DELEGATE CLASS EXTENSION. DISPLAYS NOTFICATION TO ROOMY. extension HomeViewController: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let storyboard = UIStoryboard(name: R.Identifier.Storyboard.tabBar, bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: R.Identifier.ViewController.tabBarViewController) as! UITabBarController viewController.selectedIndex = R.TabBarController.SelectedIndex.messagingViewController self.present(viewController, animated: true, completion: nil) } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print("Notification being triggered") completionHandler( [.alert,.sound,.badge]) } } //MARK: Converts a string to an UIImage. Used to convert emoji's to UIImages in roomy status. extension String { func image() -> UIImage? { let size = CGSize(width: 30, height: 35) UIGraphicsBeginImageContextWithOptions(size, false, 0); UIColor.white.set() let rect = CGRect(origin: CGPoint(), size: size) UIRectFill(CGRect(origin: CGPoint(), size: size)) (self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
ae40b2eeee2f8978e3f6fd8baad35d5c
37.065022
207
0.620722
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/wwdc_demo/ImageFeed/Model/Person.swift
mit
1
/* See LICENSE folder for this sample’s licensing information. Abstract: Model object representing a single person. */ import Foundation enum PersonUpdate { case delete(Int) case insert(Person, Int) case move(Int, Int) case reload(Int) } struct Person: CustomStringConvertible { var name: String? var imgName: String? var lastUpdate = Date() init(name: String, month: Int, day: Int, year: Int) { self.name = name self.imgName = name.lowercased() var components = DateComponents() components.day = day components.month = month components.year = year if let date = Calendar.current.date(from: components) { lastUpdate = date } } var isUpdated: Bool? { didSet { lastUpdate = Date() } } var description: String { if let name = self.name { return "<\(type(of: self)): name = \(name)>" } else { return "<\(type(of: self))>" } } }
7fd72ac39800835e8feda43532b8ee80
20.653061
63
0.557964
false
false
false
false
Dimillian/HackerSwifter
refs/heads/master
Hacker Swifter/Hacker Swifter/HTTP/Fetcher.swift
mit
1
// // Fetcher.swift // Hacker Swifter // // Created by Thomas Ricouard on 11/07/14. // Copyright (c) 2014 Thomas Ricouard. All rights reserved. // import Foundation private let _Fetcher = Fetcher() public class Fetcher { internal let baseURL = "https://news.ycombinator.com/" internal let APIURL = "https://hacker-news.firebaseio.com/v0/" internal let APIFormat = ".json" private let session = NSURLSession.sharedSession() public typealias FetchCompletion = (object: AnyObject!, error: ResponseError!, local: Bool) -> Void public typealias FetchParsing = (html: String!) -> AnyObject! public typealias FetchParsingAPI = (json: AnyObject) -> AnyObject! public enum ResponseError: String { case NoConnection = "You are not connected to the internet" case ErrorParsing = "An error occurred while fetching the requested page" case UnknownError = "An unknown error occurred" } public enum APIEndpoint: String { case Post = "item/" case User = "user/" case Top = "topstories" case New = "newstories" case Ask = "askstories" case Jobs = "jobstories" case Show = "showstories" } public class var sharedInstance: Fetcher { return _Fetcher } class func Fetch(ressource: String, parsing: FetchParsing, completion: FetchCompletion) { let cacheKey = Cache.generateCacheKey(ressource) Cache.sharedCache.objectForKey(cacheKey, completion: {(object: AnyObject!) in if let realObject: AnyObject = object { completion(object: realObject, error: nil, local: true) } }) let path = _Fetcher.baseURL + ressource let task = _Fetcher.session.dataTaskWithURL(NSURL(string: path)! , completionHandler: {(data: NSData?, response, error: NSError?) in if !(error != nil) { if let realData = data { let object: AnyObject! = parsing(html: NSString(data: realData, encoding: NSUTF8StringEncoding) as! String) if let realObject: AnyObject = object { Cache.sharedCache.setObject(realObject, key: cacheKey) } dispatch_async(dispatch_get_main_queue(), { ()->() in completion(object: object, error: nil, local: false) }) } else { dispatch_async(dispatch_get_main_queue(), { ()->() in completion(object: nil, error: ResponseError.UnknownError, local: false) }) } } else { completion(object: nil, error: ResponseError.UnknownError, local: false) } }) task.resume() } //In the future, all scraping will be removed and we'll use only the Algolia API //At the moment this function is sufixed for testing purpose class func FetchJSON(endpoint: APIEndpoint, ressource: String?, parsing: FetchParsingAPI, completion: FetchCompletion) { var path: String if let realRessource: String = ressource { path = _Fetcher.APIURL + endpoint.rawValue + realRessource + _Fetcher.APIFormat } else { path = _Fetcher.APIURL + endpoint.rawValue + _Fetcher.APIFormat } let cacheKey = Cache.generateCacheKey(path) Cache.sharedCache.objectForKey(cacheKey, completion: {(object: AnyObject!) in if let realObject: AnyObject = object { completion(object: realObject, error: nil, local: true) } }) let task = _Fetcher.session.dataTaskWithURL(NSURL(string: path)! , completionHandler: {(data: NSData?, response, error: NSError?) in if let data = data { var error: NSError? = nil var JSON: AnyObject! do { JSON = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) } catch let error1 as NSError { error = error1 JSON = nil } catch { fatalError() } if error == nil { let object: AnyObject! = parsing(json: JSON) if let object: AnyObject = object { if let realObject: AnyObject = object { Cache.sharedCache.setObject(realObject, key: cacheKey) } dispatch_async(dispatch_get_main_queue(), { ()->() in completion(object: object, error: nil, local: false) }) } else { dispatch_async(dispatch_get_main_queue(), { ()->() in completion(object: nil, error: ResponseError.ErrorParsing, local: false) }) } } else { completion(object: nil, error: ResponseError.UnknownError, local: false) } } }) task.resume() } }
cbef89f93db9b3e1e6a18c7169e03b8b
38.567164
140
0.541407
false
false
false
false
17thDimension/AudioKit
refs/heads/develop
Examples/iOS/Swift/AudioKitDemo/AudioKitDemo/Processing/AudioFilePlayer.swift
lgpl-3.0
2
// // AudioFilePlayer.swift // AudioKitDemo // // Created by Nicholas Arner on 3/1/15. // Copyright (c) 2015 AudioKit. All rights reserved. // class AudioFilePlayer: AKInstrument { var auxilliaryOutput = AKAudio() // INSTRUMENT BASED CONTROL ============================================ var speed = AKInstrumentProperty(value: 1, minimum: -2, maximum: 2) var scaling = AKInstrumentProperty(value: 1, minimum: 0.0, maximum: 3.0) var sampleMix = AKInstrumentProperty(value: 0, minimum: 0, maximum: 1) // INSTRUMENT DEFINITION =============================================== override init() { super.init() addProperty(speed) addProperty(scaling) addProperty(sampleMix) let file1 = String(NSBundle.mainBundle().pathForResource("PianoBassDrumLoop", ofType: "wav")!) let file2 = String(NSBundle.mainBundle().pathForResource("808loop", ofType: "wav")!) let fileIn1 = AKFileInput(filename: file1) fileIn1.speed = speed fileIn1.loop = true let fileIn2 = AKFileInput(filename: file2) fileIn2.speed = speed fileIn2.loop = true var fileInLeft = AKMix(input1: fileIn1.leftOutput, input2: fileIn2.leftOutput, balance: sampleMix) var fileInRight = AKMix(input1: fileIn1.rightOutput, input2: fileIn2.rightOutput, balance: sampleMix) var leftF = AKFFT( input: fileInLeft.scaledBy(0.25.ak), fftSize: 1024.ak, overlap: 256.ak, windowType: AKFFT.hammingWindow(), windowFilterSize: 1024.ak ) var leftR = AKFFT( input: fileInRight.scaledBy(0.25.ak), fftSize: 1024.ak, overlap: 256.ak, windowType: AKFFT.hammingWindow(), windowFilterSize: 1024.ak ) var scaledLeftF = AKScaledFFT( signal: leftF, frequencyRatio: scaling ) var scaledLeftR = AKScaledFFT( signal: leftR, frequencyRatio: scaling ) var scaledLeft = AKResynthesizedAudio(signal: scaledLeftF) var scaledRight = AKResynthesizedAudio(signal: scaledLeftR) var mono = AKMix(input1: scaledLeft, input2: scaledRight, balance: 0.5.ak) // Output to global effects processing auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to: mono) } }
c16c69d8c6e83b65fa46c3d6ac9ffeb5
32.103896
109
0.576923
false
false
false
false
robertherdzik/RHPlaygroundFreestyle
refs/heads/master
Hypnotize/RHHypnotize.playground/Contents.swift
mit
1
import UIKit import PlaygroundSupport let sideLenght = 200 let viewFrame = CGRect(x: 0, y: 0, width: sideLenght, height: sideLenght) let baseView = UIView(frame: viewFrame) baseView.backgroundColor = UIColor.gray // Creating our circle path let circlePath = UIBezierPath(arcCenter: baseView.center, radius: viewFrame.size.width/2, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true) let lineWidth = CGFloat(3) let shapeLayer = CAShapeLayer() shapeLayer.frame = viewFrame shapeLayer.path = circlePath.cgPath shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = UIColor.cyan.cgColor shapeLayer.lineWidth = lineWidth // Now the magic 🎩 begins, we create our Replicator 🎉 which will multiply our shapeLayer. let replicator = CAReplicatorLayer() replicator.frame = viewFrame replicator.instanceDelay = 0.05 replicator.instanceCount = 30 replicator.instanceTransform = CATransform3DMakeScale(1, 1, 1) replicator.addSublayer(shapeLayer) baseView.layer.addSublayer(replicator) let fade = CABasicAnimation(keyPath: "opacity") fade.fromValue = 0.05 fade.toValue = 0.3 fade.duration = 1.5 fade.beginTime = CACurrentMediaTime() fade.repeatCount = .infinity fade.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) shapeLayer.add(fade, forKey: "shapeLayerOpacity") let scale = CABasicAnimation(keyPath: "transform") scale.fromValue = NSValue(caTransform3D: CATransform3DMakeScale(0, 0, 1)) scale.toValue = NSValue(caTransform3D: CATransform3DMakeScale(1, 1, 1)) scale.duration = 1.5 scale.repeatCount = .infinity scale.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) shapeLayer.add(scale, forKey: "shapeLayerScale") PlaygroundPage.current.liveView = baseView
26dd10bfc87fca9292fb09f3bae92d5e
31.947368
91
0.749201
false
false
false
false
JunDang/SwiftFoundation
refs/heads/develop
Sources/UnitTests/UUIDTests.swift
mit
1
// // UUIDTests.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/2/15. // Copyright © 2015 PureSwift. All rights reserved. // import XCTest import SwiftFoundation import SwiftFoundation final class UUIDTests: XCTestCase { lazy var allTests: [(String, () -> ())] = [("testCreateRandomUUID", self.testCreateRandomUUID), ("testUUIDString", self.testUUIDString), ("testCreateFromString", self.testCreateFromString)] // MARK: - Functional Tests func testCreateRandomUUID() { // try to create without crashing let uuid = UUID() print(uuid) } func testUUIDString() { let stringValue = "5BFEB194-68C4-48E8-8F43-3C586364CB6F" guard let uuid = UUID(rawValue: stringValue) else { XCTFail("Could not create UUID from " + stringValue); return } XCTAssert(uuid.rawValue == stringValue, "UUID is \(uuid), should be \(stringValue)") } func testCreateFromString() { let stringValue = "5BFEB194-68C4-48E8-8F43-3C586364CB6F" XCTAssert((UUID(rawValue: stringValue) != nil), "Could not create UUID with string \"\(stringValue)\"") XCTAssert((UUID(rawValue: "BadInput") == nil), "UUID should not be created") } }
9a39a93ccdb16bac003e91a98b8e30f9
27.104167
111
0.60934
false
true
false
false
AlexeyGolovenkov/DevHelper
refs/heads/master
DevHelper/Ext/CommentCommand.swift
mit
1
// // CommentCommand.swift // DevHelper // // Created by Alexey Golovenkov on 12.03.17. // Copyright © 2017 Alexey Golovenkov. All rights reserved. // import Cocoa import XcodeKit class CommentCommand: NSObject, XCSourceEditorCommand { func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) { for selection in invocation.buffer.selections { guard let range = DHTextRange(textRange: selection as? XCSourceTextRange) else { continue } let newSelection = invocation.buffer.lines.comment(range: range) guard let textSelection = selection as? XCSourceTextRange else { continue } textSelection.start.column = newSelection.start.column textSelection.start.line = newSelection.start.line textSelection.end.column = newSelection.end.column textSelection.end.line = newSelection.end.line } completionHandler(nil) } }
3d036863ffc24e89dce0754e70100de9
27.875
116
0.745671
false
false
false
false
rambler-digital-solutions/rambler-it-ios
refs/heads/develop
Carthage/Checkouts/rides-ios-sdk/examples/Swift SDK/Swift SDK/RideRequestWidgetExampleViewController.swift
mit
1
// // RideRequestWidgetExampleViewController.swift // Swift SDK // // Copyright © 2015 Uber Technologies, Inc. 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 UIKit import UberRides import CoreLocation /// This class provides an example of how to use the RideRequestButton to initiate /// a ride request using the Ride Request Widget class RideRequestWidgetExampleViewController: ButtonExampleViewController { var blackRideRequestButton: RideRequestButton! var whiteRideRequestButton: RideRequestButton! let locationManger:CLLocationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.navigationItem.title = "Ride Request Widget" blackRideRequestButton = buildRideRequestWidgetButton(.native) whiteRideRequestButton = buildRideRequestWidgetButton(.implicit) whiteRideRequestButton.colorStyle = .white topView.addSubview(blackRideRequestButton) bottomView.addSubview(whiteRideRequestButton) addBlackRequestButtonConstraints() addWhiteRequestButtonConstraints() locationManger.delegate = self if !checkLocationServices() { locationManger.requestWhenInUseAuthorization() } } // Mark: Private Interface fileprivate func buildRideRequestWidgetButton(_ loginType: LoginType) -> RideRequestButton { let loginManager = LoginManager(loginType: loginType) let requestBehavior = RideRequestViewRequestingBehavior(presentingViewController: self, loginManager: loginManager) requestBehavior.modalRideRequestViewController.delegate = self let rideParameters = RideParametersBuilder().build() let accessTokenString = "access_token_string" let token = AccessToken(tokenString: accessTokenString) if TokenManager.save(accessToken: token){ // Success } else { // Unable to save } TokenManager.fetchToken() TokenManager.deleteToken() return RideRequestButton(rideParameters: rideParameters, requestingBehavior: requestBehavior) } fileprivate func addBlackRequestButtonConstraints() { blackRideRequestButton.translatesAutoresizingMaskIntoConstraints = false let centerYConstraint = NSLayoutConstraint(item: blackRideRequestButton, attribute: .centerY, relatedBy: .equal, toItem: topView, attribute: .centerY, multiplier: 1.0, constant: 0.0) let centerXConstraint = NSLayoutConstraint(item: blackRideRequestButton, attribute: .centerX, relatedBy: .equal, toItem: topView, attribute: .centerX, multiplier: 1.0, constant: 0.0) topView.addConstraints([centerYConstraint, centerXConstraint]) } fileprivate func addWhiteRequestButtonConstraints() { whiteRideRequestButton.translatesAutoresizingMaskIntoConstraints = false let centerYConstraint = NSLayoutConstraint(item: whiteRideRequestButton, attribute: .centerY, relatedBy: .equal, toItem: bottomView, attribute: .centerY, multiplier: 1.0, constant: 0.0) let centerXConstraint = NSLayoutConstraint(item: whiteRideRequestButton, attribute: .centerX, relatedBy: .equal, toItem: bottomView, attribute: .centerX, multiplier: 1.0, constant: 0.0) bottomView.addConstraints([centerYConstraint, centerXConstraint]) } fileprivate func checkLocationServices() -> Bool { let locationEnabled = CLLocationManager.locationServicesEnabled() let locationAuthorization = CLLocationManager.authorizationStatus() let locationAuthorized = locationAuthorization == .authorizedWhenInUse || locationAuthorization == .authorizedAlways return locationEnabled && locationAuthorized } fileprivate func showMessage(_ message: String) { let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.alert) let okayAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil) alert.addAction(okayAction) self.present(alert, animated: true, completion: nil) } } //MARK: ModalViewControllerDelegate extension RideRequestWidgetExampleViewController : ModalViewControllerDelegate { func modalViewControllerDidDismiss(_ modalViewController: ModalViewController) { print("did dismiss") } func modalViewControllerWillDismiss(_ modalViewController: ModalViewController) { print("will dismiss") } } //MARK: CLLocationManagerDelegate extension RideRequestWidgetExampleViewController : CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .denied || status == .restricted { showMessage("Location Services disabled.") } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { locationManger.stopUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationManger.stopUpdatingLocation() showMessage("There was an error locating you.") } }
d61ac2fd398397e114b5def60aebd19f
41.86755
193
0.722694
false
false
false
false
iosdevelopershq/code-challenges
refs/heads/master
CodeChallenge/Challenges/LetterCombinationsOfPhoneNumber/Entries/BugKrushaLetterCombinationsOfPhoneNumberEntry.swift
mit
1
// // BugKrusha.swift // CodeChallenge // // Created by Jon-Tait Beason on 11/2/15. // Copyright © 2015 iosdevelopers. All rights reserved. // import Foundation let bugKrushaLetterCombinationOfPhoneNumberEntry = CodeChallengeEntry<LetterCombinationsOfPhoneNumberChallenge>(name: "bugKrusha") { input in return getCombinations(digitString: input) } private enum Digit: String { case Two = "abc" case Three = "def" case Four = "ghi" case Five = "jkl" case Six = "mno" case Seven = "pqrs" case Eight = "tuv" case Nine = "wxyz" } private func getCharactersForNumber(number: String) -> Digit? { switch number { case "2": return Digit.Two case "3": return Digit.Three case "4": return Digit.Four case "5": return Digit.Five case "6": return Digit.Six case "7": return Digit.Seven case "8": return Digit.Eight case "9": return Digit.Nine default: break } return nil } private func getCombinations(digitString: String) -> [String] { var arrayOfCharacterSets = [String]() for (index, character) in digitString.characters.enumerated() { if let charactersForNumber = getCharactersForNumber(number: "\(character)")?.rawValue { if index == 0 { arrayOfCharacterSets = charactersForNumber.characters.map { "\($0)" } } else { var tempArray = [String]() for char in charactersForNumber.characters { for characterSet in arrayOfCharacterSets { let newString = characterSet + "\(char)" tempArray.append(newString) } } arrayOfCharacterSets = tempArray } } } return arrayOfCharacterSets }
bd62aed9df3d928e8c6b8d24ef77e082
26.769231
141
0.607202
false
false
false
false
IAskWind/IAWExtensionTool
refs/heads/master
IAWExtensionTool/IAWExtensionTool/Classes/UIKit/IAW_ImageView+Extension.swift
mit
1
// // IAWImageView.swift // IAWExtensionTool // // Created by winston on 16/11/17. // Copyright © 2016年 winston. All rights reserved. // import Foundation import UIKit import Kingfisher extension UIImageView { open func iawCircleHeader(_ url: String,radius:Int){ if url != "" { self.kf.setImage(with: URL(string:url)!, placeholder: IAW_ImgXcassetsTool.headerPhoto.image) }else{ self.image = IAW_ImgXcassetsTool.headerPhoto.image } self.layer.cornerRadius = CGFloat(radius) self.layer.borderColor = UIColor.white.cgColor self.layer.borderWidth = 2 self.layer.masksToBounds = true } open func showView(){ } // 360度旋转图片 open func rotate360Degree() { let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") // 让其在z轴旋转 rotationAnimation.toValue = NSNumber(value: .pi * 2.0) // 旋转角度 rotationAnimation.duration = 0.6 // 旋转周期 rotationAnimation.isCumulative = true // 旋转累加角度 rotationAnimation.repeatCount = MAXFLOAT // 旋转次数 layer.add(rotationAnimation, forKey: "rotationAnimation") } // 停止旋转 open func stopRotate() { layer.removeAllAnimations() } }
c0f70d7629e02fec2e35a2ca5c4723f0
26.413043
104
0.642347
false
false
false
false
shirai/SwiftLearning
refs/heads/master
playground/メソッド.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit /* * *インスタンスメソッド * */ /* 職種 */ enum Job { case Warrior, Mage, Thief, Priest func initialHitPoint() -> Int { switch self { case .Warrior: return 100 case .Mage: return 40 case .Thief: return 60 case .Priest: return 30 } } } /* キャラクタ */ class GameCharacter { var name: String var job: Job var maxHitPoint: Int { didSet { self.hitPoint = self.maxHitPoint } } var hitPoint: Int = 0 // イニシャライザ init(name: String, job: Job) { self.name = name self.job = job self.maxHitPoint = self.job.initialHitPoint() } // ダメージを与える func addDamage(damage: Int) { hitPoint -= damage if hitPoint <= 0 { print("死んだ") } } } //インスタンスメソッドを呼び出す場合は、フロパティと同様、.(ドット)をつけて呼び出します。 var player = GameCharacter(name: "ヨシヒコ", job: .Warrior) print(player.hitPoint) player.addDamage(damage: 40) print(player.hitPoint) /* * *破壊的メソッド 構造体、列挙型のメソッドはプロパティを変更することはできない mutatingをfuncの前につけて宣言することで属性値を変更できる 定数の構造体、列挙型ではmutatingメソッドを呼び出すことはできない クラスの場合は変更可能 * */ /* キャラクタ */ struct Character { var name: String var job: Job var level: Int // func changeJob(newJob: Job) { // self.job = newJob //コンパイルエラー mutating func changeJob(newJob: Job) { self.job = newJob // OK } } //定数の構造体や列挙型の破壊的メソッドを呼び出す事はできない。変数であれば可能。 let player1 = Character(name: "ヨシヒコ", job: .Warrior, level: 10) //player.changeJob(newJob:.Mage) // コンパイルエラー var player2 = Character(name: "ダンジョー", job: .Warrior, level: 10) player2.changeJob(newJob: .Mage) // OK //破壊的メソッドでは、次のようにself自体を変更することも可能。 /* ゲームキャラクタ */ struct GameCharacter2 { var name: String var job: Job var level: Int mutating func changeJob(newJob: Job) { self = GameCharacter2(name: self.name, job: newJob, level: self.level) } } var player3 = GameCharacter2(name: "ヨシヒコ", job: .Warrior, level: 10) player3.changeJob(newJob: .Mage) print(player.job == .Mage) /* オセロの駒 */ enum OthelloPiece { case White, Black mutating func reverse() { self = (self == .White ? .Black : .White) } } var piece = OthelloPiece.White piece.reverse(); print(piece == .Black) /* * *型メソッド * */ /* じゃんけん */ enum Janken { case goo, choki, paa static func sayPriming() { print("最初はグー") } } Janken.sayPriming() /* ログイン情報 */ struct LoginInfo { static var url = "https://login.example.com/" static func isSecure() -> Bool { return url.hasPrefix("https:") } var userid: String var password: String } print(LoginInfo.isSecure()) /* パーソンクラス */ class Person { class var tableName: String { return "people" //データペーステーブル名 } class func tableNameWithPrefix(prefix: String) -> String { return "\(prefix)_\(tableName)" } var name: String var address: String var tel: String var email: String init(name: String, address: String, tel: String, email: String) { self.name = name self.address = address self.tel = tel self.email = email } } print(Person.tableNameWithPrefix(prefix: "bak"))
1be566c53b4babf8753baf623bb3267c
19.294479
78
0.603386
false
false
false
false
xiajinchun/NimbleNinja
refs/heads/master
NimbleNinja/GameScene.swift
mit
1
// // GameScene.swift // NimbleNinja // // Created by Jinchun Xia on 15/4/14. // Copyright (c) 2015 TEAM. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var movingGround: NNMovingGround! var hero: NNHero! var cloudGenerator: NNCloudGenerator! var wallGenerator: NNWallGenerator! var isStarted = false var isGameOver = false override func didMoveToView(view: SKView) { /* Setup your scene here */ backgroundColor = UIColor(red: 159.0/255.0, green: 201.0/255.0, blue: 244.0/255.0, alpha: 1.0) /* add ground */ addMovingGround() /* add hero */ addHero() /* add cloud generator */ addCloudGenerator() /* add wall generator */ addWallGenerator() /* add start label */ addTapToStartLabel() /* add physics world */ addPhysicsWorld() } func addMovingGround() { movingGround = NNMovingGround(size: CGSizeMake(view!.frame.width, kMLGroundHeight)) movingGround.position = CGPointMake(0, view!.frame.size.height / 2) self.addChild(movingGround) } func addHero() { hero = NNHero() hero.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height / 2 + hero.frame.size.height / 2) self.addChild(hero) hero.breath() } func addCloudGenerator() { cloudGenerator = NNCloudGenerator(color: UIColor.clearColor(), size: view!.frame.size) cloudGenerator.position = view!.center cloudGenerator.zPosition = -10 addChild(cloudGenerator) cloudGenerator.populate(7) cloudGenerator.startGeneratingWithSpawnTime(5) } func addWallGenerator() { wallGenerator = NNWallGenerator(color: UIColor.clearColor(), size: view!.frame.size) wallGenerator.position = view!.center addChild(wallGenerator) } func addTapToStartLabel() { let tapToStartLabel = SKLabelNode(text: "Tap to start!") tapToStartLabel.name = "tapToStartLabel" tapToStartLabel.position.x = view!.center.x tapToStartLabel.position.y = view!.center.y + 40 tapToStartLabel.fontName = "Helvetice" tapToStartLabel.fontColor = UIColor.blackColor() tapToStartLabel.fontSize = 22.0 addChild(tapToStartLabel) tapToStartLabel.runAction(blinkAnimation()) } func addPhysicsWorld() { physicsWorld.contactDelegate = self } // MARK: - Game Lifecycle func start() { isStarted = true /* find the ndoe by named "tapToStartLabel" and then remove it from parent node */ let tapToStartLabel = childNodeWithName("tapToStartLabel") tapToStartLabel?.removeFromParent() hero.stop() hero.startRuning() movingGround.start() wallGenerator.startGeneratingWallsEvery(1) } func gameOver() { isGameOver = true // stop everthing hero.fail() wallGenerator.stopWalls() movingGround.stop() hero.stop() // create game over label let gameOverLabel = SKLabelNode(text: "Game Over!") gameOverLabel.fontColor = UIColor.blackColor() gameOverLabel.fontName = "Helvetice" gameOverLabel.position.x = view!.center.x gameOverLabel.position.y = view!.center.y + 40 gameOverLabel.fontSize = 22.0 addChild(gameOverLabel) gameOverLabel.runAction(blinkAnimation()) } func restart() { cloudGenerator.stopGenerating() let newScene = GameScene(size: view!.bounds.size) newScene.scaleMode = SKSceneScaleMode.AspectFill view!.presentScene(newScene) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { /* Called when a touch begins */ if isGameOver { restart() } else if !isStarted { start() } else { hero.flip() } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } // MARK: - SKPhysiscContactDeleagte func didBeginContact(contact: SKPhysicsContact) { if !isGameOver{ gameOver() } } // MARK: - Animation func blinkAnimation() -> SKAction { let duration = 0.4 let fadeOut = SKAction.fadeAlphaTo(0.0, duration: duration) let fadeIn = SKAction.fadeAlphaTo(1.0, duration: duration) let blink = SKAction.sequence([fadeOut, fadeIn]) return SKAction.repeatActionForever(blink) } }
64c0725056ffe065b60c53cd99ea9155
28.567073
130
0.603135
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
refs/heads/master
ResearchUXFactory/SBAPermissionsManager.swift
bsd-3-clause
1
// // SBAPermissionsManager.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation extension SBAPermissionsManager { public static var shared: SBAPermissionsManager { return __shared() } /** Are all the permissions granted? @param permissionTypes Permissions to check @return Whether or not all have been granted */ public func allPermissionsAuthorized(for permissionTypes:[SBAPermissionObjectType]) -> Bool { for permissionType in permissionTypes { if !self.isPermissionGranted(for: permissionType) { return false } } return true } /** Request permission for each permission in the list. @param permissions List of the permissions being requested @param alertPresenter Alert presenter to use for showing alert messages @param completion Completion handler to call when all the permissions have been requested */ public func requestPermissions(for permissions: [SBAPermissionObjectType], alertPresenter: SBAAlertPresenter?, completion: ((Bool) -> Void)?) { // Exit early if there are no permissions guard permissions.count > 0 else { completion?(true) return } DispatchQueue.main.async(execute: { // Use an enumerator to recursively step thorough each permission and request permission // for that type. var allGranted = true let enumerator = (permissions as NSArray).objectEnumerator() func enumerateRequest() { guard let permission = enumerator.nextObject() as? SBAPermissionObjectType else { completion?(allGranted) return } if self.isPermissionGranted(for: permission) { enumerateRequest() } else { self.requestPermission(for: permission, completion: { [weak alertPresenter] (success, error) in DispatchQueue.main.async(execute: { allGranted = allGranted && success if !success, let presenter = alertPresenter { let title = Localization.localizedString("SBA_PERMISSIONS_FAILED_TITLE") let message = error?.localizedDescription ?? Localization.localizedString("SBA_PERMISSIONS_FAILED_MESSAGE") presenter.showAlertWithOk(title: title, message: message, actionHandler: { (_) in enumerateRequest() }) } else { enumerateRequest() } }) }) } } enumerateRequest() }) } // MARK: Deprecated methods included for reverse-compatibility @available(*, deprecated) @objc(permissionTitleForType:) open func permissionTitle(for type: SBAPermissionsType) -> String { return self.typeIdentifierFor(for: type)?.defaultTitle() ?? "" } @available(*, deprecated) @objc(permissionDescriptionForType:) open func permissionDescription(for type: SBAPermissionsType) -> String { return self.typeIdentifierFor(for: type)?.defaultDescription() ?? "" } }
bba903094dd06ae4f53ddd903e21fd0d
41.5
147
0.614939
false
false
false
false
eleks/digital-travel-book
refs/heads/master
src/Swift/Weekend In Lviv/ViewControllers/Photo Gallery/WLPhotoGalleryVCSw.swift
mit
1
// // WLPhotoGalleryVCSw.swift // Weekend In Lviv // // Created by Admin on 13.06.14. // Copyright (c) 2014 rnd. All rights reserved. // import UIKit class ImageViewController:UIViewController { // Instance variables var index:UInt = 0 var imageView:UIImageView? = nil var _imagePath:String = "" var imagePath:String { get { return _imagePath } set (imagePath) { _imagePath = imagePath if let imageView_ = imageView? { imageView_.removeFromSuperview() } self.imageView = UIImageView(image: UIImage(contentsOfFile: self.imagePath)) self.imageView!.frame = self.view.bounds self.imageView!.contentMode = UIViewContentMode.ScaleAspectFit self.view = self.imageView! } } } class WLPhotoGalleryVCSw: UIViewController, UIScrollViewDelegate, UIPageViewControllerDataSource { // Outlets @IBOutlet weak var scrollImages:UIScrollView? @IBOutlet weak var lblSwipe:UILabel? @IBOutlet weak var btnClose:UIButton? // Instance variables var imagePathList: [String] = [] var selectedImageIndex:UInt = 0 var pageController:UIPageViewController? = nil // Instance methods override func viewDidLoad() { super.viewDidLoad() self.lblSwipe!.font = WLFontManager.sharedManager.gentiumItalic15 self.pageController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options:nil) let initialViewController:UIViewController? = self.viewControllerAtIndex(Int(self.selectedImageIndex)) if let initVC_ = initialViewController? { self.pageController!.setViewControllers([initVC_], direction:UIPageViewControllerNavigationDirection.Forward, animated:false, completion:nil) } self.addChildViewController(self.pageController!) self.view.addSubview(self.pageController!.view) self.pageController!.didMoveToParentViewController(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.pageController!.dataSource = self self.pageController!.view.frame = self.view.bounds self.pageController!.view.frame = self.scrollImages!.frame self.view.addSubview(self.pageController!.view) self.view.bringSubviewToFront(self.btnClose!) self.btnClose!.enabled = true self.view.bringSubviewToFront(self.lblSwipe!) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView()) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().postNotificationName("ShowPlayer", object:nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } /* Unavailable in Swift override func shouldAutorotateToInterfaceOrientation(toInterfaceOrientation:UIInterfaceOrientation) -> Bool { return true }*/ func btnMenuTouch(sender:AnyObject) { self.mm_drawerController!.toggleDrawerSide(MMDrawerSide.Left, animated:true, completion:nil) } //#pragma mark - Page view controller delegate func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { let imageController = viewController as ImageViewController return self.viewControllerAtIndex(Int(imageController.index) - 1) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { let imageController = viewController as ImageViewController return self.viewControllerAtIndex(Int(imageController.index) + 1) } func viewControllerAtIndex(index:Int) -> ImageViewController? { var photoVC:ImageViewController? = nil if index >= 0 && index < self.imagePathList.count { photoVC = ImageViewController() photoVC!.imagePath = self.imagePathList[Int(index)] photoVC!.index = UInt(index) } return photoVC } //#pragma mark - Page view controller data source // Actions @IBAction func btnCloseTouch(sender:AnyObject) { self.navigationController!.popViewControllerAnimated(true) } }
907f9ae82f9085bf416c68046a57f969
32.763514
161
0.644187
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Camera/View/PreviewMetalView.swift
mit
1
/* See LICENSE folder for this sample’s licensing information. Abstract: The Metal preview view. */ import CoreMedia import Metal import MetalKit class PreviewMetalView: MTKView { enum Rotation: Int { case rotate0Degrees case rotate90Degrees case rotate180Degrees case rotate270Degrees } var mirroring = false { didSet { syncQueue.sync { internalMirroring = mirroring } } } private var internalMirroring: Bool = false var rotation: Rotation = .rotate0Degrees { didSet { syncQueue.sync { internalRotation = rotation } } } private var internalRotation: Rotation = .rotate0Degrees var pixelBuffer: CVPixelBuffer? { didSet { if pixelBuffer == nil { isPreviewing = false } syncQueue.sync { internalPixelBuffer = pixelBuffer } } } var isPreviewing: Bool = false var didPreviewing: ((Bool) -> Void)? private var internalPixelBuffer: CVPixelBuffer? private let syncQueue = DispatchQueue( label: "com.silence.previewViewSyncQueue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem ) private var textureCache: CVMetalTextureCache? private var textureWidth: Int = 0 private var textureHeight: Int = 0 private var textureMirroring = false private var textureRotation: Rotation = .rotate0Degrees private var sampler: MTLSamplerState! private var renderPipelineState: MTLRenderPipelineState! private var commandQueue: MTLCommandQueue? private var vertexCoordBuffer: MTLBuffer! private var textCoordBuffer: MTLBuffer! private var internalBounds: CGRect! private var textureTranform: CGAffineTransform? func texturePointForView(point: CGPoint) -> CGPoint? { var result: CGPoint? guard let transform = textureTranform else { return result } let transformPoint = point.applying(transform) if CGRect(origin: .zero, size: CGSize(width: textureWidth, height: textureHeight)).contains(transformPoint) { result = transformPoint } else { print("Invalid point \(point) result point \(transformPoint)") } return result } func viewPointForTexture(point: CGPoint) -> CGPoint? { var result: CGPoint? guard let transform = textureTranform?.inverted() else { return result } let transformPoint = point.applying(transform) if internalBounds.contains(transformPoint) { result = transformPoint } else { print("Invalid point \(point) result point \(transformPoint)") } return result } func flushTextureCache() { textureCache = nil } private func setupTransform(width: Int, height: Int, mirroring: Bool, rotation: Rotation) { var scaleX: Float = 1.0 var scaleY: Float = 1.0 var resizeAspect: Float = 1.0 internalBounds = self.bounds textureWidth = width textureHeight = height textureMirroring = mirroring textureRotation = rotation if textureWidth > 0 && textureHeight > 0 { switch textureRotation { case .rotate0Degrees, .rotate180Degrees: scaleX = Float(internalBounds.width / CGFloat(textureWidth)) scaleY = Float(internalBounds.height / CGFloat(textureHeight)) case .rotate90Degrees, .rotate270Degrees: scaleX = Float(internalBounds.width / CGFloat(textureHeight)) scaleY = Float(internalBounds.height / CGFloat(textureWidth)) } } // Resize aspect ratio. resizeAspect = min(scaleX, scaleY) if scaleX < scaleY { scaleY = scaleX / scaleY scaleX = 1.0 } else { scaleX = scaleY / scaleX scaleY = 1.0 } if textureMirroring { scaleX *= -1.0 } // Vertex coordinate takes the gravity into account. let vertexData: [Float] = [ -scaleX, -scaleY, 0.0, 1.0, scaleX, -scaleY, 0.0, 1.0, -scaleX, scaleY, 0.0, 1.0, scaleX, scaleY, 0.0, 1.0 ] vertexCoordBuffer = device!.makeBuffer( bytes: vertexData, length: vertexData.count * MemoryLayout<Float>.size, options: [] ) // Texture coordinate takes the rotation into account. var textData: [Float] switch textureRotation { case .rotate0Degrees: textData = [ 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0 ] case .rotate180Degrees: textData = [ 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0 ] case .rotate90Degrees: textData = [ 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0 ] case .rotate270Degrees: textData = [ 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0 ] } textCoordBuffer = device?.makeBuffer( bytes: textData, length: textData.count * MemoryLayout<Float>.size, options: [] ) // Calculate the transform from texture coordinates to view coordinates var transform = CGAffineTransform.identity if textureMirroring { transform = transform.concatenating(CGAffineTransform(scaleX: -1, y: 1)) transform = transform.concatenating(CGAffineTransform(translationX: CGFloat(textureWidth), y: 0)) } switch textureRotation { case .rotate0Degrees: transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(0))) case .rotate180Degrees: transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(Double.pi))) transform = transform.concatenating( CGAffineTransform( translationX: CGFloat(textureWidth), y: CGFloat(textureHeight) ) ) case .rotate90Degrees: transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(Double.pi) / 2)) transform = transform.concatenating(CGAffineTransform(translationX: CGFloat(textureHeight), y: 0)) case .rotate270Degrees: transform = transform.concatenating(CGAffineTransform(rotationAngle: 3 * CGFloat(Double.pi) / 2)) transform = transform.concatenating(CGAffineTransform(translationX: 0, y: CGFloat(textureWidth))) } transform = transform.concatenating(CGAffineTransform(scaleX: CGFloat(resizeAspect), y: CGFloat(resizeAspect))) let tranformRect = CGRect( origin: .zero, size: CGSize(width: textureWidth, height: textureHeight) ).applying(transform) let xShift = (internalBounds.size.width - tranformRect.size.width) / 2 let yShift = (internalBounds.size.height - tranformRect.size.height) / 2 transform = transform.concatenating(CGAffineTransform(translationX: xShift, y: yShift)) textureTranform = transform.inverted() } init() { super.init(frame: .zero, device: MTLCreateSystemDefaultDevice()) configureMetal() createTextureCache() colorPixelFormat = .bgra8Unorm } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureMetal() { guard let device = device else { return } let defaultLibrary: MTLLibrary PhotoManager.shared.createBundle() if let bundle = PhotoManager.shared.bundle, let path = bundle.path(forResource: "metal/default", ofType: "metallib"), let library = try? device.makeLibrary(filepath: path) { defaultLibrary = library }else { do { defaultLibrary = try device.makeDefaultLibrary(bundle: .main) } catch { return } } let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineDescriptor.vertexFunction = defaultLibrary.makeFunction(name: "vertexPassThrough") pipelineDescriptor.fragmentFunction = defaultLibrary.makeFunction(name: "fragmentPassThrough") let samplerDescriptor = MTLSamplerDescriptor() samplerDescriptor.sAddressMode = .clampToEdge samplerDescriptor.tAddressMode = .clampToEdge samplerDescriptor.minFilter = .linear samplerDescriptor.magFilter = .linear sampler = device.makeSamplerState(descriptor: samplerDescriptor) do { renderPipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor) } catch { fatalError("Unable to create preview Metal view pipeline state. (\(error))") } preferredFramesPerSecond = 30 commandQueue = device.makeCommandQueue() } func createTextureCache() { guard let device = device else { return } var newTextureCache: CVMetalTextureCache? if CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &newTextureCache) == kCVReturnSuccess { textureCache = newTextureCache } } /// - Tag: DrawMetalTexture override func draw(_ rect: CGRect) { var pixelBuffer: CVPixelBuffer? var mirroring = false var rotation: Rotation = .rotate0Degrees syncQueue.sync { pixelBuffer = internalPixelBuffer mirroring = internalMirroring rotation = internalRotation } guard let drawable = currentDrawable, let currentRenderPassDescriptor = currentRenderPassDescriptor, let previewPixelBuffer = pixelBuffer else { return } // Create a Metal texture from the image buffer. let width = CVPixelBufferGetWidth(previewPixelBuffer) let height = CVPixelBufferGetHeight(previewPixelBuffer) if textureCache == nil { createTextureCache() } guard let textureCache = textureCache else { return } var cvTextureOut: CVMetalTexture? CVMetalTextureCacheCreateTextureFromImage( kCFAllocatorDefault, textureCache, previewPixelBuffer, nil, .bgra8Unorm, width, height, 0, &cvTextureOut ) guard let cvTexture = cvTextureOut, let texture = CVMetalTextureGetTexture(cvTexture) else { print("Failed to create preview texture") CVMetalTextureCacheFlush(textureCache, 0) return } if texture.width != textureWidth || texture.height != textureHeight || self.bounds != internalBounds || mirroring != textureMirroring || rotation != textureRotation { setupTransform( width: texture.width, height: texture.height, mirroring: mirroring, rotation: rotation ) } // Set up command buffer and encoder guard let commandQueue = commandQueue else { print("Failed to create Metal command queue") CVMetalTextureCacheFlush(textureCache, 0) return } guard let commandBuffer = commandQueue.makeCommandBuffer() else { print("Failed to create Metal command buffer") CVMetalTextureCacheFlush(textureCache, 0) return } guard let commandEncoder = commandBuffer.makeRenderCommandEncoder( descriptor: currentRenderPassDescriptor ) else { print("Failed to create Metal command encoder") CVMetalTextureCacheFlush(textureCache, 0) return } commandEncoder.label = "Preview display" commandEncoder.setRenderPipelineState(renderPipelineState!) commandEncoder.setVertexBuffer(vertexCoordBuffer, offset: 0, index: 0) commandEncoder.setVertexBuffer(textCoordBuffer, offset: 0, index: 1) commandEncoder.setFragmentTexture(texture, index: 0) commandEncoder.setFragmentSamplerState(sampler, index: 0) commandEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) commandEncoder.endEncoding() // Draw to the screen. commandBuffer.present(drawable) commandBuffer.commit() DispatchQueue.main.async { self.didPreviewing?(!self.isPreviewing) self.isPreviewing = true } } }
af757e2c4101c991eeb4d99990d8f068
32.562963
119
0.580299
false
false
false
false
kevintulod/CascadeKit-iOS
refs/heads/master
CascadeExample/CascadeExample/AppDelegate.swift
mit
1
// // AppDelegate.swift // CascadeExample // // Created by Kevin Tulod on 1/7/17. // Copyright © 2017 Kevin Tulod. All rights reserved. // import UIKit import CascadeKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let first = CascadingNavigationController(tableNumber: 1) let second = CascadingNavigationController(tableNumber: 2) let cascadeController = CascadeController.create() cascadeController.setup(first: first, second: second) window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = cascadeController window?.makeKeyAndVisible() 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:. } }
11f55b433ab2418026a9cb64ea9444c5
44.553571
285
0.740886
false
false
false
false
blackmirror-media/BMAccordion
refs/heads/develop
Pod/Classes/BMAccordionTheme.swift
mit
1
// // BMAccordionTheme.swift // // // Created by Adam Eri on 03/08/2015. // // import UIKit public class BMAccordionTheme: NSObject { // Section headers static var sectionHeight: CGFloat = 60.0 static var sectionBackgroundColor: UIColor = UIColor.whiteColor() static var sectionTextColor: UIColor = UIColor.blackColor() static var sectionFont: UIFont = UIFont.systemFontOfSize(17) // static var sectionFont: UIFont = UIFont.systemFontOfSize(17, weight: UIFontWeightRegular) static var sectionCaretColor: UIColor = UIColor.blackColor() // Badges static var badgeBackgroundColor: UIColor = UIColor.blackColor() static var badgeTextColor: UIColor = UIColor.whiteColor() static var badgeFont: UIFont = UIFont.systemFontOfSize(12) // static var badgeFont: UIFont = UIFont.systemFontOfSize(12, weight: UIFontWeightMedium) static var badgeCornerRadius: CGFloat = 9 // Cells static var cellFont: UIFont = UIFont.systemFontOfSize(17) // static var cellFont: UIFont = UIFont.systemFontOfSize(17, weight: UIFontWeightMedium) static var cellTextColor: UIColor = UIColor.lightGrayColor() static var cellBackgroundColor: UIColor = UIColor.whiteColor() // Animations static var sectionOpeningAnimation: UITableViewRowAnimation = .Left static var sectionClosingAnimation: UITableViewRowAnimation = .Left }
f495b3997cd2eed231b69a7bb5b9fc0b
35.368421
95
0.74602
false
false
false
false
senfi/KSTokenView
refs/heads/master
KSTokenView/KSUtils.swift
mit
1
// // KSUtils.swift // KSTokenView // // Created by Khawar Shahzad on 01/01/2015. // Copyright (c) 2015 Khawar Shahzad. 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 UIKit let KSTextEmpty = "\u{200B}" class KSUtils : NSObject { class func getRect(str: NSString, width: CGFloat, height: CGFloat, font: UIFont) -> CGRect { let rectangleStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle rectangleStyle.alignment = NSTextAlignment.Center let rectangleFontAttributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: rectangleStyle] return str.boundingRectWithSize(CGSizeMake(width, height), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: rectangleFontAttributes, context: nil) } class func getRect(str: NSString, width: CGFloat, font: UIFont) -> CGRect { let rectangleStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle rectangleStyle.alignment = NSTextAlignment.Center let rectangleFontAttributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: rectangleStyle] return str.boundingRectWithSize(CGSizeMake(width, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: rectangleFontAttributes, context: nil) } class func widthOfString(str: String, font: UIFont) -> CGFloat { var attrs = [NSFontAttributeName: font] var attributedString = NSMutableAttributedString(string:str, attributes:attrs) return attributedString.size().width } class func isIpad() -> Bool { return UIDevice.currentDevice().userInterfaceIdiom == .Pad } class func constrainsEnabled(view: UIView) -> Bool { if (view.constraints().count > 0) { return true } else { return false } } } extension UIColor { func darkendColor(darkRatio: CGFloat) -> UIColor { var h: CGFloat = 0.0, s: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0 if (getHue(&h, saturation: &s, brightness: &b, alpha: &a)) { return UIColor(hue: h, saturation: s, brightness: b*darkRatio, alpha: a) } else { return self } } }
21ce92f1b8409379c29bf412328282dd
43.756757
182
0.723732
false
false
false
false
taironas/gonawin-engine-ios
refs/heads/master
GonawinEngineTests/GonawinAPITeamsTests.swift
mit
1
// // GonawinAPITeamsTests.swift // GonawinEngine // // Created by Remy JOURDE on 09/03/2016. // Copyright © 2016 Remy Jourde. All rights reserved. // import Quick import Nimble import RxSwift import GonawinEngine class GonawinAPITeamsTests: QuickSpec { let disposeBag = DisposeBag() override func spec() { describe("Teams endpoint") { var engine: AuthorizedGonawinEngine! beforeEach { engine = GonawinEngine.newStubbingAuthorizedGonawinEngine() } it("returns a list of teams") { var teams: [Team]? engine.getTeams(1, count: 3) .catchError(self.log) .subscribe(onNext: { teams = $0 }) .addDisposableTo(self.disposeBag) expect(teams).toNot(beNil()) expect(teams?.count).to(equal(3)) expect(teams?[2].name).to(equal("Substitutes")) } } describe("Team endpoint") { var engine: AuthorizedGonawinEngine! beforeEach { engine = GonawinEngine.newStubbingAuthorizedGonawinEngine() } it("returns a team") { var team: Team? engine.getTeam(4260034) .catchError(self.log) .subscribe(onNext: { team = $0 }) .addDisposableTo(self.disposeBag) expect(team).toNot(beNil()) expect(team?.name).to(equal("FooFoo")) expect(team?.membersCount).to(equal(4)) expect(team?.members?[1].username).to(equal("jsmith")) expect(team?.tournaments?[2].name).to(equal("2015 Copa America")) } } } func log(error: Error) -> Observable<[Team]> { print("error : \(error)") return Observable.empty() } func log(error: Error) -> Observable<Team> { print("error : \(error)") return Observable.empty() } }
cd40ba890748cc85852682f65e7eac91
27.034884
81
0.445873
false
false
false
false
00aney/Briefinsta
refs/heads/master
Briefinsta/Sources/Services/InstagramService.swift
mit
1
// // InstagramService.swift // Briefinsta // // Created by aney on 2017. 10. 25.. // Copyright © 2017년 Ted Kim. All rights reserved. // import Moya protocol InstagramServiceType { func user(with username: String, completion: @escaping (Result<[Medium]>) -> () ) func media(with username: String, offset: String?, completion: @escaping (Result<Media>) -> () ) } final class InstagramService: InstagramServiceType { private let provider : MoyaProvider<InstagramAPI> init( provider: MoyaProvider<InstagramAPI> = MoyaProvider<InstagramAPI>(plugins: [NetworkLoggerPlugin(verbose: true)]) ) { self.provider = provider } func user(with username: String, completion: @escaping (Result<[Medium]>) -> () ) { provider.request(.user(username)) { result in switch result { case let .success(response): let data = response.data do { let apiResult = try JSONDecoder().decode(InstagramMediaAPIResult.self, from: data) let media = apiResult.user.media.items completion(Result.success(media)) } catch { completion(Result.failure(error)) } case let .failure(error): completion(Result.failure(error)) } } } func media(with username: String, offset: String?, completion: @escaping (Result<Media>) -> () ) { provider.request(.media(username, offset)) { result in switch result { case let .success(response): let data = response.data do { let apiResult = try JSONDecoder().decode(InstagramMediaAPIResult.self, from: data) let media = apiResult.user.media completion(Result.success(media)) } catch { completion(Result.failure(error)) } case let .failure(error): completion(Result.failure(error)) } } } }
5d397675608f331b76a99d95d5d44611
27.892308
116
0.626198
false
false
false
false
lancy98/HamburgerMenu
refs/heads/master
HamburgerMenu/HamburgerMenu/SlideMenuViewController.swift
mit
1
// // SlideMenuViewController.swift // DynamicTrayDemo // // Created by Lancy on 27/05/15. // Copyright (c) 2015 Lancy. All rights reserved. // import UIKit protocol DynamicTrayMenuDataSource : class { func trayViewController() -> UIViewController func mainViewController() -> UIViewController } class SlideMenuViewController: UIViewController { weak var dataSource: DynamicTrayMenuDataSource? { didSet { if let inDataSource = dataSource { let mainVC = inDataSource.mainViewController() mainViewController = mainVC addViewController(mainVC, toView: view) view.sendSubviewToBack(mainVC.view) if let tView = trayView { let trayVC = inDataSource.trayViewController() trayViewController = trayVC addViewController(trayVC, toView: trayView!) } } } } private var trayViewController: UIViewController? private var mainViewController: UIViewController? private var trayView: UIVisualEffectView? private var trayLeftEdgeConstraint: NSLayoutConstraint? private var animator: UIDynamicAnimator? private var gravity: UIGravityBehavior? private var attachment: UIAttachmentBehavior? private let widthFactor = CGFloat(0.4) // 40% width of the view private let minThresholdFactor = CGFloat(0.2) private var overlayView: UIView? private var trayWidth: CGFloat { return CGFloat(view.frame.width * widthFactor); } private var isGravityRight = false // check if the hamburger menu is being showed var isShowingTray: Bool { return isGravityRight } func showTray() { tray(true) } func hideTray() { tray(false) } func updateMainViewController(viewController: UIViewController) { if let mainVC = mainViewController { mainVC.willMoveToParentViewController(nil) mainVC.view.removeFromSuperview() mainVC.removeFromParentViewController() } addViewController(viewController, toView: view) } private func tray(show: Bool) { let pushBehavior = UIPushBehavior(items: [trayView!], mode: .Instantaneous) pushBehavior.angle = show ? CGFloat(M_PI) : 0 pushBehavior.magnitude = UI_USER_INTERFACE_IDIOM() == .Pad ? 1500 : 200 isGravityRight = show upadateGravity(isGravityRight) animator!.addBehavior(pushBehavior); } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) setUpTrayView() setUpGestureRecognizers() animator = UIDynamicAnimator(referenceView: view) setUpBehaviors() if trayViewController == nil && dataSource != nil { let trayVC = dataSource!.trayViewController() trayViewController = trayVC addViewController(trayVC, toView: trayView!) } } private func addViewController(viewController: UIViewController, toView: UIView) { addChildViewController(viewController) viewController.view.setTranslatesAutoresizingMaskIntoConstraints(false) toView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) toView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": viewController.view])) toView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": viewController.view])) } private func setUpBehaviors() { // Collision behaviour let collisionBehavior = UICollisionBehavior(items: [trayView!]) let rightInset = view.frame.width - trayWidth let edgeInset = UIEdgeInsetsMake(0, -trayWidth, 0, rightInset) collisionBehavior.setTranslatesReferenceBoundsIntoBoundaryWithInsets(edgeInset) animator!.addBehavior(collisionBehavior) // Gravity behaviour gravity = UIGravityBehavior(items: [trayView!]) animator!.addBehavior(gravity) upadateGravity(isGravityRight) } private func upadateGravity(isRight: Bool) { let angle = isRight ? 0 : M_PI gravity!.setAngle(CGFloat(angle), magnitude: 1.0) // Add the overlay if gravity is right if isRight { addOverlayView() } else { removeOverlayView() } } private func addOverlayView() { if overlayView == nil { // Create overlay view. overlayView = UIView.new() overlayView!.backgroundColor = UIColor.blackColor() overlayView!.alpha = 0.0 overlayView!.setTranslatesAutoresizingMaskIntoConstraints(false) mainViewController!.view.addSubview(overlayView!) // Fill the parent. mainViewController!.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": overlayView!])) mainViewController!.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": overlayView!])) // Add Tap Gesture let tapGesture = UITapGestureRecognizer(target: self, action: Selector("overlayTapped:")) overlayView!.addGestureRecognizer(tapGesture) // animate with alpha UIView.animateWithDuration(0.4) { self.overlayView!.alpha = 0.4 } } } private func removeOverlayView() { if overlayView != nil { UIView.animateWithDuration(0.4, animations: { self.overlayView!.alpha = 0.0 }, completion: { completed in self.overlayView!.removeFromSuperview() self.overlayView = nil }) } } func overlayTapped(tapGesture: UITapGestureRecognizer) { tray(false) // hide the tray. } private func setUpTrayView() { // Adding blur view let blurEffect = UIBlurEffect(style: .ExtraLight) trayView = UIVisualEffectView(effect: blurEffect) trayView!.setTranslatesAutoresizingMaskIntoConstraints(false) view.addSubview(trayView!) // Add constraints to blur view view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.4, constant: 0.0)) view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1.0, constant: 0.0)) view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0)) trayLeftEdgeConstraint = NSLayoutConstraint(item: trayView!, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant:-trayWidth) view.addConstraint(trayLeftEdgeConstraint!) view.layoutIfNeeded() } override func supportedInterfaceOrientations() -> Int { return Int(UIInterfaceOrientationMask.All.rawValue) } private func setUpGestureRecognizers() { // Edge pan. let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("pan:")) edgePan.edges = .Left view.addGestureRecognizer(edgePan) // Pan. let pan = UIPanGestureRecognizer (target: self, action: Selector("pan:")) trayView!.addGestureRecognizer(pan) } func pan(gesture: UIPanGestureRecognizer) { let currentPoint = gesture.locationInView(view) let xOnlyPoint = CGPointMake(currentPoint.x, view.center.y) switch(gesture.state) { case .Began: attachment = UIAttachmentBehavior(item: trayView!, attachedToAnchor: xOnlyPoint) animator!.addBehavior(attachment) case .Changed: attachment!.anchorPoint = xOnlyPoint case .Cancelled, .Ended: animator!.removeBehavior(attachment) attachment = nil let velocity = gesture.velocityInView(view) let velocityThreshold = CGFloat(500) if abs(velocity.x) > velocityThreshold { isGravityRight = velocity.x > 0 upadateGravity(isGravityRight) } else { isGravityRight = (trayView!.frame.origin.x + trayView!.frame.width) > (view.frame.width * minThresholdFactor) upadateGravity(isGravityRight) } default: if attachment != nil { animator!.removeBehavior(attachment) attachment = nil } } } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { animator!.removeAllBehaviors() if (trayView!.frame.origin.x + trayView!.frame.width) > (view.center.x * minThresholdFactor) { trayLeftEdgeConstraint?.constant = 0 isGravityRight = true } else { trayLeftEdgeConstraint?.constant = -(size.width * widthFactor) isGravityRight = false } coordinator.animateAlongsideTransition({ context in self.view.layoutIfNeeded() }, completion: { context in self.setUpBehaviors() }) } }
a792d8f919bec31174c01d99b257ab06
35.476534
175
0.619915
false
false
false
false
zorn/RGBWell
refs/heads/master
RGBWell/MainWindowController.swift
mit
1
import Cocoa class MainWindowController: NSWindowController { @IBOutlet weak var redSlider: NSSlider! @IBOutlet weak var greenSlider: NSSlider! @IBOutlet weak var blueSlider: NSSlider! @IBOutlet weak var colorWell: NSColorWell! var red = 0.0 var green = 0.0 var blue = 0.0 var alpha = 1.0 override func windowDidLoad() { super.windowDidLoad() redSlider.doubleValue = red greenSlider.doubleValue = green blueSlider.doubleValue = blue updateColor() } override var windowNibName: String? { return "MainWindowController" } @IBAction func adjustRed(sender: NSSlider) { println("R slider's value \(sender.doubleValue)") red = sender.doubleValue updateColor() } @IBAction func adjustGreen(sender: NSSlider) { println("G slider's value \(sender.doubleValue)") green = sender.doubleValue updateColor() } @IBAction func adjustBlue(sender: NSSlider) { println("B slider's value \(sender.doubleValue)") blue = sender.doubleValue updateColor() } func updateColor() { let newColor = NSColor(calibratedRed: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha)) colorWell.color = newColor } }
dfc6a090511fd2d61ca9dbaa82e06c3f
26.32
126
0.623719
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
ClientTests/MockProfile.swift
mpl-2.0
2
/* 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/. */ @testable import Client import Foundation import Account import ReadingList import Shared import Storage import Sync import XCTest import Deferred public class MockSyncManager: SyncManager { public var isSyncing = false public var lastSyncFinishTime: Timestamp? = nil public var syncDisplayState: SyncDisplayState? public func hasSyncedHistory() -> Deferred<Maybe<Bool>> { return deferMaybe(true) } public func syncClients() -> SyncResult { return deferMaybe(.Completed) } public func syncClientsThenTabs() -> SyncResult { return deferMaybe(.Completed) } public func syncHistory() -> SyncResult { return deferMaybe(.Completed) } public func syncLogins() -> SyncResult { return deferMaybe(.Completed) } public func syncEverything() -> Success { return succeed() } public func beginTimedSyncs() {} public func endTimedSyncs() {} public func applicationDidBecomeActive() { self.beginTimedSyncs() } public func applicationDidEnterBackground() { self.endTimedSyncs() } public func onNewProfile() { } public func onAddedAccount() -> Success { return succeed() } public func onRemovedAccount(account: FirefoxAccount?) -> Success { return succeed() } public func hasSyncedLogins() -> Deferred<Maybe<Bool>> { return deferMaybe(true) } } public class MockTabQueue: TabQueue { public func addToQueue(tab: ShareItem) -> Success { return succeed() } public func getQueuedTabs() -> Deferred<Maybe<Cursor<ShareItem>>> { return deferMaybe(ArrayCursor<ShareItem>(data: [])) } public func clearQueuedTabs() -> Success { return succeed() } } public class MockProfile: Profile { private let name: String = "mockaccount" func localName() -> String { return name } func shutdown() { } private var dbCreated = false lazy var db: BrowserDB = { self.dbCreated = true return BrowserDB(filename: "mock.db", files: self.files) }() /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. */ // Cliqz: added ExtendedBrowserHistory protocol to history to get extra data for telemetry signals private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory, ResettableSyncStorage, ExtendedBrowserHistory> = { return SQLiteHistory(db: self.db, prefs: MockProfilePrefs()) }() var favicons: Favicons { return self.places } lazy var queue: TabQueue = { return MockTabQueue() }() // Cliqz: added ExtendedBrowserHistory protocol to history to get extra data for telemetry signals var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage, ExtendedBrowserHistory> { return self.places } lazy var syncManager: SyncManager = { return MockSyncManager() }() lazy var certStore: CertStore = { return CertStore() }() lazy var bookmarks: protocol<BookmarksModelFactorySource, SyncableBookmarks, LocalItemSource, MirrorItemSource, ShareToDestination> = { // Make sure the rest of our tables are initialized before we try to read them! // This expression is for side-effects only. let p = self.places return MergedSQLiteBookmarks(db: self.db) }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs, files: self.files) }() lazy var prefs: Prefs = { return MockProfilePrefs() }() lazy var files: FileAccessor = { return ProfileFileAccessor(profile: self) }() lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath as String) }() lazy var recentlyClosedTabs: ClosedTabsStore = { return ClosedTabsStore(prefs: self.prefs) }() internal lazy var remoteClientsAndTabs: RemoteClientsAndTabs = { return SQLiteRemoteClientsAndTabs(db: self.db) }() private lazy var syncCommands: SyncCommands = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> = { return MockLogins(files: self.files) }() let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration() var account: FirefoxAccount? = nil func hasAccount() -> Bool { return account != nil } func hasSyncableAccount() -> Bool { return account?.actionNeeded == FxAActionNeeded.none } func getAccount() -> FirefoxAccount? { return account } func setAccount(account: FirefoxAccount) { self.account = account self.syncManager.onAddedAccount() } func removeAccount() { let old = self.account self.account = nil self.syncManager.onRemovedAccount(old) } func getClients() -> Deferred<Maybe<[RemoteClient]>> { return deferMaybe([]) } func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return deferMaybe([]) } func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return deferMaybe([]) } func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return deferMaybe(0) } func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) { } }
dabb925c58c2eaa3bdb6bbdaae3fec3f
27.575
139
0.665267
false
false
false
false
akisute/ParaMangar
refs/heads/master
ParaMangar/Sample3ViewController.swift
mit
1
// // Sample3ViewController.swift // ParaMangar // // Created by Ono Masashi on 2015/03/11. // Copyright (c) 2015年 akisute. All rights reserved. // import UIKit import ParaMangarLib class Sample3ViewController: UIViewController { @IBOutlet var targetView: UIView! @IBOutlet var animatingView: UIView! @IBOutlet var imageView: UIImageView! @IBOutlet var render1SecButton: UIButton! var animator: ParaMangar? @IBAction func onRender1SecButton(sender: UIButton) { let duration = 1.0 self.animator = ParaMangar.renderViewForDuration(self.targetView, duration: duration, block: { UIView.animateWithDuration(duration/2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in self.animatingView.transform = CGAffineTransformMakeScale(2.0, 2.0) }, completion: nil) UIView.animateWithDuration(duration/2, delay: duration/2, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in self.animatingView.transform = CGAffineTransformIdentity }, completion: nil) }).toImage(duration, completion: { image in self.animator = nil self.render1SecButton.setTitle("Completed!", forState: UIControlState.Normal) self.imageView.image = image }) } }
94ebef68c1051b51d5aea20faf6650e9
39.135135
196
0.680808
false
false
false
false
eure/ReceptionApp
refs/heads/master
iOS/ReceptionApp/Screens/ConfirmOtherViewController.swift
mit
1
// // ConfirmOtherViewController.swift // ReceptionApp // // Created by Hiroshi Kimura on 8/27/15. // Copyright © 2016 eureka, Inc. // // 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 // MARK: - ConfirmOtherViewController final class ConfirmOtherViewController: BaseConfirmViewController { // MARK: Internal @IBOutlet private(set) dynamic weak var companyNameView: UIView! @IBOutlet private(set) dynamic weak var purposeView: UIView! var transaction: OtherTransaction? // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Configuration.Color.backgroundColor self.companyNameView.backgroundColor = Configuration.Color.backgroundColor self.purposeView.backgroundColor = Configuration.Color.backgroundColor self.icons.forEach { $0.tintColor = Configuration.Color.imageTintColor } self.messageLabel.textColor = Configuration.Color.textColor self.messageLabel.font = Configuration.Font.baseBoldFont(size: 18) self.messageLabel.text = "ConfirmOtherViewController.label.confirm".l10n if let visitor = transaction?.visitor { self.companyNameLabel.attributedText = NSAttributedString.baseAttributedString( visitor.companyName, color: Configuration.Color.textColor, size: 32 ) if visitor.companyName.isEmpty { self.companyNameHeight.constant = 0 self.companyNameBottom.constant = 0 } } self.textView.attributedText = NSAttributedString.baseAttributedString( self.transaction?.visitor?.purpose ?? "", color: Configuration.Color.textColor, size: 36 ) } // MARK: BaseConfirmViewController override dynamic func handleSubmitButton(sender: AnyObject) { guard let transaction = self.transaction else { return } super.handleSubmitButton(sender) let controller = CompletionViewController.viewControllerFromStoryboard() Container.VisitorService.sendVisitor(transaction: transaction) { _ in } self.navigationController?.pushViewController(controller, animated: true) } // MARK: Private @IBOutlet private dynamic weak var companyNameLabel: UILabel! @IBOutlet private dynamic weak var textView: UITextView! @IBOutlet private dynamic var icons: [UIImageView]! @IBOutlet private dynamic weak var companyNameHeight: NSLayoutConstraint! @IBOutlet private dynamic weak var companyNameBottom: NSLayoutConstraint! }
94f2e0e7ffd2c0ab011adb5c7b368da1
35.733333
91
0.682914
false
true
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletAuthentication/Services/WalletRecovery/Validation/SeedPhraseValidator.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation import HDWalletKit public protocol SeedPhraseValidatorAPI { func validate(phrase: String) -> AnyPublisher<MnemonicValidationScore, Never> } public final class SeedPhraseValidator: SeedPhraseValidatorAPI { // MARK: - Type private enum Constant { static let seedPhraseLength: Int = 12 } // MARK: - Properties private let words: Set<String> // MARK: - Setup public init(words: Set<String> = Set(WordList.default.words)) { self.words = words } // MARK: - API public func validate(phrase: String) -> AnyPublisher<MnemonicValidationScore, Never> { if phrase.isEmpty { return .just(.none) } /// Make an array of the individual words let components = phrase .components(separatedBy: .whitespacesAndNewlines) .filter { !$0.isEmpty } if components.count < Constant.seedPhraseLength { return .just(.incomplete) } if components.count > Constant.seedPhraseLength { return .just(.excess) } /// Separate out the words that are duplicates let duplicates = Set(components.duplicates ?? []) /// The total number of duplicates entered let duplicatesCount = duplicates .map { duplicate in components.filter { $0 == duplicate }.count } .reduce(0, +) /// Make a set for all the individual entries let set = Set(phrase.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty && !duplicates.contains($0) }) guard !set.isEmpty || duplicatesCount > 0 else { return .just(.none) } /// Are all the words entered thus far valid words let entriesAreValid = set.isSubset(of: words) && duplicates.isSubset(of: words) if entriesAreValid { return .just(.valid) } /// Combine the `set` and `duplicates` to form a `Set<String>` of all /// words that are not included in the `WordList` let difference = set.union(duplicates).subtracting(words) /// Find the `NSRange` value for each word or incomplete word that is not /// included in the `WordList` let ranges = difference.map { delta -> [NSRange] in phrase.ranges(of: delta) } .flatMap { $0 } return .just(.invalid(ranges)) } } // MARK: - Convenience extension String { /// A convenience function for getting an array of `NSRange` values /// for a particular substring. fileprivate func ranges(of substring: String) -> [NSRange] { var ranges: [Range<Index>] = [] enumerateSubstrings(in: startIndex..<endIndex, options: .byWords) { word, value, _, _ in if let word = word, word == substring { ranges.append(value) } } return ranges.map { NSRange($0, in: self) } } } extension Array where Element: Hashable { public var duplicates: [Element]? { let dictionary = Dictionary(grouping: self, by: { $0 }) let pairs = dictionary.filter { $1.count > 1 } let duplicates = Array(pairs.keys) return !duplicates.isEmpty ? duplicates : nil } }
4e620e870afb8db2611416bbaabf35a0
29.472727
129
0.604415
false
false
false
false
yysskk/SwipeMenuViewController
refs/heads/master
Sources/Classes/SwipeMenuViewController.swift
mit
1
import UIKit open class SwipeMenuViewController: UIViewController, SwipeMenuViewDelegate, SwipeMenuViewDataSource { open var swipeMenuView: SwipeMenuView! open override func viewDidLoad() { super.viewDidLoad() swipeMenuView = SwipeMenuView(frame: view.frame) swipeMenuView.delegate = self swipeMenuView.dataSource = self view.addSubview(swipeMenuView) } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // potentially nil. // https://forums.developer.apple.com/thread/94426 swipeMenuView?.willChangeOrientation() } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() addSwipeMenuViewConstraints() } private func addSwipeMenuViewConstraints() { swipeMenuView.translatesAutoresizingMaskIntoConstraints = false if #available(iOS 11.0, *), view.hasSafeAreaInsets, swipeMenuView.options.tabView.isSafeAreaEnabled { NSLayoutConstraint.activate([ swipeMenuView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), swipeMenuView.leadingAnchor.constraint(equalTo: view.leadingAnchor), swipeMenuView.trailingAnchor.constraint(equalTo: view.trailingAnchor), swipeMenuView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } else { NSLayoutConstraint.activate([ swipeMenuView.topAnchor.constraint(equalTo: topLayoutGuide.topAnchor), swipeMenuView.leadingAnchor.constraint(equalTo: view.leadingAnchor), swipeMenuView.trailingAnchor.constraint(equalTo: view.trailingAnchor), swipeMenuView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } } // MARK: - SwipeMenuViewDelegate open func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewWillSetupAt currentIndex: Int) { } open func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewDidSetupAt currentIndex: Int) { } open func swipeMenuView(_ swipeMenuView: SwipeMenuView, willChangeIndexFrom fromIndex: Int, to toIndex: Int) { } open func swipeMenuView(_ swipeMenuView: SwipeMenuView, didChangeIndexFrom fromIndex: Int, to toIndex: Int) { } // MARK: - SwipeMenuViewDataSource open func numberOfPages(in swipeMenuView: SwipeMenuView) -> Int { return children.count } open func swipeMenuView(_ swipeMenuView: SwipeMenuView, titleForPageAt index: Int) -> String { return children[index].title ?? "" } open func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewControllerForPageAt index: Int) -> UIViewController { let vc = children[index] vc.didMove(toParent: self) return vc } }
18409b6630569874d328d76b102de1d7
40.614286
117
0.700309
false
false
false
false
Daemon-Devarshi/MedicationSchedulerSwift3.0
refs/heads/master
Medication/ViewControllers/AddNewForms/AddNewMedicationViewController.swift
mit
1
// // AddNewMedicationViewController.swift // Medication // // Created by Devarshi Kulshreshtha on 8/20/16. // Copyright © 2016 Devarshi. All rights reserved. // import UIKit import CoreData import EventKit class AddNewMedicationViewController: FormBaseViewController { //MARK: Constants declarations static let pushSegueIdentifier = "PushAddNewMedicationViewController" //MARK: Var declarations // Pickers fileprivate var timePicker: UIDatePicker! fileprivate var unitPicker: UIPickerView! fileprivate var priorityPicker: UIPickerView! // Values displayed in pickers fileprivate var pirorityModes: [PriorityMode] = [.high, .medium, .low] fileprivate var units: [Units] = [.pills, .ml] fileprivate var eventStore: EKEventStore? fileprivate var selectedMedicine: Medicine? fileprivate var selectedPriority: PriorityMode? fileprivate var selectedUnit: Units? fileprivate var scheduleTime: Date? var patient: Patient! { didSet { managedObjectContext = patient.managedObjectContext } } //MARK: Outlets declarations @IBOutlet weak var medicineField: UITextField! @IBOutlet weak var scheduleMedicationField: UITextField! @IBOutlet weak var dosageField: UITextField! @IBOutlet weak var selectUnitField: UITextField! @IBOutlet weak var selectPriorityField: UITextField! //MARK: Overriden methods override func viewDidLoad() { super.viewDidLoad() configureDatePicker() configurePickerViews() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let segueIdentifier = segue.identifier { if segueIdentifier == MedicinesTableViewController.pushSegueIdentifier { // passing managedObjectContext to PatientsTableViewController let medicinesTableViewController = segue.destination as! MedicinesTableViewController medicinesTableViewController.managedObjectContext = managedObjectContext medicinesTableViewController.medicineSelectionHandler = { [weak self](selectedMedicine) in // weak used to break retain cycle guard let _self = self else { return } _self.medicineField.text = selectedMedicine.name _self.selectedMedicine = selectedMedicine } } } } } //MARK:- Implementing UIPickerViewDataSource, UIPickerViewDelegate protocols extension AddNewMedicationViewController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView == unitPicker { return units.count } else if pickerView == priorityPicker{ return pirorityModes.count } return 0 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { var title: String? if pickerView == unitPicker { title = units[row].description } else if pickerView == priorityPicker{ title = pirorityModes[row].description } return title } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView == unitPicker { let value = units[row] selectedUnit = value selectUnitField.text = value.description } else if pickerView == priorityPicker { let value = pirorityModes[row] selectedPriority = value selectPriorityField.text = value.description } } } //MARK:- Utility methods extension AddNewMedicationViewController { // Scheduling reminders fileprivate func scheduleReminder() { if let eventStore = eventStore { let reminder = EKReminder(eventStore: eventStore) let notes = "\(selectedMedicine!.name!) \(dosageField.text!) \(selectedUnit!.description)" reminder.title = "Provide \(notes) to \(patient.fullName!)" reminder.notes = notes reminder.calendar = eventStore.defaultCalendarForNewReminders() let alarm = EKAlarm(absoluteDate: scheduleTime!) reminder.addAlarm(alarm) reminder.priority = selectedPriority!.rawValue let recurrenceRule = EKRecurrenceRule(recurrenceWith: .daily, interval: 1, end: nil) reminder.recurrenceRules = [recurrenceRule] // setting dueDateComponents for recurring events let gregorian = NSCalendar(identifier:NSCalendar.Identifier.gregorian) let dailyComponents = gregorian?.components([.year, .month, .day, .hour, .minute, .second, .timeZone], from: scheduleTime!) reminder.dueDateComponents = dailyComponents do { try eventStore.save(reminder, commit: true) displaySingleButtonActionAlert(withTitle: "Success!", message: "Medication successfully scheduled.") {[weak self] in // weak used to break retain cycle guard let _self = self else { return } _ = _self.navigationController?.popViewController(animated: true) } } catch { let error = error as NSError print("\(error), \(error.userInfo)") displaySingleButtonActionAlert(withTitle: "Error!", message: error.localizedDescription) } } } // Configuring date picker fileprivate func configureDatePicker() { timePicker = UIDatePicker(frame: CGRect.zero) timePicker.datePickerMode = .time timePicker.backgroundColor = UIColor.white timePicker.addTarget(self, action: #selector(AddNewMedicationViewController.medicationScheduleChanged), for: .valueChanged) scheduleMedicationField.inputView = timePicker } // Configuring all picker views fileprivate func configurePickerViews() { // configuring unitPicker unitPicker = UIPickerView() unitPicker.delegate = self unitPicker.dataSource = self selectUnitField.inputView = unitPicker // configuring priorityPicker priorityPicker = UIPickerView() priorityPicker.delegate = self priorityPicker.dataSource = self selectPriorityField.inputView = priorityPicker } } //MARK:- User actions and text field delegate extension AddNewMedicationViewController { override func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // to disable text editing on fields which have input view associated with them if textField == scheduleMedicationField || textField == selectPriorityField || textField == selectUnitField { return false } return true } func medicationScheduleChanged(_ sender:UIDatePicker) { scheduleTime = sender.date.fullMinuteTime() scheduleMedicationField.text = scheduleTime!.displayTime() } @IBAction func scheduleMedication(_ sender: AnyObject) { // validations guard let dosage = dosageField.text else { displaySingleButtonActionAlert(withTitle: "Error!", message: "Please enter all details.") return } guard let selectedMedicine = selectedMedicine, let selectedPriority = selectedPriority, let selectedUnit = selectedUnit, let scheduleTime = scheduleTime else { displaySingleButtonActionAlert(withTitle: "Error!", message: "Please enter all details.") return } // Create medication and assign values to its attributes let medication = Medication.createMedication(withPatient: patient, inManagedObjectContext: managedObjectContext) medication.dosage = NSNumber(value: Int32(dosage)!) medication.unit = NSNumber(value: Int32(selectedUnit.rawValue)) medication.priority = NSNumber(value: Int32(selectedPriority.rawValue)) medication.scheduleTime = scheduleTime as NSDate medication.medicine = selectedMedicine medication.patient = patient // saving in local db + creating reminder do { try managedObjectContext.save() // scheduling the reminder if eventStore == nil { eventStore = EKEventStore() eventStore!.requestAccess( to: .reminder, completion: {[weak self](granted, error) in guard let _self = self else { return } // Background to main thread DispatchQueue.main.async(execute: { if !granted { print("Access to store not granted") print(error!.localizedDescription) _self.displaySingleButtonActionAlert(withTitle: "Permission Declined!", message: "Reminder could not be scheduled.") } else { print("Access granted") _self.scheduleReminder() } }) }) } else { scheduleReminder() } } catch { let error = error as NSError print("\(error), \(error.userInfo)") displaySingleButtonActionAlert(withTitle: "Error!", message: error.localizedDescription) } } }
d062dbe116fc92478cbe7852fba1e93f
38.115385
168
0.612291
false
false
false
false
a1exb1/ABToolKit-pod
refs/heads/master
Pod/Classes/Autolayout/AutoLayoutHelper.swift
mit
1
// // UIViewExtensions.swift // // // Created by Shagun Madhikarmi on 09/10/2014. // Copyright (c) 2014 madhikarma. All rights reserved. // import Foundation import UIKit /** Extension of UIView for AutoLayout helper methods */ public extension UIView { // Mark: - Fill public func fillSuperView(edges: UIEdgeInsets) -> [NSLayoutConstraint] { var topConstraint: NSLayoutConstraint = self.addTopConstraint(toView: self.superview, relation: .Equal, constant: edges.top) var leftConstraint: NSLayoutConstraint = self.addLeftConstraint(toView: self.superview, relation: .Equal, constant: edges.left) var bottomConstraint: NSLayoutConstraint = self.addBottomConstraint(toView: self.superview, relation: .Equal, constant: edges.bottom) var rightConstraint: NSLayoutConstraint = self.addRightConstraint(toView: self.superview, relation: .Equal, constant: edges.right) return [topConstraint, leftConstraint, bottomConstraint, rightConstraint] } // MARK: - Left Constraints public func addLeftConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Left, toView: view, attribute: attribute, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } public func addLeftConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return self.addLeftConstraint(toView: view, attribute: .Left, relation: relation, constant: constant) } // MARK: - Right Constraints public func addRightConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Right, toView: view, attribute: attribute, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } public func addRightConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return self.addRightConstraint(toView: view, attribute: .Right, relation: relation, constant: constant) } // MARK: - Top Constraints public func addTopConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return self.addTopConstraint(toView: view, attribute: .Top, relation: relation, constant: constant) } public func addTopConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Top, toView: view, attribute: attribute, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } public func addTopMarginConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return self.addTopMarginConstraint(toView: view, attribute: .TopMargin, relation: relation, constant: constant) } public func addTopMarginConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .TopMargin, toView: view, attribute: attribute, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } // MARK: - Bottom Constraints public func addBottomConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return self.addBottomConstraint(toView: view, attribute: .Bottom, relation: relation, constant: constant) } public func addBottomConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Bottom, toView: view, attribute: attribute, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } public func addBottomMarginConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .BottomMargin, toView: view, attribute: .Bottom, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } public func addBottomMarginConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return self.addBottomConstraint(toView: view, attribute: .BottomMargin, relation: relation, constant: constant) } // MARK: - Center X Constraint public func addCenterXConstraint(toView view: UIView?) -> NSLayoutConstraint { return self.addCenterXConstraint(toView: view, relation: .Equal, constant: 0) } public func addCenterXConstraint(toView view: UIView?, constant: CGFloat) -> NSLayoutConstraint { return self.addCenterXConstraint(toView: view, relation: .Equal, constant: constant) } public func addCenterXConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .CenterX, toView: view, attribute: .CenterX, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } // MARK: - Center Y Constraint public func addCenterYConstraint(toView view: UIView?) -> NSLayoutConstraint { return self.addCenterYConstraint(toView: view, relation: .Equal, constant: 0) } public func addCenterYConstraint(toView view: UIView?, constant: CGFloat) -> NSLayoutConstraint { return self.addCenterYConstraint(toView: view, relation: .Equal, constant: constant) } public func addCenterYConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .CenterY, toView: view, attribute: .CenterY, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } // MARK: - Width Constraints public func addWidthConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Width, toView: view, attribute: .Width, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } public func addWidthConstraint(relation relation1: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return self.addWidthConstraint(toView: nil, relation: relation1, constant: constant) } // MARK: - Height Constraints public func addHeightConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Height, toView: view, attribute: .Height, relation: relation, constant: constant) self.superview?.addConstraint(constraint) return constraint } public func addHeightConstraint(relation relation1: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return self.addHeightConstraint(toView: nil, relation: relation1, constant: constant) } // MARK: - Private private func createConstraint(attribute attr1: NSLayoutAttribute, toView: UIView?, attribute attr2: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: attr1, relatedBy: relation, toItem: toView, attribute: attr2, multiplier: 1.0, constant: constant) return constraint } }
9cf322c486a5015519d20d5b91e65ddf
41.255924
193
0.692428
false
false
false
false
bosr/Zewo
refs/heads/master
Modules/Mapper/Tests/Mapper/MappableValueTests.swift
mit
1
import XCTest @testable import Mapper class MappableValueTests: XCTestCase { static var allTests: [(String, (MappableValueTests) -> () throws -> Void)] { return [ ("testNestedMappable", testNestedMappable), ("testNestedInvalidMappable", testNestedInvalidMappable), ("testNestedOptionalMappable", testNestedOptionalMappable), ("testNestedOptionalInvalidMappable", testNestedOptionalInvalidMappable), ("testArrayOfMappables", testArrayOfMappables), ("testArrayOfInvalidMappables", testArrayOfInvalidMappables), ("testInvalidArrayOfMappables", testInvalidArrayOfMappables), ("testArrayOfPartiallyInvalidMappables", testArrayOfPartiallyInvalidMappables), ("testExistingOptionalArrayOfMappables", testExistingOptionalArrayOfMappables), ("testOptionalArrayOfMappables", testOptionalArrayOfMappables), ("testOptionalArrayOfInvalidMappables", testOptionalArrayOfInvalidMappables), ("testOptionalArrayOfPartiallyInvalidMappables", testOptionalArrayOfPartiallyInvalidMappables) ] } func testNestedMappable() { struct Test: Mappable { let nest: Nested init(mapper: Mapper) throws { try self.nest = mapper.map(from: "nest") } } struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } let structuredData: StructuredData = [ "nest": ["string": "hello"] ] let test = try! Test(mapper: Mapper(structuredData: structuredData)) XCTAssertEqual(test.nest.string, "hello") } func testNestedInvalidMappable() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: Nested init(mapper: Mapper) throws { try self.nested = mapper.map(from: "nest") } } let structuredData: StructuredData = ["nest": ["strong": "er"]] let test = try? Test(mapper: Mapper(structuredData: structuredData)) XCTAssertNil(test) } func testNestedOptionalMappable() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: Nested? init(mapper: Mapper) throws { self.nested = mapper.map(optionalFrom: "nest") } } let structuredData: StructuredData = ["nest": ["string": "zewo"]] let test = try! Test(mapper: Mapper(structuredData: structuredData)) XCTAssertEqual(test.nested!.string, "zewo") } func testNestedOptionalInvalidMappable() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: Nested? init(mapper: Mapper) throws { self.nested = mapper.map(optionalFrom: "nest") } } let structuredData: StructuredData = ["nest": ["strong": "er"]] let test = try! Test(mapper: Mapper(structuredData: structuredData)) XCTAssertNil(test.nested) } func testArrayOfMappables() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: [Nested] init(mapper: Mapper) throws { try self.nested = mapper.map(arrayFrom: "nested") } } let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": "fire"], ["string": "sun"]]])) XCTAssertEqual(test.nested.count, 2) XCTAssertEqual(test.nested[1].string, "sun") } func testArrayOfInvalidMappables() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: [Nested] init(mapper: Mapper) throws { try self.nested = mapper.map(arrayFrom: "nested") } } let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": 1], ["string": 1]]])) XCTAssertTrue(test.nested.isEmpty) } func testInvalidArrayOfMappables() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: [Nested] init(mapper: Mapper) throws { try self.nested = mapper.map(arrayFrom: "nested") } } let test = try? Test(mapper: Mapper(structuredData: ["hested": [["strong": "fire"], ["strong": "sun"]]])) XCTAssertNil(test) } func testArrayOfPartiallyInvalidMappables() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: [Nested] init(mapper: Mapper) throws { try self.nested = mapper.map(arrayFrom: "nested") } } let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": 1], ["string": "fire"]]])) XCTAssertEqual(test.nested.count, 1) } func testExistingOptionalArrayOfMappables() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: [Nested]? init(mapper: Mapper) throws { self.nested = mapper.map(optionalArrayFrom: "nested") } } let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": "ring"], ["string": "fire"]]])) XCTAssertEqual(test.nested!.count, 2) } func testOptionalArrayOfMappables() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: [Nested]? init(mapper: Mapper) throws { self.nested = mapper.map(optionalArrayFrom: "nested") } } let test = try! Test(mapper: Mapper(structuredData: [])) XCTAssertNil(test.nested) } func testOptionalArrayOfInvalidMappables() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: [Nested]? init(mapper: Mapper) throws { self.nested = mapper.map(optionalArrayFrom: "nested") } } let test = try! Test(mapper: Mapper(structuredData: ["nested": [["strong": 3], ["strong": 5]]])) XCTAssertTrue(test.nested!.isEmpty) } func testOptionalArrayOfPartiallyInvalidMappables() { struct Nested: Mappable { let string: String init(mapper: Mapper) throws { try self.string = mapper.map(from: "string") } } struct Test: Mappable { let nested: [Nested]? init(mapper: Mapper) throws { self.nested = mapper.map(optionalArrayFrom: "nested") } } let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": 1], ["string": "fire"]]])) XCTAssertEqual(test.nested!.count, 1) } }
3fe59afd30e2a08342c29a21545ace6a
35.271552
114
0.55104
false
true
false
false
vermont42/Conjugar
refs/heads/master
Conjugar/TestAnalyticsService.swift
agpl-3.0
1
// // TestAnalyticsService.swift // Conjugar // // Created by Joshua Adams on 11/25/18. // Copyright © 2018 Josh Adams. All rights reserved. // import Foundation class TestAnalyticsService: AnalyticsServiceable { private var fire: (String) -> () init(fire: @escaping (String) -> () = { analytic in print(analytic) }) { self.fire = fire } func recordEvent(_ eventName: String, parameters: [String: String]?, metrics: [String: Double]?) { var analytic = eventName if let parameters = parameters { analytic += " " for (key, value) in parameters { analytic += key + ": " + value + " " } } fire(analytic) } }
7187910b0c47709ea1e1a80d959a6985
22.857143
100
0.618263
false
true
false
false
starhoshi/pi-chan
refs/heads/master
pi-chan/ViewControllers/Posts/Cell/PostTableViewCell.swift
mit
1
// // PostTableViewCell.swift // pi-chan // // Created by Kensuke Hoshikawa on 2016/04/06. // Copyright © 2016年 star__hoshi. All rights reserved. // import UIKit import Kingfisher import Font_Awesome_Swift import SwiftDate import NSDate_TimeAgo import MGSwipeTableCell class PostTableViewCell: MGSwipeTableCell { @IBOutlet weak var contentsView: UIView! @IBOutlet weak var circleThumbnail: UIImageView! @IBOutlet weak var circleUpdateThumbnail: UIImageView! @IBOutlet weak var wip: UILabel! @IBOutlet weak var category: UILabel! @IBOutlet weak var title: UILabel! @IBOutlet weak var createdBy: UILabel! @IBOutlet weak var starIcon: UILabel! @IBOutlet weak var starCount: UILabel! @IBOutlet weak var eyeIcon: UILabel! @IBOutlet weak var eyeCount: UILabel! @IBOutlet weak var commentsIcon: UILabel! @IBOutlet weak var commentsCount: UILabel! @IBOutlet weak var checkIcon: UILabel! @IBOutlet weak var checkCount: UILabel! override func awakeFromNib() { super.awakeFromNib() starIcon.setFAIcon(.FAStar, iconSize: 14) eyeIcon.setFAIcon(.FAEye, iconSize: 14) commentsIcon.setFAIcon(.FAComments, iconSize: 14) checkIcon.setFAIcon(.FACheckSquareO, iconSize: 14) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setItems(post:Post){ category.text = post.category title.text = post.name starIcon.textColor = post.star ? UIColor.esaGreen() : UIColor.esaFontBlue() eyeIcon.textColor = post.watch ? UIColor.esaGreen() : UIColor.esaFontBlue() starCount.text = String(post.stargazersCount) eyeCount.text = String(post.watchersCount) commentsCount.text = String(post.commentsCount) checkCount.text = "\(post.doneTasksCount)/\(post.tasksCount)" wip.hidden = !post.wip contentsView.alpha = post.wip ? 0.5 : 1.0 setCreatedBy(post) setThumbnail(post) } func setThumbnail(post:Post){ circleThumbnail.toCircle().kf_setImageWithURL(post.createdBy.icon) circleUpdateThumbnail.hidden = post.createdBy.screenName == post.updatedBy.screenName ? true:false circleUpdateThumbnail.toCircle().kf_setImageWithURL(post.updatedBy.icon) } func setCreatedBy(post:Post){ var createdByText = "" if post.updatedAt == post.createdAt { createdByText += "Created by \(post.createdBy.screenName) | " createdByText += post.createdAt.toDateFromISO8601()!.timeAgo() } else { createdByText += "Updated by \(post.updatedBy.screenName) | " createdByText += post.updatedAt.toDateFromISO8601()!.timeAgo() } createdBy.text = createdByText } }
3d5184f092249eb03c4954287d6cfbae
33.115385
102
0.726419
false
false
false
false
pyanfield/ataturk_olympic
refs/heads/master
swift_programming_extensions.playground/section-1.swift
mit
1
// Playground - noun: a place where people can play import UIKit // 2.20 // 扩展就是向一个已有的类、结构体或枚举类型添加新功能(functionality)。 // 扩展和 Objective-C 中的分类(categories)类似。(不过与Objective-C不同的是,Swift 的扩展没有名字。) // Swift 中的扩展可以: // 添加计算型属性和计算静态属性 // 定义实例方法和类型方法 // 提供新的构造器 // 定义下标 // 定义和使用新的嵌套类型 // 使一个已有类型符合某个协议 // 声明一个扩展使用关键字extension: // extension SomeType: SomeProtocol, AnotherProctocol { // // 协议实现写到这里 // } extension Double { var km: Double { return self * 1_000.0 } var m : Double { return self } var cm: Double { return self / 100.0 } var mm: Double { return self / 1_000.0 } var ft: Double { return self / 3.28084 } } let oneInch = 25.4.mm println("One inch is \(oneInch) meters") let threeFeet = 3.ft println("Three feet is \(threeFeet) meters") // 扩展可以添加新的计算属性,但是不可以添加存储属性,也不可以向已有属性添加属性观测器(property observers)。 // 扩展能向类中添加新的便利构造器,但是它们不能向类中添加新的指定构造器或析构函数。指定构造器和析构函数必须总是由原始的类实现来提供。 struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = Size() } let defaultRect = Rect() let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) extension Rect { init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // 扩展方法 Methods extension Int{ // 传入的时一个没有参数没有返回值的函数 func repetitions(task: () -> ()){ for i in 0..<self{ task() } } // 结构体和枚举类型中修改self或其属性的方法必须将该实例方法标注为mutating,正如来自原始实现的修改方法一样。 mutating func square(){ self = self * self } subscript(digitIndex: Int) -> Int{ var decimalBase = 1 for _ in 1...digitIndex{ decimalBase *= 10 } return (self / decimalBase) % 10 } } 3.repetitions{ println("Test repetition function on Int") } var three = 3 three.square() println(three) println(12345678[5]) // 扩展添加嵌套类型 extension Character { enum Kind { case Vowel, Consonant, Other } var kind: Kind { switch String(self).lowercaseString { case "a", "e", "i", "o", "u": return .Vowel case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": return .Consonant default: return .Other } } } func printLetterKinds(word: String) { println("'\(word)' is made up of the following kinds of letters:") for character in word { switch character.kind { case .Vowel: print("vowel ") case .Consonant: print("consonant ") case .Other: print("other ") } } print("\n") } printLetterKinds("Hello")
46bd0c979b6ea6fb37e15b845c68f3b1
21.781955
73
0.568647
false
false
false
false
rsaenzi/MyCurrencyConverterApp
refs/heads/master
MyCurrencyConverterApp/MyCurrencyConverterAppTests/App/AccessControllers/ApiAccess/Test_ApiRequest.swift
mit
1
// // Test_ApiRequest.swift // MyCurrencyConverterApp // // Created by Rigoberto Sáenz Imbacuán on 8/7/16. // Copyright © 2016 Rigoberto Sáenz Imbacuán [https://www.linkedin.com/in/rsaenzi]. All rights reserved. // import XCTest @testable import MyCurrencyConverterApp class Test_ApiRequest: XCTestCase { func test_getUniqueInstance() { // Only the first call should receive a valid instance... let _ = CurrencyConverter.app.control.apiRequest // After the first call ge must get nil... for _ in 0...10 { XCTAssertNil(ApiRequest.getUniqueInstance()) } } func test_endpointGetExchangeRates(){ // Make the request CurrencyConverter.app.control.apiRequest.endpointGetExchangeRates({ (response) in // Must inform the success of the data parsing XCTAssert(response.responseCode == eResponseCodeGetExchangeRates.Success_200) XCTAssert(response.responseMessage == "Success!") }) { (httpCode, nsError, errorDescription) in // Data can no be fetched... XCTFail() } } }
d6c5b4c26729fc66aa9695d6230be06d
28.439024
105
0.610605
false
true
false
false
24/ios-o2o-c
refs/heads/master
gxc/Order/OrderDetailViewController.swift
mit
1
import Foundation import UIKit class OrderDetailViewController: UIViewController,UIWebViewDelegate { var leftView = UIView() var rightView = UIView() var leftBtn = UIButton() var rightBtn = UIButton() var contentView = UIView() var scrollView = UIScrollView() var containerView: UIView! var buyBtn = UIButton() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_back.png"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("NavigationControllerBack")) self.navigationItem.title = "订单详情" self.navigationController?.navigationBar.barTintColor = UIColor(fromHexString: "#008FD7") var navigationBar = self.navigationController?.navigationBar /*navigation 不遮住View*/ self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = UIRectEdge() /*self view*/ self.view.backgroundColor = UIColor.whiteColor() navigationBar?.tintColor = UIColor.whiteColor() var containerSize = CGSize(width: self.view.bounds.width, height: 540) containerView = UIView(frame: CGRect(origin: CGPoint(x: 0, y:0), size:containerSize)) scrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) scrollView.contentSize = containerSize scrollView.addSubview(containerView) self.view.addSubview(scrollView) MBProgressHUD.showHUDAddedTo(self.view, animated: true) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("User_Order_Detail:"), name: GXNotifaction_User_Order_Detail, object: nil) GxApiCall().OrderDetail(GXViewState.userInfo.Token!, orderId: NSString(format: "%.0f",GXViewState.ShopOrderDetail.OrderId!)) let superview: UIView = containerView var mySegcon = UISegmentedControl(items: ["订单详情","衣物列表"]) mySegcon.selectedSegmentIndex = 0 mySegcon.backgroundColor = UIColor.whiteColor() mySegcon.tintColor = UIColor(fromHexString: "#008FD7") containerView.addSubview(mySegcon) mySegcon.addTarget(self, action: "segconChanged:", forControlEvents: UIControlEvents.ValueChanged) mySegcon.snp_makeConstraints { make in make.top.equalTo(superview.snp_top).offset(5) make.centerX.equalTo(superview.snp_centerX) make.width.equalTo(200) make.height.equalTo(35) } containerView.addSubview(contentView) contentView.snp_makeConstraints { make in make.top.equalTo(mySegcon.snp_bottom).offset(10) make.left.equalTo(superview.snp_left) make.width.equalTo(superview) make.height.equalTo(380) } } func segconChanged(segcon: UISegmentedControl) { var leftView = OrderDetailLeftViewController() var rightView = OrderDetailRightViewController() removeSubView() switch segcon.selectedSegmentIndex { case 0: segcon.selectedSegmentIndex = 0 buyBtn.hidden = false contentView.addSubview(leftView.view) case 1: segcon.selectedSegmentIndex = 1 buyBtn.hidden = true contentView.addSubview(rightView.view) default: break; } } func removeSubView() { let views = contentView.subviews for s in views { s.removeFromSuperview() } } func User_Order_Detail(notif :NSNotification) { let superview: UIView = self.view removeSubView() MBProgressHUD.hideHUDForView(self.view, animated: true) var shopOrderDetail = notif.userInfo?["GXNotifaction_User_Order_Detail"] as GX_OrderDetail GXViewState.OrderDetail = shopOrderDetail var orderDetail = shopOrderDetail.shopDetail! var leftView = OrderDetailLeftViewController() contentView.addSubview(leftView.view) //预约送衣服和 评论订单 if(orderDetail.CanCancle!) { buyBtn.setTitle("取消订单", forState: UIControlState.Normal) buyBtn.addTarget(self, action: Selector("CancelOrder"), forControlEvents: UIControlEvents.TouchUpInside) } else if(orderDetail.CanSend!) { buyBtn.setTitle("预约送衣", forState: UIControlState.Normal) buyBtn.addTarget(self, action: Selector("SendOrder"), forControlEvents: UIControlEvents.TouchUpInside) } else if(orderDetail.CanComment!) { buyBtn.setTitle("评论订单", forState: UIControlState.Normal) buyBtn.addTarget(self, action: Selector("CommonOrder"), forControlEvents: UIControlEvents.TouchUpInside) } if(!orderDetail.IsPay! && orderDetail.NoPayAmount > 0 && (orderDetail.Status! == 3 || orderDetail.Status! == 4 || orderDetail.Status! == 5 || orderDetail.Status! == 6)) { buyBtn.setTitle("去支付", forState: UIControlState.Normal) buyBtn.addTarget(self, action: Selector("PayGo"), forControlEvents: UIControlEvents.TouchUpInside) } buyBtn.backgroundColor = UIColor(fromHexString: "#E61D4C") self.view.addSubview(buyBtn) buyBtn.snp_makeConstraints { make in make.top.equalTo(self.contentView.snp_bottom) make.left.equalTo(0).offset(5) make.right.equalTo(self.contentView).offset(-5) make.height.equalTo(40) } buyBtn.layer.cornerRadius = 4 if(buyBtn.titleLabel?.text == nil || buyBtn.titleLabel?.text == "" ) { buyBtn.removeFromSuperview() } } func CancelOrder() { self.navigationController?.pushViewController(CancelOrderViewController(), animated: true) } func SendOrder() { //预约送衣服 self.navigationController?.pushViewController(SendOrderViewController(), animated: true) } func CommonOrder() { //评论订单 self.navigationController?.pushViewController(CommonOrderViewController(), animated: true) } func PayGo() { self.navigationController?.pushViewController(PayViewController(), animated: true) } override func viewDidAppear(animated: Bool) { NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("User_Order_Detail:"), name: GXNotifaction_User_Order_Detail, object: nil) GxApiCall().OrderDetail(GXViewState.userInfo.Token!, orderId: NSString(format: "%.0f",GXViewState.ShopOrderDetail.OrderId!)) } func NavigationControllerBack() { self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
7dfbc45c2f3fbcbfef1183b0fe0b1206
28.390438
199
0.619086
false
false
false
false
fuji2013/FJSImageViewController
refs/heads/master
FJSImageViewController/FJSImageViewController.swift
mit
1
// // FJSImageViewController.swift // FJSImageViewController // // Created by hf on 2015/12/20. // Copyright © 2015年 swift-studing.com. All rights reserved. // import UIKit public class FJSImageViewController: UIViewController { /** image to display */ public var image: UIImage? /** Options to specify how a view adjusts its content when its size changes */ public var contentMode: UIViewContentMode = .ScaleToFill /** Position and size of image */ public var imageViewFrame: CGRect? private var isDirty = false; private let imageView = UIImageView(image: nil) private var beforePoint = CGPointMake(0.0, 0.0) private var currentScale = CGFloat(1.0) public override func viewDidLoad() { super.viewDidLoad() configureImageView() setupGesture() } internal func handleGesture(gesture: UIGestureRecognizer){ if let tapGesture = gesture as? UITapGestureRecognizer{ tap(tapGesture) }else if let pinchGesture = gesture as? UIPinchGestureRecognizer{ pinch(pinchGesture) }else if let panGesture = gesture as? UIPanGestureRecognizer{ pan(panGesture) } } private func configureImageView(){ self.imageView.image = image self.imageView.contentMode = contentMode self.imageView.frame = imageViewFrame ?? self.view.bounds self.imageView.userInteractionEnabled = true self.view.addSubview(self.imageView) } private func setupGesture(){ let pinchGesture = UIPinchGestureRecognizer(target: self, action: "handleGesture:") self.view.addGestureRecognizer(pinchGesture) let tapGesture = UITapGestureRecognizer(target: self, action: "handleGesture:") self.view.addGestureRecognizer(tapGesture) let panGesture = UIPanGestureRecognizer(target: self, action: "handleGesture:") self.view.addGestureRecognizer(panGesture) } private func pan(gesture:UIPanGestureRecognizer){ isDirty = true var translation = gesture.translationInView(self.view) if abs(self.beforePoint.x) > 0.0 || abs(self.beforePoint.y) > 0.0{ translation = CGPointMake(self.beforePoint.x + translation.x, self.beforePoint.y + translation.y) } switch gesture.state{ case .Changed: let scaleTransform = CGAffineTransformMakeScale(self.currentScale, self.currentScale) let translationTransform = CGAffineTransformMakeTranslation(translation.x, translation.y) self.imageView.transform = CGAffineTransformConcat(scaleTransform, translationTransform) case .Ended , .Cancelled: self.beforePoint = translation default: break } } private func tap(gesture:UITapGestureRecognizer){ if isDirty{ isDirty = false UIView.animateWithDuration(0.2){ self.beforePoint = CGPointMake(0.0, 0.0) self.imageView.transform = CGAffineTransformIdentity } }else{ self.dismissViewControllerAnimated(false, completion: nil) } } private func pinch(gesture:UIPinchGestureRecognizer){ var scale = gesture.scale scale = self.currentScale + (scale - 1.0) switch gesture.state{ case .Changed: isDirty = true let scaleTransform = CGAffineTransformMakeScale(scale, scale) let transitionTransform = CGAffineTransformMakeTranslation(self.beforePoint.x, self.beforePoint.y) self.imageView.transform = CGAffineTransformConcat(scaleTransform, transitionTransform) case .Ended , .Cancelled: self.currentScale = scale default: break } } }
7fd682c9480746c9a09b04d8790b8b70
34.706422
110
0.647225
false
false
false
false
ProfileCreator/ProfileCreator
refs/heads/master
ProfileCreator/ProfileCreator/Profile Editor OutlineView/PropertyListEditor Source/Items/PropertyListType.swift
mit
1
// // PropertyListType.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Foundation // MARK: - Property List Types /// `PropertyListType` is a simple enum that contains cases for each property list type. These are /// primarily useful when you need the type of a `PropertyListItem` for use in an arbitrary boolean /// expression. For example, /// /// ``` /// extension PropertyListItem { /// var isScalar: Bool { /// return propertyListType != .ArrayType && propertyListType != .DictionaryType /// } /// } /// ``` /// /// This type of concise expression isn’t possible with `PropertyListItem` because each of its enum /// cases has an associated value. enum PropertyListType { case array case boolean case data case date case dictionary case number case string } extension PropertyListType { /// Returns the `PropertyListType` instance that corresponds to the specified index of the /// type pop-up menu, or `nil` if the index doesn’t have a known type correspondence. /// - parameter index: The index of the type pop-up menu whose type is being returned. init?(typePopUpMenuItemIndex index: Int) { switch index { case 0: self = .array case 1: self = .dictionary case 3: self = .boolean case 4: self = .data case 5: self = .date case 6: self = .number case 7: self = .string default: return nil } } /// Returns the index of the type pop-up menu that the instance corresponds to. var typePopUpMenuItemIndex: Int { switch self { case .array: return 0 case .dictionary: return 1 case .boolean: return 3 case .data: return 4 case .date: return 5 case .number: return 6 case .string: return 7 } } }
58adf62419a6d69e11d1ad786c990225
24.414634
99
0.582054
false
false
false
false
weby/Stencil
refs/heads/master
Tests/ParserSpec.swift
bsd-2-clause
1
import Spectre import Stencil func testTokenParser() { describe("TokenParser") { $0.it("can parse a text token") { let parser = TokenParser(tokens: [ Token.Text(value: "Hello World") ], namespace: Namespace()) let nodes = try parser.parse() let node = nodes.first as? TextNode try expect(nodes.count) == 1 try expect(node?.text) == "Hello World" } $0.it("can parse a variable token") { let parser = TokenParser(tokens: [ Token.Variable(value: "'name'") ], namespace: Namespace()) let nodes = try parser.parse() let node = nodes.first as? VariableNode try expect(nodes.count) == 1 let result = try node?.render(Context()) try expect(result) == "name" } $0.it("can parse a comment token") { let parser = TokenParser(tokens: [ Token.Comment(value: "Secret stuff!") ], namespace: Namespace()) let nodes = try parser.parse() try expect(nodes.count) == 0 } $0.it("can parse a tag token") { let namespace = Namespace() namespace.registerSimpleTag("known") { _ in return "" } let parser = TokenParser(tokens: [ Token.Block(value: "known"), ], namespace: namespace) let nodes = try parser.parse() try expect(nodes.count) == 1 } $0.it("errors when parsing an unknown tag") { let parser = TokenParser(tokens: [ Token.Block(value: "unknown"), ], namespace: Namespace()) try expect(try parser.parse()).toThrow(TemplateSyntaxError("Unknown template tag 'unknown'")) } } }
da1ea64a656faffc74e676a0c30cef1d
25.209677
99
0.588923
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
其他功能/CoreData练习/coreData01简单使用/coreData01/ViewController.swift
mit
1
// // ViewController.swift // coreData // // Created by i-Techsys.com on 17/1/10. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { fileprivate lazy var tableView: UITableView = UITableView(frame: self.view.frame) @IBOutlet weak var textField: UITextField! var peoples = [NSManagedObject]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self view.addSubview(tableView) self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.addClick)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(ViewController.saveClick)) peoples = getPerson() } @objc func addClick() { let alertVC = UIAlertController(title: "新建联系人", message: nil, preferredStyle: .alert) alertVC.addTextField { (textfield) in textfield.placeholder = "请输入名字" } alertVC.addTextField { (textfield) in textfield.placeholder = "请输入年龄" textfield.keyboardType = UIKeyboardType.numberPad } // 确定 let sureAction = UIAlertAction(title: "确定", style: .default, handler: {(_ action: UIAlertAction) -> Void in // let age = Int(arc4random_uniform(100)) // self.storePerson(name: self.textField.text ?? "默认文字", age: age) let text = alertVC.textFields?.first?.text let ageText = alertVC.textFields?.last?.text self.storePerson(name: text ?? "明明就是你", age: Int(ageText ?? "0")!) self.tableView.reloadData() }) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) alertVC.addAction(sureAction) alertVC.addAction(cancelAction) present(alertVC, animated: true, completion: nil) } @objc func saveClick() { let _ = getPerson() } } // MARK: - coreData extension ViewController { /// 获取托管对象内容总管 func getContext () -> NSManagedObjectContext { let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.persistentContainer.viewContext } /// 保存一条数据 func storePerson(name:String, age: Int){ let managerContext = getContext() // 定义一个entity,这个entity一定要在Xcdatamoded做好定义 let entity = NSEntityDescription.entity(forEntityName: "Person", in: managerContext) let person = NSManagedObject(entity: entity!, insertInto: managerContext) as! Person person.setValue(name, forKey: "name") person.setValue(age, forKey: "age") peoples.append(person) try? managerContext.save() } /// 获取某一entity的所有数据 func getPerson() -> [NSManagedObject]{ let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person") let searchResults = try? getContext().fetch(fetchRequest) print("numbers of \(searchResults!.count)") for p in (searchResults as! [NSManagedObject]){ print("name: \(p.value(forKey: "name")!) age: \(p.value(forKey: "age")!)") } return searchResults as! [NSManagedObject] } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return peoples.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cellID") if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: "cellID") } let person = peoples[indexPath.row] cell?.textLabel?.text = person.value(forKey: "name") as? String cell?.detailTextLabel?.text = String(describing: person.value(forKey: "age")!) return cell! } }
7fc6647251011a9a8f88b53307872b62
34.432203
151
0.640517
false
false
false
false
aleufms/JeraUtils
refs/heads/master
JeraUtils/Base/ReactiveHelper.swift
mit
1
// // ReactiveHelper.swift // Glambox // // Created by Alessandro Nakamuta on 1/28/16. // Copyright © 2016 Glambox. All rights reserved. // import RxSwift import Kingfisher public extension ObservableType where E == NSURL? { public func downloadImage(placeholder placeholder: UIImage? = nil) -> Observable<UIImage?> { return flatMapLatest { imageURL -> Observable<UIImage?> in if let imageURL = imageURL { return Observable<UIImage?>.create({ (observer) -> Disposable in observer.onNext(placeholder) let retrieveImageTask = KingfisherManager.sharedManager.retrieveImageWithURL(imageURL, optionsInfo: [.Transition(ImageTransition.Fade(1))], progressBlock: nil, completionHandler: { (image, error, cacheType, imageURL) in if let error = error{ observer.onError(error) } if let image = image{ observer.onNext(image) observer.onCompleted() } }) return AnonymousDisposable { retrieveImageTask.cancel() } }) } return Observable.just(placeholder) } } } public extension ObservableType { public func delay(time: NSTimeInterval, scheduler: SchedulerType = MainScheduler.instance) -> Observable<E> { return self.flatMap { element in Observable<Int>.timer(time, scheduler: scheduler) .map { _ in return element } } } }
dff2d238eb5cb72365b2a3a3c4427fc1
34.55102
239
0.532453
false
false
false
false
eldesperado/SpareTimeAlarmApp
refs/heads/master
SpareTimeMusicApp/NTSwitch.swift
mit
1
// // NTSwitch.swift // SpareTimeAlarmApp // // Created by Pham Nguyen Nhat Trung on 8/5/15. // Copyright (c) 2015 Pham Nguyen Nhat Trung. All rights reserved. // import Foundation import UIKit class NTSwitch: SevenSwitch { override init() { super.init() setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { onTintColor = UIColor.untAzulColor() borderColor = UIColor(white: 1, alpha: 0.41) shadowColor = UIColor.untTransparentColor() thumbTintColor = UIColor.untTransparentColor() onThumbTintColor = UIColor.whiteColor() } }
a0a57a2933a887ddbb8efc0ce77e87a7
19.09375
67
0.670295
false
false
false
false
gizmosachin/ColorSlider
refs/heads/master
Sources/ColorSlider.swift
mit
1
// // ColorSlider.swift // // Created by Sachin Patel on 1/11/15. // // The MIT License (MIT) // // Copyright (c) 2015-Present Sachin Patel (http://gizmosachin.com/) // // 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 /// The orientation in which the `ColorSlider` is drawn. public enum Orientation { /// The horizontal orientation. case horizontal /// The vertical orientation. case vertical } /// /// ColorSlider is a customizable color picker with live preview. /// /// Inspired by Snapchat, ColorSlider lets you drag to select black, white, or any color in between. /// Customize `ColorSlider` and its preview via a simple API, and receive callbacks via `UIControlEvents`. /// /// Use the convenience initializer to create a `.vertical` ColorSlider with a live preview that appears to the `.left` of it: /// ```swift /// let colorSlider = ColorSlider(orientation: .vertical, previewSide: .left) /// ``` /// /// You can create a custom preview view using the `ColorSliderPreviewing` protocol, or by subclassing `DefaultPreviewView`. /// To pass in a custom preview view, simply use the default initializer instead: /// ```swift /// let myPreviewView = MyPreviewView() /// let colorSlider = ColorSlider(orientation: .vertical, previewView: myPreviewView) /// ``` /// /// ColorSlider is a `UIControl` subclass and fully supports the following `UIControlEvents`: /// * `.valueChanged` /// * `.touchDown` /// * `.touchUpInside` /// * `.touchUpOutside` /// * `.touchCancel` /// /// Once adding your class as a target, you can get callbacks via the `color` property: /// ```swift /// colorSlider.addTarget(self, action: #selector(ViewController.changedColor(_:)), forControlEvents: .valueChanged) /// /// func changedColor(_ slider: ColorSlider) { /// var color = slider.color /// // ... /// } /// ``` /// /// Customize the appearance of ColorSlider by setting properties on the `gradientView`: /// ```swift /// // Add a border /// colorSlider.gradientView.layer.borderWidth = 2.0 /// colorSlider.gradientView.layer.borderColor = UIColor.white /// /// // Disable rounded corners /// colorSlider.gradientView.automaticallyAdjustsCornerRadius = false /// ``` /// /// ColorSlider uses the [HSB](https://en.wikipedia.org/wiki/HSL_and_HSV) color standard internally. /// You can set the `saturation` of your ColorSlider's `gradientView` to change the saturation of colors on the slider. /// See the `GradientView` and `HSBColor` for more details on how colors are calculated. /// public class ColorSlider: UIControl { /// The selected color. public var color: UIColor { get { return UIColor(hsbColor: internalColor) } set { internalColor = HSBColor(color: newValue) previewView?.colorChanged(to: color) previewView?.transition(to: .inactive) sendActions(for: .valueChanged) } } /// The background gradient view. public let gradientView: GradientView /// The preview view, passed in the required initializer. public let previewView: PreviewView? /// The layout orientation of the slider, as defined in the required initializer. internal let orientation: Orientation /// The internal HSBColor representation of `color`. internal var internalColor: HSBColor @available(*, unavailable) required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) and storyboards are unsupported, use init(orientation:) instead.") } // MARK: - Init /// - parameter orientation: The orientation of the ColorSlider. /// - parameter side: The side of the ColorSlider on which to anchor the live preview. public convenience init(orientation: Orientation = .vertical, previewSide side: DefaultPreviewView.Side = .left) { // Check to ensure the side is valid for the given orientation switch orientation { case .horizontal: assert(side == .top || side == .bottom, "The preview must be on the top or bottom for orientation \(orientation).") case .vertical: assert(side == .left || side == .right, "The preview must be on the left or right for orientation \(orientation).") } // Create the preview view let previewView = DefaultPreviewView(side: side) self.init(orientation: orientation, previewView: previewView) } /// - parameter orientation: The orientation of the ColorSlider. /// - parameter previewView: An optional preview view that stays anchored to the slider. See ColorSliderPreviewing. required public init(orientation: Orientation, previewView: PreviewView?) { self.orientation = orientation self.previewView = previewView gradientView = GradientView(orientation: orientation) internalColor = HSBColor(hue: 0, saturation: gradientView.saturation, brightness: 1) super.init(frame: .zero) addSubview(gradientView) if let currentPreviewView = previewView { currentPreviewView.isUserInteractionEnabled = false addSubview(currentPreviewView) } } } /// :nodoc: // MARK: - Layout extension ColorSlider { public override func layoutSubviews() { super.layoutSubviews() gradientView.frame = bounds if let preview = previewView { switch orientation { // Initial layout pass, set preview center as needed case .horizontal where preview.center.y != bounds.midY, .vertical where preview.center.x != bounds.midX: if internalColor.hue == 0 { // Initially set preview center to the top or left centerPreview(at: .zero) } else { // Set preview center from `internalColor` let sliderProgress = gradientView.calculateSliderProgress(for: internalColor) centerPreview(at: CGPoint(x: sliderProgress * bounds.width, y: sliderProgress * bounds.height)) } // Adjust preview view size if needed case .horizontal where autoresizesSubviews: preview.bounds.size = CGSize(width: 25, height: bounds.height + 10) case .vertical where autoresizesSubviews: preview.bounds.size = CGSize(width: bounds.width + 10, height: 25) default: break } } } /// Center the preview view at a particular point, given the orientation. /// /// * If orientation is `.horizontal`, the preview is centered at `(point.x, bounds.midY)`. /// * If orientation is `.vertical`, the preview is centered at `(bounds.midX, point.y)`. /// /// The `x` and `y` values of `point` are constrained to the bounds of the slider. /// - parameter point: The desired point at which to center the `previewView`. internal func centerPreview(at point: CGPoint) { switch orientation { case .horizontal: let boundedTouchX = (0..<bounds.width).clamp(point.x) previewView?.center = CGPoint(x: boundedTouchX, y: bounds.midY) case .vertical: let boundedTouchY = (0..<bounds.height).clamp(point.y) previewView?.center = CGPoint(x: bounds.midX, y: boundedTouchY) } } } /// :nodoc: // MARK: - UIControlEvents extension ColorSlider { /// Begins tracking a touch when the user starts dragging. public override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { super.beginTracking(touch, with: event) // Reset saturation to default value internalColor.saturation = gradientView.saturation update(touch: touch, touchInside: true) let touchLocation = touch.location(in: self) centerPreview(at: touchLocation) previewView?.transition(to: .active) sendActions(for: .touchDown) sendActions(for: .valueChanged) return true } /// Continues tracking a touch as the user drags. public override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { super.continueTracking(touch, with: event) update(touch: touch, touchInside: isTouchInside) if isTouchInside { let touchLocation = touch.location(in: self) centerPreview(at: touchLocation) } else { previewView?.transition(to: .activeFixed) } sendActions(for: .valueChanged) return true } /// Ends tracking a touch when the user finishes dragging. public override func endTracking(_ touch: UITouch?, with event: UIEvent?) { super.endTracking(touch, with: event) guard let endTouch = touch else { return } update(touch: endTouch, touchInside: isTouchInside) previewView?.transition(to: .inactive) sendActions(for: isTouchInside ? .touchUpInside : .touchUpOutside) } /// Cancels tracking a touch when the user cancels dragging. public override func cancelTracking(with event: UIEvent?) { sendActions(for: .touchCancel) } } /// :nodoc: /// MARK: - Internal Calculations fileprivate extension ColorSlider { /// Updates the internal color and preview view when a touch event occurs. /// - parameter touch: The touch that triggered the update. /// - parameter touchInside: Whether the touch that triggered the update was inside the control when the event occurred. func update(touch: UITouch, touchInside: Bool) { internalColor = gradientView.color(from: internalColor, after: touch, insideSlider: touchInside) previewView?.colorChanged(to: color) } } /// :nodoc: /// MARK: - Increase Tappable Area extension ColorSlider { /// Increase the tappable area of `ColorSlider` to a minimum of 44 points on either edge. override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // If hidden, don't customize behavior guard !isHidden else { return super.hitTest(point, with: event) } // Determine the delta between the width / height and 44, the iOS HIG minimum tap target size. // If a side is already longer than 44, add 10 points of padding to either side of the slider along that axis. let minimumSideLength: CGFloat = 44 let padding: CGFloat = -20 let dx: CGFloat = min(bounds.width - minimumSideLength, padding) let dy: CGFloat = min(bounds.height - minimumSideLength, padding) // If an increased tappable area is needed, respond appropriately let increasedTapAreaNeeded = (dx < 0 || dy < 0) let expandedBounds = bounds.insetBy(dx: dx / 2, dy: dy / 2) if increasedTapAreaNeeded && expandedBounds.contains(point) { for subview in subviews.reversed() { let convertedPoint = subview.convert(point, from: self) if let hitTestView = subview.hitTest(convertedPoint, with: event) { return hitTestView } } return self } else { return super.hitTest(point, with: event) } } }
deca3652035aa5d8b7d405ec3f9b722b
34.929936
126
0.719996
false
false
false
false
etoledom/Heyou
refs/heads/master
Heyou/Classes/Scenes/AlertController.swift
mit
1
import UIKit typealias Layout = NSLayoutConstraint.Attribute open class Heyou: UIViewController { ///Array of UI Elements to show let elements: [Element] var animator = HYModalAlertAnimator() private let alertView: AlertView private weak var presentingVC: UIViewController? // MARK: - ViewController life cycle public init(elements: [Element]) { self.elements = elements alertView = AlertView(elements: elements) super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { elements = [] alertView = AlertView(elements: elements) super.init(coder: aDecoder) } override open func viewDidLoad() { super.viewDidLoad() configureAlertView() configureBackground() } func configureBackground() { view.backgroundColor = UIColor.black.withAlphaComponent(0.4) let tap = UITapGestureRecognizer(target: self, action: #selector(self.onTap)) tap.delegate = self view.addGestureRecognizer(tap) } func configureAlertView() { view.addSubview(alertView) NSLayoutConstraint.activate([ view.centerXAnchor.constraint(equalTo: alertView.centerXAnchor), view.centerYAnchor.constraint(equalTo: alertView.centerYAnchor) ]) } func dismiss(completion: (() -> Void)? = nil) { presentingViewController?.dismiss(animated: true, completion: completion) } @objc func onTap(_ tap: UITapGestureRecognizer) { dismiss() } /// Make the alert be presendted by the given view controller. Use this method to use the custom presentation animation. /// /// - Parameter viewController: View Controller that will present this alert. open func show(onViewController viewController: UIViewController) { presentingVC = viewController viewController.definesPresentationContext = true self.transitioningDelegate = self animator.presenting = true modalPresentationStyle = UIModalPresentationStyle.overFullScreen presentingVC?.present(self, animated: true, completion: nil) } open func show() { if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } show(onViewController: topController) } } } extension Heyou: HYPresentationAnimatable { var topView: UIView { return alertView } var backgroundView: UIView { return view } } extension Heyou: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return animator } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.presenting = false return animator } } extension Heyou: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return !alertView.frame.contains(touch.location(in: view)) } }
61b2790b5bfe9d5e721f4dc7a67c34d9
30.867925
177
0.690053
false
false
false
false
OSzhou/MyTestDemo
refs/heads/master
17_SwiftTestCode/TestCode/OtherPro/MeetupChildViewController.swift
apache-2.0
1
// // MeetupChildViewController.swift // TestCode // // Created by Zhouheng on 2020/7/15. // Copyright © 2020 tataUFO. All rights reserved. // import UIKit class MeetupChildViewController: HFBaseTableViewController { let headerH: CGFloat = 88 + 52.5 + 50 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(255)) / 255.0, green: CGFloat(arc4random_uniform(255)) / 255.0, blue: CGFloat(arc4random_uniform(255)) / 255.0, alpha: 1.0) self.createUI() self.getData() } func getData() { } func createUI() { addTableview(superview: view, style: .plain) { [weak self] (tableview) in guard let self = self else { return } tableview.frame = CGRect(x: 0, y: 0, width: Constants.ScreenWidth, height: Constants.ScreenHeight - self.headerH) tableview.dataSource = self tableview.delegate = self tableview.backgroundColor = UIColor.clear tableview.tableHeaderView = self.headerView // tableview.register(MeetupPassOrRejectTableViewCell.self, forCellReuseIdentifier: MeetupPassOrRejectTableViewCell.identifier()) tableview.register(MeetupWaitingTableViewCell.self, forCellReuseIdentifier: MeetupWaitingTableViewCell.identifier()) } } /// MARK: --- lazy loading lazy var headerView: MeetupTableViewHeader = { let view = MeetupTableViewHeader(frame: CGRect(x: 0, y: 0, width: Constants.ScreenWidth, height: 50)) return view }() } extension MeetupChildViewController { func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: MeetupWaitingTableViewCell.identifier()) as! MeetupWaitingTableViewCell // let cell = tableView.dequeueReusableCell(withIdentifier: MeetupPassOrRejectTableViewCell.identifier()) as! MeetupPassOrRejectTableViewCell cell.backgroundColor = UIColor.clear cell.selectionStyle = UITableViewCell.SelectionStyle.none return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 77 } }
0bd2efdc13448d6c5b8558db566546c1
33.657895
194
0.653379
false
false
false
false
CoderJChen/SWWB
refs/heads/master
CJWB/CJWB/Classes/Profile/Tools/Emotion/CJEmotionVC.swift
apache-2.0
1
// // CJEmotionVC.swift // CJWB // // Created by 星驿ios on 2017/9/13. // Copyright © 2017年 CJ. All rights reserved. // import UIKit private let EmoticonCell = "EmoticonCell" class CJEmotionVC: UIViewController { var emotionCallBack : ( _ emotion :CJEmotionModel) -> () fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: CJEmotionCollectionViewLayout()) fileprivate lazy var toolBar : UIToolbar = UIToolbar() fileprivate lazy var manager = CJEmotionManger() init(emotionCallBack : @escaping ( _ emotion :CJEmotionModel) -> ()){ self.emotionCallBack = emotionCallBack super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setUpUI() // Do any additional setup after loading the view. } } extension CJEmotionVC{ fileprivate func setUpUI(){ view.addSubview(collectionView) view.addSubview(toolBar) collectionView.backgroundColor = UIColor.purple toolBar.backgroundColor = UIColor.darkGray collectionView.translatesAutoresizingMaskIntoConstraints = false toolBar.translatesAutoresizingMaskIntoConstraints = false let views = ["tBar" : toolBar,"cView" : collectionView] as [String : Any] let cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tBar]-0-|", options: [], metrics: nil, views: views) view.addConstraints(cons) prepareForCollectionView() prepareForToolBar() } fileprivate func prepareForCollectionView(){ collectionView.register(CJEmotionCell.self, forCellWithReuseIdentifier: EmoticonCell) collectionView.dataSource = self collectionView.delegate = self } fileprivate func prepareForToolBar(){ let titles = ["最近","默认","emoji","浪小花"] var index = 0 var tempItems = [UIBarButtonItem]() for title in titles { let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(CJEmotionVC.itemClick(item:))) item.tag = index index += 1 tempItems.append(item) tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)) } tempItems.removeLast() toolBar.items = tempItems toolBar.tintColor = UIColor.orange } @objc fileprivate func itemClick(item : UIBarButtonItem){ let tag = item.tag let indexPath = NSIndexPath(item: 0, section: tag) collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: true) } } extension CJEmotionVC : UICollectionViewDataSource, UICollectionViewDelegate{ func numberOfSections(in collectionView: UICollectionView) -> Int { return manager.packages.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCell, for: indexPath) as! CJEmotionCell let package = manager.packages[indexPath.section] let emotion = package.emotions[indexPath.item] cell.emotion = emotion return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let package = manager.packages[section] return package.emotions.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let packege = manager.packages[indexPath.section] let emotion = packege.emotions[indexPath.item] emotionCallBack(emotion) } fileprivate func insertRecentlyEmotion(emotion : CJEmotionModel){ if emotion.isRemove || emotion.isEmpty { return } if (manager.packages.first?.emotions.contains(emotion))! { let index = (manager.packages.first?.emotions.index(of: emotion)) manager.packages.first?.emotions.remove(at: index!) }else{ manager.packages.first?.emotions.remove(at: 19) } manager.packages.first?.emotions.insert(emotion, at: 0) } } class CJEmotionCollectionViewLayout: UICollectionViewFlowLayout { override func prepare() { super.prepare() let itemWH = UIScreen.main.bounds.width / 7 itemSize = CGSize(width: itemWH, height: itemWH) minimumLineSpacing = 0 minimumInteritemSpacing = 0 scrollDirection = .horizontal collectionView?.isPagingEnabled = true collectionView?.showsVerticalScrollIndicator = false collectionView?.showsHorizontalScrollIndicator = false let insetMargin = ((collectionView?.bounds.height)! - 3*itemWH) / 2 collectionView?.contentInset = UIEdgeInsetsMake(insetMargin, 0, insetMargin, 0) } }
515c46d02b4edf56dbf352e172961912
35.173611
180
0.661547
false
false
false
false
srxboys/RXExtenstion
refs/heads/master
RXExtenstion/Swift3x/RXModel.swift
mit
1
// // RXModel.swift // RXSwiftExtention // // Created by srx on 2017/3/25. // Copyright © 2017年 https://github.com/srxboys. All rights reserved. // /* * 数据模型 基类 * * 详见:https://github.com/srxboys/RXSwiftExtention * * 有个小小的改动,以前所有dict都是公共区域写的,为了让OC 用类方法,放到了 RXModel的大括号里面 * 再看RXPrintInterface.swift里面,我就没有动,就变成了不是类方法也不是实例方法的,就不提供给OC调用 */ import UIKit class RXModel: NSObject { override func setValue(_ value: Any?, forUndefinedKey key: String) { //不存在的 NSLog("error 不存在的key" + key) } /* * 所有返回的类型,一定要和 定义的类型匹配否则必崩溃 ***** */ // MARK: --- String----- /// 根据字典key获取内容为 字符串类型 public class func dictForKeyString(_ dict:[String:Any], key : String) ->String { let valueStatus = dictForKey(dict, key: key) if(!valueStatus.isValue) { return "" } let value = valueStatus.object if value is String { var count : Int = 0 #if OS_OBJECT_SWIFT3 count = (value as! String).characters.count #else //swift4 count = (value as! String).count #endif if( count > 0 && (value as! String) != "<null>") { return value as! String } else { return "" } } else if(value is [String:Any]) { return "" } else if(value is [Any]) { return "" } else { let valueString = "\(value)" var valueStringCount = 0 #if OS_OBJECT_SWIFT3 valueStringCount = valueString.characters.count; #else //swift4 valueStringCount = valueString.count; #endif if valueStringCount <= 0 { return "" } } return "\(value)" } /// 根据字典key获取内容为 数值类型 public class func dictForKeyInt(_ dict:[String:Any], key : String) ->Int { let value = dictForKeyString(dict, key: key) if(!value.isEmpty) { return Int(value)! } return 0 } // MARK: --- Bool ----- /// 根据字典key获取内容为 布尔类型 public class func dictForKeyBool(_ dict:[String:Any], key : String) ->Bool { let value = dictForKeyInt(dict, key: key) if(value > 0) { return true } return false } // MARK: --- CGFloat ----- /// 根据字典key获取内容为 CGFloat public class func dictForKeyCGFloat(_ dict:[String:Any], key : String) ->CGFloat { let value = dictForKeyString(dict, key: key) if(!value.isEmpty) { return CGFloat(Float(value)!) } return 0 } // MARK: --- Float ----- /// 根据字典key获取内容为 Float public class func dictForKeyFloat(_ dict:[String:Any], key : String) ->Float { let value = dictForKeyString(dict, key: key) if(!value.isEmpty) { return Float(value)! } return 0 } // MARK: --- Dictionary ----- /// 根据字典key获取内容为字典 返回值 [值,是否有值] public class func dictForKeyDict(_ dict:[String:Any], key : String) ->(object:[String:Any], isValue:Bool) { let valueStatus = dictForKey(dict, key: key) if(!valueStatus.isValue) { return ([String:Any](), false) } let value = valueStatus.object if value is [String:Any] { return (value as! [String:Any], true) } return ([String:Any](), false) } // MARK: --- Any ----- /// 根据字典key获取内容为任意类型 返回值 [值,是否有值] public class func dictForKey(_ dict:[String:Any], key:String) -> (object:Any, isValue:Bool) { guard dict.index(forKey: key) != nil else { return ("", false) } let anyValue = dict[key] guard anyValue != nil else { return ("", false) } if anyValue is Int { return (String(anyValue as! Int), true) } if anyValue is String { return (anyValue as! String, true) } return (anyValue!, true) } }
87d34ed5b82afb844abeeb7a9cd832dc
24.993506
111
0.530352
false
false
false
false
Za1006/TIY-Assignments
refs/heads/master
HeroTracker/HeroTracker/HeroTableViewController.swift
cc0-1.0
1
// // HeroTableViewController.swift // HeroTracker // // Created by Elizabeth Yeh on 10/12/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class HeroTableViewController: UITableViewController { var heroes = Array<Hero>() override func viewDidLoad() { super.viewDidLoad() title = "S.H.I.E.L.D. Hero Tracker" loadHeroes() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } @IBOutlet weak var HeroCell: UITableViewCell! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return heroes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("HeroCell", forIndexPath: indexPath) // Configure the cell... let aHero = heroes[indexPath.row] cell.textLabel?.text = aHero.name cell.detailTextLabel?.text = aHero.homeWorld return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let selectedHero = heroes[indexPath.row] let detailVC = storyboard?.instantiateViewControllerWithIdentifier("HeroDetailViewController") as! HeroDetailViewController detailVC.hero = selectedHero navigationController?.pushViewController(detailVC, animated: true) } // instead of doing the segue use the func above by creating a viewController but not connecting it to the TableViewController /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: Navigation private func loadHeroes() { do { let filePath = NSBundle.mainBundle().pathForResource("heroes", ofType: "json") let dataFromFile = NSData(contentsOfFile: filePath!) let heroData: NSArray! = try NSJSONSerialization.JSONObjectWithData(dataFromFile!, options:[]) as! NSArray for heroDictionary in heroData { let aHero = Hero(dictionary: heroDictionary as! NSDictionary) heroes.append(aHero) } heroes.sortInPlace({ $0.name < $1.name}) } catch let error as NSError { print(error) } } }
ff7923f351c5460571766aa18259bfcb
31.664179
157
0.659813
false
false
false
false
GraphQLSwift/Graphiti
refs/heads/main
Sources/Graphiti/Value/Value.swift
mit
1
public final class Value<EnumType: Encodable & RawRepresentable> where EnumType.RawValue == String { let value: EnumType var description: String? var deprecationReason: String? init( value: EnumType ) { self.value = value } } public extension Value { convenience init(_ value: EnumType) { self.init(value: value) } @discardableResult func description(_ description: String) -> Self { self.description = description return self } @discardableResult func deprecationReason(_ deprecationReason: String) -> Self { self.deprecationReason = deprecationReason return self } }
4a54250b96ef358f465d8515d4d6038f
22.62069
100
0.645255
false
false
false
false
chengxianghe/MissGe
refs/heads/master
MissGe/MissGe/Class/Project/Request/Home/MLLikeRequest.swift
mit
1
// // MLLikeRequest.swift // MissLi // // Created by chengxianghe on 16/7/26. // Copyright © 2016年 cn. All rights reserved. // import UIKit //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=likeit&pid=40298 class MLLikeCommentRequest: MLBaseRequest { var pid = "" //c=post&a=likeit&pid=40298 override func requestParameters() -> [String : Any]? { let dict = ["c":"post","a":"likeit","pid":"\(pid)"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } override func requestVerifyResult() -> Bool { guard let dict = self.responseObject as? NSDictionary else { return false } return (dict["result"] as? String) == "200" } } //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=article&a=likeit&aid=7992 class MLLikeArticleRequest: MLBaseRequest { var aid = "" //c=post&a=likeit&pid=40298 override func requestParameters() -> [String : Any]? { let dict = ["c":"article","a":"likeit","aid":"\(aid)"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } override func requestVerifyResult() -> Bool { guard let dict = self.responseObject as? NSDictionary else { return false } return (dict["result"] as? String) == "200" } }
c33d34347b58227326b77d0870e5bf8d
27.982456
160
0.62046
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/NewVersion/Reader/ZSVerticalViewController.swift
mit
1
// // ZSVerticalViewController.swift // zhuishushenqi // // Created by caony on 2019/7/9. // Copyright © 2019 QS. All rights reserved. // import UIKit class ZSVerticalViewController: BaseViewController, ZSReaderVCProtocol { fileprivate var pageVC:PageViewController = PageViewController() weak var toolBar:ZSReaderToolbar? weak var dataSource:UIPageViewControllerDataSource? weak var delegate:UIPageViewControllerDelegate? var nextPageHandler: ZSReaderPageHandler? var lastPageHandler: ZSReaderPageHandler? lazy var tableView:UITableView = { let tableView = UITableView(frame: .zero, style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.sectionHeaderHeight = 0.01 tableView.sectionFooterHeight = 0.01 if #available(iOS 11, *) { tableView.contentInsetAdjustmentBehavior = .never } tableView.register(ZSShelfTableViewCell.self, forCellReuseIdentifier: "\(ZSShelfTableViewCell.self)") tableView.qs_registerHeaderFooterClass(ZSBookShelfHeaderView.self) let blurEffect = UIBlurEffect(style: .extraLight) let blurEffectView = UIVisualEffectView(effect: blurEffect) tableView.backgroundView = blurEffectView return tableView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func bind(toolBar: ZSReaderToolbar) { self.toolBar = toolBar } func destroy() { pageVC.destroy() } func changeBg(style: ZSReaderStyle) { pageVC.bgView.image = style.backgroundImage } func jumpPage(page: ZSBookPage,_ animated:Bool, _ direction:UIPageViewController.NavigationDirection = .forward) { pageVC.newPage = page tableView.beginUpdates() tableView.reloadSection(UInt(page.chapterIndex), with: UITableView.RowAnimation.automatic) tableView.endUpdates() } private func setupGesture() { let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(tap:))) tap.numberOfTouchesRequired = 1 tap.numberOfTapsRequired = 1 view.addGestureRecognizer(tap) } @objc private func tapAction(tap:UITapGestureRecognizer) { toolBar?.show(inView: view, true) } } extension ZSVerticalViewController:UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } }
9a4732f8f2736c1bd638ba55265f9a62
30.574713
118
0.684019
false
false
false
false
tylerlutz/SwiftPlaygrounds
refs/heads/master
Numbers.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit //Integers var myBankAccount: Int = -500 //Unsigned Int value has to be zero or greater var myAge: UInt = 22 //Use Int64 for numebrs larger then 2,147,483,647 var bigNumber: Int64 = 2147483647 //Double up to 15 decimal points var anotherBankAccount: Double = 55.5 //Float up to 6 decimal points var someVal: Float = 5.5 //Have to cast someVal to a double var sum = anotherBankAccount * Double(someVal)
d5b729b579cb7bfe5bac91a634233cfa
21.619048
52
0.742616
false
false
false
false
AbdulBasitBashir/learn-ios9-hybrid-apps
refs/heads/master
step0_remote_website/step0_remote_website/ViewController.swift
mit
4
// // ViewController.swift // step0_remote_website // // Created by Zia Khan on 29/07/2015. // Copyright © 2015 Panacloud. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let preferences = WKPreferences() preferences.javaScriptEnabled = true let configuration = WKWebViewConfiguration() configuration.preferences = preferences /* Now instantiate the web view */ webView = WKWebView(frame: view.bounds, configuration: configuration) if let theWebView = webView{ /* Load a web page into our web view */ let url = NSURL(string: "http://www.apple.com") let urlRequest = NSURLRequest(URL: url!) theWebView.loadRequest(urlRequest) theWebView.navigationDelegate = self view.addSubview(theWebView) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
9933bfba8c523d67204dd87df41a67b3
26.425532
80
0.626067
false
true
false
false
raymondshadow/SwiftDemo
refs/heads/master
SwiftApp/StudyNote/StudyNote/Promise/SNPromise.swift
apache-2.0
1
// // RNPromise.swift // StudyNote // // Created by wuyp on 2019/11/21. // Copyright © 2019 Raymond. All rights reserved. // import Foundation import RxSwift import RxCocoa typealias YAOPromiseInputAction = (PublishSubject<Any?>, Any?) -> Void typealias YAOPromiseCatchAction = (Error) -> Void typealias YAOPromiseFinallyAction = (Any?) -> Void class SNPromise { private var inputsPool: [YAOPromiseInputAction] = [] private var catchsPool: [YAOPromiseCatchAction] = [] private var finallyAction: YAOPromiseFinallyAction = {_ in } private var execResult: Any? private var subject = PublishSubject<Any?>() private var bag = DisposeBag() init() { registerInputActionHandle() } private func registerInputActionHandle() { subject = PublishSubject<Any?>() bag = DisposeBag() subject.subscribeOn(MainScheduler.instance).subscribe(onNext: {[weak self] (value) in self?.resolveItemAction(value: value) }, onError: {[weak self] (err) in self?.rejectItemAction(err: err) }, onCompleted: {[weak self] in self?.execCompleted() }).disposed(by: bag) } } // MARK: - public extension SNPromise { @discardableResult func then(_ handle: @escaping YAOPromiseInputAction) -> SNPromise { inputsPool.append(handle) if inputsPool.count == 1 { handle(subject, nil) } return self } @discardableResult func `catch`(_ action: @escaping YAOPromiseCatchAction) -> SNPromise { catchsPool.append(action) return self } func `finally`(_ action: @escaping YAOPromiseFinallyAction) { finallyAction = action } } // MARK: - private handle each action extension SNPromise { private func resolveItemAction(value: Any? = nil) { execResult = value registerInputActionHandle() if inputsPool.count > 0 { _ = inputsPool.removeFirst() } guard inputsPool.count > 0 else { execCompleted() return } inputsPool[0](subject, value) } private func rejectItemAction(err: Error) { catchsPool.forEach { action in action(err) } execCompleted() } private func execCompleted() { inputsPool.removeAll() catchsPool.removeAll() registerInputActionHandle() finallyAction(execResult) } }
e77e900453606ee0e7809ab04b760167
24.76
93
0.595497
false
false
false
false
timd/ProiOSTableCollectionViews
refs/heads/master
Ch09/InCellCV/InCellCV/ViewController.swift
mit
1
// // ViewController.swift // InCellCV // // Created by Tim on 07/11/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var collectionView: UICollectionView! var cvData = [Int]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController { func setupData() { for index in 0...100 { cvData.append(index) } } func addButtonToCell(cell: UICollectionViewCell) { guard cell.contentView.viewWithTag(1000) != nil else { return } let button = UIButton(type: UIButtonType.RoundedRect) button.tag = 1000 button.setTitle("Tap me!", forState: UIControlState.Normal) button.sizeToFit() button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: "didTapButtonInCell:", forControlEvents: UIControlEvents.TouchUpInside) let vConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0) let hConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -10) cell.contentView.addSubview(button) cell.contentView.addConstraints([vConstraint, hConstraint]) } func didTapButtonInCell(sender: UIButton) { let cell = sender.superview!.superview as! UICollectionViewCell let indexPathAtTap = collectionView.indexPathForCell(cell) let alert = UIAlertController(title: "Something happened!", message: "A button was tapped in item \(indexPathAtTap!.row)", preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } } extension ViewController: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return cvData.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellIdentifier", forIndexPath: indexPath) if let label = cell.contentView.viewWithTag(1000) as? UILabel { label.text = "Item \(cvData[indexPath.row])" } addButtonToCell(cell) cell.layer.borderColor = UIColor.blackColor().CGColor cell.layer.borderWidth = 1.0 return cell } }
1e8218624845b39cf84595a86d002362
31.413462
225
0.661821
false
false
false
false
jamalping/XPUtil
refs/heads/master
XPUtil/UIKit/CellIdentfierable.swift
mit
1
// // CellidentfierCompatible.swift // XPUtilExample // // Created by Apple on 2018/12/18. // Copyright © 2018年 xyj. All rights reserved. // import UIKit // MARK: - TableViewCell、CollectionViewCell,遵循Cell标志协议,实现为默认实现 extension UITableViewCell: CellidentfierCompatible {} extension UICollectionViewCell: CellidentfierCompatible{} extension UITableViewHeaderFooterView: CellidentfierCompatible{} // MARK: - Cell标志协议 public protocol CellidentfierCompatible { associatedtype CompatibleType var cell: CompatibleType { get } var identier: String { get } } public struct CellIdentier<Base> { let base: Base } public extension CellidentfierCompatible { static var cell: CellIdentier<Self.Type>{ return CellIdentier.init(base: self.self) } var cell: CellIdentier<Self> { return CellIdentier.init(base: self) } var identier: String { return "\(cell.base)" } static var identier: String { return "\(cell.base)" } } // MARK: - TableViewCell、CollectionViewCell,遵循Cell标志协议,实现为默认实现 extension UITableViewCell: Cellidentfierable {} extension UICollectionViewCell: Cellidentfierable{} extension UITableViewHeaderFooterView: Cellidentfierable{} // MARK: - Cell标志协议 protocol Cellidentfierable { static var cellIdentfier: String { get } } extension Cellidentfierable where Self: UITableViewCell { static var cellIdentfier: String { return "\(self)" } var cellIdentfier: String { return Self.cellIdentfier } } extension Cellidentfierable where Self: UICollectionViewCell { static var cellIdentfier: String { return "\(self)" } var cellIdentfier: String { return Self.cellIdentfier } } extension Cellidentfierable where Self: UITableViewHeaderFooterView { static var cellIdentfier: String { return "\(self)" } var cellIdentfier: String { return Self.cellIdentfier } } /// 注册cell protocol CellRegistable {} extension UITableView: CellRegistable {} extension UICollectionView: CellRegistable {} extension CellRegistable where Self: UITableView { func registerCells<T: UITableViewCell>(_ cellClasses: [T.Type]) { cellClasses.forEach { self.registerSingleCell($0) } } func registerSingleCell<T: UITableViewCell>(_ cellClass: T.Type) { let className = "\(cellClass)" /// 存在nib文件 if let resourcePath = Bundle.main.resourcePath, FileManager.default.fileExists(atPath: resourcePath + "/\(className).nib") { let nib = UINib(nibName: className, bundle: nil) self.register(nib, forCellReuseIdentifier: cellClass.cellIdentfier) }else { self.register(cellClass, forCellReuseIdentifier: cellClass.cellIdentfier) } } } extension CellRegistable where Self: UICollectionView { func registerCells<T: UICollectionViewCell>(_ cellClasses: [T.Type]) { cellClasses.forEach { self.registerSingleCell($0) } } func registerSingleCell<T: UICollectionViewCell>(_ cellClass: T.Type) { let className = "\(cellClass)" /// 存在nib文件 if let resourcePath = Bundle.main.resourcePath, FileManager.default.fileExists(atPath: resourcePath + "/\(className).nib") { let nib = UINib(nibName: className, bundle: nil) self.register(nib, forCellWithReuseIdentifier: cellClass.cellIdentfier) }else { self.register(cellClass, forCellWithReuseIdentifier: cellClass.cellIdentfier) } } }
6d48d61986ffdc37c4e6fa2377dc2828
24.567376
132
0.680721
false
false
false
false
LeoMobileDeveloper/MDTable
refs/heads/master
MDTableExample/Extension.swift
mit
1
// // Extension.swift // MDTableExample // // Created by Leo on 2017/7/6. // Copyright © 2017年 Leo Huang. All rights reserved. // import Foundation import UIKit import CoreGraphics extension UIView { func roundCorners(_ corners: UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask } } extension Int{ func asLocalizedPlayCount()->String{ if self < 100000 { return "\(self)" }else if self < 100000000{ return "\(self/10000)万" }else{ return "\(self/100000000)亿" } } } extension UIColor{ static var theme:UIColor{ get{ return UIColor(red: 210.0 / 255.0, green: 62.0 / 255.0, blue: 57.0 / 255.0, alpha: 1.0) } } } struct ImageConst{ static let bytesPerPixel = 4 static let bitsPerComponent = 8 } //解压缩来提高效率 extension UIImage{ func decodedImage()->UIImage?{ guard let cgImage = self.cgImage else{ return nil } guard let colorspace = cgImage.colorSpace else { return nil } let width = cgImage.width let height = cgImage.height let bytesPerRow = ImageConst.bytesPerPixel * width let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: ImageConst.bitsPerComponent, bytesPerRow: bytesPerRow, space: colorspace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) guard let context = ctx else { return nil } let rect = CGRect(x: 0, y: 0, width: width, height: height) context.draw(cgImage, in: rect) guard let drawedImage = context.makeImage() else{ return nil } let result = UIImage(cgImage: drawedImage, scale:self.scale , orientation: self.imageOrientation) return result } } extension UIImageView{ func asyncSetImage(_ image:UIImage?){ DispatchQueue.global(qos: .userInteractive).async { let decodeImage = image?.decodedImage() DispatchQueue.main.async { self.image = decodeImage } } } } extension UIButton{ func asyncSetImage(_ image:UIImage,for state:UIControlState){ DispatchQueue.global(qos: .userInteractive).async { let decodeImage = image.decodedImage() DispatchQueue.main.async { self.setImage(decodeImage, for: state) } } } } extension UIView{ var x:CGFloat{ get{ return self.frame.origin.x } set{ var frame = self.frame frame.origin.x = newValue self.frame = frame } } var y:CGFloat{ get{ return self.frame.origin.y } set{ var frame = self.frame frame.origin.y = newValue self.frame = frame } } var maxX:CGFloat{ get{ return self.frame.origin.x + self.frame.width } } var maxY:CGFloat{ get{ return self.frame.origin.y + self.frame.height } } func added(to superView:UIView)->Self{ superView.addSubview(self) return self } } extension UILabel{ static func title()->UILabel{ let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.textColor = UIColor(red: 51.0 / 255.0, green: 51.0 / 255.0, blue: 51.0 / 255.0, alpha: 1.0) label.textAlignment = .left return label } static func subTitle()->UILabel{ let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.textColor = UIColor(red: 85.0 / 255.0, green: 85.0 / 255.0, blue: 85.0 / 255.0, alpha: 1.0) label.textAlignment = .left return label } } extension UIButton{ func setBackgroundColor(_ color: UIColor, for state: UIControlState){ let rect = CGRect(x: 0, y: 0, width: 1000, height: 1000) UIGraphicsBeginImageContext(rect.size) let ctx = UIGraphicsGetCurrentContext() ctx?.setFillColor(color.cgColor) ctx?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() self.setImage(image, for: state) } } extension Date{ static var dayOfToday:String{ get{ let formatter = DateFormatter() formatter.dateFormat = "dd" let date = Date() let day = formatter.string(from: date) return day } } }
cdea45d99c4f597121b969a39ad1518d
26.364641
137
0.555219
false
false
false
false
rheinfabrik/Dobby
refs/heads/master
DobbyTests/MatcherSpec.swift
apache-2.0
2
import Quick import Nimble import Dobby class MatcherSpec: QuickSpec { override func spec() { describe("Matching") { context("a matching function") { let matcher: Dobby.Matcher<Int> = matches { $0 == 0 } it("succeeds if the matching function returns true") { expect(matcher.matches(0)).to(beTrue()) } it("fails if the matching function returns false") { expect(matcher.matches(1)).to(beFalse()) } } context("anything") { let matcher: Dobby.Matcher<Int> = any() it("always succeeds") { expect(matcher.matches(0)).to(beTrue()) expect(matcher.matches(1)).to(beTrue()) } } context("anything but whatever (not)") { let matcher: Dobby.Matcher<Int> = not(0) it("succeeds if the given matcher is not matched") { expect(matcher.matches(1)).to(beTrue()) } it("fails if the given matcher is matched") { expect(matcher.matches(0)).to(beFalse()) } } context("nothing") { let matcher: Dobby.Matcher<Int?> = none() it("succeeds if the actual value equals nil") { expect(matcher.matches(nil)).to(beTrue()) } it("fails if the actual value does not equal nil") { expect(matcher.matches(0)).to(beFalse()) } } context("something") { let matcher: Dobby.Matcher<Int?> = some(0) it("succeeds if the given matcher is matched") { expect(matcher.matches(0)).to(beTrue()) } it("fails if the given matcher is not matched") { expect(matcher.matches(nil)).to(beFalse()) expect(matcher.matches(1)).to(beFalse()) } } context("a value") { let matcher: Dobby.Matcher<Int> = equals(0) it("succeeds if the actual value equals the expected value") { expect(matcher.matches(0)).to(beTrue()) } it("fails if the actual value does not equal the expected value") { expect(matcher.matches(1)).to(beFalse()) } } context("a 2-tuple") { let matcher: Dobby.Matcher<(Int, Int)> = equals((0, 1)) it("succeeds if all actual values equal the expected values") { expect(matcher.matches(0, 1)).to(beTrue()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches(1, 1)).to(beFalse()) expect(matcher.matches(0, 0)).to(beFalse()) } } context("a 3-tuple") { let matcher: Dobby.Matcher<(Int, Int, Int)> = equals((0, 1, 2)) it("succeeds if all actual values equal the expected values") { expect(matcher.matches(0, 1, 2)).to(beTrue()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches(1, 1, 2)).to(beFalse()) expect(matcher.matches(0, 0, 2)).to(beFalse()) expect(matcher.matches(0, 1, 1)).to(beFalse()) } } context("a 4-tuple") { let matcher: Dobby.Matcher<(Int, Int, Int, Int)> = equals((0, 1, 2, 3)) it("succeeds if all actual values equal the expected values") { expect(matcher.matches(0, 1, 2, 3)).to(beTrue()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches(1, 1, 2, 3)).to(beFalse()) expect(matcher.matches(0, 0, 2, 3)).to(beFalse()) expect(matcher.matches(0, 1, 1, 3)).to(beFalse()) expect(matcher.matches(0, 1, 2, 2)).to(beFalse()) } } context("a 5-tuple") { let matcher: Dobby.Matcher<(Int, Int, Int, Int, Int)> = equals((0, 1, 2, 3, 4)) it("succeeds if all actual values equal the expected values") { expect(matcher.matches(0, 1, 2, 3, 4)).to(beTrue()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches(1, 1, 2, 3, 4)).to(beFalse()) expect(matcher.matches(0, 0, 2, 3, 4)).to(beFalse()) expect(matcher.matches(0, 1, 1, 3, 4)).to(beFalse()) expect(matcher.matches(0, 1, 2, 2, 4)).to(beFalse()) expect(matcher.matches(0, 1, 2, 3, 3)).to(beFalse()) } } context("an array") { let matcher: Dobby.Matcher<[Int]> = equals([0, 1, 2]) it("succeeds if all actual values equal the expected values") { expect(matcher.matches([0, 1, 2])).to(beTrue()) } it("fails if the amount of actual values differs from the amount of expected values") { expect(matcher.matches([0, 1])).to(beFalse()) expect(matcher.matches([0, 1, 2, 3])).to(beFalse()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches([1, 1, 2])).to(beFalse()) expect(matcher.matches([0, 0, 2])).to(beFalse()) expect(matcher.matches([0, 1, 1])).to(beFalse()) } } context("a dictionary") { let matcher: Dobby.Matcher<[Int: Int]> = equals([0: 0, 1: 1, 2: 2]) it("succeeds if all actual pairs equal the expected pairs") { expect(matcher.matches([0: 0, 1: 1, 2: 2])).to(beTrue()) } it("fails if the amount of actual pairs differs from the amount of expected pairs") { expect(matcher.matches([0: 0, 1: 1])).to(beFalse()) expect(matcher.matches([0: 0, 1: 1, 2: 2, 3: 3])).to(beFalse()) } it("fails if any actual pair does not equal the expected pair") { expect(matcher.matches([0: 1, 1: 1, 2: 2])).to(beFalse()) expect(matcher.matches([0: 0, 1: 0, 2: 2])).to(beFalse()) expect(matcher.matches([0: 0, 1: 1, 2: 1])).to(beFalse()) } } context("a 2-tuple of matchers") { let matcher: Dobby.Matcher<(Int, Int)> = matches((equals(0), equals(1))) it("succeeds if all actual values equal the expected values") { expect(matcher.matches(0, 1)).to(beTrue()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches(1, 1)).to(beFalse()) expect(matcher.matches(0, 0)).to(beFalse()) } } context("a 3-tuple of matchers") { let matcher: Dobby.Matcher<(Int, Int, Int)> = matches((equals(0), equals(1), equals(2))) it("succeeds if all actual values equal the expected values") { expect(matcher.matches(0, 1, 2)).to(beTrue()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches(1, 1, 2)).to(beFalse()) expect(matcher.matches(0, 0, 2)).to(beFalse()) expect(matcher.matches(0, 1, 1)).to(beFalse()) } } context("a 4-tuple of matchers") { let matcher: Dobby.Matcher<(Int, Int, Int, Int)> = matches((equals(0), equals(1), equals(2), equals(3))) it("succeeds if all actual values equal the expected values") { expect(matcher.matches(0, 1, 2, 3)).to(beTrue()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches(1, 1, 2, 3)).to(beFalse()) expect(matcher.matches(0, 0, 2, 3)).to(beFalse()) expect(matcher.matches(0, 1, 1, 3)).to(beFalse()) expect(matcher.matches(0, 1, 2, 2)).to(beFalse()) } } context("a 5-tuple of matchers") { let matcher: Dobby.Matcher<(Int, Int, Int, Int, Int)> = matches((equals(0), equals(1), equals(2), equals(3), equals(4))) it("succeeds if all actual values equal the expected values") { expect(matcher.matches(0, 1, 2, 3, 4)).to(beTrue()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches(1, 1, 2, 3, 4)).to(beFalse()) expect(matcher.matches(0, 0, 2, 3, 4)).to(beFalse()) expect(matcher.matches(0, 1, 1, 3, 4)).to(beFalse()) expect(matcher.matches(0, 1, 2, 2, 4)).to(beFalse()) expect(matcher.matches(0, 1, 2, 3, 3)).to(beFalse()) } } context("an array of matchers") { let matcher: Dobby.Matcher<[Int]> = matches([equals(0), equals(1), equals(2)]) it("succeeds if all actual values equal the expected values") { expect(matcher.matches([0, 1, 2])).to(beTrue()) } it("fails if the amount of actual values differs from the amount of expected values") { expect(matcher.matches([0, 1])).to(beFalse()) expect(matcher.matches([0, 1, 2, 3])).to(beFalse()) } it("fails if any actual value does not equal the expected value") { expect(matcher.matches([1, 1, 2])).to(beFalse()) expect(matcher.matches([0, 0, 2])).to(beFalse()) expect(matcher.matches([0, 1, 1])).to(beFalse()) } } context("a dictionary of matchers") { let matcher: Dobby.Matcher<[Int: Int]> = matches([0: equals(0), 1: equals(1), 2: equals(2)]) it("succeeds if all actual pairs equal the expected pairs") { expect(matcher.matches([0: 0, 1: 1, 2: 2])).to(beTrue()) } it("fails if the amount of actual pairs differs from the amount of expected pairs") { expect(matcher.matches([0: 0, 1: 1])).to(beFalse()) expect(matcher.matches([0: 0, 1: 1, 2: 2, 3: 3])).to(beFalse()) } it("fails if any actual pair does not equal the expected pair") { expect(matcher.matches([0: 1, 1: 1, 2: 2])).to(beFalse()) expect(matcher.matches([0: 0, 1: 0, 2: 2])).to(beFalse()) expect(matcher.matches([0: 0, 1: 1, 2: 1])).to(beFalse()) expect(matcher.matches([3: 0, 4: 1, 5: 2])).to(beFalse()) } } } } }
064f4558623c7e13eb6e067ae72104f3
41.564103
136
0.47315
false
false
false
false
jekahy/Adoreavatars
refs/heads/master
Adoravatars/DownloadTask.swift
mit
1
// // DownloadTask.swift // Adoravatars // // Created by Eugene on 12.07.17. // Copyright © 2017 Eugene. All rights reserved. // import RxSwift protocol DownloadTaskType { var fileName:String{get} var progress:Observable<Double>{get} var status:Observable<DownloadTask.Status>{get} var updatedAt:Observable<Date>{get} var data:Observable<Data?>{get} } class DownloadTask:DownloadTaskType { enum Status:String { case queued = "queued" case inProgress = "in progress" case done = "done" case failed = "failed" } let fileName:String private let progressSubj = BehaviorSubject<Double>(value: 0) private (set) lazy var progress:Observable<Double> = self.progressSubj.asObservable().distinctUntilChanged() private let statusSubj = BehaviorSubject<Status>(value: .queued) private (set) lazy var status:Observable<Status> = self.statusSubj.asObservable() private let updatedAtSubj = BehaviorSubject<Date>(value: Date()) private (set) lazy var updatedAt:Observable<Date> = self.updatedAtSubj.asObservable() private let dataSubj = BehaviorSubject<Data?>(value:nil) private (set) lazy var data:Observable<Data?> = self.dataSubj.asObservable().shareReplay(1) private let disposeBag = DisposeBag() init(_ fileName:String, eventsObservable:Observable<DownloadTaskEvent>) { self.fileName = fileName eventsObservable.subscribe(onNext: { [weak self] downoadEvent in self?.updatedAtSubj.onNext(Date()) switch downoadEvent{ case .progress(let progress): self?.statusSubj.onNext(.inProgress) self?.progressSubj.onNext(progress) case .done(let data): self?.dataSubj.onNext(data) self?.statusSubj.onNext(.done) self?.progressSubj.onNext(1) default: break } }, onError: {[weak self] error in self?.updatedAtSubj.onNext(Date()) self?.statusSubj.onNext(.failed) }, onCompleted: { [weak self] in self?.statusSubj.onNext(.done) }).disposed(by: disposeBag) } }
dc79eba256d24e0665c38f267c6ce126
30.133333
112
0.608137
false
false
false
false
volodg/iAsync.social
refs/heads/master
Pods/iAsync.network/Lib/NSError/NSNetworkErrors/JNSNetworkError.swift
mit
1
// // JNSNetworkError.swift // Wishdates // // Created by Vladimir Gorbenko on 18.08.14. // Copyright (c) 2014 EmbeddedSources. All rights reserved. // import Foundation import iAsync_utils public class JNSNetworkError : JNetworkError { let context: JURLConnectionParams let nativeError: NSError public required init(context: JURLConnectionParams, nativeError: NSError) { self.context = context self.nativeError = nativeError super.init(description:"") } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override var localizedDescription: String { return NSLocalizedString( "J_NETWORK_GENERIC_ERROR", bundle: NSBundle(forClass: self.dynamicType), comment:"") } public class func createJNSNetworkErrorWithContext( context: JURLConnectionParams, nativeError: NSError) -> JNSNetworkError { var selfType: JNSNetworkError.Type! //select class for error let errorClasses: [JNSNetworkError.Type] = [ JNSNoInternetNetworkError.self ] selfType = firstMatch(errorClasses) { (object: JNSNetworkError.Type) -> Bool in return object.isMineNSNetworkError(nativeError) } if selfType == nil { selfType = JNSNetworkError.self } return selfType(context: context, nativeError: nativeError) } class func isMineNSNetworkError(error: NSError) -> Bool { return false } public override func copyWithZone(zone: NSZone) -> AnyObject { return self.dynamicType(context: context, nativeError: nativeError) } public override var errorLogDescription: String { return "\(self.dynamicType) : \(localizedDescription) nativeError:\(nativeError) context:\(context)" } }
3ad278946667da727e4f974e9331ca1b
26.266667
108
0.616137
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Lumia/Lumia/Frame/CatalogByConvention/CBCNodeListViewController.swift
mit
1
// // CBCNodeListViewController.swift // Lumia // // Created by xiAo_Ju on 2020/1/20. // Copyright © 2020 黄伯驹. All rights reserved. // import UIKit // https://github.com/material-foundation/cocoapods-catalog-by-convention /** A node describes a single navigable page in the Catalog by Convention. A node either has children or it is an example. - If a node has children, then the node should be represented by a list of some sort. - If a node is an example, then the example controller can be instantiated with createExampleViewController. */ class CBCNode { /** The title for this node. */ private(set) var title: String /** The children of this node. */ var children: [CBCNode] = [] /** The example you wish to debug as the initial view controller. If there are multiple examples with catalogIsDebug returning YES the debugLeaf will hold the example that has been iterated on last in the hierarchy tree. */ var debugLeaf: CBCNode? /** This NSDictionary holds all the metadata related to this CBCNode. If it is an example noe, a primary demo, related info, if presentable in Catalog, etc. */ var metadata: [String: Any]? /** Returns true if this is an example node. */ var isExample: Bool { return exampleClass != nil } /** Returns YES if this the primary demo for this component. Can only return true if isExample also returns YES. */ var isPrimaryDemo: Bool { guard let v = metadata?[CBCIsPrimaryDemo] as? Bool else { return false } return v } /** Returns YES if this is a presentable example. */ var isPresentable: Bool { guard let v = metadata?[CBCIsPresentable] as? Bool else { return false } return v } /** Returns String representation of exampleViewController class name if it exists */ var exampleViewControllerName: String? { assert(exampleClass != nil, "This node has no associated example.") return exampleClass?.description() } /** Returns an instance of a UIViewController for presentation purposes. Check that isExample returns YES before invoking. */ var createExampleViewController: UIViewController { assert(exampleClass != nil, "This node has no associated example.") return CBCViewControllerFromClass(exampleClass!, metadata!) } /** Returns a description of the example. Check that isExample returns YES before invoking. */ var exampleDescription: String? { guard let description = metadata?[CBCDescription] as? String else { return nil } return description } /** Returns a link to related information for the example. */ var exampleRelatedInfo: URL? { guard let relatedInfo = metadata?[CBCRelatedInfo] as? URL else { return nil } return relatedInfo } fileprivate var map: [String: Any] = [:] fileprivate var exampleClass: UIViewController.Type? init(title: String) { self.title = title CBCFixViewDebuggingIfNeeded() } fileprivate func add(_ child: CBCNode) { map[child.title] = child children.append(child) } fileprivate func finalizeNode() { children = children.sorted(by: { $0.title == $1.title }) } } public class CBCNodeListViewController: UIViewController { /** Initializes a CBCNodeViewController instance with a non-example node. */ init(node: CBCNode) { super.init(nibName: nil, bundle: nil) self.node = node title = node.title } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.bounds, style: .grouped) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") return tableView }() /** The node that this view controller must represent. */ private(set) var node: CBCNode! public override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let selectedRow = tableView.indexPathForSelectedRow else { return } transitionCoordinator?.animate(alongsideTransition: { context in self.tableView.deselectRow(at: selectedRow, animated: true) }, completion: { context in if context.isCancelled { self.tableView.selectRow(at: selectedRow, animated: false, scrollPosition: .none) } }) } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tableView.flashScrollIndicators() } } extension CBCNodeListViewController: UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return node.children.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = node.children[indexPath.row].title cell.accessoryType = .disclosureIndicator return cell; } } extension CBCNodeListViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let node = self.node.children[indexPath.row] var viewController: UIViewController? = CBCNodeListViewController(node: node) if node.isExample { viewController = node.createExampleViewController } show(viewController!, sender: nil) } } func CBCAddNodeFromBreadCrumbs(_ tree: CBCNode, _ breadCrumbs: [String], _ aClass: UIViewController.Type, _ metadata: [String: Any]) { // Walk down the navigation tree one breadcrumb at a time, creating nodes along the way. var node = tree for (ix, title) in breadCrumbs.enumerated() { let isLastCrumb = ix == breadCrumbs.count - 1 // Don't walk the last crumb if let n = node.map[title] as? CBCNode, !isLastCrumb { node = n continue } let child = CBCNode(title: title) node.add(child) child.metadata = metadata if child.metadata?[CBCIsPrimaryDemo] as? Bool ?? false { node.metadata = child.metadata } if child.metadata?[CBCIsDebug] as? Bool ?? false { tree.debugLeaf = child } node = child } node.exampleClass = aClass } func CBCCreateTreeWithOnlyPresentable(_ onlyPresentable: Bool) -> CBCNode { let allClasses = CBCGetAllCompatibleClasses() let filteredClasses = allClasses.filter { objc in let metadata = CBCCatalogMetadataFromClass(objc) let breadcrumbs = metadata[CBCBreadcrumbs] var validObject = breadcrumbs != nil && (breadcrumbs as? [Any] != nil) if onlyPresentable { validObject = validObject && (metadata[CBCIsPresentable] as? Bool ?? false) } return validObject } let tree = CBCNode(title: "Root") for aClass in filteredClasses { // Each example view controller defines its own breadcrumbs (metadata[CBCBreadcrumbs]). let metadata = CBCCatalogMetadataFromClass(aClass) let breadCrumbs = metadata[CBCBreadcrumbs] as? [Any] if (breadCrumbs?.first as? String) != nil { CBCAddNodeFromBreadCrumbs(tree, breadCrumbs as! [String], aClass, metadata); } else if (breadCrumbs?.first as? [String]) != nil { for parallelBreadCrumb in breadCrumbs! { CBCAddNodeFromBreadCrumbs(tree, parallelBreadCrumb as! [String], aClass, metadata) } } } // Perform final post-processing on the nodes. var queue = [tree] while queue.count > 0 { let node = queue.first queue.remove(at: 0) queue.append(contentsOf: node!.children) node?.finalizeNode() } return tree } func CBCCreateNavigationTree() -> CBCNode { return CBCCreateTreeWithOnlyPresentable(false) } func CBCCreatePresentableNavigationTree() -> CBCNode { return CBCCreateTreeWithOnlyPresentable(true) }
4ede31fe6a1a9a23056f23a816e90fe7
30.74359
134
0.650358
false
false
false
false
mperovic/ISO8601Formatter
refs/heads/master
ISO8601/ISO8601.swift
mit
1
// // main.swift // ISO8601 // // Created by Miroslav Perovic on 6/23/15. // Copyright © 2015 Miroslav Perovic. All rights reserved. // import Foundation final class ISO8601Formatter: NSFormatter { enum ISO8601DateStyle: Int { case CalendarLongStyle // Default (YYYY-MM-DD) case CalendarShortStyle // (YYYYMMDD) case OrdinalLongStyle // (YYYY-DDD) case OrdinalShortStyle // (YYYYDDD) case WeekLongStyle // (YYYY-Www-D) case WeekShortStyle // (YYYYWwwD) } enum ISO8601TimeStyle: Int { case None case LongStyle // Default (hh:mm:ss) case ShortStyle // (hhmmss) } enum ISO8601TimeZoneStyle: Int { case None case UTC // Default (Z) case LongStyle // (±hh:mm) case ShortStyle // (±hhmm) } enum ISO8601FractionSeparator: Int { case Comma // Default (,) case Dot // (.) } var dateStyle: ISO8601DateStyle var timeStyle: ISO8601TimeStyle var fractionSeparator: ISO8601FractionSeparator var timeZoneStyle: ISO8601TimeZoneStyle var fractionDigits: Int let days365 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] let days366 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] convenience override init() { self.init( dateStyle: .CalendarLongStyle, timeStyle: .LongStyle, fractionSeparator: .Comma, fractionDigits: 6, timeZoneStyle: .UTC ) } init(dateStyle: ISO8601DateStyle, timeStyle: ISO8601TimeStyle, fractionSeparator: ISO8601FractionSeparator, fractionDigits: Int, timeZoneStyle: ISO8601TimeZoneStyle) { self.dateStyle = dateStyle self.timeStyle = timeStyle self.fractionSeparator = fractionSeparator self.fractionDigits = fractionDigits self.timeZoneStyle = timeZoneStyle super.init() } required convenience init?(coder aDecoder: NSCoder) { self.init( dateStyle: .CalendarLongStyle, timeStyle: .LongStyle, fractionSeparator: .Comma, fractionDigits: 6, timeZoneStyle: .UTC ) } func stringFromDate(date: NSDate) -> String? { let calendar = NSCalendar.currentCalendar() if timeZoneStyle == .UTC { calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0) } let dateComponents = calendar.components( [.Year, .Month, .Day, .WeekOfYear, .Hour, .Minute, .Second, .Weekday, .WeekdayOrdinal, .WeekOfYear, .YearForWeekOfYear, .TimeZone], fromDate: date ) var string: String if dateComponents.year < 0 || dateComponents.year > 9999 { return nil } string = String(format: "%04li", dateComponents.year) if dateStyle == .WeekLongStyle || dateStyle == .WeekShortStyle { // For weekOfYear calculation see more at: https://en.wikipedia.org/wiki/ISO_8601#Week_dates if date.weekOfYear() == 53 { string = String(format: "%04li", dateComponents.year - 1) } } switch dateStyle { case .CalendarLongStyle: string = string + String(format: "-%02i-%02i", dateComponents.month, dateComponents.day) case .CalendarShortStyle: string = string + String(format: "%02i%02i", dateComponents.month, dateComponents.day) case .OrdinalLongStyle: string = string + String(format: "-%03i", date.dayOfYear()) case .OrdinalShortStyle: string = string + String(format: "%03i", date.dayOfYear()) case .WeekLongStyle: if dateComponents.weekday > 1 { string = string + String(format: "-W%02i-%01i", date.weekOfYear(), dateComponents.weekday - 1) } else { string = string + String(format: "-W%02i-%01i", date.weekOfYear(), 7) } case .WeekShortStyle: if dateComponents.weekday > 1 { string = string + String(format: "W%02i%01i", dateComponents.weekOfYear, dateComponents.weekday - 1) } else { string = string + String(format: "W%02i%01i", dateComponents.weekOfYear, 7) } } let timeString: String switch timeStyle { case .LongStyle: timeString = String(format: "T%02i:%02i:%02i", dateComponents.hour, dateComponents.minute, dateComponents.second) case .ShortStyle: timeString = String(format: "T%02i:%02i:%02i", dateComponents.hour, dateComponents.minute, dateComponents.second) case .None: return string } string = string + timeString if let timeZone = dateComponents.timeZone { let timeZoneString: String switch timeZoneStyle { case .UTC: timeZoneString = "Z" case .LongStyle, .ShortStyle: let hoursOffset = timeZone.secondsFromGMT / 3600 let secondsOffset = 0 let sign = hoursOffset >= 0 ? "+" : "-" if timeZoneStyle == .LongStyle { timeZoneString = String(format: "%@%02i:%02i", sign, hoursOffset, secondsOffset) } else { timeZoneString = String(format: "%@%02i%02i", sign, hoursOffset, secondsOffset) } case .None: return string } string = string + timeZoneString } return string } func dateFromString(string: String) -> NSDate? { let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! gregorian.firstWeekday = 2 // Monday let str = self.convertBasicToExtended(string) let scanner = NSScanner(string: str) scanner.charactersToBeSkipped = nil let dateComponents = NSDateComponents() // Year var year = 0 guard scanner.scanInteger(&year) else { return nil } guard year >= 0 && year <= 9999 else { return nil } dateComponents.year = year // Month or Week guard scanner.scanString("-", intoString: nil) else { return gregorian.dateFromComponents(dateComponents) } var month = 0 var ordinalDay = 0 switch dateStyle { case .CalendarLongStyle, .CalendarShortStyle: guard scanner.scanInteger(&month) else { return gregorian.dateFromComponents(dateComponents) } dateComponents.month = month case .OrdinalLongStyle, .OrdinalShortStyle: guard scanner.scanInteger(&ordinalDay) else { return gregorian.dateFromComponents(dateComponents) } let daysArray: [Int] if ((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0 { daysArray = days366 } else { daysArray = days365 } var theMonth = 0 for startDay in daysArray { theMonth++ if startDay > ordinalDay { month = theMonth - 1 break } } dateComponents.month = month case .WeekLongStyle, .WeekShortStyle: guard scanner.scanString("W", intoString: nil) else { return gregorian.dateFromComponents(dateComponents) } var week = 0 guard scanner.scanInteger(&week) else { return gregorian.dateFromComponents(dateComponents) } if week < 0 || week > 53 { return gregorian.dateFromComponents(dateComponents) } dateComponents.weekOfYear = week } // Day or DayOfWeek var day = 0 switch dateStyle { case .CalendarLongStyle, .CalendarShortStyle: guard scanner.scanString("-", intoString: nil) else { return gregorian.dateFromComponents(dateComponents) } guard scanner.scanInteger(&day) else { return gregorian.dateFromComponents(dateComponents) } dateComponents.day = day case .OrdinalLongStyle, .OrdinalShortStyle: let daysArray: [Int] if ((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0 { daysArray = days366 } else { daysArray = days365 } var theDay = 0 var previousStartDay = 0 for startDay in daysArray { if startDay > ordinalDay { theDay = ordinalDay - previousStartDay break } previousStartDay = startDay } dateComponents.day = theDay case .WeekLongStyle, .WeekShortStyle: guard scanner.scanString("-", intoString: nil) else { return gregorian.dateFromComponents(dateComponents) } guard scanner.scanInteger(&day) else { return gregorian.dateFromComponents(dateComponents) } if day < 0 || day > 7 { return gregorian.dateFromComponents(dateComponents) } else { dateComponents.weekday = day } } // Time guard scanner.scanCharactersFromSet(NSCharacterSet(charactersInString: "T"), intoString: nil) else { return gregorian.dateFromComponents(dateComponents) } // Hour var hour = 0 guard scanner.scanInteger(&hour) else { return gregorian.dateFromComponents(dateComponents) } if timeStyle != .None { if hour < 0 || hour > 23 { return gregorian.dateFromComponents(dateComponents) } else { dateComponents.hour = hour } } // Minute guard scanner.scanString(":", intoString: nil) else { return gregorian.dateFromComponents(dateComponents) } var minute = 0 guard scanner.scanInteger(&minute) else { return gregorian.dateFromComponents(dateComponents) } if timeStyle != .None { if minute < 0 || minute > 59 { return gregorian.dateFromComponents(dateComponents) } else { dateComponents.minute = minute } } // Second var scannerLocation = scanner.scanLocation if scanner.scanString(":", intoString: nil) { var second = 0 guard scanner.scanInteger(&second) else { return gregorian.dateFromComponents(dateComponents) } if timeStyle != .None { if second < 0 || second > 59 { return gregorian.dateFromComponents(dateComponents) } else { dateComponents.second = second } } } else { scanner.scanLocation = scannerLocation } // Zulu scannerLocation = scanner.scanLocation scanner.scanUpToString("Z", intoString: nil) if scanner.scanString("Z", intoString: nil) { dateComponents.timeZone = NSTimeZone(forSecondsFromGMT: 0) return gregorian.dateFromComponents(dateComponents) } // Move back to the end of time scanner.scanLocation = scannerLocation // Look for offset let signs = NSCharacterSet(charactersInString: "+-") scanner.scanUpToCharactersFromSet(signs, intoString: nil) var sign: NSString? guard scanner.scanCharactersFromSet(signs, intoString: &sign) else { return gregorian.dateFromComponents(dateComponents) } // Offset hour var timeZoneOffset = 0 var timeZoneOffsetHour = 0 var timeZoneOffsetMinute = 0 guard scanner.scanInteger(&timeZoneOffsetHour) else { return gregorian.dateFromComponents(dateComponents) } // Check for colon let colonExists = scanner.scanString(":", intoString: nil) if !colonExists && timeZoneOffsetHour > 14 { timeZoneOffsetMinute = timeZoneOffsetHour % 100 timeZoneOffsetHour = Int(floor(Double(timeZoneOffsetHour) / 100.0)) } else { scanner.scanInteger(&timeZoneOffsetMinute) } timeZoneOffset = (timeZoneOffsetHour * 60 * 60) + (timeZoneOffsetMinute * 60) dateComponents.timeZone = NSTimeZone(forSecondsFromGMT: timeZoneOffset * (sign == "-" ? -1 : 1)) return gregorian.dateFromComponents(dateComponents) } // Private methods private func checkAndUpdateTimeZone(string: NSMutableString, insertAtIndex index: Int) -> NSMutableString { if self.timeZoneStyle == .ShortStyle { string.insertString(":", atIndex: index) } return string } private func convertBasicToExtended(string: String) -> String { func checkAndUpdateTimeStyle(var string: NSMutableString, insertAtIndex index: Int) -> NSMutableString { if (self.timeStyle == .LongStyle) { string = self.checkAndUpdateTimeZone(string, insertAtIndex: index + 9) } else if (self.timeStyle == .ShortStyle) { string = self.checkAndUpdateTimeZone(string, insertAtIndex: index + 7) string.insertString(":", atIndex: index + 2) string.insertString(":", atIndex: index) } return string } var str: NSMutableString = NSMutableString(string: string) switch self.dateStyle { case .CalendarLongStyle: str = checkAndUpdateTimeStyle(str, insertAtIndex: 13) case .CalendarShortStyle: str = checkAndUpdateTimeStyle(str, insertAtIndex: 11) str.insertString("-", atIndex: 6) str.insertString("-", atIndex: 4) case .OrdinalLongStyle: str = checkAndUpdateTimeStyle(str, insertAtIndex: 11) case .OrdinalShortStyle: str = checkAndUpdateTimeStyle(str, insertAtIndex: 10) str.insertString("-", atIndex: 4) case .WeekLongStyle: str = checkAndUpdateTimeStyle(str, insertAtIndex: 13) case .WeekShortStyle: str = checkAndUpdateTimeStyle(str, insertAtIndex: 11) str.insertString("-", atIndex: 7) str.insertString("-", atIndex: 4) } return String(str) } } extension NSDate { func isLeapYear() -> Bool { let dateComponents = NSCalendar.currentCalendar().components( [.Year, .Month, .Day, .WeekOfYear, .Hour, .Minute, .Second, .Weekday, .WeekdayOrdinal, .WeekOfYear, .TimeZone], fromDate: self ) return ((dateComponents.year % 4) == 0 && (dateComponents.year % 100) != 0) || (dateComponents.year % 400) == 0 ? true : false } func dayOfYear() -> Int { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "D" return Int(dateFormatter.stringFromDate(self))! } func weekOfYear() -> Int { let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! gregorian.firstWeekday = 2 // Monday gregorian.minimumDaysInFirstWeek = 4 let components = gregorian.components([.WeekOfYear, .YearForWeekOfYear], fromDate: self) let week = components.weekOfYear return week } }
29426891c5a91e1c5ad7a15cb590b734
28.015487
168
0.688577
false
false
false
false
apple/swift-nio-extras
refs/heads/main
Sources/NIOHTTPCompression/HTTPRequestDecompressor.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import CNIOExtrasZlib import NIOHTTP1 import NIOCore /// Channel hander to decompress incoming HTTP data. public final class NIOHTTPRequestDecompressor: ChannelDuplexHandler, RemovableChannelHandler { /// Expect to receive `HTTPServerRequestPart` from the network public typealias InboundIn = HTTPServerRequestPart /// Pass `HTTPServerRequestPart` to the next pipeline state in an inbound direction. public typealias InboundOut = HTTPServerRequestPart /// Pass through `HTTPServerResponsePart` outbound. public typealias OutboundIn = HTTPServerResponsePart /// Pass through `HTTPServerResponsePart` outbound. public typealias OutboundOut = HTTPServerResponsePart private struct Compression { let algorithm: NIOHTTPDecompression.CompressionAlgorithm let contentLength: Int } private var decompressor: NIOHTTPDecompression.Decompressor private var compression: Compression? private var decompressionComplete: Bool /// Initialise with limits. /// - Parameter limit: Limit to how much inflation can occur to protect against bad cases. public init(limit: NIOHTTPDecompression.DecompressionLimit) { self.decompressor = NIOHTTPDecompression.Decompressor(limit: limit) self.compression = nil self.decompressionComplete = false } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let request = self.unwrapInboundIn(data) switch request { case .head(let head): if let encoding = head.headers[canonicalForm: "Content-Encoding"].first?.lowercased(), let algorithm = NIOHTTPDecompression.CompressionAlgorithm(header: encoding), let length = head.headers[canonicalForm: "Content-Length"].first.flatMap({ Int($0) }) { do { try self.decompressor.initializeDecoder(encoding: algorithm) self.compression = Compression(algorithm: algorithm, contentLength: length) } catch let error { context.fireErrorCaught(error) return } } context.fireChannelRead(data) case .body(var part): guard let compression = self.compression else { context.fireChannelRead(data) return } while part.readableBytes > 0 && !self.decompressionComplete { do { var buffer = context.channel.allocator.buffer(capacity: 16384) let result = try self.decompressor.decompress(part: &part, buffer: &buffer, compressedLength: compression.contentLength) if result.complete { self.decompressionComplete = true } context.fireChannelRead(self.wrapInboundOut(.body(buffer))) } catch let error { context.fireErrorCaught(error) return } } if part.readableBytes > 0 { context.fireErrorCaught(NIOHTTPDecompression.ExtraDecompressionError.invalidTrailingData) } case .end: if self.compression != nil { let wasDecompressionComplete = self.decompressionComplete self.decompressor.deinitializeDecoder() self.compression = nil self.decompressionComplete = false if !wasDecompressionComplete { context.fireErrorCaught(NIOHTTPDecompression.ExtraDecompressionError.truncatedData) } } context.fireChannelRead(data) } } } #if swift(>=5.6) @available(*, unavailable) extension NIOHTTPRequestDecompressor: Sendable {} #endif
bce9871c2be3a240f67e7477ed515a1c
37.875
140
0.613918
false
false
false
false
younata/RSSClient
refs/heads/master
TethysKitSpecs/Models/NetworkPagedCollectionSpec.swift
mit
1
import Quick import Nimble import Result import CBGPromise import FutureHTTP @testable import TethysKit private enum SomeError: Error { case whatever } final class NetworkPagedCollectionSpec: QuickSpec { override func spec() { var subject: NetworkPagedCollection<String>! var httpClient: FakeHTTPClient! var pagesRequested: [String?] = [] var nextPageIndex: String? = nil beforeEach { pagesRequested = [] httpClient = FakeHTTPClient() subject = NetworkPagedCollection<String>( httpClient: httpClient, requestFactory: { (pageNumber: String?) -> URLRequest in pagesRequested.append(pageNumber) let number = pageNumber ?? "" return URLRequest(url: URL(string: "https://example.com/\(number)")!) }, dataParser: { (data: Data) throws -> ([String], String?) in guard let contents = String(data: data, encoding: .utf8) else { throw SomeError.whatever } return (contents.components(separatedBy: ","), nextPageIndex) } ) } it("immediately makes a request using the number given") { expect(httpClient.requests).to(haveCount(1)) expect(httpClient.requests.last).to(equal(URLRequest(url: URL(string: "https://example.com/")!))) expect(pagesRequested).to(equal([nil])) } func theCommonCollectionProperties(startIndex: NetworkPagedIndex, endIndex: NetworkPagedIndex, underestimatedCount: Int, line: UInt = #line) { describe("asking for common collection properties at this point") { it("startIndex") { expect(subject.startIndex, line: line).to(equal(startIndex)) } it("endIndex") { expect(subject.endIndex, line: line).to(equal(endIndex)) } it("underestimatedCount") { expect(subject.underestimatedCount, line: line).to(equal(underestimatedCount)) } } } theCommonCollectionProperties(startIndex: 0, endIndex: NetworkPagedIndex(actualIndex: 0, isIndefiniteEnd: true), underestimatedCount: 0) it("converts to anycollection without hanging") { expect(AnyCollection(subject)).toNot(beNil()) } describe("when the request succeeds with valid data") { beforeEach { nextPageIndex = "2" httpClient.requestPromises.last?.resolve(.success(HTTPResponse( body: "foo,bar,baz,qux".data(using: .utf8)!, status: .ok, mimeType: "Text/Plain", headers: [:] ))) } it("doesn't yet make another request") { expect(httpClient.requests).to(haveCount(1)) expect(httpClient.requests.last).to(equal(URLRequest(url: URL(string: "https://example.com/")!))) expect(pagesRequested).to(equal([nil])) } theCommonCollectionProperties(startIndex: 0, endIndex: NetworkPagedIndex(actualIndex: 4, isIndefiniteEnd: true), underestimatedCount: 4) it("converts to anycollection without hanging") { expect(AnyCollection(subject)).toNot(beNil()) } it("makes another request when you reach the 75% point on the iteration/access") { guard subject.underestimatedCount >= 3 else { fail("not enough items loaded yet") return } expect(subject[0]).to(equal("foo")) expect(httpClient.requests).to(haveCount(1)) expect(subject[1]).to(equal("bar")) expect(httpClient.requests).to(haveCount(1)) expect(subject[2]).to(equal("baz")) // the 75% point expect(httpClient.requests).to(haveCount(2)) expect(httpClient.requests.last).to(equal(URLRequest(url: URL(string: "https://example.com/2")!))) expect(pagesRequested).to(equal([nil, "2"])) } it("doesn't make multiple requests for the same data point") { guard subject.underestimatedCount >= 4 else { fail("not enough items loaded yet") return } expect(subject[3]).to(equal("qux")) expect(httpClient.requests).to(haveCount(2)) expect(subject[2]).to(equal("baz")) expect(httpClient.requests).to(haveCount(2)) } describe("if this next request succeeds with a next page") { beforeEach { nextPageIndex = "3" guard httpClient.requestCallCount == 1 else { return } _ = subject[3] httpClient.requestPromises.last?.resolve(.success(HTTPResponse( body: "a,b,c,d".data(using: .utf8)!, status: .ok, mimeType: "Text/Plain", headers: [:] ))) } it("doesn't yet request the third page") { expect(httpClient.requests).to(haveCount(2)) expect(pagesRequested).to(equal([nil, "2"])) } theCommonCollectionProperties(startIndex: 0, endIndex: NetworkPagedIndex(actualIndex: 8, isIndefiniteEnd: true), underestimatedCount: 8) it("converts to anycollection without hanging") { expect(AnyCollection(subject)).toNot(beNil()) } it("doesn't re-request data it already has") { _ = subject[2] expect(httpClient.requests).to(haveCount(2)) } it("makes another request when you reach the 75% point on the iteration/access for THIS requested data") { guard subject.underestimatedCount >= 7 else { fail("not enough items loaded yet") return } expect(subject[4]).to(equal("a")) expect(httpClient.requests).to(haveCount(2)) expect(subject[5]).to(equal("b")) expect(httpClient.requests).to(haveCount(2)) expect(subject[6]).to(equal("c")) // the 75% point (index 6, as opposed to index 5 for 75% of entire data set). expect(httpClient.requests).to(haveCount(3)) expect(httpClient.requests.last).to(equal(URLRequest(url: URL(string: "https://example.com/3")!))) expect(pagesRequested).to(equal([nil, "2", "3"])) } it("doesn't make multiple requests for the same data point") { guard subject.underestimatedCount >= 8 else { fail("not enough items loaded yet") return } expect(subject[7]).to(equal("d")) expect(httpClient.requests).to(haveCount(3)) expect(subject[6]).to(equal("c")) expect(httpClient.requests).to(haveCount(3)) } } describe("if this request succeeds with no next page") { beforeEach { nextPageIndex = nil guard httpClient.requestCallCount == 1 else { return } _ = subject[3] httpClient.requestPromises.last?.resolve(.success(HTTPResponse( body: "a,b,c,d".data(using: .utf8)!, status: .ok, mimeType: "Text/Plain", headers: [:] ))) } it("doesn't request the third data, even when the entire collection is iterated through") { expect(httpClient.requests).to(haveCount(2)) guard httpClient.requestCallCount == 2 else { fail("Expected to have made 2 requests") return } expect(pagesRequested).to(equal([nil, "2"])) expect(Array(subject)).to(equal(["foo", "bar", "baz", "qux", "a", "b", "c", "d"])) expect(httpClient.requests).to(haveCount(2)) expect(pagesRequested).to(equal([nil, "2"])) } theCommonCollectionProperties(startIndex: 0, endIndex: NetworkPagedIndex(actualIndex: 8, isIndefiniteEnd: false), underestimatedCount: 8) it("converts to anycollection without hanging") { expect(AnyCollection(subject)).to(haveCount(8)) expect(Array(AnyCollection(subject))).to(equal(["foo", "bar", "baz", "qux", "a", "b", "c", "d"])) } } } } }
79b57b7db9090e1494df27d5383d1bec
40.904545
153
0.515457
false
false
false
false
Chantalisima/Spirometry-app
refs/heads/master
EspiroGame/InstructionGameViewController.swift
apache-2.0
1
// // InstructionGameViewController.swift // EspiroGame // // Created by Chantal de Leste on 28/4/17. // Copyright © 2017 Universidad de Sevilla. All rights reserved. // import UIKit import CoreBluetooth class InstructionGameViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var mainPeripheral: CBPeripheral? var mainView: MainViewController? @IBOutlet weak var tableView: UITableView! var number: [String] = ["1.","2.","3.","4.","5."] var instruccions: [String] = [" Select the correct resistance in the pep device","Place mouthpiece into your mouth","Inhale a large breath","Hold the breath for 3 or 4 second","Exhale for 3 or 4 seconds, keeping the spacecraft floating and keep the spacecraft sailing without touching the spikes "] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("InstruccionTableViewCell", owner: self, options: nil)?.first as! InstruccionTableViewCell cell.instruction.numberOfLines = 0 cell.number.text = number[indexPath.row] cell.instruction.text = instruccions[indexPath.row] return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "game"{ let trainningController: TrainningViewController = segue.destination as! TrainningViewController trainningController.mainPeripheral = self.mainPeripheral print("segue to test") if self.mainPeripheral != nil { mainPeripheral?.delegate = trainningController mainPeripheral?.discoverServices(nil) print("peripheral equal to test peripheral") } } } }
b7dcf850a551b4fbb359ec8ba6511301
32.319444
302
0.644018
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/TransitionsLibrary/TransitionsLibrary/Classes/PortalAnimationTransitioning.swift
mit
1
// // Copyright © 2016年 xiAo_Ju. All rights reserved. // class PortalAnimationTransitioning: ReversibleAnimationTransitioning { override func animateTransition(_ context: UIViewControllerContextTransitioning, fromVC: UIViewController, toVC: UIViewController, fromView: UIView, toView: UIView) { if reverse { executeReverseAnimation(context, fromVC: fromVC, toVC: toVC, fromView: fromView, toView: toView) } else { executeForwardsAnimation(context, fromVC: fromVC, toVC: toVC, fromView: fromView, toView: toView) } } let ZOOM_SCALE: CGFloat = 0.8 func executeForwardsAnimation(_ context: UIViewControllerContextTransitioning, fromVC: UIViewController, toVC: UIViewController, fromView: UIView, toView: UIView) { let containerView = context.containerView let toViewSnapshot = toView.resizableSnapshotView(from: toView.frame, afterScreenUpdates: true, withCapInsets: UIEdgeInsets.zero) let scale = CATransform3DIdentity toViewSnapshot!.layer.transform = CATransform3DScale(scale, ZOOM_SCALE, ZOOM_SCALE, 1) containerView.addSubview(toViewSnapshot!) containerView.sendSubviewToBack(toViewSnapshot!) let leftSnapshotRegion = CGRect(x: 0, y: 0, width: fromView.frame.width / 2, height: fromView.frame.height) let leftHandView = fromView.resizableSnapshotView(from: leftSnapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero) leftHandView!.frame = leftSnapshotRegion containerView.addSubview(leftHandView!) let rightSnapshotRegion = CGRect(x: fromView.frame.width / 2, y: 0, width: fromView.frame.width / 2, height: fromView.frame.height) let rightHandView = fromView.resizableSnapshotView(from: rightSnapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero) rightHandView!.frame = rightSnapshotRegion containerView.addSubview(rightHandView!) fromView.removeFromSuperview() let duration = transitionDuration(using: context) UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { let leftOffset = CGRect.offsetBy(leftHandView!.frame) leftHandView!.frame = leftOffset(-leftHandView!.frame.width, 0) let rightOffset = CGRect.offsetBy(rightHandView!.frame) rightHandView!.frame = rightOffset(rightHandView!.frame.width, 0) toViewSnapshot!.center = toView.center toViewSnapshot!.frame = toView.frame }) { (flag) in if context.transitionWasCancelled { containerView.addSubview(fromView) removeOtherViews(fromView) } else { containerView.addSubview(toView) removeOtherViews(toView) } context.completeTransition(!context.transitionWasCancelled) } } func executeReverseAnimation(_ context: UIViewControllerContextTransitioning, fromVC: UIViewController, toVC: UIViewController, fromView: UIView, toView: UIView) { let containerView = context.containerView containerView.addSubview(fromView) toView.frame = context.finalFrame(for: toVC) let offset = CGRect.offsetBy(toView.frame) toView.frame = offset(toView.frame.width, 0) containerView.addSubview(toView) let leftSnapshotRegion = CGRect(x: 0, y: 0, width: toView.frame.width / 2, height: toView.frame.height) let leftHandView = toView.resizableSnapshotView(from: leftSnapshotRegion, afterScreenUpdates: true, withCapInsets: UIEdgeInsets.zero) leftHandView!.frame = leftSnapshotRegion let leftOffset = CGRect.offsetBy(leftHandView!.frame) leftHandView!.frame = leftOffset(-leftHandView!.frame.width, 0) containerView.addSubview(leftHandView!) let rightSnapshotRegion = CGRect(x: toView.frame.width / 2, y: 0, width: toView.frame.width / 2, height: toView.frame.height) let rightHandView = toView.resizableSnapshotView(from: rightSnapshotRegion, afterScreenUpdates: true, withCapInsets: UIEdgeInsets.zero) rightHandView!.frame = rightSnapshotRegion let rightOffset = CGRect.offsetBy(rightHandView!.frame) rightHandView!.frame = rightOffset(rightHandView!.frame.width, 0) containerView.addSubview(rightHandView!) let duration = transitionDuration(using: context) UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { leftHandView!.frame = leftOffset(leftHandView!.frame.width, 0) rightHandView!.frame = rightOffset(-rightHandView!.frame.width, 0) let scale = CATransform3DIdentity fromView.layer.transform = CATransform3DScale(scale, self.ZOOM_SCALE, self.ZOOM_SCALE, 1) }) { (flag) in if context.transitionWasCancelled { removeOtherViews(fromView) } else { removeOtherViews(toView) toView.frame = (containerView.bounds) } context.completeTransition(!context.transitionWasCancelled) } } } func removeOtherViews(_ viewToKeep: UIView) { if let containerView = viewToKeep.superview { for view in containerView.subviews { if view != viewToKeep { view.removeFromSuperview() } } } }
1f93a47fcaedeba064ac17557db54ac2
51.754717
170
0.670601
false
false
false
false
cpmpercussion/microjam
refs/heads/develop
chirpey/ChirpRecorder.swift
mit
1
// // Recorder.swift // microjam // // Created by Henrik Brustad on 21/08/2017. // Copyright © 2017 Charles Martin. All rights reserved. // import UIKit /// A ChirpPlayerController with the ability to record a new ChirpPerformance class ChirpRecorder: ChirpPlayer { /// The ChirpRecorder's ChirpRecordingView var recordingView: ChirpRecordingView /// Storage for whether the recorder is enabled or not, controls whether touches are stored and playback starts on touch. var recordingEnabled = false /// Storage of the present playback/recording state: playing, recording or idle var isRecording = false /// Tells us whether the recording has been added to the stack in the performance handler var recordingIsDone = false /// Description of the ChirpPlayer with it's first ChirpPerformance. override var description: String { guard let perfString = chirpViews.first?.performance?.description else { return "ChirpRecorder-NoPerformance" } return "ChirpRecorder-" + perfString } init(frame: CGRect) { recordingView = ChirpRecordingView(frame: frame) recordingView.clipsToBounds = true recordingView.contentMode = .scaleAspectFill super.init() } /// Convenience initialiser for creating a ChirpRecorder with the same performances as a given ChirpPlayer convenience init(frame: CGRect, player: ChirpPlayer) { self.init(frame: frame) chirpViews = player.chirpViews } /// Convenience initialiser for creating a ChirpRecorder with an array of backing ChirpPerformances convenience init(withArrayOfPerformances performanceArray: [ChirpPerformance]) { let dummyFrame = CGRect.zero self.init(frame: dummyFrame) for perf in performanceArray { let chirp = ChirpView(with: dummyFrame, andPerformance: perf) chirpViews.append(chirp) } } /// Starts a new recording if recordingEnabled, time is controlled by the superclass's progressTimer. func record() -> Bool { if recordingEnabled { if !isRecording { print("ChirpRecorder: Starting recording") isRecording = true recordingView.recording = true // Starting progresstimer and playback of performances if any play() return true } } return false } /// Override the superclass's play function to only playback once a recording is finished. override func play() { super.play() if recordingIsDone { play(chirp: recordingView) } } /// Override superclass's stop function to control recording state. override func stop() { super.stop() if isRecording { isRecording = false if self.recordingView.saveRecording() != nil { self.recordingIsDone = true self.recordingEnabled = false } } if recordingIsDone, let performance = recordingView.performance { // print("ChirpRecorder: Adding performance image as my display image: \(performance.title())") self.recordingView.setImage() // clear the animation layer and reset the saved image } } /// closeEachChirpView from the list. func clearChirpViews() { for chirp in chirpViews { chirp.closeGracefully() } chirpViews = [ChirpView]() // set to nothing. } }
b019563d32b70b95361842983ae6ee79
35.510204
125
0.64114
false
false
false
false
bixubot/AcquainTest
refs/heads/master
ChatRoom/ChatRoom/MessageController.swift
mit
1
// // MessageController.swift // ChatRoom // // Contains all the messages sent/received for current user from other users. Designated to be the root view when app is initiated. // // Created by Binwei Xu on 3/16/17. // Copyright © 2017 Binwei Xu. All rights reserved. // import UIKit import Firebase class MessageController: UITableViewController { let cellId = "cellId" override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout)) let newmessageimage = UIImage(named: "new_message_icon") navigationItem.rightBarButtonItem = UIBarButtonItem(image: newmessageimage, style: .plain, target: self, action: #selector(handleNewMessage)) // self.navigationController?.navigationBar.barTintColor = UIColor.black; // if user is not logged in, show the login page checkIfUserIsLoggedIn() tableView.register(UserCell.self, forCellReuseIdentifier: cellId) } // to store all messages and group by users in a dictionary var messages = [Message]() var messagesDictionary = [String: Message]() // acquire messages and present them func observeUserMessages(){ guard let uid = FIRAuth.auth()?.currentUser?.uid else { return } //acquire the list of messages related to the current user let ref = FIRDatabase.database().reference().child("user-messages").child(uid) ref.observe(.childAdded, with: { (snapshot) in let userId = snapshot.key FIRDatabase.database().reference().child("user-messages").child(uid).child(userId).observe(.childAdded, with: { (snapshot) in let messageId = snapshot.key self.fetchMessageWithMessageId(messageId: messageId) }, withCancel: nil) }, withCancel: nil) } private func fetchMessageWithMessageId(messageId: String){ let messageReference = FIRDatabase.database().reference().child("messages").child(messageId) // get the actual message from the list messageReference.observeSingleEvent(of: .value, with: { (snapshot2) in if let dictionary = snapshot2.value as? [String: AnyObject]{ let message = Message() message.setValuesForKeys(dictionary) if let chatPartnerId = message.chatPartnerId() { self.messagesDictionary[chatPartnerId] = message } self.attemptReloadTable() //so we don't constantly reload data which causes gliches } }, withCancel: nil) } private func attemptReloadTable() { self.timer?.invalidate() self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.handleReloadTable), userInfo: nil, repeats: false) } var timer: Timer? func handleReloadTable() { self.messages = Array(self.messagesDictionary.values) self.messages.sort(by: { (m1, m2) -> Bool in return (m1.timestamp?.intValue)! > (m2.timestamp?.intValue)! }) //this will crash because of background thread, so lets call this on dispatch_async main thread //dispatch_async(dispatch_get_main_queue()) DispatchQueue.main.async { self.tableView.reloadData() } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messagesDictionary.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell let message = messages[indexPath.row] cell.message = message return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 66 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let message = messages[indexPath.row] guard let chatPartnerId = message.chatPartnerId() else { return // seek a better to catch error or missing data } let ref = FIRDatabase.database().reference().child("users").child(chatPartnerId) ref.observeSingleEvent(of: .value, with: { (snapshot) in guard let dictionary = snapshot.value as? [String: AnyObject] else { return // seek a better to catch error or missing data } let user = User() user.id = chatPartnerId user.setValuesForKeys(dictionary) self.showChatControllerForUser(user: user) }, withCancel: nil) } override func viewWillAppear(_ animated: Bool) { checkIfUserIsLoggedIn() } // allow user to send a new message to another user func handleNewMessage() { let newMessageController = NewMessageController() //this allow user to click another user in the NewMessageController by creating a reference with var messagesController so that it will come back to current MessageController. newMessageController.messagesController = self // allows newMessageController to have a navigation bar at the top let navController = UINavigationController(rootViewController: newMessageController) present(navController, animated: true, completion: nil) } // helper method to check if a user is logged in func checkIfUserIsLoggedIn(){ if FIRAuth.auth()?.currentUser?.uid == nil{ perform(#selector(handleLogout), with: nil, afterDelay: 0) } else { fetchUserAndSetupNavBarTitle() } } // fetch info of current user to setup the nav bar func fetchUserAndSetupNavBarTitle() { guard let uid = FIRAuth.auth()?.currentUser?.uid else { // for some reason uid = nil return } FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: Any] { let user = User() user.setValuesForKeys(dictionary) self.setupNavBarWithUser(user: user) } }, withCancel: nil) } // setup the layout of components in tab bar and present the view func setupNavBarWithUser(user: User) { messages.removeAll() messagesDictionary.removeAll() tableView.reloadData() observeUserMessages() let titleView = UIView() titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40) titleView.backgroundColor = UIColor.clear let containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false titleView.addSubview(containerView) containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true let profileImageView = UIImageView() profileImageView.translatesAutoresizingMaskIntoConstraints = false profileImageView.contentMode = .scaleAspectFill profileImageView.layer.cornerRadius = 20 profileImageView.clipsToBounds = true if let profileImageUrl = user.profileImageUrl { profileImageView.loadImageUsingCacheWithUrlString(urlString: profileImageUrl) } containerView.addSubview(profileImageView) //ios 9 constrant anchors: need x,y,width,height anchors profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true let nameLabel = UILabel() titleView.addSubview(nameLabel) containerView.addSubview(nameLabel) nameLabel.text = user.name nameLabel.translatesAutoresizingMaskIntoConstraints = false nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true nameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true self.navigationItem.titleView = titleView } // present the chat log view func showChatControllerForUser(user: User){ let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout()) chatLogController.user = user navigationController?.pushViewController(chatLogController, animated: true) } // helper that handle the logout func handleLogout() { // when logout bottom is clicked, sign out the current account do { try FIRAuth.auth()?.signOut() } catch let logoutError{ print(logoutError) } let loginController = LoginController() loginController.messagesController = self //allow nav bar title update present(loginController, animated:true, completion: nil) } }
208f380c6868e7ae21a5d629379bf46f
39.532787
183
0.649949
false
false
false
false
shial4/VaporGCM
refs/heads/master
Sources/VaporGCM/DeviceGroup.swift
mit
1
// // DeviceGroup.swift // VaporGCM // // Created by Shial on 12/04/2017. // // import JSON ///Request operation type public enum DeviceGroupOperation: String { ///Create a device group case create = "create" ///Add devices from an existing group case add = "add" ///Remove devices from an existing group. ///If you remove all existing registration tokens from a device group, FCM deletes the device group. case remove = "remove" } ///With device group messaging, you can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user. All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group. public struct DeviceGroup { ///Operation parameter for the request public let operation: DeviceGroupOperation ///name or identifier public let notificationKeyName: String ///deviceToken Device token or topic to which message will be send public let registrationIds: [String] /** Create DeviceGroup instance - parameter operation: Operation parameter for the request - parameter name: Name or identifier - parameter registrationIds: Device token or topic to which message will be send */ public init(operation: DeviceGroupOperation, name: String, registrationIds: [String]) { self.operation = operation self.notificationKeyName = name self.registrationIds = registrationIds } public func makeJSON() throws -> JSON { let json = try JSON([ "operation": operation.rawValue.makeNode(in: nil), "notification_key_name": notificationKeyName.makeNode(in: nil), "registration_ids": try registrationIds.makeNode(in: nil) ].makeNode(in: nil)) return json } }
c85986bcce5de8962db79d740b774654
36.346154
355
0.69207
false
false
false
false
legendecas/Rocket.Chat.iOS
refs/heads/sdk
Test.Shared/WebSocketMock+CommonResponse.swift
mit
1
// // WebSocketMock+CommonResponse.swift // Rocket.Chat // // Created by Lucas Woo on 8/13/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON enum WebSocketMockCommonResponse { case connect case login case livechatInitiate case livechatRegisterGuest case livechatSendMessage case livechatSendOfflineMessage } extension WebSocketMock { // swiftlint:disable function_body_length // swiftlint:disable cyclomatic_complexity func use(_ commonResponse: WebSocketMockCommonResponse) { switch commonResponse { case .connect: use { json, send in guard json["msg"].stringValue == "connect" else { return } send(JSON(object: ["msg": "connected"])) } case .login: use { json, send in guard json["msg"].stringValue == "method" else { return } guard json["method"] == "login" else { return } // LiveChat Login if json["params"][0]["resume"].stringValue == "YadDPc_6IfL7YJuySZ3DkOx-LSdbCtUcsypMdHVgQhx" { send(JSON(object: [ "fields": [ "profile": [ "guest": true, "token": "6GQSl9lVbgaZjTVyJRbN" ], "username": "guest-1984" ], "collection": "users", "id": "QtiyRkneTHcWYZefn", "msg": "added" ])) send(JSON(object: [ "id": json["id"].stringValue, "result": [ "id": "QtiyRkneTHcWYZefn", "token": "YadDPc_6IfL7YJuySZ3DkOx-LSdbCtUcsypMdHVgQhx", "tokenExpires": [ "$date": 2510411097067 ] ], "msg": "result" ])) } } case .livechatInitiate: use { json, send in guard json["msg"].stringValue == "method" else { return } guard json["method"] == "livechat:getInitialData" else { return } let data: [String: Any] = [ "id": json["id"].stringValue, "result": [ "transcript": false, "registrationForm": true, "offlineTitle": "Leave a message (Changed)", "triggers": [], "displayOfflineForm": true, "offlineSuccessMessage": "", "departments": [ [ "_id": "sGDPYaB9i47CNRLNu", "numAgents": 1, "enabled": true, "showOnRegistration": true, "_updatedAt": [ "$date": 1500709708181 ], "description": "department description", "name": "1depart" ], [ "_id": "qPYPJuL6ZPTrRrzTN", "numAgents": 1, "enabled": true, "showOnRegistration": true, "_updatedAt": [ "$date": 1501163003597 ], "description": "tech support", "name": "2depart" ] ], "offlineMessage": "localhost: We are not online right now. Please leave us a message:", "title": "Rocket.Local", "color": "#C1272D", "room": nil, "offlineUnavailableMessage": "Not available offline form", "enabled": true, "offlineColor": "#666666", "videoCall": false, "language": "", "transcriptMessage": "Would you like a copy of this chat emailed?", "online": true, "allowSwitchingDepartments": true ] as [String: Any?], "msg": "result" ] send(JSON(object: data)) } case .livechatRegisterGuest: use { json, send in guard json["msg"].stringValue == "method" else { return } guard json["method"] == "livechat:registerGuest" else { return } let data: [String: Any] = [ "id": json["id"].stringValue, "result": [ "token": "YadDPc_6IfL7YJuySZ3DkOx-LSdbCtUcsypMdHVgQhx", "userId": "QtiyRkneTHcWYZefn" ], "msg": "result" ] send(JSON(object: data)) } case .livechatSendMessage: use { json, send in guard json["msg"].stringValue == "method" else { return } guard json["method"] == "livechat:sendMessageLivechat" else { return } send(JSON(object: [ "id": json["id"].stringValue, "result": [ "showConnecting": false, "rid": "9dNp4a1a8IpqpNqedTI5", "_id": "FF99C7A4-BBF9-4798-A03B-802FB31955B2", "channels": [], "token": "6GQSl9lVbgaZjTVyJRbN", "alias": "Test", "mentions": [], "u": [ "_id": "QtiyRkneTHcWYZefn", "username": "guest-1984", "name": "Test" ], "ts": [ "$date": 1502635097560 ], "msg": "test", "_updatedAt": [ "$date": 1502635097567 ], "newRoom": true ], "msg": "result" ])) } case .livechatSendOfflineMessage: use { json, send in guard json["msg"].stringValue == "method" else { return } guard json["method"] == "livechat:sendOfflineMessage" else { return } send(JSON(object: [ "id": json["id"].stringValue, "msg": "result" ])) } } } // swiftlint:enable cyclomatic_complexity // swiftlint:enable function_body_length }
b2180764a7993d5af6fec7cbf74bc0e1
40.297143
111
0.381071
false
false
false
false
alisidd/iOS-WeJ
refs/heads/master
WeJ/Play Tracks/BackgroundTask.swift
gpl-3.0
1
// // BackgroundTask.swift // // Created by Yaro on 8/27/16. // Copyright © 2016 Yaro. All rights reserved. // import AVFoundation class BackgroundTask { static var player = AVAudioPlayer() static var isPlaying = false static func startBackgroundTask() { DispatchQueue.global(qos: .userInitiated).async { if !isPlaying { NotificationCenter.default.addObserver(self, selector: #selector(interuptedAudio), name: NSNotification.Name.AVAudioSessionInterruption, object: AVAudioSession.sharedInstance()) playAudio() isPlaying = true } } } static func stopBackgroundTask() { DispatchQueue.global(qos: .userInitiated).async { if isPlaying { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVAudioSessionInterruption, object: nil) player.stop() isPlaying = false } } } @objc static func interuptedAudio(_ notification: Notification) { if notification.name == NSNotification.Name.AVAudioSessionInterruption && notification.userInfo != nil { var info = notification.userInfo! var intValue = 0 (info[AVAudioSessionInterruptionTypeKey]! as AnyObject).getValue(&intValue) if intValue == 1 { playAudio() } } } private static func playAudio() { do { let bundle = Bundle.main.path(forResource: "BlankAudio", ofType: "wav") let alertSound = URL(fileURLWithPath: bundle!) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers) try AVAudioSession.sharedInstance().setActive(true) try player = AVAudioPlayer(contentsOf: alertSound) player.numberOfLoops = -1 player.volume = 0.01 player.prepareToPlay() player.play() } catch { print(error) } } }
bf00965efaadf8803e4c3cb9369e4147
34.12069
193
0.614629
false
false
false
false
proxyco/RxBluetoothKit
refs/heads/master
Source/BluetoothManager.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2016 Polidea // // 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 RxSwift import CoreBluetooth // swiftlint:disable line_length /** BluetoothManager is a class implementing ReactiveX API which wraps all Core Bluetooth Manager's functions allowing to discover, connect to remote peripheral devices and more. It's using thin layer behind `RxCentralManagerType` protocol which is implemented by `RxCBCentralManager` and should not be used directly by the user of a RxBluetoothKit library. You can start using this class by discovering available services of nearby peripherals. Before calling any public `BluetoothManager`'s functions you should make sure that Bluetooth is turned on and powered on. It can be done by calling and observing returned value of `monitorState()` and then chaining it with `scanForPeripherals(_:options:)`: bluetoothManager.rx_state .filter { $0 == .PoweredOn } .take(1) .flatMap { manager.scanForPeripherals(nil) } As a result you will receive `ScannedPeripheral` which contains `Peripheral` object, `AdvertisementData` and peripheral's RSSI registered during discovery. You can then `connectToPeripheral(_:options:)` and do other operations. - seealso: `Peripheral` */ public class BluetoothManager { /// Implementation of Central Manager private let centralManager: RxCentralManagerType /// Queue on which all observables are serialised if needed private let subscriptionQueue: SerializedSubscriptionQueue /// Lock which should be used before accessing any internal structures private let lock = NSLock() /// Queue of scan operations which are waiting for an execution private var scanQueue: [ScanOperation] = [] // MARK: Initialization /** Creates new `BluetoothManager` instance with specified implementation of `RxCentralManagerType` protocol which will be used by this class. Most of a time `RxCBCentralManager` should be chosen by the user. - parameter centralManager: Implementation of `RxCentralManagerType` protocol used by this class. - parameter queueScheduler: Scheduler on which all serialised operations are executed (such as scans). By default main thread is used. */ init(centralManager: RxCentralManagerType, queueScheduler: SchedulerType = ConcurrentMainScheduler.instance) { self.centralManager = centralManager self.subscriptionQueue = SerializedSubscriptionQueue(scheduler: queueScheduler) } /** Creates new `BluetoothManager` instance. By default all operations and events are executed and received on main thread. - warning: If you pass background queue to the method make sure to observe results on main thread for UI related code. - parameter queue: Queue on which bluetooth callbacks are received. By default main thread is used. - parameter options: An optional dictionary containing initialization options for a central manager. For more info about it please refer to [`Central Manager initialization options`](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/index.html) */ convenience public init(queue: dispatch_queue_t = dispatch_get_main_queue(), options: [String : AnyObject]? = nil) { self.init(centralManager: RxCBCentralManager(queue: queue), queueScheduler: ConcurrentDispatchQueueScheduler(queue: queue)) } // MARK: Scanning /** Scans for `Peripheral`s after subscription to returned observable. First parameter `serviceUUIDs` is an array of `Service` UUIDs which needs to be implemented by a peripheral to be discovered. If user don't want to filter any peripherals, `nil` can be used instead. Additionally dictionary of [`CBCentralManager` specific options](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/#//apple_ref/doc/constant_group/Peripheral_Scanning_Options) can be passed to allow further customisation. Scans by default are infinite streams of `ScannedPeripheral` structures which need to be stopped by the user. For example this can be done by limiting scanning to certain number of peripherals or time: bluetoothManager.scanForPeripherals(nil) .timeout(3.0, timeoutScheduler) .take(2) If different scan is currently in progress and peripherals needed by a user can be discovered by it, new scan is shared. Otherwise scan is queued on thread specified in `init(centralManager:queueScheduler:)` and will be executed when other scans finished with complete/error event or were unsubscribed. As a result you will receive `ScannedPeripheral` which contains `Peripheral` object, `AdvertisementData` and peripheral's RSSI registered during discovery. You can then `connectToPeripheral(_:options:)` and do other operations. - seealso: `Peripheral` - parameter serviceUUIDs: Services of peripherals to search for. Nil value will accept all peripherals. - parameter options: Optional scanning options. - returns: Infinite stream of scanned peripherals. */ public func scanForPeripherals(serviceUUIDs: [CBUUID]?, options: [String: AnyObject]? = nil) -> Observable<ScannedPeripheral> { return Observable.deferred { let observable: Observable<ScannedPeripheral> = { Void -> Observable<ScannedPeripheral> in // If it's possible use existing scan - take if from the queue self.lock.lock(); defer { self.lock.unlock() } if let elem = self.scanQueue.findElement({ $0.acceptUUIDs(serviceUUIDs) }) { guard serviceUUIDs != nil else { return elem.observable } // When binding to existing scan we need to make sure that services are // filtered properly return elem.observable.filter { scannedPeripheral in if let services = scannedPeripheral.advertisementData.serviceUUIDs { return Set(services).isSupersetOf(serviceUUIDs!) } return false } } let scanOperationBox = WeakBox<ScanOperation>() // Create new scan which will be processed in a queue let operation = Observable.create { (element: AnyObserver<ScannedPeripheral>) -> Disposable in // Observable which will emit next element, when peripheral is discovered. let disposable = self.centralManager.rx_didDiscoverPeripheral .map { (peripheral, advertisment, rssi) -> ScannedPeripheral in let peripheral = Peripheral(manager: self, peripheral: peripheral) let advertismentData = AdvertisementData(advertisementData: advertisment) return ScannedPeripheral(peripheral: peripheral, advertisementData: advertismentData, RSSI: rssi) } .subscribe(element) // Start scanning for devices self.centralManager.scanForPeripheralsWithServices(serviceUUIDs, options: options) return AnonymousDisposable { // When disposed, stop all scans, and remove scanning operation from queue self.centralManager.stopScan() disposable.dispose() do { self.lock.lock(); defer { self.lock.unlock() } if let index = self.scanQueue.indexOf({ $0 == scanOperationBox.value! }) { self.scanQueue.removeAtIndex(index) } } } } .queueSubscribeOn(self.subscriptionQueue) .publish() .refCount() let scanOperation = ScanOperation(UUIDs: serviceUUIDs, observable: operation) self.scanQueue.append(scanOperation) scanOperationBox.value = scanOperation return operation }() // Allow scanning as long as bluetooth is powered on return self.ensureState(.PoweredOn, observable: observable) } } // MARK: State /** Continuous state of `BluetoothManager` instance described by `BluetoothState` which is equivalent to [`CBManagerState`](https://developer.apple.com/reference/corebluetooth/cbmanager/1648600-state). - returns: Observable that emits `Next` immediately after subscribtion with current state of Bluetooth. Later, whenever state changes events are emitted. Observable is infinite : doesn't generate `Complete`. */ public var rx_state: Observable<BluetoothState> { return Observable.deferred { return self.centralManager.rx_didUpdateState.startWith(self.centralManager.state) } } /** Current state of `BluetoothManager` instance described by `BluetoothState` which is equivalent to [`CBManagerState`](https://developer.apple.com/reference/corebluetooth/cbmanager/1648600-state). - returns: Current state of `BluetoothManager` as `BluetoothState`. */ public var state: BluetoothState { return centralManager.state } // MARK: Peripheral's Connection Management /** Establishes connection with `Peripheral` after subscription to returned observable. It's user responsibility to close connection with `cancelConnectionToPeripheral(_:)` after subscription was completed. Unsubscribing from returned observable cancels connection attempt. By default observable is waiting infinitely for successful connection. Additionally you can pass optional [dictionary](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/#//apple_ref/doc/constant_group/Peripheral_Connection_Options) to customise the behaviour of connection. - parameter peripheral: The `Peripheral` to which `BluetoothManager` is attempting to connect. - parameter options: Dictionary to customise the behaviour of connection. - returns: Observable which emits next and complete events after connection is established. */ public func connectToPeripheral(peripheral: Peripheral, options: [String: AnyObject]? = nil) -> Observable<Peripheral> { let success = centralManager.rx_didConnectPeripheral .filter { $0 == peripheral.peripheral } .take(1) .map { _ in return peripheral } let error = centralManager.rx_didFailToConnectPeripheral .filter { $0.0 == peripheral.peripheral } .take(1) .flatMap { (peripheral, error) -> Observable<Peripheral> in Observable.error(BluetoothError.PeripheralConnectionFailed( Peripheral(manager: self, peripheral: peripheral), error)) } let observable = Observable<Peripheral>.create { observer in if let error = BluetoothError.errorFromState(self.centralManager.state) { observer.onError(error) return NopDisposable.instance } guard !peripheral.isConnected else { observer.onNext(peripheral) observer.onCompleted() return NopDisposable.instance } let disposable = success.amb(error).subscribe(observer) self.centralManager.connectPeripheral(peripheral.peripheral, options: options) return AnonymousDisposable { if !peripheral.isConnected { self.centralManager.cancelPeripheralConnection(peripheral.peripheral) disposable.dispose() } } } return ensureState(.PoweredOn, observable: observable) } /** Cancels an active or pending local connection to a `Peripheral` after observable subscription. It is not guaranteed that physical connection will be closed immediately as well and all pending commands will not be executed. - parameter peripheral: The `Peripheral` to which the `BluetoothManager` is either trying to connect or has already connected. - returns: Observable which emits next and complete events when peripheral successfully cancelled connection. */ public func cancelConnectionToPeripheral(peripheral: Peripheral) -> Observable<Peripheral> { let observable = Observable<Peripheral>.create { observer in let disposable = self.monitorPeripheralDisconnection(peripheral).take(1).subscribe(observer) self.centralManager.cancelPeripheralConnection(peripheral.peripheral) return AnonymousDisposable { disposable.dispose() } } return ensureState(.PoweredOn, observable: observable) } // MARK: Retrieving Lists of Peripherals /** Returns observable list of the `Peripheral`s which are currently connected to the `BluetoothManager` and contain all of the specified `Service`'s UUIDs. - parameter serviceUUIDs: A list of `Service` UUIDs - returns: Observable which emits retrieved `Peripheral`s. They are in connected state and contain all of the `Service`s with UUIDs specified in the `serviceUUIDs` parameter. Just after that complete event is emitted */ public func retrieveConnectedPeripheralsWithServices(serviceUUIDs: [CBUUID]) -> Observable<[Peripheral]> { let observable = Observable<[Peripheral]>.deferred { return self.centralManager.retrieveConnectedPeripheralsWithServices(serviceUUIDs).map { (peripheralTable: [RxPeripheralType]) -> [Peripheral] in peripheralTable.map { Peripheral(manager: self, peripheral: $0) } } } return ensureState(.PoweredOn, observable: observable) } /** Returns observable list of `Peripheral`s by their identifiers which are known to `BluetoothManager`. - parameter identifiers: List of `Peripheral`'s identifiers which should be retrieved. - returns: Observable which emits next and complete events when list of `Peripheral`s are retrieved. */ public func retrievePeripheralsWithIdentifiers(identifiers: [NSUUID]) -> Observable<[Peripheral]> { let observable = Observable<[Peripheral]>.deferred { return self.centralManager.retrievePeripheralsWithIdentifiers(identifiers).map { (peripheralTable: [RxPeripheralType]) -> [Peripheral] in peripheralTable.map { Peripheral(manager: self, peripheral: $0) } } } return ensureState(.PoweredOn, observable: observable) } // MARK: Internal functions /** Ensure that `state` is and will be the only state of `BluetoothManager` during subscription. Otherwise error is emitted. - parameter state: `BluetoothState` which should be present during subscription. - parameter observable: Observable into which potential errors should be merged. - returns: New observable which merges errors with source observable. */ func ensureState<T>(state: BluetoothState, observable: Observable<T>) -> Observable<T> { let statesObservable = rx_state .filter { $0 != state && BluetoothError.errorFromState($0) != nil } .map { state -> T in throw BluetoothError.errorFromState(state)! } return Observable.absorb(statesObservable, observable) } /** Ensure that specified `peripheral` is connected during subscription. - parameter peripheral: `Peripheral` which should be connected during subscription. - returns: Observable which emits error when `peripheral` is disconnected during subscription. */ func ensurePeripheralIsConnected<T>(peripheral: Peripheral) -> Observable<T> { return Observable.deferred { if !peripheral.isConnected { return Observable.error(BluetoothError.PeripheralDisconnected(peripheral, nil)) } return self.centralManager.rx_didDisconnectPeripheral .filter { $0.0 == peripheral.peripheral } .flatMap { (_, error) -> Observable<T> in return Observable.error(BluetoothError.PeripheralDisconnected(peripheral, error)) } } } /** Emits `Peripheral` instance when it's connected. - Parameter peripheral: `Peripheral` which is monitored for connection. - Returns: Observable which emits next events when `peripheral` was connected. */ public func monitorPeripheralConnection(peripheral: Peripheral) -> Observable<Peripheral> { return monitorPeripheralAction(centralManager.rx_didConnectPeripheral, peripheral: peripheral) } /** Emits `Peripheral` instance when it's disconnected. - Parameter peripheral: `Peripheral` which is monitored for disconnection. - Returns: Observable which emits next events when `peripheral` was disconnected. */ public func monitorPeripheralDisconnection(peripheral: Peripheral) -> Observable<Peripheral> { return monitorPeripheralAction(centralManager.rx_didDisconnectPeripheral.map { $0.0 }, peripheral: peripheral) } func monitorPeripheralAction(peripheralAction: Observable<RxPeripheralType>, peripheral: Peripheral) -> Observable<Peripheral> { let observable = peripheralAction .filter { $0 == peripheral.peripheral } .map { _ in peripheral } return ensureState(.PoweredOn, observable: observable) } #if os(iOS) /** Emits `RestoredState` instance, when state of `BluetoothManager` has been restored - Returns: Observable which emits next events state has been restored */ public func listenOnRestoredState() -> Observable<RestoredState> { return centralManager .rx_willRestoreState .take(1) .map { RestoredState(restoredStateDictionary: $0, bluetoothManager: self) } } #endif }
027e363b62ef5e6548554cb7bb9102a1
47.838235
216
0.666566
false
false
false
false
KeepGoing2016/Swift-
refs/heads/master
DUZB_XMJ/DUZB_XMJ/Classes/Home/Model/NormalCellModel.swift
apache-2.0
1
// // NormalCellModel.swift // DUZB_XMJ // // Created by user on 16/12/27. // Copyright © 2016年 XMJ. All rights reserved. // import UIKit class NormalCellModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间图片对应的URLString var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播(普通房间) 1 : 手机直播(秀场房间) var isVertical : Int = 0 /// 房间名称 var room_name : String = "" /// 主播昵称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" init(dict : [String:Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
5f925336dc7bed939a50a311a8618121
19.361111
72
0.548431
false
false
false
false
DianQK/rx-sample-code
refs/heads/master
RxDataSourcesExample/CellButtonClickTableViewController.swift
mit
1
// // CellButtonClickTableViewController.swift // RxDataSourcesExample // // Created by DianQK on 04/10/2016. // Copyright © 2016 T. All rights reserved. // import UIKit import RxSwift import RxCocoa import SafariServices class InfoTableViewCell: UITableViewCell { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet fileprivate weak var detailButton: UIButton! { didSet { detailButton.layer.borderColor = UIColor.black.cgColor detailButton.layer.borderWidth = 1 detailButton.layer.cornerRadius = 5 detailButton.addTarget(self, action: #selector(_detailButtonTap), for: .touchUpInside) } } var detailButtonTap: (() -> ())? var title: String? { get { return titleLabel.text } set(title) { titleLabel.text = title } } var disposeBag = DisposeBag() override func prepareForReuse() { super.prepareForReuse() disposeBag = DisposeBag() } private dynamic func _detailButtonTap() { detailButtonTap?() } } class CellButtonClickTableViewController: UITableViewController { struct Info { let name: String let url: URL } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = nil tableView.delegate = nil let infoItems = [ Info(name: "Apple Developer", url: URL(string: "https://developer.apple.com/")!), Info(name: "GitHub", url: URL(string: "https://github.com")!), Info(name: "Dribbble", url: URL(string: "https://dribbble.com")!) ] Observable.just(infoItems) .bindTo(tableView.rx.items(cellIdentifier: "InfoTableViewCell", cellType: InfoTableViewCell.self)) { [unowned self] (row, element, cell) in cell.title = element.name // cell.detailButtonTap = { // let safari = SFSafariViewController(url: element.url) // safari.preferredControlTintColor = UIColor.black // self.showDetailViewController(safari, sender: nil) // } cell.detailButton.rx.tap .map { element.url } .subscribe(onNext: { url in print("Open :\(url)") let safari = SFSafariViewController(url: element.url) safari.preferredControlTintColor = UIColor.black self.showDetailViewController(safari, sender: nil) }) .disposed(by: cell.disposeBag) } .disposed(by: rx.disposeBag) } }
638c06e521248421ee4f15a36378648c
28.846154
151
0.575847
false
false
false
false
Minecodecraft/EstateBand
refs/heads/master
EstateBand/HealthyViewController.swift
mit
1
// // HealthyViewController.swift // EstateBand // // Created by Minecode on 2017/6/27. // Copyright © 2017年 org.minecode. All rights reserved. // import UIKit class HealthyViewController: UIViewController { // 控件 @IBOutlet weak var sosButton: UIButton! @IBOutlet weak var restButton: UIButton! @IBOutlet weak var refreshButton: UIButton! @IBOutlet weak var healthyLabel: UILabel! @IBOutlet weak var notiLabel: UILabel! // 数据 var rate: Int = 85 override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { sosButton.layer.cornerRadius = 50 restButton.layer.cornerRadius = 50 refreshButton.layer.cornerRadius = 50 self.notiLabel.textColor = UIColor.green self.notiLabel.text = "Healthy" self.healthyLabel.textColor = UIColor.green self.healthyLabel.text = String(rate) } @IBAction func sosAction(_ sender: UIButton) { } @IBAction func restAction(_ sender: UIButton) { } @IBAction func refreshAction(_ sender: UIButton) { let arc = arc4random_uniform(10) rate += Int(arc) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(1.0) healthyLabel.text = String(rate) if rate >= 100 { healthyLabel.textColor = UIColor.red notiLabel.textColor = UIColor.red notiLabel.text = String("You need rest now!") } UIView.commitAnimations() } }
16b76e3cf080951d0f92edad18be13fc
22.811594
57
0.587949
false
false
false
false
MisterZhouZhou/Objective-C-Swift-StudyDemo
refs/heads/master
SwiftDemo/SwiftDemo/classes/modules/Main/ZWRootViewController.swift
apache-2.0
1
// // ZWRootViewController.swift // Swift-Demo // // Created by rayootech on 16/6/2. // Copyright © 2016年 rayootech. All rights reserved. // import UIKit class ZWRootViewController: ZWBaseViewController ,UITableViewDataSource,UITableViewDelegate { var dataArray:Dictionary<String,String> = Dictionary<String,String>() //UITableView lazy var mainTableView: UITableView = { let tempTableView = UITableView (frame: CGRectZero, style: UITableViewStyle.Plain) tempTableView.delegate = self tempTableView.dataSource = self return tempTableView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.whiteColor() //添加视图 self .addSubVies() //设置布局 self .layout() } //添加视图 func addSubVies () { //添加UITableView self.view.addSubview(self.mainTableView) //去除底部多余线 self.mainTableView.tableFooterView = UIView() } //设置布局 func layout() { self.mainTableView.snp_makeConstraints { (make) in make.left.top.equalTo(self.view) make.width.equalTo(self.view) make.height.equalTo(self.view) } } //UITableView DataSource ,Delegate func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArray.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Default, reuseIdentifier: "cell") let dict:Dictionary<String,String> = self.dataArray for (index,value) in dict.keys.enumerate(){ if index == indexPath.row { cell.textLabel?.text = value } } cell.selectionStyle = .None return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var vcStr :String = String() let dict:Dictionary<String,String> = self.dataArray for (index,value) in dict.values.enumerate(){ if index == indexPath.row { vcStr = value } } //进行跳转 self.navigationController!.pushViewControllerWithName(vcStr) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
5a823c9acd1986994a94aac5e040feb4
26.918919
109
0.618264
false
false
false
false
Shivam0911/IOS-Training-Projects
refs/heads/master
ListViewToGridViewConverter ONLINE/ListViewToGridViewConverter/listViewCell.swift
mit
2
// // listViewCell.swift // ListViewToGridViewConverter // // Created by MAC on 13/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit class listViewCell: UICollectionViewCell { @IBOutlet weak var carImage: UIImageView! @IBOutlet weak var carName: UILabel! override func awakeFromNib() { super.awakeFromNib() // carImage.layer.cornerRadius = carImage.layer.bounds.height/2 // Initialization code } func populateTheData(_ data : [String:String]){ print(#function) let imageUrl = data["CarImage"]! self.carImage.backgroundColor = UIColor(patternImage: UIImage(named: imageUrl)!) // carImage.backgroundColor = UIColor.cyan carName.text = data["CarName"]! } override func prepareForReuse() { } }
dc56d060130081702e88cdb436bd9b78
24.666667
88
0.644628
false
false
false
false
wangyun-hero/sinaweibo-with-swift
refs/heads/master
sinaweibo/Classes/View/Compose/View/WYComposeButton.swift
mit
1
// // WYComposeButton.swift // sinaweibo // // Created by 王云 on 16/9/7. // Copyright © 2016年 王云. All rights reserved. // import UIKit class WYComposeButton: UIButton { //取消button点击之后的高亮效果 override var isHighlighted: Bool{ set{ } get{ return false } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI() { imageView?.contentMode = .center //文字居中 titleLabel?.textAlignment = .center } func test() { print("ssss") } override func layoutSubviews() { super.layoutSubviews() let width = self.frame.width let height = self.frame.height imageView?.frame = CGRect(x: 0, y: 0, width: width, height: width) titleLabel?.frame = CGRect(x: 0, y: width, width: width, height: height - width) } }
032657e18b96686441ecd74547955178
18.472727
88
0.54155
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Extensions/UIViewController/UIViewControllerDimming.swift
mit
1
// // UIViewControllerDimming.swift // Rocket.Chat // // Created by Matheus Cardoso on 11/23/18. // import UIKit let kDimViewAlpha: CGFloat = 0.6 let kDimViewAnimationDuration = 0.25 class DimView: UIView { } extension UIViewController { var dimViewTag: Int { return "Dim_View".hashValue } var dimView: DimView { if let res = view.viewWithTag(dimViewTag) as? DimView { res.frame = view.bounds return res } else { let dimView = DimView(frame: view.bounds) dimView.tag = dimViewTag dimView.backgroundColor = .black dimView.alpha = kDimViewAlpha view.addSubview(dimView) return dimView } } func startDimming() { view.bringSubviewToFront(dimView) dimView.isHidden = false UIView.animate(withDuration: kDimViewAnimationDuration) { [dimView] in dimView.alpha = kDimViewAlpha } } func stopDimming() { UIView.animate(withDuration: kDimViewAnimationDuration, animations: { [dimView] in dimView.alpha = 0 }, completion: { [dimView] _ in dimView.isHidden = true }) } }
0bdbbce1a469e1b5ade6151f8333bc25
22.519231
90
0.596893
false
false
false
false
siberianisaev/NeutronBarrel
refs/heads/master
NeutronBarrel/DataProtocol.swift
mit
1
// // DataProtocol.swift // NeutronBarrel // // Created by Andrey Isaev on 24/04/2017. // Copyright © 2018 Flerov Laboratory. All rights reserved. // import Foundation import AppKit enum TOFKind: String { case TOF = "TOF" case TOF2 = "TOF2" } class DataProtocol { fileprivate var dict = [String: Int]() { didSet { AVeto = dict["AVeto"] TOF = dict[TOFKind.TOF.rawValue] TOF2 = dict[TOFKind.TOF2.rawValue] NeutronsOld = dict["Neutrons"] Neutrons_N = getValues(ofTypes: ["N1", "N2", "N3", "N4"], prefix: false) NeutronsNew = getValues(ofTypes: ["NNeut"]) CycleTime = dict["THi"] BeamEnergy = dict["EnergyHi"] BeamCurrent = dict["BeamTokHi"] BeamBackground = dict["BeamFonHi"] BeamIntegral = dict["IntegralHi"] AlphaWell = getValues(ofTypes: ["AWel"]) AlphaWellFront = getValues(ofTypes: ["AWFr"]) AlphaWellBack = getValues(ofTypes: ["AWBk"]) AlphaMotherFront = getValues(ofTypes: ["AFr"]) AlphaDaughterFront = getValues(ofTypes: ["AdFr"]) AlphaFront = AlphaMotherFront.union(AlphaDaughterFront) AlphaMotherBack = getValues(ofTypes: ["ABack", "ABk"]) AlphaDaughterBack = getValues(ofTypes: ["AdBk"]) AlphaBack = AlphaMotherBack.union(AlphaDaughterBack) Gamma = getValues(ofTypes: ["Gam"]) } } fileprivate func getValues(ofTypes types: [String], prefix: Bool = true) -> Set<Int> { var result = [Int]() for type in types { let values = dict.filter({ (key: String, value: Int) -> Bool in if prefix { return self.keyFor(value: value)?.hasPrefix(type) == true } else { return self.keyFor(value: value) == type } }).values result.append(contentsOf: values) } return Set(result) } fileprivate var BeamEnergy: Int? fileprivate var BeamCurrent: Int? fileprivate var BeamBackground: Int? fileprivate var BeamIntegral: Int? fileprivate var AVeto: Int? fileprivate var TOF: Int? fileprivate var TOF2: Int? fileprivate var NeutronsOld: Int? fileprivate var Neutrons_N = Set<Int>() fileprivate var NeutronsNew = Set<Int>() fileprivate var CycleTime: Int? fileprivate var AlphaWell = Set<Int>() fileprivate var AlphaWellFront = Set<Int>() fileprivate var AlphaWellBack = Set<Int>() fileprivate var AlphaMotherFront = Set<Int>() fileprivate var AlphaDaughterFront = Set<Int>() fileprivate var AlphaFront = Set<Int>() fileprivate var AlphaMotherBack = Set<Int>() fileprivate var AlphaDaughterBack = Set<Int>() fileprivate var AlphaBack = Set<Int>() fileprivate var Gamma = Set<Int>() fileprivate var isAlphaCache = [Int: Bool]() func isAlpha(eventId: Int) -> Bool { if let b = isAlphaCache[eventId] { return b } else { var b = false for s in [AlphaFront, AlphaBack, AlphaWell, AlphaWellFront, AlphaWellBack, AlphaMotherFront, AlphaMotherBack, AlphaDaughterFront, AlphaDaughterBack] { if s.contains(eventId) { b = true break } } isAlphaCache[eventId] = b return b } } class func load(_ path: String?) -> DataProtocol { var result = [String: Int]() if let path = path { do { var content = try String(contentsOfFile: path, encoding: String.Encoding.utf8) content = content.replacingOccurrences(of: " ", with: "") let words = Event.words for line in content.components(separatedBy: CharacterSet.newlines) { if false == line.contains(":") || line.starts(with: "#") { continue } let set = CharacterSet(charactersIn: ":,") let components = line.components(separatedBy: set).filter() { $0 != "" } let count = components.count if words == count { let key = components[count-1] let value = Int(components[0]) result[key] = value } } } catch { print("Error load protocol from file at path \(path): \(error)") } } let p = DataProtocol() p.dict = result if p.dict.count == 0 { let alert = NSAlert() alert.messageText = "Error" alert.informativeText = "Please select protocol!" alert.addButton(withTitle: "OK") alert.alertStyle = .warning alert.runModal() } p.encoderForEventIdCache.removeAll() p.isValidEventIdForTimeCheckCache.removeAll() return p } fileprivate var isValidEventIdForTimeCheckCache = [Int: Bool]() /** Not all events have time data. */ func isValidEventIdForTimeCheck(_ eventId: Int) -> Bool { if let cached = isValidEventIdForTimeCheckCache[eventId] { return cached } let value = isAlpha(eventId: eventId) || isTOFEvent(eventId) != nil || isGammaEvent(eventId) || isNeutronsOldEvent(eventId) || isNeutronsNewEvent(eventId) || isNeutrons_N_Event(eventId) || isVETOEvent(eventId) isValidEventIdForTimeCheckCache[eventId] = value return value } func keyFor(value: Int) -> String? { for (k, v) in dict { if v == value { return k } } return nil } func position(_ eventId: Int) -> String { if AlphaMotherFront.contains(eventId) { return "Fron" } else if AlphaMotherBack.contains(eventId) { return "Back" } else if AlphaDaughterFront.contains(eventId) { return "dFron" } else if AlphaDaughterBack.contains(eventId) { return "dBack" } else if isVETOEvent(eventId) { return "Veto" } else if isGammaEvent(eventId) { return "Gam" } else if isAlphaWellBackEvent(eventId) { return "WBack" } else if isAlphaWellFrontEvent(eventId) { return "WFront" } else { return "Wel" } } func isAlphaFronEvent(_ eventId: Int) -> Bool { return AlphaFront.contains(eventId) } func isAlphaBackEvent(_ eventId: Int) -> Bool { return AlphaBack.contains(eventId) } func isAlphaWellEvent(_ eventId: Int) -> Bool { return AlphaWell.contains(eventId) } func isAlphaWellFrontEvent(_ eventId: Int) -> Bool { return AlphaWellFront.contains(eventId) } func isAlphaWellBackEvent(_ eventId: Int) -> Bool { return AlphaWellBack.contains(eventId) } func isGammaEvent(_ eventId: Int) -> Bool { return Gamma.contains(eventId) } func isVETOEvent(_ eventId: Int) -> Bool { return AVeto == eventId } func isTOFEvent(_ eventId: Int) -> TOFKind? { if TOF == eventId { return .TOF } else if TOF2 == eventId { return .TOF2 } return nil } func isNeutronsNewEvent(_ eventId: Int) -> Bool { return NeutronsNew.contains(eventId) } func isNeutronsOldEvent(_ eventId: Int) -> Bool { return NeutronsOld == eventId } func isNeutrons_N_Event(_ eventId: Int) -> Bool { return Neutrons_N.contains(eventId) } func hasNeutrons_N() -> Bool { return Neutrons_N.count > 0 } func isCycleTimeEvent(_ eventId: Int) -> Bool { return CycleTime == eventId } func isBeamEnergy(_ eventId: Int) -> Bool { return BeamEnergy == eventId } func isBeamCurrent(_ eventId: Int) -> Bool { return BeamCurrent == eventId } func isBeamBackground(_ eventId: Int) -> Bool { return BeamBackground == eventId } func isBeamIntegral(_ eventId: Int) -> Bool { return BeamIntegral == eventId } fileprivate var encoderForEventIdCache = [Int: CUnsignedShort]() func encoderForEventId(_ eventId: Int) -> CUnsignedShort { if let cached = encoderForEventIdCache[eventId] { return cached } var value: CUnsignedShort if let key = keyFor(value: eventId), let rangeDigits = key.rangeOfCharacter(from: .decimalDigits), let substring = String(key[rangeDigits.lowerBound...]).components(separatedBy: CharacterSet.init(charactersIn: "., ")).first, let encoder = Int(substring) { value = CUnsignedShort(encoder) } else if (AlphaWell.contains(eventId) && AlphaWell.count == 1) || (Gamma.contains(eventId) && Gamma.count == 1) { value = 1 } else { value = 0 } encoderForEventIdCache[eventId] = value return value } }
56ba36432b7d8ad83e6374f4a85f0aa2
32.4
263
0.557314
false
false
false
false
brentsimmons/Frontier
refs/heads/master
BeforeTheRename/FrontierCore/FrontierCore/ThreadSupervisor.swift
gpl-2.0
1
// // ThreadSupervisor.swift // FrontierCore // // Created by Brent Simmons on 4/23/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation // When Frontier creates a thread, it should use ThreadSupervisor, which counts and manages threads. The thread verbs need ThreadSupervisor. public struct ThreadSupervisor { public static let mainThreadID = 0 public static let unknownThreadID = -1 public static var numberOfThreads: Int { get { return threads.count + 1 // Add one for main thread } } private static var threads = [Int: ManagedThread]() private static let lock = NSLock() private static var incrementingThreadID = 1 public static func createAndRunThread(block: @escaping VoidBlock) { let thread = ManagedThread(block: block) thread.name = "Frontier Thread" lock.lock() thread.identifier = incrementingThreadID incrementingThreadID = incrementingThreadID + 1 threads[thread.identifier] = thread lock.unlock() thread.start() } public static func currentThreadID() -> Int { if Thread.isMainThread { return mainThreadID } if let thread = Thread.current as? ManagedThread { return thread.identifier } return unknownThreadID } // MARK: Thread callback static func threadDidComplete(identifier: Int) { lock.lock() threads[identifier] = nil lock.unlock() } }
1835aff42b7da868f8c1a92a258b5eac
20.968254
140
0.721098
false
false
false
false
appfoundry/DRYLogging
refs/heads/master
Example/Tests/DefaultLoggerInheritanceSpec.swift
mit
1
// // DefaultLoggerInheritanceSpec.swift // DRYLogging // // Created by Michael Seghers on 15/11/2016. // Copyright © 2016 Michael Seghers. All rights reserved. // import Foundation import Quick import Nimble import DRYLogging class DefaultLoggerInheritanceSpec : QuickSpec { override func spec() { describe("DefaultLogger Inheritance") { var child:DefaultLogger! var parent:DefaultLogger! var grandParent:DefaultLogger! beforeEach { grandParent = DefaultLogger(name: "grandparent") parent = DefaultLogger(name: "parent", parent: grandParent) child = DefaultLogger(name: "child", parent: parent) } context("logger hierarchy from grandParent to child") { it("child should inherit logLevel from parent") { parent.logLevel = .info expect(child.isInfoEnabled) == true } it("child should override parent logging level when set") { parent.logLevel = .info child.logLevel = .error expect(child.isInfoEnabled) == false } } context("logger hierarchy with appenders") { var childAppender:LoggingAppenderMock! var parentAppender:LoggingAppenderMock! var grandParentAppender:LoggingAppenderMock! beforeEach { child.logLevel = .info grandParentAppender = LoggingAppenderMock() grandParent.add(appender: grandParentAppender) parentAppender = LoggingAppenderMock() parent.add(appender: parentAppender) childAppender = LoggingAppenderMock() child.add(appender: childAppender) } it("should append the message to the parent appender") { child.info("test") expect(parentAppender.messages).to(haveCount(1)) } it("should append the message to the parent appender") { child.info("test") expect(grandParentAppender.messages).to(haveCount(1)) } } } } }
9ad9bb9e3f2b2cf81c3bbcb8bdbf3781
34.614286
75
0.514641
false
false
false
false
tLewisII/TJLSet
refs/heads/master
TJLSet/Source/Set.swift
mit
1
// // Set.swift // TJLSet // // Created by Terry Lewis II on 6/5/14. // Copyright (c) 2014 Blue Plover Productions LLC. All rights reserved. // import Foundation operator infix ∩ {} operator infix ∪ {} struct Set<A: Hashable> : Sequence { var bucket:Dictionary<A, Bool> = Dictionary() var array:Array<A> { var arr = Array<A>() for (key, _) in bucket { arr += key } return arr } var count:Int { return bucket.count } init(items:A...) { for obj in items { bucket[obj] = true } } init(array:Array<A>) { for obj in array { bucket[obj] = true } } func any() -> A { let ar = self.array let index = Int(arc4random_uniform(UInt32(ar.count))) return ar[index] } func contains(item:A) -> Bool { if let c = bucket[item] { return c } else { return false } } func member(item:A) -> A? { if self.contains(item) { return .Some(item) } else { return nil } } func interectsSet(set:Set<A>) -> Bool { for x in set { if self.contains(x) { return true } } return false } func intersect(set:Set<A>) -> Set<A> { var array:[A] = Array() for x in self { if let memb = set.member(x) { array += memb } } return Set(array:array) } func minus(set:Set<A>) -> Set<A> { var array:[A] = Array() for x in self { if !set.contains(x) { array += x } } return Set(array:array) } func union(set:Set<A>) -> Set<A> { var current = self.array current += set.array return Set(array: current) } func add(item:A) -> Set<A> { if contains(item) { return self } else { var arr = array arr += item return Set(array:arr) } } func filter(f:(A -> Bool)) -> Set<A> { var array = Array<A>() for x in self { if f(x) { array += x } } return Set(array: array) } func map<B>(f:(A -> B)) -> Set<B> { var array:Array<B> = Array() for x in self { array += f(x) } return Set<B>(array: array) } func generate() -> SetGenerator<A> { let items = self.array return SetGenerator(items: items[0..<items.count]) } } struct SetGenerator<A> : Generator { mutating func next() -> A? { if items.isEmpty { return nil } let ret = items[0] items = items[1..<items.count] return ret } var items:Slice<A> } extension Set : Printable,DebugPrintable { var description:String { return "\(self.array)" } var debugDescription:String { return "\(self.array)" } } func ==<A: Equatable>(lhs:Set<A>, rhs:Set<A>) -> Bool { return lhs.bucket == rhs.bucket } func !=<A: Equatable>(lhs:Set<A>, rhs:Set<A>) -> Bool { return lhs.bucket != rhs.bucket } func +=<A>(set:Set<A>, item:A) -> Set<A> { if set.contains(item) { return set } else { var arr = set.array arr += item return Set(array:arr) } } func -<A>(lhs:Set<A>, rhs:Set<A>) -> Set<A> { return lhs.minus(rhs) } func ∩<A>(lhs:Set<A>, rhs:Set<A>) -> Set<A> { return lhs.intersect(rhs) } func ∪<A>(lhs:Set<A>, rhs:Set<A>) -> Set<A> { return lhs.union(rhs) }
cb7c56b4ef15fda5fad43fd962b4fc91
19.263441
72
0.462192
false
false
false
false
caopengxu/scw
refs/heads/master
scw/scw/Code/Sign/RegisterController.swift
mit
1
// // RegisterController.swift // scw // // Created by cpx on 2017/7/27. // Copyright © 2017年 scw. All rights reserved. // import UIKit class RegisterController: UIViewController { var judgeAgreement = true @IBOutlet weak var phoneNumberTextF: MyTextFieldFont! @IBOutlet weak var verificationTextF: MyTextFieldFont! @IBOutlet weak var passwordTextF: MyTextFieldFont! // MARK:=== viewDidLoad override func viewDidLoad() { super.viewDidLoad() } // MARK:=== 倒计时 @IBAction func countDownBtnClick(_ sender: CountDownButton) { sender.startCountDown() } // MARK:=== 点击注册按钮 @IBAction func registerBtnClick(_ sender: PXCustomButton) { } // MARK:=== 点击对勾按钮 @IBAction func judgeAgreementBtnClick(_ sender: UIButton) { if sender.tag == 0 { sender.tag = 1; sender.setImage(#imageLiteral(resourceName: "对勾灰色"), for: .normal) judgeAgreement = false } else { sender.tag = 0; sender.setImage(#imageLiteral(resourceName: "对勾红色"), for: .normal) judgeAgreement = true } } // MARK:=== 点击用户协议按钮 @IBAction func agreementBtnClick(_ sender: UIButton) { } // MARK:=== 点击返回按钮 @IBAction func returnBtnClick(_ sender: PXCustomButton) { view.endEditing(true) navigationController?.popViewController(animated: true) } // 点击其他地方收起键盘 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } // MARK:=== 隐藏状态栏 override var prefersStatusBarHidden: Bool { return true } } // MARK:=== <UITextFieldDelegate> extension RegisterController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.5) { self.view.frame = CGRect.init(x: 0, y: -100, width: __ScreenWidth, height: __ScreenHeight) } } func textFieldDidEndEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.3) { self.view.frame = CGRect.init(x: 0, y: 0, width: __ScreenWidth, height: __ScreenHeight) } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if phoneNumberTextF == textField { if (phoneNumberTextF.text?.lengthOfBytes(using: String.Encoding.utf8))! >= __PhoneNumberLength { print("手机号格式不对") return false } } if passwordTextF == textField { if (passwordTextF.text?.lengthOfBytes(using: String.Encoding.utf8))! >= __PasswordLength { print("密码最多支持15位") return false } } return true } }
193e85609ee5449b09cd68b53310df16
24.404959
129
0.561158
false
false
false
false
BalestraPatrick/Tweetometer
refs/heads/master
Tweetometer/UserTopBarViewController.swift
mit
2
// // UserTopBarViewController.swift // Tweetometer // // Created by Patrick Balestra on 8/15/18. // Copyright © 2018 Patrick Balestra. All rights reserved. // import UIKit import TweetometerKit protocol UserTopBarDelegate { func openSettings(sender: UIView) } class UserTopBarViewController: UIViewController { struct Dependencies { let twitterSession: TwitterSession let delegate: UserTopBarDelegate } private var dependencies: Dependencies! @IBOutlet private var profileImageView: UIImageView! @IBOutlet private var yourTimelineLabel: UILabel! @IBOutlet private var usernameLabel: UILabel! @IBOutlet var settingsButton: UIButton! static func instantiate(with dependencies: Dependencies) -> UserTopBarViewController { let this = StoryboardScene.UserTopBar.initialScene.instantiate() this.dependencies = dependencies return this } override func viewDidLoad() { super.viewDidLoad() loadData() } private func loadData() { dependencies.twitterSession.loadUserData { result in switch result { case .success(let user): self.profileImageView?.kf.setImage(with: URL(string: user.profileImageURL)!) case .error: self.profileImageView?.image = Asset.placeholder.image } } profileImageView?.kf.indicatorType = .activity profileImageView.layer.cornerRadius = profileImageView.bounds.width / 2 profileImageView.layer.masksToBounds = true } @IBAction func openSettings(_ sender: UIView) { dependencies.delegate.openSettings(sender: sender) } }
0fc751e241c671b92928507765126479
28.275862
92
0.682568
false
false
false
false
SomnusLee1988/Azure
refs/heads/master
Pods/SLAlertController/SLAlertController/Classes/Extensions/UIImageExtension.swift
mit
2
// // UIImageExtension.swift // Pods // // Created by Somnus on 16/6/24. // // import Foundation import UIKit public extension UIImage { convenience init(color: UIColor, size: CGSize = CGSizeMake(1, 1)) { let rect = CGRectMake(0, 0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.init(CGImage: image.CGImage!) } func imageWithColor(color:UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale); let context:CGContextRef = UIGraphicsGetCurrentContext()!; CGContextTranslateCTM(context, 0, self.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, .Normal); let rect = CGRectMake(0, 0, self.size.width, self.size.height); CGContextClipToMask(context, rect, self.CGImage); color.setFill(); CGContextFillRect(context, rect); let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } func imageFitInSize(viewsize:CGSize) -> UIImage { // calculate the fitted size let size:CGSize = self.fitSize(self.size, inSize: viewsize); UIGraphicsBeginImageContext(viewsize); let dwidth:CGFloat = (viewsize.width - size.width) / 2.0; let dheight:CGFloat = (viewsize.height - size.height) / 2.0; let rect:CGRect = CGRectMake(dwidth, dheight, size.width, size.height); self.drawInRect(rect); let newimg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newimg; } func fitSize(thisSize:CGSize, inSize aSize:CGSize) -> CGSize { var scale:CGFloat; var newsize = thisSize; if (newsize.height > 0) && (newsize.height > aSize.height) { scale = aSize.height / newsize.height; newsize.width *= scale; newsize.height *= scale; } if (newsize.width > 0) && (newsize.width >= aSize.width) { scale = aSize.width / newsize.width; newsize.width *= scale; newsize.height *= scale; } return newsize; } }
7372f6b049778e2ff7388a225f8e1566
30.974359
79
0.606656
false
false
false
false
accepton/accepton-apple
refs/heads/master
Pod/Classes/AcceptOnUIMachine/Drivers/AcceptOnUIMachinePaymentDriver.swift
mit
1
import UIKit //A payment driver is a generic interface for one payment processor public protocol AcceptOnUIMachinePaymentDriverDelegate: class { func transactionDidFailForDriver(driver: AcceptOnUIMachinePaymentDriver, withMessage message: String) //Transaction has completed func transactionDidSucceedForDriver(driver: AcceptOnUIMachinePaymentDriver, withChargeRes chargeRes: [String:AnyObject]) func transactionDidCancelForDriver(driver: AcceptOnUIMachinePaymentDriver) var api: AcceptOnAPI { get } } public class AcceptOnUIMachinePaymentDriver: NSObject { //----------------------------------------------------------------------------------------------------- //Properties //----------------------------------------------------------------------------------------------------- public weak var delegate: AcceptOnUIMachinePaymentDriverDelegate! class var name: String { return "<unnamed>" } //Tokens that were retrieved from the drivers public var nonceTokens: [String:AnyObject] = [:] //Email is only for credit-card forms var email: String? //Meta-data is passed through from formOptions var metadata: [String:AnyObject] { return self.formOptions.metadata } //----------------------------------------------------------------------------------------------------- //Constructors //----------------------------------------------------------------------------------------------------- var formOptions: AcceptOnUIMachineFormOptions! public required init(formOptions: AcceptOnUIMachineFormOptions) { self.formOptions = formOptions } public func beginTransaction() { } //At this point, you should have filled out the nonceTokens, optionally the raw credit card information //and optionally 'email' properties. The 'email' property is passed as part of the transaction and is //used for credit-card transactions only. For drivers that have more complex semantics, e.g. ApplePay, //where you need to interleave actions within the transaction handshake, override the //readyToCompleteTransactionDidFail and readyToCompleteTransactionDidSucceed to modify that behaviour. func readyToCompleteTransaction(userInfo: Any?=nil) { if nonceTokens.count > 0 || self.formOptions.creditCardParams != nil { let chargeInfo = AcceptOnAPIChargeInfo(rawCardInfo: self.formOptions.creditCardParams, cardTokens: self.nonceTokens, email: email, metadata: self.metadata) self.delegate.api.chargeWithTransactionId(self.formOptions.token.id, andChargeinfo: chargeInfo) { chargeRes, err in if let err = err { self.readyToCompleteTransactionDidFail(userInfo, withMessage: err.localizedDescription) return } self.readyToCompleteTransactionDidSucceed(userInfo, withChargeRes: chargeRes!) } } else { self.readyToCompleteTransactionDidFail(userInfo, withMessage: "Could not connect to any payment processing services") } } //Override these functions if you need to interleave actions in the transaction stage. E.g. Dismiss //a 3rd party UI or a 3-way handshake //////////////////////////////////////////////////////////////////////////////////// func readyToCompleteTransactionDidFail(userInfo: Any?, withMessage message: String) { // dispatch_async(dispatch_get_main_queue()) { self.delegate.transactionDidFailForDriver(self, withMessage: message) // } } func readyToCompleteTransactionDidSucceed(userInfo: Any?, withChargeRes chargeRes: [String:AnyObject]) { // dispatch_async(dispatch_get_main_queue()) { self.delegate.transactionDidSucceedForDriver(self, withChargeRes: chargeRes) // } } //////////////////////////////////////////////////////////////////////////////////// }
ca59b77139894a7bd3adc1e43b3225bf
47.095238
167
0.598762
false
false
false
false
iAladdin/SwiftyFORM
refs/heads/master
Source/Cells/ViewControllerCell.swift
mit
1
// // ViewControllerCell.swift // SwiftyFORM // // Created by Simon Strandgaard on 05/11/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit public class ViewControllerFormItemCellModel { public let title: String public let placeholder: String public init(title: String, placeholder: String) { self.title = title self.placeholder = placeholder } } public class ViewControllerFormItemCell: UITableViewCell, SelectRowDelegate { public let model: ViewControllerFormItemCellModel let innerDidSelectRow: (ViewControllerFormItemCell, ViewControllerFormItemCellModel) -> Void public init(model: ViewControllerFormItemCellModel, didSelectRow: (ViewControllerFormItemCell, ViewControllerFormItemCellModel) -> Void) { self.model = model self.innerDidSelectRow = didSelectRow super.init(style: .Value1, reuseIdentifier: nil) accessoryType = .DisclosureIndicator textLabel?.text = model.title detailTextLabel?.text = model.placeholder } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func form_didSelectRow(indexPath: NSIndexPath, tableView: UITableView) { DLog("will invoke") // hide keyboard when the user taps this kind of row tableView.form_firstResponder()?.resignFirstResponder() innerDidSelectRow(self, model) DLog("did invoke") } }
490e04bf7c740db6781b1b5505003129
28.869565
139
0.773654
false
false
false
false
justin999/gitap
refs/heads/master
gitap/PhotosCollectionViewDataSource.swift
mit
1
// // PhotosCollectionViewDataSource.swift // gitap // // Created by Koichi Sato on 2017/02/05. // Copyright © 2017 Koichi Sato. All rights reserved. // import UIKit import Photos let photoThumbnailCountInRow:CGFloat = 3 let minimumSpacingBetweenCells: CGFloat = 1 let photoThumbnailLength = UIScreen.main.bounds.width / photoThumbnailCountInRow - (photoThumbnailCountInRow - minimumSpacingBetweenCells) let photoThumbnailSize = CGSize(width: photoThumbnailLength, height: photoThumbnailLength) class PhotosCollectionViewDataSource: NSObject { var stateController: StateController var fetchResult: PHFetchResult<PHAsset>! fileprivate let imageManager = PHCachingImageManager() init(collectionView: UICollectionView, stateController: StateController) { self.stateController = stateController super.init() collectionView.dataSource = self } } extension PhotosCollectionViewDataSource: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return fetchResult.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let asset = fetchResult.object(at: indexPath.item) // Dequeue a GridViewCell. let cellId = String(describing: PhotoGridViewCell.self) Utils.registerCCell(collectionView, nibName: cellId, cellId: cellId) guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? PhotoGridViewCell else { fatalError("unexpected cell in collection view") } // Request an image for the asset from the PHCachingImageManager. cell.representedAssetIdentifier = asset.localIdentifier imageManager.requestImage(for: asset, targetSize: photoThumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: { image, _ in // The cell may have been recycled by the time this handler gets called; // set the cell's thumbnail image only if it's still showing the same asset. if cell.representedAssetIdentifier == asset.localIdentifier { cell.thumbnailImage = image } }) return cell } }
0d006c97b913f41e3a4de41c53ddb83c
37.387097
146
0.712605
false
false
false
false
material-motion/material-motion-swift
refs/heads/develop
examples/HowToUseReactiveConstraintsExample.swift
apache-2.0
1
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. 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 UIKit import MaterialMotion class HowToUseReactiveConstraintsExampleViewController: ExampleViewController { var runtime: MotionRuntime! override func viewDidLoad() { super.viewDidLoad() let exampleView = center(createExampleView(), within: view) view.addSubview(exampleView) let axisLine = UIView(frame: .init(x: view.bounds.midX - 8, y: 0, width: 16, height: view.bounds.height)) axisLine.backgroundColor = .secondaryColor view.insertSubview(axisLine, belowSubview: exampleView) runtime = MotionRuntime(containerView: view) let axisCenterX = runtime.get(axisLine.layer).position.x() runtime.add(Draggable(), to: exampleView) { $0 .startWith(exampleView.layer.position) .xLocked(to: axisCenterX) } runtime.add(Draggable(), to: axisLine) { $0.yLocked(to: axisLine.layer.position.y) } } override func exampleInformation() -> ExampleInfo { return .init(title: type(of: self).catalogBreadcrumbs().last!, instructions: "Drag the view to move it on the y axis.") } }
2a6561f8f4e1789953ed70d8cc29cc39
33.204082
109
0.73568
false
false
false
false
dhardiman/MVVMTools
refs/heads/master
Sources/MVVM/TableViewCellSource.swift
mit
1
// // TableViewCellSource.swift // MVVM // // Created by Dave Hardiman on 22/03/2016. // Copyright © 2016 David Hardiman. All rights reserved. // import UIKit /** * A `View` that can be reused */ public protocol ViewCell: View { static var defaultReuseIdentifier: String { get } } // MARK: - Default implementation of reuse identifier for table view cells public extension ViewCell where Self: UITableViewCell { static var defaultReuseIdentifier: String { return String(describing: self) } } /** * A protocol that describes a source for MVVM compatible table view cells */ public protocol TableViewCellSource: UITableViewDataSource { /// The type of the view model being used by the cells. Used as a type /// constraint in the extension below associatedtype CellViewModelType: ViewModel /// The table view being supplied var tableView: UITableView! { get set } } public extension TableViewCellSource { /** Registers a table cell by nib name with the current table view - parameter _: The type of the cell being registered */ func registerNib<T: UITableViewCell>(_: T.Type, bundle: Bundle? = nil) where T: ViewCell { let nib = UINib(nibName: (String(describing: T.self)), bundle: bundle) tableView?.register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) } /** Retgisters a table cell by its class - parameter _: The type of the cell being registered */ func registerClass<T: UITableViewCell>(_: T.Type) where T: ViewCell { tableView?.register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) } /** Dequeues a cell from the current table view and configures the cell's view model with the specified item - parameter item: The item for the cell to display - parameter atIndexPath: The indexPath to dequeue the cell for - returns: A configured cell */ func cell<VC: ViewCell>(forItem item: CellViewModelType.ModelType, at indexPath: IndexPath) -> VC where VC.ViewModelType == Self.CellViewModelType, VC: UITableViewCell { guard let cell = tableView?.dequeueReusableCell(withIdentifier: VC.defaultReuseIdentifier, for: indexPath) as? VC else { fatalError("No cell registered for \(VC.defaultReuseIdentifier)") } cell.viewModel.model = item return cell } }
7c1340b63af40b15df9ee87e419d4c0b
31.621622
128
0.690555
false
false
false
false
Thomvis/BrightFutures
refs/heads/master
Tests/BrightFuturesTests/ExecutionContextTests.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2014 Thomas Visser // // 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 XCTest import BrightFutures class Counter { var i: Int = 0 } class ExecutionContextTests: XCTestCase { func testImmediateOnMainThreadContextOnMainThread() { let counter = Counter() counter.i = 1 immediateOnMainExecutionContext { XCTAssert(Thread.isMainThread) counter.i = 2 } XCTAssertEqual(counter.i, 2) } func testImmediateOnMainThreadContextOnBackgroundThread() { let e = self.expectation() DispatchQueue.global().async { immediateOnMainExecutionContext { XCTAssert(Thread.isMainThread) e.fulfill() } } self.waitForExpectations(timeout: 2, handler: nil) } func testDispatchQueueToContext() { let key = DispatchSpecificKey<String>() let value1 = "abc" let queue1 = DispatchQueue(label: "test1", qos: DispatchQoS.default, attributes: [], autoreleaseFrequency: .inherit, target: nil) queue1.setSpecific(key: key, value: value1) let e1 = self.expectation() queue1.context { XCTAssertEqual(DispatchQueue.getSpecific(key: key), value1) e1.fulfill() } let value2 = "def" let queue2 = DispatchQueue(label: "test2", qos: DispatchQoS.default, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil) queue2.setSpecific(key: key, value: value2) let e2 = self.expectation() queue2.context { XCTAssertEqual(DispatchQueue.getSpecific(key: key), value2) e2.fulfill() } self.waitForExpectations(timeout: 2, handler: nil) } }
b0b569ca52ca666cb88cdb18629966c6
33.809524
146
0.652873
false
true
false
false
sunweifeng/SWFKit
refs/heads/master
SWFKit/Classes/Extend/URL+Helper.swift
mit
1
// // URL+Helper.swift // SWFKit // // Created by 孙伟峰 on 2016/12/12. // Copyright © 2017年 Sun Weifeng. All rights reserved. // import UIKit public extension URL { public func getQuery() -> Dictionary<String, String>? { var dict = Dictionary<String, String>() guard let queryStr = self.query else { return nil } let queryArr = queryStr.components(separatedBy: "&") for queryItemStr in queryArr { let queryItemArr = queryItemStr.components(separatedBy: "=") if queryItemArr.count == 2 { let name = queryItemArr[0] let value = queryItemArr[1] dict[name] = value } } return dict } }
eff82de97b5fba12e1a9eaa782c1d039
25.607143
72
0.558389
false
false
false
false