repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
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
darincon/MaskedLabel
refs/heads/master
MaskedLabel/MaskedLabel.swift
mit
1
// // MaskedLabel.swift // MaskedLabel // // Created by Diego Rincon on 4/17/17. // Copyright © 2017 Scire Studios. All rights reserved. // import UIKit public enum FillOption { case background, text } open class MaskedLabel: UILabel { /// An array of UIColor that defines the gradient. If it contains only one /// element, it will be applied as start and end color. In case this property /// is nil or an empty array, the value of fillColor will be used instead. open var gradientColors: [UIColor]? /// The location for each color provided in components. Each location must be a /// CGFloat value in the range of 0 to 1, inclusive. If 0 and 1 are not in the /// locations array, Quartz uses the colors provided that are closest to 0 and /// 1 for those locations. open var gradientLocations: [CGFloat]? /// The coordinate that defines the starting point of the gradient. open var startPoint: CGPoint? /// The coordinate that defines the ending point of the gradient. open var endPoint: CGPoint? /// Set this property when a constant color is needed instead of a gradient. /// If both this property and gradientColors are set, this color is omitted /// and the gradient will be applied to the text. The default value is /// UIColor.black. open var fillColor: UIColor = UIColor.black /// A constant indicating if the gradient, or color, will be applied to the /// label's background, making the text transparent, or to the text. open var fillOption = FillOption.text // TODO: Change to private internal var colorComponents: [CGFloat]? { get { guard let gradientColors = gradientColors, gradientColors.count > 0 else { return nil } var colorComponents = [CGFloat]() for color in gradientColors { var red = CGFloat(0.0) var green = CGFloat(0.0) var blue = CGFloat(0.0) var alpha = CGFloat(0.0) color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) colorComponents += [red, green, blue, alpha] } if colorComponents.count <= 4 { colorComponents += colorComponents } return colorComponents } } public init() { super.init(frame: CGRect.zero) commonInit() } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { textColor = UIColor.white } override open func drawText(in rect: CGRect) { super.drawText(in: rect) let context = UIGraphicsGetCurrentContext() defer { context?.restoreGState() } guard let mask = context?.mask(with: fillOption) else { return } context?.saveGState() context?.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: rect.height)) context?.clear(rect) context?.clip(to: rect, mask: mask) if let colorComponents = colorComponents { let startPoint = self.startPoint ?? CGPoint(x: rect.minX, y: rect.minY) let endPoint = self.endPoint ?? CGPoint(x: rect.maxX, y: rect.maxY) context?.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: rect.height)) context?.drawGradient(withColorComponents: colorComponents, locations: gradientLocations, startPoint: startPoint, endPoint: endPoint) } else { context?.fill(rect, with: fillColor) } } }
c3a22d2de3451f3c268cb983b30aa149
31.422764
145
0.582748
false
false
false
false
1457792186/JWSwift
refs/heads/0331
AlamofireSwift/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift
apache-2.0
56
// // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /** * KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher. */ public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]() /** Items could be added into KingfisherOptionsInfo. */ public enum KingfisherOptionsInfoItem { /// The associated value of this member should be an ImageCache object. Kingfisher will use the specified /// cache object when handling related operations, including trying to retrieve the cached images and store /// the downloaded image to it. case targetCache(ImageCache) /// The associated value of this member should be an ImageDownloader object. Kingfisher will use this /// downloader to download the images. case downloader(ImageDownloader) /// Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `ForceTransition` as well. case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used. case downloadPriority(Float) /// If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource. case forceRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `Transition` option for more. case forceTransition /// If set, `Kingfisher` will only cache the value in memory but not in disk. case cacheMemoryOnly /// If set, `Kingfisher` will only try to retrieve the image from cache not from network. case onlyFromCache /// Decode the image in background thread before using. case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks. case callbackDispatchQueue(DispatchQueue?) /// The associated value of this member will be used as the scale factor when converting retrieved data to an image. /// It is the image scale, instead of your screen scale. You may need to specify the correct scale when you dealing /// with 2x or 3x retina images. case scaleFactor(CGFloat) /// Whether all the GIF data should be preloaded. Default it false, which means following frames will be /// loaded on need. If true, all the GIF data will be loaded and decoded into memory. This option is mainly /// used for back compatibility internally. You should not set it directly. `AnimatedImageView` will not preload /// all data, while a normal image view (`UIImageView` or `NSImageView`) will load all data. Choose to use /// corresponding image view type instead of setting this option. case preloadAllGIFData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the request. You can modify the request for some customizing purpose, /// such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original request /// will be sent without any modification by default. case requestModifier(ImageDownloadRequestModifier) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happenes when you are using /// KingfisherManager or the image extension methods), the converted image will also be sent to cache as well as the /// image view. `DefaultImageProcessor.default` will be used by default. case processor(ImageProcessor) /// Supply an `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// `DefaultCacheSerializer.default` will be used by default. case cacheSerializer(CacheSerializer) /// Keep the existing image while setting another image to an image view. /// By setting this option, the placeholder image parameter of imageview extension method /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading } precedencegroup ItemComparisonPrecedence { associativity: none higherThan: LogicalConjunctionPrecedence } infix operator <== : ItemComparisonPrecedence // This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values. func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool { switch (lhs, rhs) { case (.targetCache(_), .targetCache(_)): return true case (.downloader(_), .downloader(_)): return true case (.transition(_), .transition(_)): return true case (.downloadPriority(_), .downloadPriority(_)): return true case (.forceRefresh, .forceRefresh): return true case (.forceTransition, .forceTransition): return true case (.cacheMemoryOnly, .cacheMemoryOnly): return true case (.onlyFromCache, .onlyFromCache): return true case (.backgroundDecode, .backgroundDecode): return true case (.callbackDispatchQueue(_), .callbackDispatchQueue(_)): return true case (.scaleFactor(_), .scaleFactor(_)): return true case (.preloadAllGIFData, .preloadAllGIFData): return true case (.requestModifier(_), .requestModifier(_)): return true case (.processor(_), .processor(_)): return true case (.cacheSerializer(_), .cacheSerializer(_)): return true case (.keepCurrentImageWhileLoading, .keepCurrentImageWhileLoading): return true default: return false } } extension Collection where Iterator.Element == KingfisherOptionsInfoItem { func firstMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? { return index { $0 <== target }.flatMap { self[$0] } } func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] { return self.filter { !($0 <== target) } } } public extension Collection where Iterator.Element == KingfisherOptionsInfoItem { /// The target `ImageCache` which is used. public var targetCache: ImageCache { if let item = firstMatchIgnoringAssociatedValue(.targetCache(.default)), case .targetCache(let cache) = item { return cache } return ImageCache.default } /// The `ImageDownloader` which is specified. public var downloader: ImageDownloader { if let item = firstMatchIgnoringAssociatedValue(.downloader(.default)), case .downloader(let downloader) = item { return downloader } return ImageDownloader.default } /// Member for animation transition when using UIImageView. public var transition: ImageTransition { if let item = firstMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = item { return transition } return ImageTransition.none } /// A `Float` value set as the priority of image download task. The value for it should be /// between 0.0~1.0. public var downloadPriority: Float { if let item = firstMatchIgnoringAssociatedValue(.downloadPriority(0)), case .downloadPriority(let priority) = item { return priority } return URLSessionTask.defaultPriority } /// Whether an image will be always downloaded again or not. public var forceRefresh: Bool { return contains{ $0 <== .forceRefresh } } /// Whether the transition should always happen or not. public var forceTransition: Bool { return contains{ $0 <== .forceTransition } } /// Whether cache the image only in memory or not. public var cacheMemoryOnly: Bool { return contains{ $0 <== .cacheMemoryOnly } } /// Whether only load the images from cache or not. public var onlyFromCache: Bool { return contains{ $0 <== .onlyFromCache } } /// Whether the image should be decoded in background or not. public var backgroundDecode: Bool { return contains{ $0 <== .backgroundDecode } } /// Whether the image data should be all loaded at once if it is a GIF. public var preloadAllGIFData: Bool { return contains { $0 <== .preloadAllGIFData } } /// The queue of callbacks should happen from Kingfisher. public var callbackDispatchQueue: DispatchQueue { if let item = firstMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)), case .callbackDispatchQueue(let queue) = item { return queue ?? DispatchQueue.main } return DispatchQueue.main } /// The scale factor which should be used for the image. public var scaleFactor: CGFloat { if let item = firstMatchIgnoringAssociatedValue(.scaleFactor(0)), case .scaleFactor(let scale) = item { return scale } return 1.0 } /// The `ImageDownloadRequestModifier` will be used before sending a download request. public var modifier: ImageDownloadRequestModifier { if let item = firstMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)), case .requestModifier(let modifier) = item { return modifier } return NoModifier.default } /// `ImageProcessor` for processing when the downloading finishes. public var processor: ImageProcessor { if let item = firstMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)), case .processor(let processor) = item { return processor } return DefaultImageProcessor.default } /// `CacheSerializer` to convert image to data for storing in cache. public var cacheSerializer: CacheSerializer { if let item = firstMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)), case .cacheSerializer(let cacheSerializer) = item { return cacheSerializer } return DefaultCacheSerializer.default } /// Keep the existing image while setting another image to an image view. /// Or the placeholder will be used while downloading. public var keepCurrentImageWhileLoading: Bool { return contains { $0 <== .keepCurrentImageWhileLoading } } }
20b2a0fb3d40fbd07720021edfbd6041
42.933333
159
0.698746
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Notifications/Scheduling Local Notifications/Scheduling Local Notifications/AppDelegate.swift
mit
1
// // AppDelegate.swift // Scheduling Local Notifications // // Created by Domenico Solazzo on 15/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /* First ask the user if we are allowed to perform local notifications */ let settings = UIUserNotificationSettings(types: .alert, categories: nil) application.registerUserNotificationSettings(settings) return true } func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { if notificationSettings.types == nil{ /* The user did not allow us to send notifications */ return } let notification = UILocalNotification() // This is a property of type NSDate that dictates to iOS // when the instance of the local notification has to be fired. This is required. notification.fireDate = Date(timeIntervalSinceNow: 8) // The time zone in which the given fire-date is specified notification.timeZone = Calendar.current.timeZone // The text that has to be displayed to the user when // your notification is displayed on screen notification.alertBody = "A new item has been downloaded" notification.hasAction = true // It represents the action that the user can take on your local notification notification.alertAction = "View" // The badge number for your app icon notification.applicationIconBadgeNumber += 1 // More additional information about the local notification notification.userInfo = [ "Key 1": "Value1", "Key 2": "Value2" ] /* Schedule the notification */ application.scheduleLocalNotification(notification) } }
9c269b617dacc21570c417f385c0214d
32.484375
144
0.644424
false
false
false
false
zpz1237/NirBillBoard
refs/heads/master
NirBillboard/AppDelegate.swift
mit
1
// // AppDelegate.swift // NirBillboard // // Created by Nirvana on 7/11/15. // Copyright © 2015 NSNirvana. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let userHasOnboardedKey = "user_has_onboarded" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() application.statusBarStyle = .LightContent let userHasOnboardedAlready = NSUserDefaults.standardUserDefaults().boolForKey(userHasOnboardedKey); if userHasOnboardedAlready { //如只想第一次打开应用时显示,使用这行代码 //self.setupNormalRootVC(false); //测试用代码 self.window!.rootViewController = self.generateOnboardingViewController() } // Otherwise the user hasn't onboarded yet, so set the root view controller for the application to the // onboarding view controller generated and returned by this method. else { self.window!.rootViewController = self.generateOnboardingViewController() } //这句好像并没有什么卵用 self.window!.makeKeyAndVisible() return true } func generateOnboardingViewController() -> OnboardingViewController { let firstPage: OnboardingContentViewController = OnboardingContentViewController(title: "What A Beautiful Photo", body: "This city background image is so beautiful", image: UIImage(named: "blue"), buttonText: "") { } let secondPage: OnboardingContentViewController = OnboardingContentViewController(title: "I'm So Sorry", body: "I can't get over the nice blurry background photo.", image: UIImage(named: "red"), buttonText: "Start") { self.handleOnboardingCompletion() } let onboardingVC: OnboardingViewController = OnboardingViewController(backgroundImage: UIImage(named: "Background"), contents: [firstPage, secondPage]) return onboardingVC } func handleOnboardingCompletion() { // Now that we are done onboarding, we can set in our NSUserDefaults that we've onboarded now, so in the // future when we launch the application we won't see the onboarding again. NSUserDefaults.standardUserDefaults().setBool(true, forKey: userHasOnboardedKey) // Setup the normal root view controller of the application, and set that we want to do it animated so that // the transition looks nice from onboarding to normal app. setupNormalRootVC(true) } //展示主页面函数:此处以代码方式设置主页面 func setupNormalRootVC(animated : Bool) { // Here I'm just creating a generic view controller to represent the root of my application. let storyBoard = UIStoryboard(name: "Main", bundle: nil) let mainVC = storyBoard.instantiateViewControllerWithIdentifier("TabBarViewID") // If we want to animate it, animate the transition - in this case we're fading, but you can do it // however you want. if animated { UIView.transitionWithView(self.window!, duration: 0.5, options:.TransitionCrossDissolve, animations: { () -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.window!.rootViewController = mainVC }) //self.window!.rootViewController = mainVC }, completion:nil) } // Otherwise we just want to set the root view controller normally. else { self.window?.rootViewController = mainVC; } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
2e0b22ea4afda00004483bcef5df3665
44.15748
285
0.670619
false
false
false
false
izotx/iTenWired-Swift
refs/heads/master
ItenWired+NSDate.swift
bsd-2-clause
1
// // ItenWired+NSDate.swift // Conference App // // Created by Felipe N. Brito on 7/21/16. // // import Foundation extension NSDate { func isGreaterThanDate(dateToCompare: NSDate) -> Bool { var isGreater = false if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending { isGreater = true } return isGreater } func isLessThanDate(dateToCompare: NSDate) -> Bool { var isLess = false if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending { isLess = true } return isLess } func equalToDate(dateToCompare: NSDate) -> Bool { var isEqualTo = false if self.compare(dateToCompare) == NSComparisonResult.OrderedSame { isEqualTo = true } return isEqualTo } func addDays(daysToAdd: Int) -> NSDate { let secondsInDays: NSTimeInterval = Double(daysToAdd) * 60 * 60 * 24 let dateWithDaysAdded: NSDate = self.dateByAddingTimeInterval(secondsInDays) return dateWithDaysAdded } func addHours(hoursToAdd: Int) -> NSDate { let secondsInHours: NSTimeInterval = Double(hoursToAdd) * 60 * 60 let dateWithHoursAdded: NSDate = self.dateByAddingTimeInterval(secondsInHours) return dateWithHoursAdded } func addSeconds(secondsToAdd: Double) -> NSDate { let seconds: NSTimeInterval = secondsToAdd let dateWithSecondsAdded: NSDate = self.dateByAddingTimeInterval(seconds) return dateWithSecondsAdded } }
a6a4004d0c5fc533932d8cffcda52d73
25.571429
86
0.61327
false
false
false
false
AnthonyMDev/QueryGenie
refs/heads/master
QueryGenie/CoreData/AttributeQueryProtocol.swift
mit
1
// // AttributeQueryProtocol.swift // // Created by Anthony Miller on 1/4/17. // import Foundation import CoreData /// A query that can be executed to fetch a dictionary of properties on core data objects. public protocol AttributeQueryProtocol: CoreDataQueryable { var returnsDistinctResults: Bool { get set } var propertiesToFetch: [String] { get set } } /* * MARK: - Distinct */ extension AttributeQueryProtocol { public func distinct() -> Self { var clone = self clone.returnsDistinctResults = true return self } } /* * MARK: - GenericQueryable */ extension AttributeQueryProtocol { public func objects() -> AnyCollection<Self.Element> { do { let fetchRequest = self.toFetchRequest() as NSFetchRequest<NSDictionary> fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType var results: [Self.Element] = [] let dicts: [NSDictionary] if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { dicts = try fetchRequest.execute() } else { dicts = try self.context.fetch(fetchRequest) } try dicts.forEach { guard $0.count == 1, let value = $0.allValues.first as? Self.Element else { throw Error.unexpectedValue($0) } results.append(value) } return AnyCollection(results) } catch { return AnyCollection<Self.Element>([]) } } } extension AttributeQueryProtocol where Self.Element: NSDictionary { public func objects() -> AnyCollection<Self.Element> { do { return try AnyCollection(self.context.fetch(self.toFetchRequest() as NSFetchRequest<Self.Element>)) } catch { return AnyCollection<Self.Element>([]) } } } /* * MARK: - CoreDataQueryable */ extension AttributeQueryProtocol where Self.Element: NSDictionary { public final func toFetchRequest<ResultType: NSFetchRequestResult>() -> NSFetchRequest<ResultType> { let fetchRequest = NSFetchRequest<ResultType>() fetchRequest.entity = self.entityDescription fetchRequest.fetchOffset = self.offset fetchRequest.fetchLimit = self.limit fetchRequest.fetchBatchSize = (self.limit > 0 && self.batchSize > self.limit ? 0 : self.batchSize) fetchRequest.predicate = self.predicate fetchRequest.sortDescriptors = self.sortDescriptors fetchRequest.resultType = .dictionaryResultType fetchRequest.returnsDistinctResults = self.returnsDistinctResults fetchRequest.propertiesToFetch = self.propertiesToFetch return fetchRequest } }
928ad4da6b7c24c4d1693df41e6dc09e
25.90991
111
0.59692
false
false
false
false
cxpyear/spdbapp
refs/heads/master
spdbapp/spdbapp/MainViewController.swift
bsd-3-clause
1
// // ViewController.swift // spdbapp // // Created by tommy on 15/5/7. // Copyright (c) 2015年 shgbit. All rights reserved. // import UIKit import Foundation import Alamofire class MainViewController: UIViewController,UIAlertViewDelegate { @IBOutlet weak var btnConf: UIButton! @IBOutlet weak var lbConfName: UILabel! @IBOutlet weak var btnReconnect: UIButton! @IBOutlet weak var lblShowState: UILabel! @IBOutlet weak var btnRegister: UIButton! @IBOutlet weak var lblShowUserName: UILabel! var current = GBMeeting() var local = GBBox() var settingsBundle = SettingsBundleConfig() var timer = Poller() var flag = false override func viewDidLoad() { super.viewDidLoad() var style = NSMutableParagraphStyle() style.lineSpacing = 20 style.alignment = NSTextAlignment.Center var attr = [NSParagraphStyleAttributeName : style] var name = "暂无会议" lbConfName.attributedText = NSAttributedString(string: name, attributes : attr) //初始化时候btnconf背景颜色为灰色,点击无效 btnConf.layer.cornerRadius = 8 btnConf.backgroundColor = UIColor.grayColor() btnConf.enabled = false btnRegister.layer.cornerRadius = 8 btnRegister.enabled = false btnRegister.backgroundColor = UIColor.grayColor() // btnRegister.addTarget(self, action: "toRegis", forControlEvents: UIControlEvents.TouchUpInside) timer.start(self, method: "checkstatus:",timerInter: 5.0) btnReconnect.addTarget(self, action: "getReconn", forControlEvents: UIControlEvents.TouchUpInside) btnReconnect.layer.cornerRadius = 8 if appManager.netConnect == true { ShowToolbarState.netConnectSuccess(self.lblShowState,btn: self.btnReconnect) } var options = NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old appManager.addObserver(self, forKeyPath: "current", options: options, context: nil) appManager.addObserver(self, forKeyPath: "local", options: options, context: nil) createFile() var loginPoller = Poller() loginPoller.start(self, method: "getValue", timerInter: 2.0) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { // Create a new variable to store the instance of DocViewController if segue.identifier == "ToAgendaVC" { //ToAgendaVC var obj = segue.destinationViewController as! AgendaViewController obj.meetingName = self.lbConfName.text! } } func getName() -> Bool{ var filePath = NSHomeDirectory().stringByAppendingPathComponent("Documents/UserInfo.txt") var readData = NSData(contentsOfFile: filePath) var name = NSString(data: readData!, encoding: NSUTF8StringEncoding)! as NSString if (name.length > 0 && appManager.netConnect == true){ self.lblShowUserName.text = "当前用户:\(name)" return true } return false } func getValue(){ if getName() == true { self.btnRegister.hidden = true self.btnConf.enabled = true btnConf.backgroundColor = UIColor(red: 123/255, green: 0/255, blue: 31/255, alpha: 1.0) } } func createFile() { var filePath = NSHomeDirectory().stringByAppendingPathComponent("Documents/UserInfo.txt") NSFileManager.defaultManager().removeItemAtPath(filePath, error: nil) var b = NSFileManager.defaultManager().fileExistsAtPath(filePath) ? true :false if b == false{ var isCreateFile: Bool = NSFileManager.defaultManager().createFileAtPath(filePath, contents: nil, attributes: nil) if isCreateFile == true{ println("uasername文件创建成功") } } } func toRegis(){ let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let loginVC: RegisViewController = storyboard.instantiateViewControllerWithIdentifier("view") as! RegisViewController loginVC.modalPresentationStyle = UIModalPresentationStyle.CurrentContext self.presentViewController(loginVC, animated: false, completion: nil) } //页面下方的“重连”按钮出发的事件 func getReconn(){ ShowToolbarState.netConnectLinking(self.lblShowState, btn: self.btnReconnect) appManager.starttimer() } //定时器,每隔5s刷新页面下方的toolbar控件显示 func checkstatus(timer: NSTimer){ if appManager.netConnect == true { ShowToolbarState.netConnectSuccess(self.lblShowState,btn: self.btnReconnect) self.btnRegister.enabled = true self.btnRegister.backgroundColor = UIColor(red: 123/255, green: 0, blue: 31/255, alpha: 1) self.btnRegister.addTarget(self, action: "toRegis", forControlEvents: UIControlEvents.TouchUpInside) } else{ ShowToolbarState.netConnectFail(self.lblShowState,btn: self.btnReconnect) } self.lblShowState.reloadInputViews() self.btnReconnect.reloadInputViews() } override func viewDidAppear(animated: Bool) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "defaultsSettingsChanged", name: NSUserDefaultsDidChangeNotification, object: nil) } override func viewDidDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self) } func defaultsSettingsChanged() { let standardDefaults = NSUserDefaults.standardUserDefaults() // 监听txtFileURL是否发生改变 默认情况下是192.168.16.142 var value = standardDefaults.stringForKey("txtBoxURL") println("value = \(value)") if (value?.isEmpty == true){ standardDefaults.setObject("192.168.16.142", forKey: "txtBoxURL") standardDefaults.synchronize() } println("url new value ============ \(value)") standardDefaults.synchronize() var isClearHistoryInfo = standardDefaults.boolForKey("clear_historyInfo") println("isclearpdffile = \(isClearHistoryInfo)") if isClearHistoryInfo == true{ server.clearHistoryInfo("pdf") isClearHistoryInfo = false standardDefaults.synchronize() } var isClearConfigInfo = standardDefaults.boolForKey("clear_configInfo") if isClearConfigInfo == true{ server.clearHistoryInfo("txt") isClearHistoryInfo = false standardDefaults.synchronize() } } //监听会议名是否发生改变 private var myContext = 1 //显示当前会议名 override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if keyPath == "current"{ if !object.current.name.isEmpty{ self.lbConfName.text = object.current.name } } if keyPath == "local"{ if object.local.name.isEmpty{ UIAlertView(title: "当前id未注册", message: "请先注册id", delegate: self, cancelButtonTitle: "确定").show() } } } deinit{ appManager.removeObserver(self, forKeyPath: "current", context: &myContext) appManager.removeObserver(self, forKeyPath: "local",context: &myContext) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
f0615b9c110f89c3c747a8d26e7a0145
33.070485
156
0.636928
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/UIScrollViewDemo/UIScrollViewDemo/BannerView/CycleView.swift
mit
1
// // Copyright © 2016年 xiAo_Ju. All rights reserved. // import UIKit class CycleView: UIView, UIScrollViewDelegate { // MARK: - 🍀 变量 var scrollView: UIScrollView! var page = 0 // 当前处于的页面,默认为0 private var imageViewX: CGFloat = 0 var canCycle = true // 能否循环 var canAutoRun: Bool = true { // 能否自动滑动 didSet { if canAutoRun { timerInit() } else { timer?.invalidate() timer = nil } } } var timer: Timer? // 计时器(用来控制自动滑动) // MARK: - 💖 初始化 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white scrollView = UIScrollView(frame: CGRect(origin: CGPoint.zero, size: frame.size)) scrollView.isPagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.isUserInteractionEnabled = false // 这句和下一句可以让点击响应到父类 #SO addGestureRecognizer(scrollView.panGestureRecognizer) addSubview(scrollView) scrollView.delegate = self } // MARK: - 💜 UIScrollViewDelegate func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if canAutoRun { // 计时器 inValidate timer?.invalidate() timer = nil } } func scrollViewDidScroll(_ scrollView: UIScrollView) { page = Int(scrollView.contentOffset.x / scrollView.frame.width) if canCycle { if page <= 0 { let value = data.count - 2 if scrollView.contentOffset.x < scrollView.frame.width / 2 && (value >= 0) { scrollView.contentOffset.x = scrollView.frame.width * CGFloat(value) + scrollView.contentOffset.x } } else if page >= data.count - 1 { // 最后一个 scrollView.contentOffset.x = scrollView.frame.width } else { } // 卡顿版本 // let count = data.count // if scrollView.contentOffset.x == 0.0 { // scrollView.contentOffset.x = scrollView.frame.width * CGFloat(count - 2) // } else if scrollView.contentOffset.x == scrollView.frame.width * CGFloat(count - 1) { // scrollView.contentOffset.x = scrollView.frame.width // } } } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { timerInit() } var data: [String]! func set(contents: [String]) { data = [contents[0]] + contents + [contents[contents.count - 1]] let width = scrollView.frame.width scrollView.contentSize = CGSize(width: width * CGFloat(data.count), height: scrollView.frame.height) for (i, _) in data.enumerated() { let contentLabel = UILabel(frame: CGRect(x: CGFloat(i) * width, y: 0, width: width, height: scrollView.frame.height)) contentLabel.text = i.description contentLabel.font = UIFont.systemFont(ofSize: 58) contentLabel.textAlignment = .center contentLabel.textColor = .white contentLabel.backgroundColor = UIColor(white: CGFloat(i) / 10, alpha: 1) contentLabel.tag = i scrollView.addSubview(contentLabel) } scrollView.contentOffset.x = scrollView.frame.width timerInit() } func timerInit() { if canAutoRun { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(autoSetCurrentContentOffset), userInfo: nil, repeats: true) } } @objc func autoSetCurrentContentOffset() { // let n = Int(scrollView.contentOffset.x / scrollView.frame.width) // 放开这句解决不能滚动整屏 let n = scrollView.contentOffset.x / scrollView.frame.width let x = CGFloat(n) * scrollView.frame.width scrollView.setContentOffset(CGPoint(x: x + scrollView.frame.width, y: scrollView.contentOffset.y), animated: true) } }
209698fbaa3116d0f4f4242444044681
35.275862
151
0.583888
false
false
false
false
bingoogolapple/SwiftNote-PartOne
refs/heads/master
CustomTableViewCellCode/CustomTableViewCellCode/ChatCell.swift
apache-2.0
1
// // ChatCell.swift // CustomTableViewCellCode // // Created by bingoogol on 14/8/21. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ChatCell: UITableViewCell { var iconIv:UIImageView! var msgBtn:UIButton! override init(style: UITableViewCellStyle, reuseIdentifier: String) { super.init(style: style, reuseIdentifier: reuseIdentifier) // 实例化图像视图 var imageView = UIImageView() imageView.frame = CGRect(x: 10, y: 10, width: 60, height: 60) imageView.image = UIImage(named: "0.png") self.contentView.addSubview(imageView) iconIv = imageView // 实例化聊天按钮 var button : UIButton! = UIButton.buttonWithType(UIButtonType.Custom) as UIButton button.frame = CGRect(x: 100, y: 10, width: 200, height: 60) var normalImage = UIImage(named:"chatfrom_bg_normal.png") var leftCap = Int(normalImage.size.width) / 2 var topCap = Int(normalImage.size.height) / 2 normalImage = normalImage.stretchableImageWithLeftCapWidth(leftCap, topCapHeight: topCap) button.setBackgroundImage(normalImage, forState: UIControlState.Normal) var highlightImage = UIImage(named:"chatfrom_bg_focused.png") highlightImage = highlightImage.stretchableImageWithLeftCapWidth(leftCap, topCapHeight: topCap) button.setBackgroundImage(highlightImage, forState: UIControlState.Highlighted) button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) self.contentView.addSubview(button) msgBtn = button } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
83c24ecf92c6b395f65c1c90989afc42
35.617021
103
0.680233
false
false
false
false
Ivacker/swift
refs/heads/master
stdlib/public/core/LazyCollection.swift
apache-2.0
10
//===--- LazyCollection.swift ---------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A collection on which normally-eager operations such as `map` and /// `filter` are implemented lazily. /// /// Please see `LazySequenceType` for background; `LazyCollectionType` /// is an analogous component, but for collections. /// /// To add new lazy collection operations, extend this protocol with /// methods that return lazy wrappers that are themselves /// `LazyCollectionType`s. /// /// - See Also: `LazySequenceType`, `LazyCollection` public protocol LazyCollectionType : CollectionType, LazySequenceType { /// A `CollectionType` that can contain the same elements as this one, /// possibly with a simpler type. /// /// - See also: `elements` typealias Elements: CollectionType = Self } /// When there's no special associated `Elements` type, the `elements` /// property is provided. extension LazyCollectionType where Elements == Self { /// Identical to `self`. public var elements: Self { return self } } /// A collection containing the same elements as a `Base` collection, /// but on which some operations such as `map` and `filter` are /// implemented lazily. /// /// - See also: `LazySequenceType`, `LazyCollection` public struct LazyCollection<Base : CollectionType> : LazyCollectionType { /// The type of the underlying collection public typealias Elements = Base /// The underlying collection public var elements: Elements { return _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = Base.Index /// Construct an instance with `base` as its underlying Collection /// instance. public init(_ base: Base) { self._base = base } internal var _base: Base } /// Forward implementations to the base collection, to pick up any /// optimizations it might implement. extension LazyCollection : SequenceType { /// Return a *generator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func generate() -> Base.Generator { return _base.generate() } /// Return a value less than or equal to the number of elements in /// `self`, **nondestructively**. /// /// - Complexity: O(N). public func underestimateCount() -> Int { return _base.underestimateCount() } public func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Base.Generator.Element> { return _base._copyToNativeArrayBuffer() } public func _initializeTo( ptr: UnsafeMutablePointer<Base.Generator.Element> ) -> UnsafeMutablePointer<Base.Generator.Element> { return _base._initializeTo(ptr) } public func _customContainsEquatableElement( element: Base.Generator.Element ) -> Bool? { return _base._customContainsEquatableElement(element) } } extension LazyCollection : CollectionType { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. public var startIndex: Base.Index { return _base.startIndex } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Base.Index { return _base.endIndex } /// Access the element at `position`. /// /// - Requires: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(position: Base.Index) -> Base.Generator.Element { return _base[position] } /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) public subscript(bounds: Range<Index>) -> LazyCollection<Slice<Base>> { return Slice(base: _base, bounds: bounds).lazy } /// Returns `true` iff `self` is empty. public var isEmpty: Bool { return _base.isEmpty } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndexType`; /// O(N) otherwise. public var count: Index.Distance { return _base.count } // The following requirement enables dispatching for indexOf when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; /// `nil` otherwise. /// /// - Complexity: O(N). public func _customIndexOfEquatableElement( element: Base.Generator.Element ) -> Index?? { return _base._customIndexOfEquatableElement(element) } /// Returns the first element of `self`, or `nil` if `self` is empty. public var first: Base.Generator.Element? { return _base.first } @available(*, unavailable, renamed="Base") public typealias S = Void } /// Augment `self` with lazy methods such as `map`, `filter`, etc. extension CollectionType { /// A collection with contents identical to `self`, but on which /// normally-eager operations such as `map` and `filter` are /// implemented lazily. /// /// - See Also: `LazySequenceType`, `LazyCollectionType`. public var lazy: LazyCollection<Self> { return LazyCollection(self) } } extension LazyCollectionType { /// Identical to `self`. public var lazy: Self { // Don't re-wrap already-lazy collections return self } } @available(*, unavailable, message="Please use the collection's '.lazy' property") public func lazy<Base : CollectionType>(s: Base) -> LazyCollection<Base> { fatalError("unavailable") } @available(*, unavailable, renamed="LazyCollection") public struct LazyForwardCollection<T> {} @available(*, unavailable, renamed="LazyCollection") public struct LazyBidirectionalCollection<T> {} @available(*, unavailable, renamed="LazyCollection") public struct LazyRandomAccessCollection<T> {} // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
115464e479ee3000b5d7b4ee818abc87
30.377451
82
0.680987
false
false
false
false
lfaoro/Cast
refs/heads/master
Carthage/Checkouts/RxSwift/RxTests/RxSwiftTests/Tests/Observable+BindingTest.swift
mit
1
// // Observable+BindingTest.swift // RxSwift // // Created by Krunoslav Zaher on 4/15/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import XCTest import RxSwift class ObservableBindingTest : RxTest { } // refCount extension ObservableBindingTest { func testRefCount_DeadlockSimple() { let subject = MySubject<Int>() var nEvents = 0 let observable = TestConnectableObservable(o: sequenceOf(0, 1, 2), s: subject) let _d = observable .subscribeNext { n in nEvents++ } .scopedDispose observable.connect().dispose() XCTAssertEqual(nEvents, 3) } func testRefCount_DeadlockErrorAfterN() { let subject = MySubject<Int>() var nEvents = 0 let observable = TestConnectableObservable(o: [sequenceOf(0, 1, 2), failWith(testError)].concat(), s: subject) let _d = observable.subscribeError { n in nEvents++ } .scopedDispose observable.connect().dispose() XCTAssertEqual(nEvents, 1) } func testRefCount_DeadlockErrorImmediatelly() { let subject = MySubject<Int>() var nEvents = 0 let observable = TestConnectableObservable(o: failWith(testError), s: subject) let _d = observable.subscribeError { n in nEvents++ } .scopedDispose observable.connect().dispose() XCTAssertEqual(nEvents, 1) } func testRefCount_DeadlockEmpty() { let subject = MySubject<Int>() var nEvents = 0 let observable = TestConnectableObservable(o: empty(), s: subject) let d = observable.subscribeCompleted { nEvents++ } .scopedDispose observable.connect().dispose() XCTAssertEqual(nEvents, 1) } func testRefCount_ConnectsOnFirst() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 1), next(220, 2), next(230, 3), next(240, 4), completed(250) ]) let subject = MySubject<Int>() let conn = TestConnectableObservable(o: xs, s: subject) let res = scheduler.start { conn.refCount() } XCTAssertEqual(res.messages, [ next(210, 1), next(220, 2), next(230, 3), next(240, 4), completed(250) ]) XCTAssertTrue(subject.diposed) } func testRefCount_NotConnected() { _ = TestScheduler(initialClock: 0) var disconnected = false var count = 0 let xs: Observable<Int> = deferred { count++ return create { obs in return AnonymousDisposable { disconnected = true } } } let subject = MySubject<Int>() let conn = TestConnectableObservable(o: xs, s: subject) let refd = conn .refCount() let dis1 = refd.subscribe(NopObserver()) XCTAssertEqual(1, count) XCTAssertEqual(1, subject.subscribeCount) XCTAssertFalse(disconnected) let dis2 = refd.subscribe(NopObserver()) XCTAssertEqual(1, count) XCTAssertEqual(2, subject.subscribeCount) XCTAssertFalse(disconnected) dis1.dispose() XCTAssertFalse(disconnected) dis2.dispose() XCTAssertTrue(disconnected) disconnected = false let dis3 = refd.subscribe(NopObserver()) XCTAssertEqual(2, count) XCTAssertEqual(3, subject.subscribeCount) XCTAssertFalse(disconnected) dis3.dispose() XCTAssertTrue(disconnected); } func testRefCount_Error() { let xs: Observable<Int> = failWith(testError) let res = xs.publish().refCount() res .subscribe { event in switch event { case .Next: XCTAssertTrue(false) case .Error(let error): XCTAssertErrorEqual(error, testError) case .Completed: XCTAssertTrue(false) } } res .subscribe { event in switch event { case .Next: XCTAssertTrue(false) case .Error(let error): XCTAssertErrorEqual(error, testError) case .Completed: XCTAssertTrue(false) } } } func testRefCount_Publish() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 1), next(220, 2), next(230, 3), next(240, 4), next(250, 5), next(260, 6), next(270, 7), next(280, 8), next(290, 9), completed(300) ]) let res = xs.publish().refCount() var d1: Disposable! let o1: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(215) { d1 = res.subscribe(o1) } scheduler.scheduleAt(235) { d1.dispose() } var d2: Disposable! let o2: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(225) { d2 = res.subscribe(o2) } scheduler.scheduleAt(275) { d2.dispose() } var d3: Disposable! let o3: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(255) { d3 = res.subscribe(o3) } scheduler.scheduleAt(265) { d3.dispose() } var d4: Disposable! let o4: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(285) { d4 = res.subscribe(o4) } scheduler.scheduleAt(320) { d4.dispose() } scheduler.start() XCTAssertEqual(o1.messages, [ next(220, 2), next(230, 3) ]) XCTAssertEqual(o2.messages, [ next(230, 3), next(240, 4), next(250, 5), next(260, 6), next(270, 7) ]) XCTAssertEqual(o3.messages, [ next(260, 6) ]) XCTAssertEqual(o4.messages, [ next(290, 9), completed(300) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(215, 275), Subscription(285, 300) ]) } } // replay extension ObservableBindingTest { func testReplay_DeadlockSimple() { var nEvents = 0 let observable = sequenceOf(0, 1, 2).replay(3).refCount() _ = observable .subscribeNext { n in nEvents++ } .scopedDispose XCTAssertEqual(nEvents, 3) } func testReplay_DeadlockErrorAfterN() { var nEvents = 0 let observable = [sequenceOf(0, 1, 2), failWith(testError)].concat().replay(3).refCount() _ = observable .subscribeError { n in nEvents++ } .scopedDispose XCTAssertEqual(nEvents, 1) } func testReplay_DeadlockErrorImmediatelly() { var nEvents = 0 let observable: Observable<Int> = failWith(testError).replay(3).refCount() _ = observable.subscribeError { n in nEvents++ } .scopedDispose XCTAssertEqual(nEvents, 1) } func testReplay_DeadlockEmpty() { var nEvents = 0 let observable: Observable<Int> = empty().replay(3).refCount() _ = observable.subscribeCompleted { nEvents++ } .scopedDispose XCTAssertEqual(nEvents, 1) } func testReplay1_DeadlockSimple() { var nEvents = 0 let observable = sequenceOf(0, 1, 2).replay(1).refCount() _ = observable .subscribeNext { n in nEvents++ } .scopedDispose XCTAssertEqual(nEvents, 3) } func testReplay1_DeadlockErrorAfterN() { var nEvents = 0 let observable = [just(0, 1, 2), failWith(testError)].concat().replay(1).refCount() _ = observable.subscribeError { n in nEvents++ } .scopedDispose XCTAssertEqual(nEvents, 1) } func testReplay1_DeadlockErrorImmediatelly() { var nEvents = 0 let observable: Observable<Int> = failWith(testError).replay(1).refCount() _ = observable.subscribeError { n in nEvents++ } .scopedDispose XCTAssertEqual(nEvents, 1) } func testReplay1_DeadlockEmpty() { var nEvents = 0 let observable: Observable<Int> = empty().replay(1).refCount() _ = observable.subscribeCompleted { nEvents++ } .scopedDispose XCTAssertEqual(nEvents, 1) } func testReplayCount_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<ReplaySubject<Int>>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start(); XCTAssertEqual(res.messages, [ next(450, 5), next(450, 6), next(450, 7), next(520, 11), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 550), Subscription(650, 800) ]) } func testReplayCount_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<ReplaySubject<Int>>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start(); XCTAssertEqual(res.messages, [ next(450, 5), next(450, 6), next(450, 7), next(520, 11), next(560, 20), error(600, testError), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayCount_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<ReplaySubject<Int>>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start(); XCTAssertEqual(res.messages, [ next(450, 5), next(450, 6), next(450, 7), next(520, 11), next(560, 20), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayCount_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<ReplaySubject<Int>>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(475) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start(); XCTAssertEqual(res.messages, [ next(450, 5), next(450, 6), next(450, 7), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 550), Subscription(650, 800), ]) } func testReplayOneCount_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<ReplaySubject<Int>>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start(); XCTAssertEqual(res.messages, [ next(450, 7), next(520, 11), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 550), Subscription(650, 800) ]) } func testReplayOneCount_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<ReplaySubject<Int>>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start(); XCTAssertEqual(res.messages, [ next(450, 7), next(520, 11), next(560, 20), error(600, testError), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayOneCount_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<ReplaySubject<Int>>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start(); XCTAssertEqual(res.messages, [ next(450, 7), next(520, 11), next(560, 20), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayOneCount_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<ReplaySubject<Int>>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res: MockObserver<Int> = scheduler.createObserver() scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(475) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start(); XCTAssertEqual(res.messages, [ next(450, 7), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 550), Subscription(650, 800), ]) } }
05732db22779d267cb5c522eed9f642d
29.236
118
0.517529
false
true
false
false
devxoul/Then
refs/heads/master
Sources/Then/Then.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Suyeol Jeon (xoul.kr) // // 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 #if !os(Linux) import CoreGraphics #endif #if os(iOS) || os(tvOS) import UIKit.UIGeometry #endif public protocol Then {} extension Then where Self: Any { /// Makes it available to set properties with closures just after initializing and copying the value types. /// /// let frame = CGRect().with { /// $0.origin.x = 10 /// $0.size.width = 100 /// } @inlinable public func with(_ block: (inout Self) throws -> Void) rethrows -> Self { var copy = self try block(&copy) return copy } /// Makes it available to execute something with closures. /// /// UserDefaults.standard.do { /// $0.set("devxoul", forKey: "username") /// $0.set("[email protected]", forKey: "email") /// $0.synchronize() /// } @inlinable public func `do`(_ block: (Self) throws -> Void) rethrows { try block(self) } } extension Then where Self: AnyObject { /// Makes it available to set properties with closures just after initializing. /// /// let label = UILabel().then { /// $0.textAlignment = .center /// $0.textColor = UIColor.black /// $0.text = "Hello, World!" /// } @inlinable public func then(_ block: (Self) throws -> Void) rethrows -> Self { try block(self) return self } } extension NSObject: Then {} #if !os(Linux) extension CGPoint: Then {} extension CGRect: Then {} extension CGSize: Then {} extension CGVector: Then {} #endif extension Array: Then {} extension Dictionary: Then {} extension Set: Then {} extension JSONDecoder: Then {} extension JSONEncoder: Then {} #if os(iOS) || os(tvOS) extension UIEdgeInsets: Then {} extension UIOffset: Then {} extension UIRectEdge: Then {} #endif
2936e6ee9fb9be1d5ae4e09effeb0269
28.785714
109
0.674889
false
false
false
false
linhaosunny/smallGifts
refs/heads/master
小礼品/小礼品/Classes/Module/Me/Chat/ChatBar/RecordButton.swift
mit
1
// // RecordButton.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/29. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit fileprivate let titleLabelFont = fontSize16 fileprivate let titleLabelColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1.0) fileprivate let normalText = "按住 说话" fileprivate let hightLightText = "松开 结束" fileprivate let cancelText = "送开 取消" fileprivate let hightLightColor = UIColor(white: 0.0, alpha: 0.3) class RecordButton: UIView { //MARK: 属性 weak var delegate:RecordButtonDelegate? //MARK: 懒加载 var titleLabel:UILabel = { let label = UILabel() label.font = fontSize16 label.textColor = titleLabelColor label.textAlignment = .center label.text = normalText return label }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupRecordButton() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // setupRecordButtonSubView() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { backgroundColor = hightLightColor titleLabel.text = hightLightText delegate?.recordButtonTouchedBegin() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let point = touch.location(in: self) as CGPoint if (point.x >= 0 && point.x <= self.bounds.width) && (point.y >= 0 && point.y <= self.bounds.height) { titleLabel.text = hightLightText delegate?.recordButtonTouchedMoved(true) } else { titleLabel.text = cancelText delegate?.recordButtonTouchedMoved(false) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { backgroundColor = UIColor.clear titleLabel.text = normalText guard let touch = touches.first else { return } let point = touch.location(in: self) as CGPoint if (point.x >= 0 && point.x <= self.bounds.width) && (point.y >= 0 && point.y <= self.bounds.height) { //: 结束 delegate?.recordButtonTouchedEnd() } else { //: 取消 delegate?.recordButtonTouchedCancel() } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { backgroundColor = UIColor.clear titleLabel.text = normalText //: 取消 delegate?.recordButtonTouchedCancel() } //MARK: 私有方法 private func setupRecordButton() { addSubview(titleLabel) setupRecordButtonSubView() } private func setupRecordButtonSubView() { titleLabel.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets.zero) } } } //MARK: 协议 protocol RecordButtonDelegate:NSObjectProtocol { func recordButtonTouchedBegin() func recordButtonTouchedMoved(_ isMovingIn:Bool) func recordButtonTouchedEnd() func recordButtonTouchedCancel() }
0bafda07aaa1edd8e6e69bce241c965c
25.550388
86
0.595912
false
false
false
false
noxytrux/KnightWhoSaidSwift
refs/heads/master
KnightWhoSaidSwift/Utilities.swift
mit
1
// // Utilities.swift // KnightWhoSaidSwift // // Created by Marcin Pędzimąż on 18.09.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import SpriteKit struct mapDataStruct { var object: UInt32 //BGRA! var playerSpawn: UInt8 { return UInt8(object & 0x000000FF) } var ground: UInt8 { return UInt8((object & 0x0000FF00) >> 8) } var grass: UInt8 { return UInt8((object & 0x00FF0000) >> 16) } var wall: UInt8 { return UInt8((object & 0xFF000000) >> 24) } var desc : String { return "(\(self.ground),\(self.grass),\(self.wall),\(self.playerSpawn))" } } func createARGBBitmapContext(inImage: CGImage) -> CGContext { var bitmapByteCount = 0 var bitmapBytesPerRow = 0 let pixelsWide = CGImageGetWidth(inImage) let pixelsHigh = CGImageGetHeight(inImage) bitmapBytesPerRow = Int(pixelsWide) * 4 bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapData = malloc(bitmapByteCount) let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue ) let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, 8, bitmapBytesPerRow, colorSpace, bitmapInfo.rawValue) return context! } func loadMapData(mapName: String) -> (data: UnsafeMutablePointer<Void>, width: Int, height: Int) { let image = UIImage(named: mapName) let inImage = image?.CGImage let cgContext = createARGBBitmapContext(inImage!) let imageWidth = CGImageGetWidth(inImage) let imageHeight = CGImageGetHeight(inImage) var rect = CGRectZero rect.size.width = CGFloat(imageWidth) rect.size.height = CGFloat(imageHeight) CGContextDrawImage(cgContext, rect, inImage) let dataPointer = CGBitmapContextGetData(cgContext) return (dataPointer, imageWidth, imageHeight) } func loadFramesFromAtlas(atlas: SKTextureAtlas) -> [SKTexture] { return (atlas.textureNames as [String]).map { atlas.textureNamed($0) } } func loadFramesFromAtlasWithName(atlasName: String, baseFileName: String, numberOfFrames: Int) -> [SKTexture] { let atlas = SKTextureAtlas(named: atlasName) return [SKTexture]( (1...numberOfFrames).map { i in let fileName = "\(baseFileName)_prefix_\(i).png" return atlas.textureNamed(fileName) } ) } extension SKEmitterNode { //broken in xCode 6.0 :( works only in 6.1Beta class func emitterNodeWithName(name: String) -> SKEmitterNode { return NSKeyedUnarchiver.unarchiveObjectWithFile(NSBundle.mainBundle().pathForResource(name, ofType: "sks")!) as! SKEmitterNode } class func sharedSmokeEmitter() -> SKEmitterNode { let smoke = SKEmitterNode() smoke.particleTexture = SKTexture(imageNamed: "particle1.png") smoke.particleColor = UIColor.blackColor() smoke.numParticlesToEmit = 10 smoke.particleBirthRate = 100 smoke.particleLifetime = 1 smoke.emissionAngleRange = 360 smoke.particleSpeed = 100 smoke.particleSpeedRange = 50 smoke.xAcceleration = 0 smoke.yAcceleration = 200 smoke.particleAlpha = 0.8 smoke.particleAlphaRange = 0.2 smoke.particleAlphaSpeed = -0.5 smoke.particleScale = 0.6 smoke.particleScaleRange = 0.4 smoke.particleScaleSpeed = -0.5 smoke.particleRotation = 0 smoke.particleRotationRange = 360 smoke.particleRotationSpeed = 5 smoke.particleColorBlendFactor = 1 smoke.particleColorBlendFactorRange = 0.2 smoke.particleColorBlendFactorSpeed = -0.2 smoke.particleBlendMode = SKBlendMode.Alpha return smoke } class func sharedBloodEmitter() -> SKEmitterNode { let blood = SKEmitterNode() blood.particleTexture = SKTexture(imageNamed: "particle0.png") blood.particleColor = UIColor.redColor() blood.numParticlesToEmit = 35 blood.particleBirthRate = 200 blood.particleLifetime = 1.5 blood.emissionAngleRange = 360 blood.particleSpeed = 50 blood.particleSpeedRange = 20 blood.xAcceleration = 0 blood.yAcceleration = 0 blood.particleAlpha = 0.8 blood.particleAlphaRange = 0.2 blood.particleAlphaSpeed = -0.5 blood.particleScale = 1.5 blood.particleScaleRange = 0.4 blood.particleScaleSpeed = -0.5 blood.particleRotation = 0 blood.particleRotationRange = 0 blood.particleRotationSpeed = 0 blood.particleColorBlendFactor = 1 blood.particleColorBlendFactorRange = 0 blood.particleColorBlendFactorSpeed = 0 blood.particleBlendMode = SKBlendMode.Alpha return blood } class func sharedSparkleEmitter() -> SKEmitterNode { let sparcle = SKEmitterNode() sparcle.particleTexture = SKTexture(imageNamed: "particle2.png") sparcle.particleColor = UIColor.yellowColor() sparcle.numParticlesToEmit = 60 sparcle.particleBirthRate = 250 sparcle.particleLifetime = 0.7 sparcle.emissionAngle = 0 sparcle.emissionAngleRange = 90 sparcle.particleSpeed = 100 sparcle.particleSpeedRange = 50 sparcle.xAcceleration = 0 sparcle.yAcceleration = 0 sparcle.particleAlpha = 0.8 sparcle.particleAlphaRange = 0.2 sparcle.particleAlphaSpeed = -0.5 sparcle.particleScale = 1.0 sparcle.particleScaleRange = 0.4 sparcle.particleScaleSpeed = -0.5 sparcle.particleRotation = 0 sparcle.particleRotationRange = 0 sparcle.particleRotationSpeed = 0 sparcle.particleColorBlendFactor = 1 sparcle.particleColorBlendFactorRange = 0 sparcle.particleColorBlendFactorSpeed = 0 sparcle.particleBlendMode = SKBlendMode.Add return sparcle } } func runOneShotEmitter(emitter: SKEmitterNode, withDuration duration: CGFloat) { let waitAction = SKAction.waitForDuration(NSTimeInterval(duration)) let birthRateSet = SKAction.runBlock { emitter.particleBirthRate = 0.0 } let waitAction2 = SKAction.waitForDuration(NSTimeInterval(emitter.particleLifetime + emitter.particleLifetimeRange)) let removeAction = SKAction.removeFromParent() let sequence = [ waitAction, birthRateSet, waitAction2, removeAction] emitter.runAction(SKAction.sequence(sequence)) }
4fd8e7b38e09faa50f26847772c1fbba
30.273128
135
0.627694
false
false
false
false
Chris-Perkins/Lifting-Buddy
refs/heads/master
Lifting Buddy/HelperFunctions.swift
mit
1
// // HelperFunctions.swift // Lifting Buddy // // Created by Christopher Perkins on 7/16/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // /// Functions to help make the application more readable. /// Application defaults are stored here. import UIKit import RealmSwift import Realm import SwiftCharts import CDAlertView // Time amount values (used in graphing) public enum TimeAmount: String { case month = "MONTH" case year = "YEAR" case alltime = "ALL-TIME" } // Used in getting user defined color scheme from userdefaults public let colorSchemeKey = "colorScheme" public enum ColorScheme: Int { case light = 0 case dark = 1 } public var activeColorScheme: ColorScheme { guard let storedValue = UserDefaults.standard.value(forKey: colorSchemeKey) as? Int, let colorScheme = ColorScheme(rawValue: storedValue) else { fatalError("Could not retrieve the active color scheme") } return colorScheme } public func setNewColorScheme(_ scheme: ColorScheme) { let userDefaults = UserDefaults.standard userDefaults.set(scheme.rawValue, forKey: colorSchemeKey) } // An associated array for easy parsing public let TimeAmountArray = [TimeAmount.month, TimeAmount.year, TimeAmount.alltime] public let daysOfTheWeekChars = ["S", "M", "T", "W", "T", "F", "S"] // Returns the height of the status bar (battery view, etc) var statusBarHeight: CGFloat { let statusBarSize = UIApplication.shared.statusBarFrame.size return Swift.min(statusBarSize.width, statusBarSize.height) } // MARK: Operators // let's us do pow function easier. precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ^^ : PowerPrecedence func ^^ (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power))) } // MARK: Global functions // Gets the colors associated with an index func getColorsForIndex(_ passedIndex: Int) -> [UIColor] { var colors = [UIColor]() let modCount = 10 // Lets us modify the index that was passed in var index = passedIndex // + 1 so index starting at 0 is given a color index += 1 var i = 0 var previousColor = -1 while index > 0 { var color: UIColor? var colorIndex = mod(x: index, m: modCount) if colorIndex == previousColor { colorIndex = mod(x: colorIndex + 1, m: modCount) } switch (colorIndex) { case 0: color = .niceRed case 1: color = .niceBlue case 2: color = .niceGreen case 3: color = .niceYellow case 4: color = .niceCyan case 5: color = .niceBrown case 6: color = .nicePurple case 7: color = .niceMediterranean case 8: color = .niceMaroon case 9: color = .niceOrange default: fatalError("Modulo returned OOB value. Check case amount in ExerciseChartCreator -> GetLineColor Method") } i += 1 // Up this based on mod count. Should be the ceil of closest 10 to modCount // Ex: modCount 9 -> 10, modCount 11 -> 100 index = index / 10^^i previousColor = colorIndex colors.append(color!) } return colors } // Just mods a number so it doesn't return -1 func mod(x: Int, m: Int) -> Int { let r = x % m return r < 0 ? r + m : r } func mod(x: Float, m: Float) -> Float { let r = x.truncatingRemainder(dividingBy: m) return r < 0 ? r + m : r } // MARK: Extensions extension BetterTextField { public static var defaultHeight: CGFloat { return 50 } } extension Chart { public static var defaultHeight: CGFloat { return 300 } } extension ChartSettings { // Default chart settings for this project public static func getDefaultSettings() -> ChartSettings { var chartSettings = ChartSettings() chartSettings.leading = 10 chartSettings.top = 10 chartSettings.trailing = 15 chartSettings.bottom = 10 chartSettings.labelsToAxisSpacingX = 5 chartSettings.labelsToAxisSpacingY = 5 chartSettings.axisTitleLabelsToLabelsSpacing = 4 chartSettings.axisStrokeWidth = 0.2 chartSettings.spacingBetweenAxesX = 8 chartSettings.spacingBetweenAxesY = 8 chartSettings.labelsSpacing = 0 return chartSettings } } extension NSDate { // Returns the default date formatter for this project public static func getDateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "dd MMM yyyy" return formatter } // Get the current day of the week (in string format) ex: "Monday" public func dayOfTheWeek() -> String? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.string(from: self as Date) } // Gets the day of the week as a string public func getDayOfWeek(_ fromDate: String, formatter: DateFormatter = NSDate.getDateFormatter()) -> Int? { guard let date = formatter.date(from: fromDate) else { return nil } let myCalendar = Calendar(identifier: .gregorian) let weekDay = myCalendar.component(.weekday, from: date) return weekDay } } extension Date { private static let daysOfTheWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; /// Returns the amount of seconds from another date func seconds(from date: Date) -> Int { return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0 } public static func getDaysOfTheWeekStrings() -> [String] { return daysOfTheWeek; } /** Attempts to convert an index into the correspondent weekday string; 0-indexed. - Parameter index: the index of the date (0 is Sunday, 6 is Saturday) - Returns: A String representing the name of the weekday if the index is valid; nil otherwise. */ public static func convertDayIndexToWeekdayName(dayIndex index: Int) -> String? { if (index < 0 || index >= daysOfTheWeek.count) { return nil } return daysOfTheWeek[index] } /** Attempts to convert a String into the index of the day of the week it's related to; 0-indexed. - Parameter weekdayName: The String that represents a weekday name - Returns: The index of the weekday (0-indexed) if it could be found; nil otherwise. */ public static func convertWeekdayNameToIndex(weekdayName: String) -> Int? { if (daysOfTheWeek.contains(weekdayName)) { return daysOfTheWeek.index(of: weekdayName) } else { return nil } } /** Attempts to get the day of the week for the Date instance; 0-indexed. - Returns: The index of the day of the week this date is; 0-indexed. */ public func getDayOfTheWeekIndex() -> Int { let date = Date() let myCalendar = Calendar(identifier: .gregorian) let weekDay = myCalendar.component(.weekday, from: date) return weekDay - 1 } } extension Int { public func modulo(_ moduloNumber: Int) -> Int { let moduloValue = self % moduloNumber return moduloValue < 0 ? moduloValue + moduloNumber : moduloValue } } extension NSLayoutConstraint { // Clings a view to the entirety of toView public static func clingViewToView(view: UIView, toView: UIView) { view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: view, withCopyView: toView, attribute: .right).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: view, withCopyView: toView, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: view, withCopyView: toView, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: view, withCopyView: toView, attribute: .bottom).isActive = true } // Return a constraint that will place a view below's top a view with padding public static func createViewBelowViewConstraint(view: UIView, belowView: UIView, withPadding: CGFloat = 0) -> NSLayoutConstraint { return NSLayoutConstraint(item: belowView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: -withPadding) } // Return a constraint that will create a width constraint for the given view public static func createWidthConstraintForView(view: UIView, width: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width) } // Return a constraint that will create a height constraint for the given view public static func createHeightConstraintForView(view: UIView, height: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height) } // Just a faster way to create a layout constraint copy. The original way is waaaay too long. public static func createViewAttributeCopyConstraint(view: UIView, withCopyView: UIView, attribute: NSLayoutConstraint.Attribute, multiplier: CGFloat = 1.0, plusConstant: CGFloat = 0.0) -> NSLayoutConstraint { return NSLayoutConstraint(item: withCopyView, attribute: attribute, relatedBy: .equal, toItem: view, attribute: attribute, multiplier: (1/multiplier), constant: -plusConstant) } } extension PrettyButton { public static var defaultHeight: CGFloat { return 50 } override func setDefaultProperties() { backgroundColor = .niceBlue setOverlayColor(color: .niceYellow) setOverlayStyle(style: .fade) cornerRadius = 0 } } extension PrettySegmentedControl { public static var defaultHeight: CGFloat { return 30 } } extension String { var floatValue: Float? { return Float(self) } } extension UIColor { public static var primaryBlackWhiteColor: UIColor { switch(activeColorScheme) { case .light: return .white case .dark: return .niceBlack } } public static var lightBlackWhiteColor: UIColor { switch(activeColorScheme) { case .light: return .niceLightGray case .dark: return .niceDarkestGray } } public static var lightestBlackWhiteColor: UIColor { switch(activeColorScheme) { case .light: return .niceLightestGray case .dark: return .niceDarkGray } } public static var oppositeBlackWhiteColor: UIColor { switch(activeColorScheme) { case .light: return .niceBlack case .dark: return .white } } public static var niceBlack: UIColor { return UIColor(hue: 0, saturation: 0, brightness: 0.075, alpha: 1.0) } public static var niceBlue: UIColor { switch(activeColorScheme) { case .light: return UIColor(red: 0.291269, green: 0.459894, blue: 0.909866, alpha: 1) case .dark: return UIColor(red: 0.4196, green: 0.6196, blue: 0.909866, alpha: 1.0) } } public static var niceBrown: UIColor { return UIColor(red: 0.6471, green: 0.3647, blue: 0.149, alpha: 1.0) } public static var niceCyan: UIColor { return UIColor(red: 0.149, green: 0.651, blue: 0.6588, alpha: 1.0) } public static var niceDarkGray: UIColor { return UIColor(hue: 0, saturation: 0, brightness: 0.225, alpha: 1.0) } public static var niceDarkestGray: UIColor { return UIColor(hue: 0, saturation: 0, brightness: 0.15, alpha: 1.0) } public static var niceGreen: UIColor { return UIColor(red: 0.27, green: 0.66, blue: 0.3, alpha: 1) } public static var niceLabelBlue: UIColor { return UIColor(red: 0.44, green: 0.56, blue: 0.86, alpha: 1) } public static var niceLightBlue: UIColor { return UIColor(red: 0.8, green: 0.78, blue: 0.96, alpha: 1) } public static var niceLightGray: UIColor { return UIColor(hue: 0, saturation: 0, brightness: 0.895, alpha: 1.0) } public static var niceLightestGray: UIColor { return UIColor(hue: 0, saturation: 0, brightness: 0.95, alpha: 1.0) } public static var niceLightGreen: UIColor { switch(activeColorScheme) { case .light: return UIColor(red: 0.85, green: 0.95, blue: 0.85, alpha: 1) case .dark: return UIColor(red: 0.1176, green: 0.2667, blue: 0.1176, alpha: 1.0) } } public static var niceLightRed: UIColor { return UIColor(red: 0.9686, green: 0.5176, blue: 0.3647, alpha: 1.0) } public static var niceMaroon: UIColor { return UIColor(red: 0.349, green: 0.0784, blue: 0.0784, alpha: 1.0) } public static var niceMediterranean: UIColor { return UIColor(red: 0.0745, green: 0.2235, blue: 0.3373, alpha: 1.0) } public static var niceOrange: UIColor { return UIColor(red: 1, green: 0.4118, blue: 0.1569, alpha: 1.0) } public static var nicePurple: UIColor { return UIColor(red: 0.5882, green: 0.1451, blue: 0.6392, alpha: 1.0) } public static var niceRed: UIColor { return UIColor(red: 1.0, green: 0.5, blue: 0.5, alpha: 1) } public static var niceYellow: UIColor { return UIColor(red: 0.90, green: 0.70, blue: 0.16, alpha: 1) } } extension UIImage { public func rotateNinetyDegreesClockwise() -> UIImage { return UIImage(cgImage: cgImage!, scale: 1, orientation: UIImage.Orientation.right) } public func rotateNinetyDegreesCounterClockwise() -> UIImage { return UIImage(cgImage: cgImage!, scale: 1, orientation: UIImage.Orientation.left) } } extension UILabel { public static var titleLabelTextColor: UIColor { return .niceBlue } public static var titleLabelBackgroundColor: UIColor { return .lightestBlackWhiteColor } public static var titleLabelHeight: CGFloat { return 50.0 } override func setDefaultProperties() { font = UIFont.boldSystemFont(ofSize: 18.0) textAlignment = .center textColor = .niceBlue } } extension UITableView { // Returns all cells in a uitableview public func getAllCells() -> [UITableViewCell] { var cells = [UITableViewCell]() for i in 0...numberOfSections - 1 { for j in 0...numberOfRows(inSection: i) { if let cell = cellForRow(at: IndexPath(row: j, section: i)) { cells.append(cell) } } } return cells } } extension UITableViewCell { public static var defaultHeight: CGFloat { return 50 } } extension UITextField { var isNumeric: Bool { if let text = text { if text.count == 0 { return true } let setNums: Set<Character> = Set(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0") return Set(text).isSubset(of: setNums) } else { return false } } override func setDefaultProperties() { // View select / deselect events addTarget(self, action: #selector(textfieldSelected(sender:)), for: .editingDidBegin) addTarget(self, action: #selector(textfieldDeselected(sender:)), for: .editingDidEnd) // View prettiness textAlignment = .center } // MARK: Textfield events @objc func textfieldSelected(sender: UITextField) { UIView.animate(withDuration: 0.1, animations: { sender.backgroundColor = .niceYellow sender.textColor = .white }) } @objc func textfieldDeselected(sender: UITextField) { UIView.animate(withDuration: 0.1, animations: { sender.backgroundColor = .primaryBlackWhiteColor sender.textColor = .oppositeBlackWhiteColor }) } @objc public func setPlaceholderString(_ placeholder: String?) { if let placeholder = placeholder { let attributedText = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: UIColor.oppositeBlackWhiteColor.withAlphaComponent( 0.25)]) attributedPlaceholder = attributedText } else { attributedPlaceholder = nil } } @objc public func getPlaceholderString() -> String? { return attributedPlaceholder?.string } public func resetColors() { setPlaceholderString(getPlaceholderString()) textfieldDeselected(sender: self) } } extension UIView { // Shows a view over this view using constraints static func slideView(_ coveringView: UIView, overView inView: UIView) { // Don't want user interacting with the view if it shouldn't be interactable at this time. inView.isUserInteractionEnabled = false inView.addSubview(coveringView) // Constraints take up the whole view. Start above the view (not visible) coveringView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: coveringView, withCopyView: inView, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: coveringView, withCopyView: inView, attribute: .width).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: coveringView, withCopyView: inView, attribute: .height).isActive = true /* We can use the inView's height as the basis for "above this view" since coveringView's height is equal to the height of the inView */ let heightConstraint = NSLayoutConstraint.createViewAttributeCopyConstraint( view: coveringView, withCopyView: inView, attribute: .top, plusConstant: -inView.frame.height) heightConstraint.isActive = true // Activate these constraints inView.layoutIfNeeded() // Moves the view to the bottom upon calling layout if needed heightConstraint.constant = 0 // Animate the transition between top to bottom to slide down UIView.animate(withDuration: 0.2, animations: { inView.layoutIfNeeded() }, completion: {Bool in inView.isUserInteractionEnabled = true }) } // Calls layoutSubviews on ALL subviews recursively func layoutAllSubviews() { for subview in subviews { (subview as? UITextField)?.resetColors() subview.layoutAllSubviews() } layoutSubviews() } @objc func setDefaultProperties() { // Override me! } // Removes all subviews from a given view func removeAllSubviews() { for subview in subviews { subview.removeFromSuperview() } } // Removes itself from this superview by sliding up and fading out func removeSelfNicelyWithAnimation() { // Prevent user interaction with all subviews for subview in subviews { subview.isUserInteractionEnabled = false } // Slide up, then remove from view UIView.animate(withDuration: 0.2, animations: { self.frame = CGRect(x: 0, y: -self.frame.height, width: self.frame.width, height: self.frame.height) }, completion: { (finished:Bool) -> Void in self.removeFromSuperview() }) } }
7f78d822cafe45925075779bcf3d75f3
33
117
0.564951
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
refs/heads/master
uoregon-cis-422/SafeRide/Pods/SwiftWebSocket/Source/WebSocket.swift
gpl-3.0
1
/* * SwiftWebSocket (websocket.swift) * * Copyright (C) Josh Baker. All Rights Reserved. * Contact: @tidwall, [email protected] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * */ import Foundation private let windowBufferSize = 0x2000 private class Payload { var ptr : UnsafeMutablePointer<UInt8> var cap : Int var len : Int init(){ len = 0 cap = windowBufferSize ptr = UnsafeMutablePointer<UInt8>(malloc(cap)) } deinit{ free(ptr) } var count : Int { get { return len } set { if newValue > cap { while cap < newValue { cap *= 2 } ptr = UnsafeMutablePointer<UInt8>(realloc(ptr, cap)) } len = newValue } } func append(bytes: UnsafePointer<UInt8>, length: Int){ let prevLen = len count = len+length memcpy(ptr+prevLen, bytes, length) } var array : [UInt8] { get { var array = [UInt8](count: count, repeatedValue: 0) memcpy(&array, ptr, count) return array } set { count = 0 append(newValue, length: newValue.count) } } var nsdata : NSData { get { return NSData(bytes: ptr, length: count) } set { count = 0 append(UnsafePointer<UInt8>(newValue.bytes), length: newValue.length) } } var buffer : UnsafeBufferPointer<UInt8> { get { return UnsafeBufferPointer<UInt8>(start: ptr, count: count) } set { count = 0 append(newValue.baseAddress, length: newValue.count) } } } private enum OpCode : UInt8, CustomStringConvertible { case Continue = 0x0, Text = 0x1, Binary = 0x2, Close = 0x8, Ping = 0x9, Pong = 0xA var isControl : Bool { switch self { case .Close, .Ping, .Pong: return true default: return false } } var description : String { switch self { case Continue: return "Continue" case Text: return "Text" case Binary: return "Binary" case Close: return "Close" case Ping: return "Ping" case Pong: return "Pong" } } } /// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection. public struct WebSocketEvents { /// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data. public var open : ()->() = {} /// An event to be called when the WebSocket connection's readyState changes to .Closed. public var close : (code : Int, reason : String, wasClean : Bool)->() = {(code, reason, wasClean) in} /// An event to be called when an error occurs. public var error : (error : ErrorType)->() = {(error) in} /// An event to be called when a message is received from the server. public var message : (data : Any)->() = {(data) in} /// An event to be called when a pong is received from the server. public var pong : (data : Any)->() = {(data) in} /// An event to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events. public var end : (code : Int, reason : String, wasClean : Bool, error : ErrorType?)->() = {(code, reason, wasClean, error) in} } /// The WebSocketBinaryType enum is used by the binaryType property and indicates the type of binary data being transmitted by the WebSocket connection. public enum WebSocketBinaryType : CustomStringConvertible { /// The WebSocket should transmit [UInt8] objects. case UInt8Array /// The WebSocket should transmit NSData objects. case NSData /// The WebSocket should transmit UnsafeBufferPointer<UInt8> objects. This buffer is only valid during the scope of the message event. Use at your own risk. case UInt8UnsafeBufferPointer public var description : String { switch self { case UInt8Array: return "UInt8Array" case NSData: return "NSData" case UInt8UnsafeBufferPointer: return "UInt8UnsafeBufferPointer" } } } /// The WebSocketReadyState enum is used by the readyState property to describe the status of the WebSocket connection. @objc public enum WebSocketReadyState : Int, CustomStringConvertible { /// The connection is not yet open. case Connecting = 0 /// The connection is open and ready to communicate. case Open = 1 /// The connection is in the process of closing. case Closing = 2 /// The connection is closed or couldn't be opened. case Closed = 3 private var isClosed : Bool { switch self { case .Closing, .Closed: return true default: return false } } /// Returns a string that represents the ReadyState value. public var description : String { switch self { case Connecting: return "Connecting" case Open: return "Open" case Closing: return "Closing" case Closed: return "Closed" } } } private let defaultMaxWindowBits = 15 /// The WebSocketCompression struct is used by the compression property and manages the compression options for the WebSocket connection. public struct WebSocketCompression { /// Used to accept compressed messages from the server. Default is true. public var on = false /// request no context takeover. public var noContextTakeover = false /// request max window bits. public var maxWindowBits = defaultMaxWindowBits } /// The WebSocketService options are used by the services property and manages the underlying socket services. public struct WebSocketService : OptionSetType { public typealias RawValue = UInt var value: UInt = 0 init(_ value: UInt) { self.value = value } public init(rawValue value: UInt) { self.value = value } public init(nilLiteral: ()) { self.value = 0 } public static var allZeros: WebSocketService { return self.init(0) } static func fromMask(raw: UInt) -> WebSocketService { return self.init(raw) } public var rawValue: UInt { return self.value } /// No services. public static var None: WebSocketService { return self.init(0) } /// Allow socket to handle VoIP. public static var VoIP: WebSocketService { return self.init(1 << 0) } /// Allow socket to handle video. public static var Video: WebSocketService { return self.init(1 << 1) } /// Allow socket to run in background. public static var Background: WebSocketService { return self.init(1 << 2) } /// Allow socket to handle voice. public static var Voice: WebSocketService { return self.init(1 << 3) } } private let atEndDetails = "streamStatus.atEnd" private let timeoutDetails = "The operation couldn’t be completed. Operation timed out" private let timeoutDuration : CFTimeInterval = 30 public enum WebSocketError : ErrorType, CustomStringConvertible { case Memory case NeedMoreInput case InvalidHeader case InvalidAddress case Network(String) case LibraryError(String) case PayloadError(String) case ProtocolError(String) case InvalidResponse(String) case InvalidCompressionOptions(String) public var description : String { switch self { case .Memory: return "Memory" case .NeedMoreInput: return "NeedMoreInput" case .InvalidAddress: return "InvalidAddress" case .InvalidHeader: return "InvalidHeader" case let .InvalidResponse(details): return "InvalidResponse(\(details))" case let .InvalidCompressionOptions(details): return "InvalidCompressionOptions(\(details))" case let .LibraryError(details): return "LibraryError(\(details))" case let .ProtocolError(details): return "ProtocolError(\(details))" case let .PayloadError(details): return "PayloadError(\(details))" case let .Network(details): return "Network(\(details))" } } public var details : String { switch self { case .InvalidResponse(let details): return details case .InvalidCompressionOptions(let details): return details case .LibraryError(let details): return details case .ProtocolError(let details): return details case .PayloadError(let details): return details case .Network(let details): return details default: return "" } } } private class UTF8 { var text : String = "" var count : UInt32 = 0 // number of bytes var procd : UInt32 = 0 // number of bytes processed var codepoint : UInt32 = 0 // the actual codepoint var bcount = 0 init() { text = "" } func append(byte : UInt8) throws { if count == 0 { if byte <= 0x7F { text.append(UnicodeScalar(byte)) return } if byte == 0xC0 || byte == 0xC1 { throw WebSocketError.PayloadError("invalid codepoint: invalid byte") } if byte >> 5 & 0x7 == 0x6 { count = 2 } else if byte >> 4 & 0xF == 0xE { count = 3 } else if byte >> 3 & 0x1F == 0x1E { count = 4 } else { throw WebSocketError.PayloadError("invalid codepoint: frames") } procd = 1 codepoint = (UInt32(byte) & (0xFF >> count)) << ((count-1) * 6) return } if byte >> 6 & 0x3 != 0x2 { throw WebSocketError.PayloadError("invalid codepoint: signature") } codepoint += UInt32(byte & 0x3F) << ((count-procd-1) * 6) if codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) { throw WebSocketError.PayloadError("invalid codepoint: out of bounds") } procd += 1 if procd == count { if codepoint <= 0x7FF && count > 2 { throw WebSocketError.PayloadError("invalid codepoint: overlong") } if codepoint <= 0xFFFF && count > 3 { throw WebSocketError.PayloadError("invalid codepoint: overlong") } procd = 0 count = 0 text.append(UnicodeScalar(codepoint)) } return } func append(bytes : UnsafePointer<UInt8>, length : Int) throws { if length == 0 { return } if count == 0 { var ascii = true for i in 0 ..< length { if bytes[i] > 0x7F { ascii = false break } } if ascii { text += NSString(bytes: bytes, length: length, encoding: NSASCIIStringEncoding) as! String bcount += length return } } for i in 0 ..< length { try append(bytes[i]) } bcount += length } var completed : Bool { return count == 0 } static func bytes(string : String) -> [UInt8]{ let data = string.dataUsingEncoding(NSUTF8StringEncoding)! return [UInt8](UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(data.bytes), count: data.length)) } static func string(bytes : [UInt8]) -> String{ if let str = NSString(bytes: bytes, length: bytes.count, encoding: NSUTF8StringEncoding) { return str as String } return "" } } private class Frame { var inflate = false var code = OpCode.Continue var utf8 = UTF8() var payload = Payload() var statusCode = UInt16(0) var finished = true static func makeClose(statusCode: UInt16, reason: String) -> Frame { let f = Frame() f.code = .Close f.statusCode = statusCode f.utf8.text = reason return f } func copy() -> Frame { let f = Frame() f.code = code f.utf8.text = utf8.text f.payload.buffer = payload.buffer f.statusCode = statusCode f.finished = finished f.inflate = inflate return f } } private class Delegate : NSObject, NSStreamDelegate { @objc func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent){ manager.signal() } } @_silgen_name("zlibVersion") private func zlibVersion() -> COpaquePointer @_silgen_name("deflateInit2_") private func deflateInit2(strm : UnsafeMutablePointer<Void>, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @_silgen_name("deflateInit_") private func deflateInit(strm : UnsafeMutablePointer<Void>, level : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @_silgen_name("deflateEnd") private func deflateEnd(strm : UnsafeMutablePointer<Void>) -> CInt @_silgen_name("deflate") private func deflate(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt @_silgen_name("inflateInit2_") private func inflateInit2(strm : UnsafeMutablePointer<Void>, windowBits : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @_silgen_name("inflateInit_") private func inflateInit(strm : UnsafeMutablePointer<Void>, version : COpaquePointer, stream_size : CInt) -> CInt @_silgen_name("inflate") private func inflateG(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt @_silgen_name("inflateEnd") private func inflateEndG(strm : UnsafeMutablePointer<Void>) -> CInt private func zerror(res : CInt) -> ErrorType? { var err = "" switch res { case 0: return nil case 1: err = "stream end" case 2: err = "need dict" case -1: err = "errno" case -2: err = "stream error" case -3: err = "data error" case -4: err = "mem error" case -5: err = "buf error" case -6: err = "version error" default: err = "undefined error" } return WebSocketError.PayloadError("zlib: \(err): \(res)") } private struct z_stream { var next_in : UnsafePointer<UInt8> = nil var avail_in : CUnsignedInt = 0 var total_in : CUnsignedLong = 0 var next_out : UnsafeMutablePointer<UInt8> = nil var avail_out : CUnsignedInt = 0 var total_out : CUnsignedLong = 0 var msg : UnsafePointer<CChar> = nil var state : COpaquePointer = nil var zalloc : COpaquePointer = nil var zfree : COpaquePointer = nil var opaque : COpaquePointer = nil var data_type : CInt = 0 var adler : CUnsignedLong = 0 var reserved : CUnsignedLong = 0 } private class Inflater { var windowBits = 0 var strm = z_stream() var tInput = [[UInt8]]() var inflateEnd : [UInt8] = [0x00, 0x00, 0xFF, 0xFF] var bufferSize = windowBufferSize var buffer = UnsafeMutablePointer<UInt8>(malloc(windowBufferSize)) init?(windowBits : Int){ if buffer == nil { return nil } self.windowBits = windowBits let ret = inflateInit2(&strm, windowBits: -CInt(windowBits), version: zlibVersion(), stream_size: CInt(sizeof(z_stream))) if ret != 0 { return nil } } deinit{ inflateEndG(&strm) free(buffer) } func inflate(bufin : UnsafePointer<UInt8>, length : Int, final : Bool) throws -> (p : UnsafeMutablePointer<UInt8>, n : Int){ var buf = buffer var bufsiz = bufferSize var buflen = 0 for i in 0 ..< 2{ if i == 0 { strm.avail_in = CUnsignedInt(length) strm.next_in = UnsafePointer<UInt8>(bufin) } else { if !final { break } strm.avail_in = CUnsignedInt(inflateEnd.count) strm.next_in = UnsafePointer<UInt8>(inflateEnd) } while true { strm.avail_out = CUnsignedInt(bufsiz) strm.next_out = buf inflateG(&strm, flush: 0) let have = bufsiz - Int(strm.avail_out) bufsiz -= have buflen += have if strm.avail_out != 0{ break } if bufsiz == 0 { bufferSize *= 2 let nbuf = UnsafeMutablePointer<UInt8>(realloc(buffer, bufferSize)) if nbuf == nil { throw WebSocketError.PayloadError("memory") } buffer = nbuf buf = buffer+Int(buflen) bufsiz = bufferSize - buflen } } } return (buffer, buflen) } } private class Deflater { var windowBits = 0 var memLevel = 0 var strm = z_stream() var bufferSize = windowBufferSize var buffer = UnsafeMutablePointer<UInt8>(malloc(windowBufferSize)) init?(windowBits : Int, memLevel : Int){ if buffer == nil { return nil } self.windowBits = windowBits self.memLevel = memLevel let ret = deflateInit2(&strm, level: 6, method: 8, windowBits: -CInt(windowBits), memLevel: CInt(memLevel), strategy: 0, version: zlibVersion(), stream_size: CInt(sizeof(z_stream))) if ret != 0 { return nil } } deinit{ deflateEnd(&strm) free(buffer) } func deflate(bufin : UnsafePointer<UInt8>, length : Int, final : Bool) -> (p : UnsafeMutablePointer<UInt8>, n : Int, err : NSError?){ return (nil, 0, nil) } } /// WebSocketDelegate is an Objective-C alternative to WebSocketEvents and is used to delegate the events for the WebSocket connection. @objc public protocol WebSocketDelegate { /// A function to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data. func webSocketOpen() /// A function to be called when the WebSocket connection's readyState changes to .Closed. func webSocketClose(code: Int, reason: String, wasClean: Bool) /// A function to be called when an error occurs. func webSocketError(error: NSError) /// A function to be called when a message (string) is received from the server. optional func webSocketMessageText(text: String) /// A function to be called when a message (binary) is received from the server. optional func webSocketMessageData(data: NSData) /// A function to be called when a pong is received from the server. optional func webSocketPong() /// A function to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events. optional func webSocketEnd(code: Int, reason: String, wasClean: Bool, error: NSError?) } /// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455. private class InnerWebSocket: Hashable { var id : Int var mutex = pthread_mutex_t() let request : NSURLRequest! let subProtocols : [String]! var frames : [Frame] = [] var delegate : Delegate var inflater : Inflater! var deflater : Deflater! var outputBytes : UnsafeMutablePointer<UInt8> var outputBytesSize : Int = 0 var outputBytesStart : Int = 0 var outputBytesLength : Int = 0 var inputBytes : UnsafeMutablePointer<UInt8> var inputBytesSize : Int = 0 var inputBytesStart : Int = 0 var inputBytesLength : Int = 0 var createdAt = CFAbsoluteTimeGetCurrent() var connectionTimeout = false var eclose : ()->() = {} var _eventQueue : dispatch_queue_t? = dispatch_get_main_queue() var _subProtocol = "" var _compression = WebSocketCompression() var _allowSelfSignedSSL = false var _services = WebSocketService.None var _event = WebSocketEvents() var _eventDelegate: WebSocketDelegate? var _binaryType = WebSocketBinaryType.UInt8Array var _readyState = WebSocketReadyState.Connecting var _networkTimeout = NSTimeInterval(-1) var url : String { return request.URL!.description } var subProtocol : String { get { return privateSubProtocol } } var privateSubProtocol : String { get { lock(); defer { unlock() }; return _subProtocol } set { lock(); defer { unlock() }; _subProtocol = newValue } } var compression : WebSocketCompression { get { lock(); defer { unlock() }; return _compression } set { lock(); defer { unlock() }; _compression = newValue } } var allowSelfSignedSSL : Bool { get { lock(); defer { unlock() }; return _allowSelfSignedSSL } set { lock(); defer { unlock() }; _allowSelfSignedSSL = newValue } } var services : WebSocketService { get { lock(); defer { unlock() }; return _services } set { lock(); defer { unlock() }; _services = newValue } } var event : WebSocketEvents { get { lock(); defer { unlock() }; return _event } set { lock(); defer { unlock() }; _event = newValue } } var eventDelegate : WebSocketDelegate? { get { lock(); defer { unlock() }; return _eventDelegate } set { lock(); defer { unlock() }; _eventDelegate = newValue } } var eventQueue : dispatch_queue_t? { get { lock(); defer { unlock() }; return _eventQueue; } set { lock(); defer { unlock() }; _eventQueue = newValue } } var binaryType : WebSocketBinaryType { get { lock(); defer { unlock() }; return _binaryType } set { lock(); defer { unlock() }; _binaryType = newValue } } var readyState : WebSocketReadyState { get { return privateReadyState } } var privateReadyState : WebSocketReadyState { get { lock(); defer { unlock() }; return _readyState } set { lock(); defer { unlock() }; _readyState = newValue } } func copyOpen(request: NSURLRequest, subProtocols : [String] = []) -> InnerWebSocket{ let ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false) ws.eclose = eclose ws.compression = compression ws.allowSelfSignedSSL = allowSelfSignedSSL ws.services = services ws.event = event ws.eventQueue = eventQueue ws.binaryType = binaryType return ws } var hashValue: Int { return id } init(request: NSURLRequest, subProtocols : [String] = [], stub : Bool = false){ pthread_mutex_init(&mutex, nil) self.id = manager.nextId() self.request = request self.subProtocols = subProtocols self.outputBytes = UnsafeMutablePointer<UInt8>.alloc(windowBufferSize) self.outputBytesSize = windowBufferSize self.inputBytes = UnsafeMutablePointer<UInt8>.alloc(windowBufferSize) self.inputBytesSize = windowBufferSize self.delegate = Delegate() if stub{ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){ self } } else { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){ manager.add(self) } } } deinit{ if outputBytes != nil { free(outputBytes) } if inputBytes != nil { free(inputBytes) } pthread_mutex_init(&mutex, nil) } @inline(__always) private func lock(){ pthread_mutex_lock(&mutex) } @inline(__always) private func unlock(){ pthread_mutex_unlock(&mutex) } private var dirty : Bool { lock() defer { unlock() } if exit { return false } if connectionTimeout { return true } if stage != .ReadResponse && stage != .HandleFrames { return true } if rd.streamStatus == .Opening && wr.streamStatus == .Opening { return false; } if rd.streamStatus != .Open || wr.streamStatus != .Open { return true } if rd.streamError != nil || wr.streamError != nil { return true } if rd.hasBytesAvailable || frames.count > 0 || inputBytesLength > 0 { return true } if outputBytesLength > 0 && wr.hasSpaceAvailable{ return true } return false } enum Stage : Int { case OpenConn case ReadResponse case HandleFrames case CloseConn case End } var stage = Stage.OpenConn var rd : NSInputStream! var wr : NSOutputStream! var atEnd = false var closeCode = UInt16(0) var closeReason = "" var closeClean = false var closeFinal = false var finalError : ErrorType? var exit = false var more = true func step(){ if exit { return } do { try stepBuffers(more) try stepStreamErrors() more = false switch stage { case .OpenConn: try openConn() stage = .ReadResponse case .ReadResponse: try readResponse() privateReadyState = .Open fire { self.event.open() self.eventDelegate?.webSocketOpen() } stage = .HandleFrames case .HandleFrames: try stepOutputFrames() if closeFinal { privateReadyState = .Closing stage = .CloseConn return } let frame = try readFrame() switch frame.code { case .Text: fire { self.event.message(data: frame.utf8.text) self.eventDelegate?.webSocketMessageText?(frame.utf8.text) } case .Binary: fire { switch self.binaryType { case .UInt8Array: self.event.message(data: frame.payload.array) case .NSData: self.event.message(data: frame.payload.nsdata) // The WebSocketDelegate is necessary to add Objective-C compability and it is only possible to send binary data with NSData. self.eventDelegate?.webSocketMessageData?(frame.payload.nsdata) case .UInt8UnsafeBufferPointer: self.event.message(data: frame.payload.buffer) } } case .Ping: let nframe = frame.copy() nframe.code = .Pong lock() frames += [nframe] unlock() case .Pong: fire { switch self.binaryType { case .UInt8Array: self.event.pong(data: frame.payload.array) case .NSData: self.event.pong(data: frame.payload.nsdata) case .UInt8UnsafeBufferPointer: self.event.pong(data: frame.payload.buffer) } self.eventDelegate?.webSocketPong?() } case .Close: lock() frames += [frame] unlock() default: break } case .CloseConn: if let error = finalError { self.event.error(error: error) self.eventDelegate?.webSocketError(error as NSError) } privateReadyState = .Closed if rd != nil { closeConn() fire { self.eclose() self.event.close(code: Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal) self.eventDelegate?.webSocketClose(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal) } } stage = .End case .End: fire { self.event.end(code: Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError) self.eventDelegate?.webSocketEnd?(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError as? NSError) } exit = true manager.remove(self) } } catch WebSocketError.NeedMoreInput { more = true } catch { if finalError != nil { return } finalError = error if stage == .OpenConn || stage == .ReadResponse { stage = .CloseConn } else { var frame : Frame? if let error = error as? WebSocketError{ switch error { case .Network(let details): if details == atEndDetails{ stage = .CloseConn frame = Frame.makeClose(1006, reason: "Abnormal Closure") atEnd = true finalError = nil } case .ProtocolError: frame = Frame.makeClose(1002, reason: "Protocol error") case .PayloadError: frame = Frame.makeClose(1007, reason: "Payload error") default: break } } if frame == nil { frame = Frame.makeClose(1006, reason: "Abnormal Closure") } if let frame = frame { if frame.statusCode == 1007 { self.lock() self.frames = [frame] self.unlock() manager.signal() } else { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){ self.lock() self.frames += [frame] self.unlock() manager.signal() } } } } } } func stepBuffers(more: Bool) throws { if rd != nil { if stage != .CloseConn && rd.streamStatus == NSStreamStatus.AtEnd { if atEnd { return; } throw WebSocketError.Network(atEndDetails) } if more { while rd.hasBytesAvailable { var size = inputBytesSize while size-(inputBytesStart+inputBytesLength) < windowBufferSize { size *= 2 } if size > inputBytesSize { let ptr = UnsafeMutablePointer<UInt8>(realloc(inputBytes, size)) if ptr == nil { throw WebSocketError.Memory } inputBytes = ptr inputBytesSize = size } let n = rd.read(inputBytes+inputBytesStart+inputBytesLength, maxLength: inputBytesSize-inputBytesStart-inputBytesLength) if n > 0 { inputBytesLength += n } } } } if wr != nil && wr.hasSpaceAvailable && outputBytesLength > 0 { let n = wr.write(outputBytes+outputBytesStart, maxLength: outputBytesLength) if n > 0 { outputBytesLength -= n if outputBytesLength == 0 { outputBytesStart = 0 } else { outputBytesStart += n } } } } func stepStreamErrors() throws { if finalError == nil { if connectionTimeout { throw WebSocketError.Network(timeoutDetails) } if let error = rd?.streamError { throw WebSocketError.Network(error.localizedDescription) } if let error = wr?.streamError { throw WebSocketError.Network(error.localizedDescription) } } } func stepOutputFrames() throws { lock() defer { frames = [] unlock() } if !closeFinal { for frame in frames { try writeFrame(frame) if frame.code == .Close { closeCode = frame.statusCode closeReason = frame.utf8.text closeFinal = true return } } } } @inline(__always) func fire(block: ()->()){ if let queue = eventQueue { dispatch_sync(queue) { block() } } else { block() } } var readStateSaved = false var readStateFrame : Frame? var readStateFinished = false var leaderFrame : Frame? func readFrame() throws -> Frame { var frame : Frame var finished : Bool if !readStateSaved { if leaderFrame != nil { frame = leaderFrame! finished = false leaderFrame = nil } else { frame = try readFrameFragment(nil) finished = frame.finished } if frame.code == .Continue{ throw WebSocketError.ProtocolError("leader frame cannot be a continue frame") } if !finished { readStateSaved = true readStateFrame = frame readStateFinished = finished throw WebSocketError.NeedMoreInput } } else { frame = readStateFrame! finished = readStateFinished if !finished { let cf = try readFrameFragment(frame) finished = cf.finished if cf.code != .Continue { if !cf.code.isControl { throw WebSocketError.ProtocolError("only ping frames can be interlaced with fragments") } leaderFrame = frame return cf } if !finished { readStateSaved = true readStateFrame = frame readStateFinished = finished throw WebSocketError.NeedMoreInput } } } if !frame.utf8.completed { throw WebSocketError.PayloadError("incomplete utf8") } readStateSaved = false readStateFrame = nil readStateFinished = false return frame } func closeConn() { rd.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) wr.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) rd.delegate = nil wr.delegate = nil rd.close() wr.close() } func openConn() throws { let req = request.mutableCopy() as! NSMutableURLRequest req.setValue("websocket", forHTTPHeaderField: "Upgrade") req.setValue("Upgrade", forHTTPHeaderField: "Connection") if req.valueForHTTPHeaderField("User-Agent") == nil { req.setValue("SwiftWebSocket", forHTTPHeaderField: "User-Agent") } req.setValue("13", forHTTPHeaderField: "Sec-WebSocket-Version") if req.URL == nil || req.URL!.host == nil{ throw WebSocketError.InvalidAddress } if req.URL!.port == nil || req.URL!.port!.integerValue == 80 || req.URL!.port!.integerValue == 443 { req.setValue(req.URL!.host!, forHTTPHeaderField: "Host") } else { req.setValue("\(req.URL!.host!):\(req.URL!.port!.integerValue)", forHTTPHeaderField: "Host") } req.setValue(req.URL!.absoluteString, forHTTPHeaderField: "Origin") if subProtocols.count > 0 { req.setValue(subProtocols.joinWithSeparator(","), forHTTPHeaderField: "Sec-WebSocket-Protocol") } if req.URL!.scheme != "wss" && req.URL!.scheme != "ws" { throw WebSocketError.InvalidAddress } if compression.on { var val = "permessage-deflate" if compression.noContextTakeover { val += "; client_no_context_takeover; server_no_context_takeover" } val += "; client_max_window_bits" if compression.maxWindowBits != 0 { val += "; server_max_window_bits=\(compression.maxWindowBits)" } req.setValue(val, forHTTPHeaderField: "Sec-WebSocket-Extensions") } let security: TCPConnSecurity let port : Int if req.URL!.scheme == "wss" { port = req.URL!.port?.integerValue ?? 443 security = .NegoticatedSSL } else { port = req.URL!.port?.integerValue ?? 80 security = .None } var path = CFURLCopyPath(req.URL!) as String if path == "" { path = "/" } if let q = req.URL!.query { if q != "" { path += "?" + q } } var reqs = "GET \(path) HTTP/1.1\r\n" for key in req.allHTTPHeaderFields!.keys { if let val = req.valueForHTTPHeaderField(key) { reqs += "\(key): \(val)\r\n" } } var keyb = [UInt32](count: 4, repeatedValue: 0) for i in 0 ..< 4 { keyb[i] = arc4random() } let rkey = NSData(bytes: keyb, length: 16).base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) reqs += "Sec-WebSocket-Key: \(rkey)\r\n" reqs += "\r\n" var header = [UInt8]() for b in reqs.utf8 { header += [b] } let addr = ["\(req.URL!.host!)", "\(port)"] if addr.count != 2 || Int(addr[1]) == nil { throw WebSocketError.InvalidAddress } var (rdo, wro) : (NSInputStream?, NSOutputStream?) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? CFStreamCreatePairWithSocketToHost(nil, addr[0], UInt32(Int(addr[1])!), &readStream, &writeStream); rdo = readStream!.takeRetainedValue() wro = writeStream!.takeRetainedValue() (rd, wr) = (rdo!, wro!) rd.setProperty(security.level, forKey: NSStreamSocketSecurityLevelKey) wr.setProperty(security.level, forKey: NSStreamSocketSecurityLevelKey) if services.contains(.VoIP) { rd.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) wr.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) } if services.contains(.Video) { rd.setProperty(NSStreamNetworkServiceTypeVideo, forKey: NSStreamNetworkServiceType) wr.setProperty(NSStreamNetworkServiceTypeVideo, forKey: NSStreamNetworkServiceType) } if services.contains(.Background) { rd.setProperty(NSStreamNetworkServiceTypeBackground, forKey: NSStreamNetworkServiceType) wr.setProperty(NSStreamNetworkServiceTypeBackground, forKey: NSStreamNetworkServiceType) } if services.contains(.Voice) { rd.setProperty(NSStreamNetworkServiceTypeVoice, forKey: NSStreamNetworkServiceType) wr.setProperty(NSStreamNetworkServiceTypeVoice, forKey: NSStreamNetworkServiceType) } if allowSelfSignedSSL { let prop: Dictionary<NSObject,NSObject> = [kCFStreamSSLPeerName: kCFNull, kCFStreamSSLValidatesCertificateChain: NSNumber(bool: false)] rd.setProperty(prop, forKey: kCFStreamPropertySSLSettings as String) wr.setProperty(prop, forKey: kCFStreamPropertySSLSettings as String) } rd.delegate = delegate wr.delegate = delegate rd.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) wr.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) rd.open() wr.open() try write(header, length: header.count) } func write(bytes: UnsafePointer<UInt8>, length: Int) throws { if outputBytesStart+outputBytesLength+length > outputBytesSize { var size = outputBytesSize while outputBytesStart+outputBytesLength+length > size { size *= 2 } let ptr = UnsafeMutablePointer<UInt8>(realloc(outputBytes, size)) if ptr == nil { throw WebSocketError.Memory } outputBytes = ptr outputBytesSize = size } memcpy(outputBytes+outputBytesStart+outputBytesLength, bytes, length) outputBytesLength += length } func readResponse() throws { let end : [UInt8] = [ 0x0D, 0x0A, 0x0D, 0x0A ] let ptr = UnsafeMutablePointer<UInt8>(memmem(inputBytes+inputBytesStart, inputBytesLength, end, 4)) if ptr == nil { throw WebSocketError.NeedMoreInput } let buffer = inputBytes+inputBytesStart let bufferCount = ptr-(inputBytes+inputBytesStart) let string = NSString(bytesNoCopy: buffer, length: bufferCount, encoding: NSUTF8StringEncoding, freeWhenDone: false) as? String if string == nil { throw WebSocketError.InvalidHeader } let header = string! var needsCompression = false var serverMaxWindowBits = 15 let clientMaxWindowBits = 15 var key = "" let trim : (String)->(String) = { (text) in return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())} let eqval : (String,String)->(String) = { (line, del) in return trim(line.componentsSeparatedByString(del)[1]) } let lines = header.componentsSeparatedByString("\r\n") for i in 0 ..< lines.count { let line = trim(lines[i]) if i == 0 { if !line.hasPrefix("HTTP/1.1 101"){ throw WebSocketError.InvalidResponse(line) } } else if line != "" { var value = "" if line.hasPrefix("\t") || line.hasPrefix(" ") { value = trim(line) } else { key = "" if let r = line.rangeOfString(":") { key = trim(line.substringToIndex(r.startIndex)) value = trim(line.substringFromIndex(r.endIndex)) } } switch key.lowercaseString { case "sec-websocket-subprotocol": privateSubProtocol = value case "sec-websocket-extensions": let parts = value.componentsSeparatedByString(";") for p in parts { let part = trim(p) if part == "permessage-deflate" { needsCompression = true } else if part.hasPrefix("server_max_window_bits="){ if let i = Int(eqval(line, "=")) { serverMaxWindowBits = i } } } default: break } } } if needsCompression { if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 { throw WebSocketError.InvalidCompressionOptions("server_max_window_bits") } if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 { throw WebSocketError.InvalidCompressionOptions("client_max_window_bits") } inflater = Inflater(windowBits: serverMaxWindowBits) if inflater == nil { throw WebSocketError.InvalidCompressionOptions("inflater init") } deflater = Deflater(windowBits: clientMaxWindowBits, memLevel: 8) if deflater == nil { throw WebSocketError.InvalidCompressionOptions("deflater init") } } inputBytesLength -= bufferCount+4 if inputBytesLength == 0 { inputBytesStart = 0 } else { inputBytesStart += bufferCount+4 } } class ByteReader { var start : UnsafePointer<UInt8> var end : UnsafePointer<UInt8> var bytes : UnsafePointer<UInt8> init(bytes: UnsafePointer<UInt8>, length: Int){ self.bytes = bytes start = bytes end = bytes+length } func readByte() throws -> UInt8 { if bytes >= end { throw WebSocketError.NeedMoreInput } let b = bytes.memory bytes += 1 return b } var length : Int { return end - bytes } var position : Int { get { return bytes - start } set { bytes = start + newValue } } } var fragStateSaved = false var fragStatePosition = 0 var fragStateInflate = false var fragStateLen = 0 var fragStateFin = false var fragStateCode = OpCode.Continue var fragStateLeaderCode = OpCode.Continue var fragStateUTF8 = UTF8() var fragStatePayload = Payload() var fragStateStatusCode = UInt16(0) var fragStateHeaderLen = 0 var buffer = [UInt8](count: windowBufferSize, repeatedValue: 0) var reusedPayload = Payload() func readFrameFragment(leader : Frame?) throws -> Frame { var inflate : Bool var len : Int var fin = false var code : OpCode var leaderCode : OpCode var utf8 : UTF8 var payload : Payload var statusCode : UInt16 var headerLen : Int var leader = leader let reader = ByteReader(bytes: inputBytes+inputBytesStart, length: inputBytesLength) if fragStateSaved { // load state reader.position += fragStatePosition inflate = fragStateInflate len = fragStateLen fin = fragStateFin code = fragStateCode leaderCode = fragStateLeaderCode utf8 = fragStateUTF8 payload = fragStatePayload statusCode = fragStateStatusCode headerLen = fragStateHeaderLen fragStateSaved = false } else { var b = try reader.readByte() fin = b >> 7 & 0x1 == 0x1 let rsv1 = b >> 6 & 0x1 == 0x1 let rsv2 = b >> 5 & 0x1 == 0x1 let rsv3 = b >> 4 & 0x1 == 0x1 if inflater != nil && (rsv1 || (leader != nil && leader!.inflate)) { inflate = true } else if rsv1 || rsv2 || rsv3 { throw WebSocketError.ProtocolError("invalid extension") } else { inflate = false } code = OpCode.Binary if let c = OpCode(rawValue: (b & 0xF)){ code = c } else { throw WebSocketError.ProtocolError("invalid opcode") } if !fin && code.isControl { throw WebSocketError.ProtocolError("unfinished control frame") } b = try reader.readByte() if b >> 7 & 0x1 == 0x1 { throw WebSocketError.ProtocolError("server sent masked frame") } var len64 = Int64(b & 0x7F) var bcount = 0 if b & 0x7F == 126 { bcount = 2 } else if len64 == 127 { bcount = 8 } if bcount != 0 { if code.isControl { throw WebSocketError.ProtocolError("invalid payload size for control frame") } len64 = 0 var i = bcount-1 while i >= 0 { b = try reader.readByte() len64 += Int64(b) << Int64(i*8) i -= 1 } } len = Int(len64) if code == .Continue { if code.isControl { throw WebSocketError.ProtocolError("control frame cannot have the 'continue' opcode") } if leader == nil { throw WebSocketError.ProtocolError("continue frame is missing it's leader") } } if code.isControl { if leader != nil { leader = nil } if inflate { throw WebSocketError.ProtocolError("control frame cannot be compressed") } } statusCode = 0 if leader != nil { leaderCode = leader!.code utf8 = leader!.utf8 payload = leader!.payload } else { leaderCode = code utf8 = UTF8() payload = reusedPayload payload.count = 0 } if leaderCode == .Close { if len == 1 { throw WebSocketError.ProtocolError("invalid payload size for close frame") } if len >= 2 { let b1 = try reader.readByte() let b2 = try reader.readByte() statusCode = (UInt16(b1) << 8) + UInt16(b2) len -= 2 if statusCode < 1000 || statusCode > 4999 || (statusCode >= 1004 && statusCode <= 1006) || (statusCode >= 1012 && statusCode <= 2999) { throw WebSocketError.ProtocolError("invalid status code for close frame") } } } headerLen = reader.position } let rlen : Int let rfin : Bool let chopped : Bool if reader.length+reader.position-headerLen < len { rlen = reader.length rfin = false chopped = true } else { rlen = len-reader.position+headerLen rfin = fin chopped = false } let bytes : UnsafeMutablePointer<UInt8> let bytesLen : Int if inflate { (bytes, bytesLen) = try inflater!.inflate(reader.bytes, length: rlen, final: rfin) } else { (bytes, bytesLen) = (UnsafeMutablePointer<UInt8>(reader.bytes), rlen) } reader.bytes += rlen if leaderCode == .Text || leaderCode == .Close { try utf8.append(bytes, length: bytesLen) } else { payload.append(bytes, length: bytesLen) } if chopped { // save state fragStateHeaderLen = headerLen fragStateStatusCode = statusCode fragStatePayload = payload fragStateUTF8 = utf8 fragStateLeaderCode = leaderCode fragStateCode = code fragStateFin = fin fragStateLen = len fragStateInflate = inflate fragStatePosition = reader.position fragStateSaved = true throw WebSocketError.NeedMoreInput } inputBytesLength -= reader.position if inputBytesLength == 0 { inputBytesStart = 0 } else { inputBytesStart += reader.position } let f = Frame() (f.code, f.payload, f.utf8, f.statusCode, f.inflate, f.finished) = (code, payload, utf8, statusCode, inflate, fin) return f } var head = [UInt8](count: 0xFF, repeatedValue: 0) func writeFrame(f : Frame) throws { if !f.finished{ throw WebSocketError.LibraryError("cannot send unfinished frames") } var hlen = 0 let b : UInt8 = 0x80 var deflate = false if deflater != nil { if f.code == .Binary || f.code == .Text { deflate = true // b |= 0x40 } } head[hlen] = b | f.code.rawValue hlen += 1 var payloadBytes : [UInt8] var payloadLen = 0 if f.utf8.text != "" { payloadBytes = UTF8.bytes(f.utf8.text) } else { payloadBytes = f.payload.array } payloadLen += payloadBytes.count if deflate { } var usingStatusCode = false if f.statusCode != 0 && payloadLen != 0 { payloadLen += 2 usingStatusCode = true } if payloadLen < 126 { head[hlen] = 0x80 | UInt8(payloadLen) hlen += 1 } else if payloadLen <= 0xFFFF { head[hlen] = 0x80 | 126 hlen += 1 var i = 1 while i >= 0 { head[hlen] = UInt8((UInt16(payloadLen) >> UInt16(i*8)) & 0xFF) hlen += 1 i -= 1 } } else { head[hlen] = UInt8((0x1 << 7) + 127) hlen += 1 var i = 7 while i >= 0 { head[hlen] = UInt8((UInt64(payloadLen) >> UInt64(i*8)) & 0xFF) hlen += 1 i -= 1 } } let r = arc4random() var maskBytes : [UInt8] = [UInt8(r >> 0 & 0xFF), UInt8(r >> 8 & 0xFF), UInt8(r >> 16 & 0xFF), UInt8(r >> 24 & 0xFF)] for i in 0 ..< 4 { head[hlen] = maskBytes[i] hlen += 1 } if payloadLen > 0 { if usingStatusCode { var sc = [UInt8(f.statusCode >> 8 & 0xFF), UInt8(f.statusCode >> 0 & 0xFF)] for i in 0 ..< 2 { sc[i] ^= maskBytes[i % 4] } head[hlen] = sc[0] hlen += 1 head[hlen] = sc[1] hlen += 1 for i in 2 ..< payloadLen { payloadBytes[i-2] ^= maskBytes[i % 4] } } else { for i in 0 ..< payloadLen { payloadBytes[i] ^= maskBytes[i % 4] } } } try write(head, length: hlen) try write(payloadBytes, length: payloadBytes.count) } func close(code : Int = 1000, reason : String = "Normal Closure") { let f = Frame() f.code = .Close f.statusCode = UInt16(truncatingBitPattern: code) f.utf8.text = reason sendFrame(f) } func sendFrame(f : Frame) { lock() frames += [f] unlock() manager.signal() } func send(message : Any) { let f = Frame() if let message = message as? String { f.code = .Text f.utf8.text = message } else if let message = message as? [UInt8] { f.code = .Binary f.payload.array = message } else if let message = message as? UnsafeBufferPointer<UInt8> { f.code = .Binary f.payload.append(message.baseAddress, length: message.count) } else if let message = message as? NSData { f.code = .Binary f.payload.nsdata = message } else { f.code = .Text f.utf8.text = "\(message)" } sendFrame(f) } func ping() { let f = Frame() f.code = .Ping sendFrame(f) } func ping(message : Any){ let f = Frame() f.code = .Ping if let message = message as? String { f.payload.array = UTF8.bytes(message) } else if let message = message as? [UInt8] { f.payload.array = message } else if let message = message as? UnsafeBufferPointer<UInt8> { f.payload.append(message.baseAddress, length: message.count) } else if let message = message as? NSData { f.payload.nsdata = message } else { f.utf8.text = "\(message)" } sendFrame(f) } } private func ==(lhs: InnerWebSocket, rhs: InnerWebSocket) -> Bool { return lhs.id == rhs.id } private enum TCPConnSecurity { case None case NegoticatedSSL var level: String { switch self { case .None: return NSStreamSocketSecurityLevelNone case .NegoticatedSSL: return NSStreamSocketSecurityLevelNegotiatedSSL } } } // Manager class is used to minimize the number of dispatches and cycle through network events // using fewers threads. Helps tremendously with lowing system resources when many conncurrent // sockets are opened. private class Manager { var queue = dispatch_queue_create("SwiftWebSocketInstance", nil) var once = dispatch_once_t() var mutex = pthread_mutex_t() var cond = pthread_cond_t() var websockets = Set<InnerWebSocket>() var _nextId = 0 init(){ pthread_mutex_init(&mutex, nil) pthread_cond_init(&cond, nil) dispatch_async(dispatch_queue_create("SwiftWebSocket", nil)) { var wss : [InnerWebSocket] = [] while true { var wait = true wss.removeAll() pthread_mutex_lock(&self.mutex) for ws in self.websockets { wss.append(ws) } for ws in wss { self.checkForConnectionTimeout(ws) if ws.dirty { pthread_mutex_unlock(&self.mutex) ws.step() pthread_mutex_lock(&self.mutex) wait = false } } if wait { self.wait(250) } pthread_mutex_unlock(&self.mutex) } } } func checkForConnectionTimeout(ws : InnerWebSocket) { if ws.rd != nil && ws.wr != nil && (ws.rd.streamStatus == .Opening || ws.wr.streamStatus == .Opening) { let age = CFAbsoluteTimeGetCurrent() - ws.createdAt if age >= timeoutDuration { ws.connectionTimeout = true } } } func wait(timeInMs : Int) -> Int32 { var ts = timespec() var tv = timeval() gettimeofday(&tv, nil) ts.tv_sec = time(nil) + timeInMs / 1000; let v1 = Int(tv.tv_usec * 1000) let v2 = Int(1000 * 1000 * Int(timeInMs % 1000)) ts.tv_nsec = v1 + v2; ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000); ts.tv_nsec %= (1000 * 1000 * 1000); return pthread_cond_timedwait(&self.cond, &self.mutex, &ts) } func signal(){ pthread_mutex_lock(&mutex) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func add(websocket: InnerWebSocket) { pthread_mutex_lock(&mutex) websockets.insert(websocket) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func remove(websocket: InnerWebSocket) { pthread_mutex_lock(&mutex) websockets.remove(websocket) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func nextId() -> Int { pthread_mutex_lock(&mutex) defer { pthread_mutex_unlock(&mutex) } _nextId += 1 return _nextId } } private let manager = Manager() /// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455. public class WebSocket: NSObject { private var ws: InnerWebSocket private var id = manager.nextId() private var opened: Bool public override var hashValue: Int { return id } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public convenience init(_ url: String){ self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: []) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public convenience init(url: NSURL){ self.init(request: NSURLRequest(URL: url), subProtocols: []) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols. public convenience init(_ url: String, subProtocols : [String]){ self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: subProtocols) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol. public convenience init(_ url: String, subProtocol : String){ self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [subProtocol]) } /// Create a WebSocket connection from an NSURLRequest; Also include a list of protocols. public init(request: NSURLRequest, subProtocols : [String] = []){ let hasURL = request.URL != nil opened = hasURL ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: !hasURL) super.init() var outer : WebSocket? = self ws.eclose = { [unowned self] in self.opened = false if outer != nil{ outer = nil } } } /// Create a WebSocket object with a deferred connection; the connection is not opened until the .open() method is called. public convenience override init(){ self.init(request: NSURLRequest(), subProtocols: []) } /// The URL as resolved by the constructor. This is always an absolute URL. Read only. public var url : String{ return ws.url } /// A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object. public var subProtocol : String{ return ws.subProtocol } /// The compression options of the WebSocket. public var compression : WebSocketCompression{ get { return ws.compression } set { ws.compression = newValue } } /// Allow for Self-Signed SSL Certificates. Default is false. public var allowSelfSignedSSL : Bool{ get { return ws.allowSelfSignedSSL } set { ws.allowSelfSignedSSL = newValue } } /// The services of the WebSocket. public var services : WebSocketService{ get { return ws.services } set { ws.services = newValue } } /// The events of the WebSocket. public var event : WebSocketEvents{ get { return ws.event } set { ws.event = newValue } } /// The queue for firing off events. default is main_queue public var eventQueue : dispatch_queue_t?{ get { return ws.eventQueue } set { ws.eventQueue = newValue } } /// A WebSocketBinaryType value indicating the type of binary data being transmitted by the connection. Default is .UInt8Array. public var binaryType : WebSocketBinaryType{ get { return ws.binaryType } set { ws.binaryType = newValue } } /// The current state of the connection; this is one of the WebSocketReadyState constants. Read only. public var readyState : WebSocketReadyState{ return ws.readyState } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public func open(url: String){ open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: []) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public func open(nsurl url: NSURL){ open(request: NSURLRequest(URL: url), subProtocols: []) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols. public func open(url: String, subProtocols : [String]){ open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: subProtocols) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol. public func open(url: String, subProtocol : String){ open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [subProtocol]) } /// Opens a deferred or closed WebSocket connection from an NSURLRequest; Also include a list of protocols. public func open(request request: NSURLRequest, subProtocols : [String] = []){ if opened{ return } opened = true ws = ws.copyOpen(request, subProtocols: subProtocols) } /// Opens a closed WebSocket connection from an NSURLRequest; Uses the same request and protocols as previously closed WebSocket public func open(){ open(request: ws.request, subProtocols: ws.subProtocols) } /** Closes the WebSocket connection or connection attempt, if any. If the connection is already closed or in the state of closing, this method does nothing. :param: code An integer indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal closure) is assumed. :param: reason A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters). */ public func close(code : Int = 1000, reason : String = "Normal Closure"){ if !opened{ return } opened = false ws.close(code, reason: reason) } /** Transmits message to the server over the WebSocket connection. :param: message The message to be sent to the server. */ public func send(message : Any){ if !opened{ return } ws.send(message) } /** Transmits a ping to the server over the WebSocket connection. :param: optional message The data to be sent to the server. */ public func ping(message : Any){ if !opened{ return } ws.ping(message) } /** Transmits a ping to the server over the WebSocket connection. */ public func ping(){ if !opened{ return } ws.ping() } } public func ==(lhs: WebSocket, rhs: WebSocket) -> Bool { return lhs.id == rhs.id } extension WebSocket { /// The events of the WebSocket using a delegate. public var delegate : WebSocketDelegate? { get { return ws.eventDelegate } set { ws.eventDelegate = newValue } } /** Transmits message to the server over the WebSocket connection. :param: text The message (string) to be sent to the server. */ @objc public func send(text text: String){ send(text) } /** Transmits message to the server over the WebSocket connection. :param: data The message (binary) to be sent to the server. */ @objc public func send(data data: NSData){ send(data) } }
50e4c0e83b16aa298046224757c99cc7
36.358904
227
0.554781
false
false
false
false
dduan/swift
refs/heads/master
stdlib/public/SDK/SceneKit/SceneKit.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import SceneKit // Clang module // MARK: Exposing SCNFloat #if os(OSX) public typealias SCNFloat = CGFloat #elseif os(iOS) || os(tvOS) public typealias SCNFloat = Float #endif // MARK: Working with SCNVector3 extension SCNVector3 { public init(_ x: Float, _ y: Float, _ z: Float) { self.x = SCNFloat(x) self.y = SCNFloat(y) self.z = SCNFloat(z) } public init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat) { self.x = SCNFloat(x) self.y = SCNFloat(y) self.z = SCNFloat(z) } public init(_ x: Double, _ y: Double, _ z: Double) { self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z)) } public init(_ x: Int, _ y: Int, _ z: Int) { self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z)) } public init(_ v: float3) { self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z)) } public init(_ v: double3) { self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z)) } } extension float3 { public init(_ v: SCNVector3) { self.init(Float(v.x), Float(v.y), Float(v.z)) } } extension double3 { public init(_ v: SCNVector3) { self.init(Double(v.x), Double(v.y), Double(v.z)) } } // MARK: Working with SCNVector4 extension SCNVector4 { public init(_ x: Float, _ y: Float, _ z: Float, _ w: Float) { self.x = SCNFloat(x) self.y = SCNFloat(y) self.z = SCNFloat(z) self.w = SCNFloat(w) } public init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat, _ w: CGFloat) { self.x = SCNFloat(x) self.y = SCNFloat(y) self.z = SCNFloat(z) self.w = SCNFloat(w) } public init(_ x: Double, _ y: Double, _ z: Double, _ w: Double) { self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z), SCNFloat(w)) } public init(_ x: Int, _ y: Int, _ z: Int, _ w: Int) { self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z), SCNFloat(w)) } public init(_ v: float4) { self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z), SCNFloat(v.w)) } public init(_ v: double4) { self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z), SCNFloat(v.w)) } } extension float4 { public init(_ v: SCNVector4) { self.init(Float(v.x), Float(v.y), Float(v.z), Float(v.w)) } } extension double4 { public init(_ v: SCNVector4) { self.init(Double(v.x), Double(v.y), Double(v.z), Double(v.w)) } } // MARK: Working with SCNMatrix4 extension SCNMatrix4 { public init(_ m: float4x4) { self.init( m11: SCNFloat(m[0,0]), m12: SCNFloat(m[0,1]), m13: SCNFloat(m[0,2]), m14: SCNFloat(m[0,3]), m21: SCNFloat(m[1,0]), m22: SCNFloat(m[1,1]), m23: SCNFloat(m[1,2]), m24: SCNFloat(m[1,3]), m31: SCNFloat(m[2,0]), m32: SCNFloat(m[2,1]), m33: SCNFloat(m[2,2]), m34: SCNFloat(m[2,3]), m41: SCNFloat(m[3,0]), m42: SCNFloat(m[3,1]), m43: SCNFloat(m[3,2]), m44: SCNFloat(m[3,3])) } public init(_ m: double4x4) { self.init( m11: SCNFloat(m[0,0]), m12: SCNFloat(m[0,1]), m13: SCNFloat(m[0,2]), m14: SCNFloat(m[0,3]), m21: SCNFloat(m[1,0]), m22: SCNFloat(m[1,1]), m23: SCNFloat(m[1,2]), m24: SCNFloat(m[1,3]), m31: SCNFloat(m[2,0]), m32: SCNFloat(m[2,1]), m33: SCNFloat(m[2,2]), m34: SCNFloat(m[2,3]), m41: SCNFloat(m[3,0]), m42: SCNFloat(m[3,1]), m43: SCNFloat(m[3,2]), m44: SCNFloat(m[3,3])) } } extension float4x4 { public init(_ m: SCNMatrix4) { self.init([ float4(Float(m.m11), Float(m.m12), Float(m.m13), Float(m.m14)), float4(Float(m.m21), Float(m.m22), Float(m.m23), Float(m.m24)), float4(Float(m.m31), Float(m.m32), Float(m.m33), Float(m.m34)), float4(Float(m.m41), Float(m.m42), Float(m.m43), Float(m.m44)) ]) } } extension double4x4 { public init(_ m: SCNMatrix4) { self.init([ double4(Double(m.m11), Double(m.m12), Double(m.m13), Double(m.m14)), double4(Double(m.m21), Double(m.m22), Double(m.m23), Double(m.m24)), double4(Double(m.m31), Double(m.m32), Double(m.m33), Double(m.m34)), double4(Double(m.m41), Double(m.m42), Double(m.m43), Double(m.m44)) ]) } } // MARK: APIs refined for Swift @available(iOS, introduced: 8.0) @available(OSX, introduced: 10.8) extension SCNGeometryElement { public convenience init<IndexType : Integer>( indices: [IndexType], primitiveType: SCNGeometryPrimitiveType ) { let indexCount = indices.count let primitiveCount: Int switch primitiveType { case .triangles: primitiveCount = indexCount / 3 case .triangleStrip: primitiveCount = indexCount - 2 case .line: primitiveCount = indexCount / 2 case .point: primitiveCount = indexCount } self.init( data: NSData(bytes: indices, length: indexCount * sizeof(IndexType)), primitiveType: primitiveType, primitiveCount: primitiveCount, bytesPerIndex: sizeof(IndexType)) } } @warn_unused_result @_silgen_name("SCN_Swift_SCNSceneSource_entryWithIdentifier") internal func SCN_Swift_SCNSceneSource_entryWithIdentifier( self_: AnyObject, _ uid: NSString, _ entryClass: AnyObject) -> AnyObject? @available(iOS, introduced: 8.0) @available(OSX, introduced: 10.8) extension SCNSceneSource { @warn_unused_result public func entryWithIdentifier<T>(uid: String, withClass entryClass: T.Type) -> T? { return SCN_Swift_SCNSceneSource_entryWithIdentifier( self, uid, entryClass as! AnyObject) as! T? } }
bcd23215c9e288d53a674b89769c1148
29.909574
97
0.613664
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Frontend/Home/Wallpapers/v1/Utilities/WallpaperStorageUtility.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/ import Foundation import Shared enum WallpaperStorageError: Error { case fileDoesNotExistError case noDataAtFilePath case failedToConvertImage case failedSavingFile case cannotFindWallpaperDirectory case cannotFindThumbnailDirectory } /// Responsible for writing or deleting wallpaper data to/from memory. struct WallpaperStorageUtility: WallpaperMetadataCodableProtocol, Loggable { private var userDefaults: UserDefaultsInterface private var fileManager: FileManagerInterface // MARK: - Initializer init( with userDefaults: UserDefaultsInterface = UserDefaults.standard, and fileManager: FileManagerInterface = FileManager.default ) { self.userDefaults = userDefaults self.fileManager = fileManager } // MARK: - Storage func store(_ metadata: WallpaperMetadata) throws { let filePathProvider = WallpaperFilePathProvider(with: fileManager) if let filePath = filePathProvider.metadataPath() { let data = try encodeToData(from: metadata) // TODO: [roux] - rename old file to preserve metadata in case of write // error. This is more than it first seems. try removeFileIfItExists(at: filePath) let successfullyCreated = fileManager.createFile( atPath: filePath.path, contents: data, attributes: nil) if !successfullyCreated { throw WallpaperStorageError.failedSavingFile } } } func store(_ wallpaper: Wallpaper) throws { let encoded = try JSONEncoder().encode(wallpaper) userDefaults.set(encoded, forKey: PrefsKeys.Wallpapers.CurrentWallpaper) } func store(_ image: UIImage, withName name: String, andKey key: String) throws { let filePathProvider = WallpaperFilePathProvider(with: fileManager) guard let filePath = filePathProvider.imagePathWith(name: name), let pngRepresentation = image.pngData() else { throw WallpaperStorageError.failedToConvertImage } try removeFileIfItExists(at: filePath) try pngRepresentation.write(to: filePath, options: .atomic) } // MARK: - Retrieval func fetchMetadata() throws -> WallpaperMetadata? { let filePathProvider = WallpaperFilePathProvider(with: fileManager) guard let filePath = filePathProvider.metadataPath() else { return nil } if !fileManager.fileExists(atPath: filePath.path) { throw WallpaperStorageError.fileDoesNotExistError } if let data = fileManager.contents(atPath: filePath.path) { return try decodeMetadata(from: data) } else { throw WallpaperStorageError.noDataAtFilePath } } public func fetchCurrentWallpaper() -> Wallpaper { if let data = userDefaults.object(forKey: PrefsKeys.Wallpapers.CurrentWallpaper) as? Data { do { return try JSONDecoder().decode(Wallpaper.self, from: data) } catch { browserLog.error("WallpaperStorageUtility decoding error: \(error.localizedDescription)") } } return Wallpaper(id: "fxDefault", textColor: nil, cardColor: nil, logoTextColor: nil) } public func fetchImageNamed(_ name: String) throws -> UIImage? { let filePathProvider = WallpaperFilePathProvider(with: fileManager) guard let filePath = filePathProvider.imagePathWith(name: name), let fileData = FileManager.default.contents(atPath: filePath.path), let image = UIImage(data: fileData) else { return nil } return image } // MARK: - Deletion public func cleanupUnusedAssets() throws { try removeUnusedLargeWallpaperFiles() try removeUnusedThumbnails() } // MARK: - Helper functions private func removeUnusedLargeWallpaperFiles() throws { let filePathProvider = WallpaperFilePathProvider(with: fileManager) guard let wallpaperDirectory = filePathProvider.wallpaperDirectoryPath() else { throw WallpaperStorageError.cannotFindWallpaperDirectory } try removefiles(from: wallpaperDirectory, excluding: try directoriesToKeep()) } private func directoriesToKeep() throws -> [String] { let filePathProvider = WallpaperFilePathProvider(with: fileManager) let currentWallpaper = fetchCurrentWallpaper() return [ currentWallpaper.id, filePathProvider.thumbnailsKey, filePathProvider.metadataKey ] } private func removeUnusedThumbnails() throws { let filePathProvider = WallpaperFilePathProvider(with: fileManager) guard let thumbnailsDirectory = filePathProvider.folderPath(forKey: filePathProvider.thumbnailsKey), let metadata = try fetchMetadata() else { throw WallpaperStorageError.cannotFindThumbnailDirectory } let availableThumbnailIDs = metadata.collections .filter { $0.isAvailable } .flatMap { $0.wallpapers } .map { $0.thumbnailID } try removefiles(from: thumbnailsDirectory, excluding: availableThumbnailIDs) } private func removefiles(from directory: URL, excluding filesToKeep: [String]) throws { let directoryContents = try fileManager.contentsOfDirectory( at: directory, includingPropertiesForKeys: nil, options: []) for url in directoryContents.filter({ !filesToKeep.contains($0.lastPathComponent) }) { try removeFileIfItExists(at: url) } } private func removeFileIfItExists(at url: URL) throws { if fileManager.fileExists(atPath: url.path) { try fileManager.removeItem(at: url) } } }
7c6de89a3c5bc9c12bafcba6ed80b0df
35.129412
108
0.662488
false
false
false
false
akpw/VisualBinaryTrees
refs/heads/master
VisualBinaryTrees.playground/Sources/Tree/TreeSamples/TreeNodeRef.swift
gpl-3.0
1
// GNU General Public License. See the LICENSE file for more details. // Copyright © 2016 Arseniy Kuznetsov. All rights reserved. import UIKit /// A Sample Tree implemented as a reference type public final class TreeNodeRef<Element: Comparable>: QuickLookableBinaryTree, TraversableBinaryTree { fileprivate(set) public var element: Element public var left: TreeNodeRef? public var right: TreeNodeRef? // default is in-order traversal public var traversalStrategy: TraversalStrategy.Type? = InOrderTraversalStrategy.self public init(_ element: Element) { self.element = element } } extension TreeNodeRef: BinarySearchTree { public func insert(_ element: Element) { if element < self.element { if let l = left { l.insert(element) } else { left = TreeNodeRef(element) } } else { if let r = right { r.insert(element) } else { right = TreeNodeRef(element) } } } } extension TreeNodeRef: ExpressibleByArrayLiteral { convenience public init <S: Sequence>(_ elements: S) where S.Iterator.Element == Element { self.init(elements: Array(elements)) } convenience public init(arrayLiteral elements: Element...) { self.init(elements: elements) } convenience public init(elements: [Element]) { let minimalHeightSequence = SequenceHelper.minimalHeightBSTSequence(elements: elements) guard let first = minimalHeightSequence.first(where: { _ in true }) else { fatalError("can not init a tree from an empty sequence") } self.init(first) for value in minimalHeightSequence.dropFirst() { insert(value) } } }
57eb1184b8385f3dfa93740e92880edd
35.895833
95
0.647092
false
false
false
false
bengottlieb/Chronicle
refs/heads/master
Chronicle/Framework Code/ImageMessageMac.swift
mit
1
// // ImageMessage.swift // Chronicle // // Created by Ben Gottlieb on 6/6/15. // Copyright (c) 2015 Stand Alone, inc. All rights reserved. // import Foundation import AppKit public func clog(@autoclosure image: () -> NSImage, @autoclosure text: () -> String = { "" }(), priority: Message.Priority = DEFAULT_PRIORITY, tags: [String]? = nil, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: Int = __LINE__, column: Int = __COLUMN__) -> Message? { if !isLoggingEnabled || priority.rawValue < Chronicle.instance.minimumVisiblePriority.rawValue { return nil } var message = ImageMessage(image: image(), text: text(), priority: priority, tags: tags, file: file, function: function, line: line, column: column) Chronicle.instance.logMessage(message) return message } public func clog(image: NSImage, text: String = "", priority: Message.Priority = DEFAULT_PRIORITY, tags: [String]? = nil, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: Int = __LINE__, column: Int = __COLUMN__) { var message = ImageMessage(image: image, text: text, priority: priority, tags: tags, file: file, function: function, line: line, column: column) Chronicle.instance.logMessage(message) } public class ImageMessage: Message { let image: NSImage? public init(image img: NSImage, text t: String, priority p: Priority = DEFAULT_PRIORITY, tags tg: [String]? = nil, file: StaticString? = nil, function: StaticString? = nil, line: Int? = nil, column: Int? = nil) { image = img super.init(text: t, priority: p, tags: tg, file: file, function: function, line: line, column: column) } public required init(coder: NSCoder) { if let data = coder.decodeObjectForKey("img") as? NSData { image = NSImage(data: data) } else { image = nil } super.init(coder: coder) } public override func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) if let image = self.image { var reps = image.representations var props = [NSImageCompressionFactor: 0.85] if let imageData = NSBitmapImageRep.representationOfImageRepsInArray(reps, usingType: .NSJPEGFileType, properties: props) { aCoder.encodeObject(imageData, forKey: "img") } } } public override var description: String { var string = super.description if let image = self.image { string += " (image: \(Int(image.size.width)) x \(Int(image.size.height)))" } return string } }
94858ca959048371e4bcf393e479c102
37.03125
297
0.693919
false
false
false
false
rb-de0/Fluxer
refs/heads/master
FluxerTests/Observable/Operator/RefCountTests.swift
mit
1
// // RefCountTests.swift // Fluxer // // Created by rb_de0 on 2017/04/11. // Copyright © 2017年 rb_de0. All rights reserved. // import XCTest @testable import Fluxer class RefCountTests: XCTestCase { func testNotShare() { let value = ObservableValue(0) var mapCalledCount = 0 let map = value.map { value -> Int in mapCalledCount += 1 return value * 2 } _ = map.subscribe { print($0) } _ = map.subscribe { print($0) } value.value = 10 XCTAssertEqual(mapCalledCount, 2) } func testShare() { let value = ObservableValue(0) var mapCalledCount = 0 let map = value.map { value -> Int in mapCalledCount += 1 return value * 2 }.share() _ = map.subscribe { print($0) } _ = map.subscribe { print($0) } value.value = 10 XCTAssertEqual(mapCalledCount, 1) } func testDisconnect() { let value = ObservableValue(0) var mapCalledCount = 0 let map = value.map { value -> Int in mapCalledCount += 1 return value * 2 }.share() let disposable = map.subscribe { print($0) } value.value = 10 XCTAssertEqual(mapCalledCount, 1) disposable.dispose() value.value = 10 XCTAssertEqual(mapCalledCount, 1) } }
b38383f739ec0dfeba89788da4f127bb
19.059524
50
0.453412
false
true
false
false
kuruvilla6970/Zoot
refs/heads/master
Source/JS API/NavigationBar.swift
mit
1
// // NavigationBar.swift // THGHybridWeb // // Created by Angelo Di Paolo on 6/3/15. // Copyright (c) 2015 TheHolyGrail. All rights reserved. // import JavaScriptCore @objc protocol NavigationBarJSExport: JSExport { func setTitle(title: JSValue, _ callback: JSValue?) func setButtons(buttonsToSet: AnyObject?, _ callback: JSValue?, _ testingCallback: JSValue?) } @objc public class NavigationBar: ViewControllerChild { private var callback: JSValue? private var buttons: [Int: BarButton]? { didSet { if let buttons = buttons { if let leftButton = buttons[0]?.barButtonItem { parentViewController?.navigationItem.leftBarButtonItem = leftButton } else { parentViewController?.navigationItem.leftBarButtonItem = nil } if let rightButton = buttons[1]?.barButtonItem { parentViewController?.navigationItem.rightBarButtonItem = rightButton } else { parentViewController?.navigationItem.rightBarButtonItem = nil } } else { parentViewController?.navigationItem.leftBarButtonItem = nil parentViewController?.navigationItem.rightBarButtonItem = nil } } } } extension NavigationBar: NavigationBarJSExport { func setTitle(title: JSValue, _ callback: JSValue? = nil) { dispatch_async(dispatch_get_main_queue()) { self.parentViewController?.navigationItem.title = title.asString callback?.callWithArguments(nil) } } func setButtons(options: AnyObject?, _ callback: JSValue? = nil, _ testingCallback: JSValue? = nil) { self.callback = callback dispatch_async(dispatch_get_main_queue()) { if let buttonsToSet = options as? [[String: AnyObject]], let callback = callback where buttonsToSet.count > 0 { self.buttons = BarButton.dictionaryFromJSONArray(buttonsToSet, callback: callback) // must set buttons on main thread } else { self.buttons = nil } testingCallback?.callWithArguments(nil) // only for testing purposes } } }
f5d41dbc48e0cc5d1bca197c1c381f28
34.058824
137
0.591023
false
true
false
false
volendavidov/NagBar
refs/heads/master
NagBar/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // NagBar // // Created by Volen Davidov on 10.01.16. // Copyright © 2016 Volen Davidov. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var preferencesWindow: PreferencesWindowController? var passwordWindow: PasswordPromptController? @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(_ notification: Notification) { // init the configuration InitConfig().initConfig() // check if the Dock icon should be displayed if !Settings().boolForKey("showDockIcon") { NSApp.setActivationPolicy(.accessory) } // check for new versions if Settings().boolForKey("newVersionCheck") { CheckNewVersion().checkNewVersion() } // ask for passwords in case they are not saved if !Settings().boolForKey("savePassword") && MonitoringInstances().getAllEnabled().count > 0 { self.showPasswordPrompt() } self.refreshStatusData() let timer = Timer(timeInterval: Settings().doubleForKey("refreshInterval"), target: self, selector: #selector(self.refreshStatusData), userInfo: nil, repeats: true) RunLoop.current.add(timer, forMode: RunLoop.Mode.common) } @IBAction func openPreferences(_ sender: AnyObject) { if self.preferencesWindow == nil { self.preferencesWindow = PreferencesWindowController(windowNibName: "PreferencesWindow") } self.preferencesWindow!.showWindow(self) } @objc func refreshStatusData() { LoadMonitoringData().refreshStatusData() } func showPasswordPrompt() { if self.passwordWindow == nil { self.passwordWindow = PasswordPromptController(windowNibName: "PasswordPrompt") } self.passwordWindow!.showWindow(self) } }
a90b7ee6e70d912534607867d2dd825e
30.887097
172
0.644917
false
false
false
false
Ethenyl/JAMFKit
refs/heads/master
JamfKit/Sources/Models/ComputerCommand/ComputerCommandGeneral.swift
mit
1
// // Copyright © 2017-present JamfKit. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // @objc(JMFKComputerCommandGeneral) public final class ComputerCommandGeneral: NSObject, Requestable { // MARK: - Constants static let CommandKey = "command" static let PasscodeKey = "passcode" // MARK: - Properties @objc public var command = "" @objc public var passcode: UInt = 0 // MARK: - Initialization public init?(json: [String: Any], node: String = "") { guard let command = json[ComputerCommandGeneral.CommandKey] as? String, let passcode = json[ComputerCommandGeneral.PasscodeKey] as? UInt else { return nil } self.command = command self.passcode = passcode } public init?(command: String, passcode: UInt) { guard !command.isEmpty, passcode > 0 else { return nil } self.command = command self.passcode = passcode } // MARK: - Functions public func toJSON() -> [String: Any] { var json = [String: Any]() json[ComputerCommandGeneral.CommandKey] = command json[ComputerCommandGeneral.PasscodeKey] = passcode return json } }
76ac33a295944c7f5dcaaf14efb72e09
23.290909
102
0.613772
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Localization/Locale/Locale/ViewController.swift
mit
1
// // ViewController.swift // Locale // // Created by Domenico Solazzo // import UIKit class ViewController: UIViewController { @IBOutlet var localeLabel : UILabel! @IBOutlet var flagImageView : UIImageView! @IBOutlet var labels : [UILabel]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // User locale let locale = Foundation.Locale.current // User preferred language let currentLangID = (Foundation.Locale.preferredLanguages )[0] let displayLang = (locale as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: currentLangID) let capitalized = displayLang?.capitalized(with: locale) localeLabel.text = capitalized labels[0].text = NSLocalizedString("LABEL_ONE", comment: "The number 1") labels[1].text = NSLocalizedString("LABEL_TWO", comment: "The number 2") labels[2].text = NSLocalizedString("LABEL_THREE", comment: "The number 3") labels[3].text = NSLocalizedString("LABEL_FOUR", comment: "The number 4") labels[4].text = NSLocalizedString("LABEL_FIVE", comment: "The number 5") let flagFile = NSLocalizedString("FLAG_FILE", comment: "Name of the flag") flagImageView.image = UIImage(named: flagFile) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
5b0e5ac8d3602cf66dad2d0444467d24
34.511628
115
0.666012
false
false
false
false
kysonyangs/ysbilibili
refs/heads/master
ysbilibili/Classes/Home/Bangumi/BangumiDetail/View/Commend/YSCommendTableViewCell.swift
mit
1
// // ZHNcommendTableViewCell.swift // zhnbilibili // // Created by 张辉男 on 17/1/2. // Copyright © 2017年 zhn. All rights reserved. // import UIKit class YSCommendTableViewCell: UITableViewCell { var isHotSectionBottom = false { didSet { if isHotSectionBottom { cellLineView.isHidden = true }else { cellLineView.isHidden = false } } } // 为了方便子类赋值 public let nameFont = UIFont.systemFont(ofSize: 15) public let timeFont = UIFont.systemFont(ofSize: 12) public let nameColr = UIColor.darkGray public let timeColor = UIColor.lightGray public let contentFont = UIFont.systemFont(ofSize: 15) var commendModel: YSPlayCommendModel? { didSet { //1. 加载数据 initStatus() } } // MARK - 懒加载控件 lazy var headImageView: UIImageView = { let headImageView = UIImageView() headImageView.contentMode = .scaleAspectFill headImageView.ysCornerRadius = 15 headImageView.clipsToBounds = true return headImageView }() lazy var levelIconImageView: UIImageView = { let levelIconImageView = UIImageView() levelIconImageView.contentMode = .scaleAspectFill return levelIconImageView }() lazy var nameLabel: UILabel = { let nameLabel = UILabel() nameLabel.font = UIFont.systemFont(ofSize: 15) nameLabel.textColor = UIColor.darkGray return nameLabel }() lazy var floorLabel: UILabel = { let floorLabel = UILabel() floorLabel.font = UIFont.systemFont(ofSize: 12) floorLabel.textColor = UIColor.lightGray return floorLabel }() lazy var timeLabel: UILabel = { let timeLabel = UILabel() timeLabel.font = UIFont.systemFont(ofSize: 12) timeLabel.textColor = UIColor.lightGray return timeLabel }() lazy var replyCoutIcon: UIImageView = { let replyCoutIcon = UIImageView() replyCoutIcon.image = UIImage(named: "circle_reply_ic")?.ysTintColor(kNavBarColor) replyCoutIcon.contentMode = .scaleAspectFill return replyCoutIcon }() lazy var likeIcon: UIImageView = { let likeIcon = UIImageView() likeIcon.contentMode = .scaleAspectFill likeIcon.image = UIImage(named: "like") return likeIcon }() lazy var replayLabel: UILabel = { let replayLabel = UILabel() replayLabel.font = UIFont.systemFont(ofSize: 12) replayLabel.textColor = UIColor.lightGray return replayLabel }() lazy var likeLabel: UILabel = { let likeLabel = UILabel() likeLabel.font = UIFont.systemFont(ofSize: 12) likeLabel.textColor = UIColor.lightGray return likeLabel }() lazy var reportButton: UIButton = { let reportButton = UIButton() reportButton.setBackgroundImage(UIImage(named: "common_more"), for: .normal) reportButton.sizeToFit() return reportButton }() lazy var contentLabel: WTKAutoHighLightLabel = { let contentLabel = WTKAutoHighLightLabel() contentLabel.w_highColor = kNavBarColor contentLabel.w_normalColor = UIColor.ysColor(red: 25, green: 25, blue: 25, alpha: 1) contentLabel.numberOfLines = 0 contentLabel.font = UIFont.systemFont(ofSize: 15) return contentLabel }() lazy var cellLineView: UIImageView = { let cellLineView = UIImageView() cellLineView.backgroundColor = kCellLineGrayColor return cellLineView }() // MARK - life cycle override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.accessoryType = .none self.selectionStyle = .none self.backgroundColor = kHomeBackColor addUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() initFrames() } //初始化方法 class func commendCell(tableView: UITableView) -> YSCommendTableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "YSCommendTableViewCell") if cell == nil { cell = YSCommendTableViewCell(style: .default, reuseIdentifier: "YSCommendTableViewCell") } return cell as! YSCommendTableViewCell } } // MARK - 私有方法 extension YSCommendTableViewCell { func initStatus() { // 1.加载头像 if let avatar = commendModel?.member?.avatar { headImageView.sd_setImage(with: URL(string: avatar)) } // 2.加载名字 if let name = commendModel?.member?.uname { nameLabel.text = name } // 3.加载楼层 if let floor = commendModel?.floor { floorLabel.text = "# \(floor)" } // 4.加载时间 if let ctime = commendModel?.ctime { timeLabel.text = ctime.commendTime() } // 5.加载评论数 if let reply = commendModel?.count { if reply == 0{ replayLabel.isHidden = true replyCoutIcon.isHidden = true }else { replayLabel.isHidden = false replyCoutIcon.isHidden = false } replayLabel.text = "\(reply)" } // 6.加载点赞数 if let like = commendModel?.like { likeLabel.text = "\(like)" } // 7.加载内容 if let content = commendModel?.content?.message { // contentLabel.text = content contentLabel.wtk_setText(content) } // 8.加载等级 if let level = commendModel?.member?.level_info?.current_level { levelIconImageView.image = UIImage(named: "misc_level_whiteLv\(level)") } } fileprivate func addUI() { self.addSubview(headImageView) self.addSubview(levelIconImageView) self.addSubview(nameLabel) self.addSubview(floorLabel) self.addSubview(timeLabel) self.addSubview(replyCoutIcon) self.addSubview(replayLabel) self.addSubview(likeIcon) self.addSubview(likeLabel) self.addSubview(reportButton) self.addSubview(contentLabel) self.addSubview(cellLineView) // 手势添加 headImageView.isUserInteractionEnabled = true let tap = UITapGestureRecognizer { [weak self] in guard let mid = self?.commendModel?.member?.mid else {return} YSNotificationHelper.recommendSelectedHomePage(mid: mid) } headImageView.addGestureRecognizer(tap) } fileprivate func initFrames() { headImageView.snp.makeConstraints { (make) in make.top.left.equalTo(self).offset(15) make.size.equalTo(CGSize(width: 30, height: 30)) } levelIconImageView.snp.makeConstraints { (make) in make.centerX.equalTo(headImageView) make.top.equalTo(headImageView.snp.bottom).offset(5) make.size.equalTo(CGSize(width: 15, height: 10)) } nameLabel.snp.makeConstraints { (make) in make.top.equalTo(headImageView.snp.top) make.left.equalTo(headImageView.snp.right).offset(10) } floorLabel.snp.makeConstraints { (make) in make.left.equalTo(nameLabel) make.top.equalTo(nameLabel.snp.bottom).offset(2) } timeLabel.snp.makeConstraints { (make) in make.centerY.equalTo(floorLabel) make.left.equalTo(floorLabel.snp.right).offset(10) } reportButton.snp.makeConstraints { (make) in make.centerY.equalTo(nameLabel) make.right.equalTo(self).offset(-10) } likeLabel.snp.makeConstraints { (make) in make.centerY.equalTo(reportButton) make.right.equalTo(reportButton.snp.left).offset(-15) } likeIcon.snp.makeConstraints { (make) in make.centerY.equalTo(reportButton) make.right.equalTo(likeLabel.snp.left).offset(-5) } replayLabel.snp.makeConstraints { (make) in make.centerY.equalTo(reportButton) make.right.equalTo(likeIcon.snp.left).offset(-25) } replyCoutIcon.snp.makeConstraints { (make) in make.centerY.equalTo(reportButton) make.right.equalTo(replayLabel.snp.left).offset(-5) } contentLabel.snp.makeConstraints { (make) in make.left.equalTo(floorLabel.snp.left) make.right.equalTo(reportButton.snp.right) make.top.equalTo(floorLabel.snp.bottom).offset(10) make.bottom.equalTo(self).offset(-20) } cellLineView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self) make.height.equalTo(0.5) } } }
81447d79bbc510e23d3b23f4030bfe63
33.326996
101
0.610102
false
false
false
false
huangboju/Moots
refs/heads/master
算法学习/LeetCode/LeetCode/SearchInsert.swift
mit
1
// // SearchInsert.swift // LeetCode // // Created by jourhuang on 2021/2/28. // Copyright © 2021 伯驹 黄. All rights reserved. // import Foundation func searchInsert(_ nums: [Int], _ target: Int) -> Int { var start = 0 var end = nums.count - 1 while start <= end { let mid = start + (end - start) / 2 if nums[mid] == target { return mid } else if nums[mid] > target { end -= 1 } else { start += 1 } } return start }
448cf34c73d76e00c01954e6b13b06f9
19.68
56
0.50677
false
false
false
false
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
AztecTests/Formatters/FontFormatterTests.swift
gpl-2.0
2
import XCTest @testable import Aztec // MARK: - FontFormatter Tests // class FontFormatterTests: XCTestCase { let boldFormatter = BoldFormatter() let italicFormatter = ItalicFormatter() func testApplyAttribute() { var attributes: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: UIFont.systemFontSize)] var font: UIFont? //test adding a non-existent testApplyAttribute attributes = boldFormatter.apply(to: attributes) //this should add a new attribute to it font = attributes[.font] as? UIFont XCTAssertNotNil(font) XCTAssertTrue(font!.containsTraits(.traitBold)) //test addding a existent attribute attributes = boldFormatter.apply(to: attributes) // this shouldn't change anything in the attributes font = attributes[.font] as? UIFont XCTAssertNotNil(font) XCTAssertTrue(font!.containsTraits(.traitBold)) } func testRemoveAttributes() { var attributes: [NSAttributedString.Key : Any] = [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)] var font: UIFont? //test removing a existent attribute attributes = boldFormatter.remove(from: attributes) font = attributes[.font] as? UIFont XCTAssertNotNil(font) XCTAssertFalse(font!.containsTraits(.traitBold)) attributes = [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)] //test removing a non-existent testApplyAttribute attributes = italicFormatter.remove(from: attributes) font = attributes[.font] as? UIFont XCTAssertNotNil(font) XCTAssertTrue(font!.containsTraits(.traitBold)) } func testPresentAttributes() { var attributes: [NSAttributedString.Key : Any] = [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)] //test when attribute is present XCTAssertTrue(boldFormatter.present(in: attributes)) //test when attributes is not present XCTAssertFalse(italicFormatter.present(in: attributes)) // apply attribute and check again attributes = italicFormatter.apply(to: attributes) XCTAssertTrue(italicFormatter.present(in: attributes)) } }
80fe5b1eb81f2611d2a3ff76674a4bb6
36.633333
118
0.685562
false
true
false
false
JaSpa/swift
refs/heads/master
test/Parse/pattern_without_variables.swift
apache-2.0
38
// RUN: %target-typecheck-verify-swift -parse-as-library let _ = 1 // expected-error{{global variable declaration does not bind any variables}} func foo() { let _ = 1 // OK } struct Foo { let _ = 1 // expected-error{{property declaration does not bind any variables}} var (_, _) = (1, 2) // expected-error{{property declaration does not bind any variables}} func foo() { let _ = 1 // OK } } // <rdar://problem/19786845> Warn on "let" and "var" when no data is bound in a pattern enum SimpleEnum { case Bar } func testVarLetPattern(a : SimpleEnum) { switch a { case let .Bar: break // expected-warning {{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{8-12=}} } switch a { case let x: _ = x; break // Ok. } switch a { case let _: break // expected-warning {{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{8-12=}} } switch (a, 42) { case let (_, x): _ = x; break // ok } // expected-warning @+1 {{'if' condition is always true}} if case let _ = "str" {} // expected-warning {{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{11-15=}} }
b9d84e7ffbb54b7070e75d0e3ad570d0
29.230769
129
0.616624
false
false
false
false
connienguyen/volunteers-iOS
refs/heads/development
VOLA/VOLA/ViewControllers/ConnectEmailViewController.swift
gpl-2.0
1
// // ConnectEmailViewController.swift // VOLA // // Created by Connie Nguyen on 8/9/17. // Copyright © 2017 Systers-Opensource. All rights reserved. // import UIKit /// Protocol for updating view on delegate of ConnectEmailViewController protocol ConnectEmailViewControllerDelegate: class { /** Add connected login for email/password - Parameters: - email: Email address for connected login - password: Password for connected login */ func emailDidConnect(email: String, password: String) } /// View controller for creating a new email connected login class ConnectEmailViewController: UIViewController { @IBOutlet weak var emailTextField: VLTextField! @IBOutlet weak var passowrdTextField: VLTextField! @IBOutlet weak var confirmTextField: VLTextField! weak var delegate: ConnectEmailViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() emailTextField.validator = .email passowrdTextField.validator = .password setUpValidatableFields() confirmTextField.addTarget(self, action: #selector(confirmFieldDidChange(_:)), for: .editingDidEnd) } } // MARK: - IBActions extension ConnectEmailViewController { /// Validate text inputs and add email conneted login via delegate @IBAction func onConnectPressed(_ sender: Any) { let errorDescriptions = validationErrorDescriptions guard let email = emailTextField.text, let password = passowrdTextField.text, let confirm = confirmTextField.text, password == confirm, errorDescriptions.isEmpty else { let errorMessage = errorDescriptions.joinLocalized() showErrorAlert(errorTitle: VLError.validation.localizedDescription, errorMessage: errorMessage) return } delegate?.emailDidConnect(email: email, password: password) navigationController?.popViewController(animated: true) } } // MARK: - Validatable; protocol to validate applicable text fields on view controller extension ConnectEmailViewController: Validatable { var fieldsToValidate: [VLTextField] { return [emailTextField, passowrdTextField] } /// Validate confirmTextField on editing did end func confirmFieldDidChange(_ textfield: VLTextField) { confirmTextField.isValid = confirmTextField.text == passowrdTextField.text } }
450164c7cdb9df0b82845e42fd1160ce
33.638889
107
0.697273
false
false
false
false
akkakks/firefox-ios
refs/heads/master
Client/Frontend/Settings/SettingsTableViewController.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/. */ import Base32 import UIKit class SettingsTableViewController: UITableViewController { let SectionAccount = 3 let ItemAccountStatus = 0 let ItemAccountDisconnect = 1 let SectionSearch = 0 let NumberOfSections = 3 let SectionShadowsocks = 1 let ItemServer = 0 let ItemQRCode = 1 let ItemHelp = 2 let ItemAbout = 3 let SectionPrivacy = 2 let ClearHistory = 0 var profile: Profile! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Settings", comment: "Settings") navigationItem.leftBarButtonItem = UIBarButtonItem( title: NSLocalizedString("Done", comment: "Settings"), style: UIBarButtonItemStyle.Done, target: navigationController, action: "SELdone") } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.Default } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: UITableViewCell if indexPath.section == SectionAccount { if indexPath.item == ItemAccountStatus { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: nil) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator updateCell(cell, toReflectAccount: profile.getAccount()) } else if indexPath.item == ItemAccountDisconnect { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.textLabel?.text = NSLocalizedString("Disconnect", comment: "Settings") } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) } } else if indexPath.section == SectionSearch { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.textLabel?.text = NSLocalizedString("Search", comment: "Settings") } else if indexPath.section == SectionShadowsocks { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator if indexPath.item == ItemServer { cell.textLabel?.text = NSLocalizedString("Server Settings", comment: "Settings") } else if indexPath.item == ItemQRCode { cell.textLabel?.text = NSLocalizedString("Config via QRCode", comment: "Settings") } else if indexPath.item == ItemHelp { cell.textLabel?.text = NSLocalizedString("Help", comment: "Settings") } else if indexPath.item == ItemAbout { cell.textLabel?.text = NSLocalizedString("About", comment: "Settings") } } else if indexPath.section == SectionPrivacy { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.textLabel?.text = NSLocalizedString("Clear History", comment: "Clear History") } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) } // So that the seperator line goes all the way to the left edge. cell.separatorInset = UIEdgeInsetsZero return cell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return NumberOfSections } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionAccount { if profile.getAccount() == nil { // Just "Sign in". return 0 } else { // Account state, and "Disconnect." return 2 } } else if section == SectionSearch { return 1 } else if section == SectionShadowsocks { return 4 } else if section == SectionPrivacy { return 1 } else { return 0 } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == SectionAccount { return nil } else if section == SectionSearch { return NSLocalizedString("Search Settings", comment: "Title for search settings section.") } else if section == SectionShadowsocks { return NSLocalizedString("Shadowsocks", comment: "Title for Shadowsocks section.") } else if section == SectionPrivacy { return NSLocalizedString("Privacy", comment: "Title for Privacy section.") } else { return nil } } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == SectionAccount { switch indexPath.item { case ItemAccountStatus: let viewController = FxAContentViewController() viewController.delegate = self if let account = profile.getAccount() { switch account.getActionNeeded() { case .None, .NeedsVerification: let cs = NSURLComponents(URL: profile.accountConfiguration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .NeedsPassword: let cs = NSURLComponents(URL: profile.accountConfiguration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .NeedsUpgrade: // In future, we'll want to link to an upgrade page. break } } else { viewController.url = profile.accountConfiguration.signInURL } navigationController?.pushViewController(viewController, animated: true) case ItemAccountDisconnect: maybeDisconnectAccount() default: break } } else if indexPath.section == SectionSearch { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines navigationController?.pushViewController(viewController, animated: true) } else if indexPath.section == SectionShadowsocks { if indexPath.item == ItemServer { self.navigationController?.pushViewController(Shadowsocks.globalShadowsocks().settingsViewController(), animated: true) } else if indexPath.item == ItemQRCode { self.navigationController?.pushViewController(Shadowsocks.globalShadowsocks().qrcodeViewController(), animated: true) } else if indexPath.item == ItemHelp { Shadowsocks.globalShadowsocks().showHelp() } else if indexPath.item == ItemAbout { self.navigationController?.pushViewController(Shadowsocks.globalShadowsocks().aboutViewController(), animated: true) } } else if indexPath.section == SectionPrivacy { profile.history.clear({ (success) -> Void in UIAlertView(title: nil, message: NSLocalizedString("Cleared", comment: "Cleared"), delegate: nil, cancelButtonTitle: "OK").show() }) } return nil } func updateCell(cell: UITableViewCell, toReflectAccount account: FirefoxAccount?) { if let account = account { cell.textLabel?.text = account.email cell.detailTextLabel?.text = nil switch account.getActionNeeded() { case .None: break case .NeedsVerification: cell.detailTextLabel?.text = NSLocalizedString("Verify your email address.", comment: "Settings") case .NeedsPassword: // This assumes we never recycle cells. cell.detailTextLabel?.textColor = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) // Firefox orange! cell.detailTextLabel?.text = NSLocalizedString("Enter your password to connect.", comment: "Settings") case .NeedsUpgrade: cell.detailTextLabel?.textColor = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) // Firefox orange! cell.detailTextLabel?.text = NSLocalizedString("Upgrade Firefox to connect.", comment: "Settings") cell.accessoryType = UITableViewCellAccessoryType.None } } else { cell.textLabel?.text = NSLocalizedString("", comment: "Settings") } } func maybeDisconnectAccount() { let alertController = UIAlertController( title: NSLocalizedString("Disconnect Firefox Account?", comment: "Settings"), message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Settings"), preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", comment: "Settings"), style: .Cancel) { (action) in // Do nothing. }) alertController.addAction( UIAlertAction(title: NSLocalizedString("Disconnect", comment: "Settings"), style: .Destructive) { (action) in self.profile.setAccount(nil) self.tableView.reloadData() }) presentViewController(alertController, animated: true, completion: nil) } } extension SettingsTableViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) { if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil { // The /settings endpoint sends a partial "login"; ignore it entirely. NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.") return } // TODO: Error handling. let state = FirefoxAccountState.Engaged( verified: data["verified"].asBool ?? false, sessionToken: data["sessionToken"].asString!.hexDecodedData, keyFetchToken: data["keyFetchToken"].asString!.hexDecodedData, unwrapkB: data["unwrapBKey"].asString!.hexDecodedData ) let account = FirefoxAccount( email: data["email"].asString!, uid: data["uid"].asString!, authEndpoint: profile.accountConfiguration.authEndpointURL, contentEndpoint: profile.accountConfiguration.profileEndpointURL, oauthEndpoint: profile.accountConfiguration.oauthEndpointURL, state: state ) profile.setAccount(account) tableView.reloadData() navigationController?.popToRootViewControllerAnimated(true) } func contentViewControllerDidCancel(viewController: FxAContentViewController) { NSLog("didCancel") navigationController?.popToRootViewControllerAnimated(true) } }
599dbcd3038a6150b1e36740e1988fa0
46.552419
167
0.629526
false
false
false
false
exyte/Macaw-Examples
refs/heads/master
DesignAwardedApps/Zova/Zova/Nodes/ActivityBar.swift
mit
1
import Foundation import Macaw class ActivityBar: Group { let legend: Legend var jumpAnimation: Animation? init() { legend = Legend() let dataSet = [ (("0", 50.0, 0.9), Transform.identity), (("10", 50.0, 0.6), Transform.move(dx: 52, dy: 0)), (("21", 130.0, 0.6), Transform.move(dx: 104, dy: 0)), (("42", 50.0, 0.6), Transform.move(dx: 236, dy: 0)) ] let segments = dataSet.enumerated().map { (index, data) in let segment = BarSegment( text: data.0.0, width: data.0.1, opacity: data.0.2, last: index == dataSet.count - 1 ) segment.place = data.1 return segment }.group() let scoreValue = Shape( form: Circle(r: 2), fill: mainColor, place: Transform.move(dx: 16, dy: 4) ) let barGroup = Group( contents: [segments, scoreValue], place: Transform.move(dx: 5.0, dy: 70.0) ) super.init(contents: [barGroup, legend]) jump() } func jump() { jumpAnimation = legend.placeVar.animation( to: Transform.move(dx: 0.0, dy: -8.0), during: 2.0 ).autoreversed().cycle() jumpAnimation?.play() } func stopJumping() { jumpAnimation?.stop() } } class BarSegment: Group { init(text: String, width: Double, opacity: Double, last: Bool) { let legend = Text( text: text, font: Font(name: regularFont, size: 12), fill: Color.white, align: .min, baseline: .alphabetic, place: Transform.move(dx: 0, dy: -5) ) let segment = Shape( form: Rect(w: width, h: 8), fill: !last ? Color.white.with(a: opacity) : LinearGradient( degree: 0, from: Color.white.with(a: opacity), to: mainColor ) ) super.init(contents: [legend, segment]) } } class Legend: Group { init() { let border = Shape( form: Rect(w: 80, h: 30).round(r: 16.0), fill: Color.white ) let low = Text( text: "Low", font: Font(name: regularFont, size: 20), fill: mainColor, align: .mid, baseline: .mid, place: Transform.move(dx: 40, dy: 15) ) let line = Shape( form: Rect(x: 20, y: 30, w: 2, h: 40), fill: LinearGradient( degree: 90, from: Color.white.with(a: 0.8), to: mainColor ) ) super.init(contents: [border, low, line]) } }
a75070ddc2ebb5abda9288a25f7d43e3
25.87037
72
0.451413
false
false
false
false
ProfileCreator/ProfileCreator
refs/heads/master
ProfileCreator/ProfileCreator/Profile Editor TableView CellViews/PayloadCellViewFooter.swift
mit
1
// // PayloadCellViewPadding.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa import ProfilePayloads class PayloadCellViewFooter: NSTableCellView, ProfileCreatorCellView { // MARK: - // MARK: PayloadCellView Variables var height: CGFloat = 0.0 let separator = NSBox(frame: NSRect(x: 250.0, y: 15.0, width: kPreferencesWindowWidth - (20.0 + 20.0), height: 250.0)) var textFieldRow1 = NSTextField() var textFieldRow2: NSTextField? // MARK: - // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(row1: String, row2 row2String: String?) { super.init(frame: NSRect.zero) // --------------------------------------------------------------------- // Setup Variables // --------------------------------------------------------------------- var constraints = [NSLayoutConstraint]() // --------------------------------------------------------------------- // Create and add vertical separator // --------------------------------------------------------------------- self.setup(separator: self.separator, constraints: &constraints) // --------------------------------------------------------------------- // Setup Static View Content // --------------------------------------------------------------------- // Row 1 self.setup(row: self.textFieldRow1, lastRow: nil, constraints: &constraints) self.textFieldRow1.stringValue = row1 // Row 2 if let row2 = row2String { self.textFieldRow2 = NSTextField() self.setup(row: self.textFieldRow2!, lastRow: self.textFieldRow1, constraints: &constraints) self.textFieldRow2?.stringValue = row2 } // --------------------------------------------------------------------- // Add spacing to bottom // --------------------------------------------------------------------- self.updateHeight(34.0) // --------------------------------------------------------------------- // Activate Layout Constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(constraints) } func updateHeight(_ height: CGFloat) { self.height += height } // MARK: - // MARK: Setup Layout Constraints private func setup(row: NSTextField, lastRow: NSTextField?, constraints: inout [NSLayoutConstraint]) { // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- self.addSubview(row) row.translatesAutoresizingMaskIntoConstraints = false row.lineBreakMode = .byWordWrapping row.isBordered = false row.isBezeled = false row.drawsBackground = false row.isEditable = false row.isSelectable = false row.textColor = .tertiaryLabelColor row.preferredMaxLayoutWidth = kEditorTableViewColumnPayloadWidth row.alignment = .center row.font = NSFont.systemFont(ofSize: 10, weight: .light) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Top if let lastRowTextField = lastRow { constraints.append(NSLayoutConstraint(item: row, attribute: .top, relatedBy: .equal, toItem: lastRowTextField, attribute: .bottom, multiplier: 1.0, constant: 2.0)) self.updateHeight(8 + row.intrinsicContentSize.height) } else { constraints.append(NSLayoutConstraint(item: row, attribute: .top, relatedBy: .equal, toItem: self.separator, attribute: .top, multiplier: 1.0, constant: 8.0)) self.updateHeight(16 + row.intrinsicContentSize.height) } // Leading constraints.append(NSLayoutConstraint(item: row, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0)) // Trailing constraints.append(NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: row, attribute: .trailing, multiplier: 1.0, constant: 8.0)) } private func setup(separator: NSBox, constraints: inout [NSLayoutConstraint]) { separator.translatesAutoresizingMaskIntoConstraints = false separator.boxType = .separator // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- self.addSubview(separator) constraints.append(NSLayoutConstraint(item: separator, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 16.0)) // Leading constraints.append(NSLayoutConstraint(item: separator, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 8.0)) // Trailing constraints.append(NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: separator, attribute: .trailing, multiplier: 1, constant: 8.0)) } }
3d9bbddf8958d578474566a04ece0655
42.16185
122
0.37284
false
false
false
false
apegroup/APEReactiveNetworking
refs/heads/master
APEReactiveNetworking/Source/RequestBuilder/ApeRequestBuilder.swift
mit
1
// // ApeRequestBuilder.swift // app-architecture // // Created by Magnus Eriksson on 11/05/16. // Copyright © 2016 Apegroup. All rights reserved. // import Foundation public final class ApeRequestBuilder: HttpRequestBuilder { private let endpoint: Endpoint private var contentTypeHeader : Http.ContentType? private var additionalHeaders: Http.RequestHeaders = [:] private var bodyData: Data? // MARK: Public public init(endpoint: Endpoint) { self.endpoint = endpoint } public func setHeader(_ header: (key: String, value: String)) -> HttpRequestBuilder { additionalHeaders[header.key] = header.value return self } public func setBody(data: Data, contentType: Http.ContentType) -> HttpRequestBuilder { self.contentTypeHeader = contentType self.bodyData = data return self } ///Builds a URLRequest with the provided components public func build() -> ApeURLRequest { let headers = makeHeaders() return makeRequest(with: headers, body: bodyData) } // MARK: Private private func makeHeaders() -> Http.RequestHeaders { var headers = self.additionalHeaders if let contentTypeHeader = contentTypeHeader { headers["Content-Type"] = contentTypeHeader.description } let device = UIDevice.current headers["X-Client-OS"] = device.systemName headers["X-Client-OS-Version"] = device.systemVersion headers["X-Client-Device-Type"] = device.modelName headers["X-Client-Device-VendorId"] = device.identifierForVendor?.uuidString ?? "unknown" //FIXME: Fix headers below //headers["X-Apegroup-Client-App-Version"] = "0.1" //headers["Accept-Language"] = "sv-SE" return headers } private func makeRequest(with headers: Http.RequestHeaders, body: Data?) -> ApeURLRequest { guard let url = URL(string: endpoint.absoluteUrl) else { preconditionFailure("Endpoint contains invalid url: '\(endpoint.absoluteUrl)'") } var request = URLRequest(url: url) request.httpMethod = endpoint.httpMethod.rawValue request.httpBody = body for (header, value) in headers { request.setValue(value, forHTTPHeaderField: header) } return ApeURLRequest(urlRequest: request, acceptedResponseCodes: endpoint.acceptedResponseCodes) } }
8f07cf765271de0b4f3d6868722f78a1
29.975
104
0.652946
false
false
false
false
WickedColdfront/Slide-iOS
refs/heads/master
Slide for Reddit/YouTubeViewController.swift
apache-2.0
1
// // YouTubeViewController.swift // Slide for Reddit // // Created by Carlos Crane on 6/18/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import UIKit class YouTubeViewController: UIViewController, YTPlayerViewDelegate { var panGestureRecognizer: UIPanGestureRecognizer? var originalPosition: CGPoint? var currentPositionTouched: CGPoint? var url: URL? var parentVC: UIViewController? init(bUrl: URL, parent: UIViewController){ self.url = bUrl super.init(nibName: nil, bundle: nil) self.parentVC = parent var url = bUrl.absoluteString if(url.contains("#t=")){ url = url.replacingOccurrences(of: "#t=", with: url.contains("?") ? "&t=" : "?t=") } let i = URL.init(string: url) if let dictionary = i?.queryDictionary { if let t = dictionary["t"]{ millis = getTimeFromString(t); } else if let start = dictionary["start"] { millis = getTimeFromString(start); } if let list = dictionary["list"]{ playlist = list } if let v = dictionary["v"]{ video = v } else if let w = dictionary["w"]{ video = w } else if url.lowercased().contains("youtu.be"){ video = getLastPathSegment(url) } if let u = dictionary["u"]{ let param = u video = param.substring(param.indexOf("=")! + 1, length: param.contains("&") ? param.indexOf("&")! : param.length); } } else { let w = WebsiteViewController.init(url: bUrl, subreddit: "") parentVC!.present(w, animated: true) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func getLastPathSegment(_ path: String) -> String { var inv = path if(inv.endsWith("/")){ inv = inv.substring(0, length: inv.length - 1) } let slashindex = inv.lastIndexOf("/")! print("Index is \(slashindex)") inv = inv.substring(slashindex + 1, length: inv.length - slashindex - 1) return inv } var millis = 0 var video = "" var playlist = "" func getTimeFromString(_ time: String) -> Int { var timeAdd = 0; for s in time.components(separatedBy: "s|m|h"){ if(time.contains(s + "s")){ timeAdd += Int(s)!; } else if(time.contains(s + "m")){ timeAdd += 60 * Int(s)!; } else if(time.contains(s + "h")){ timeAdd += 3600 * Int(s)!; } } if(timeAdd == 0){ timeAdd+=Int(time)!; } return timeAdd * 1000; } var player = YTPlayerView() func playerViewDidBecomeReady(_ playerView: YTPlayerView) { self.player.playVideo() } override func loadView() { self.view = YTPlayerView(frame: CGRect.zero) self.player = self.view as! YTPlayerView self.player.delegate = self if(!playlist.isEmpty){ player.load(withPlaylistId: playlist) } else { player.load(withVideoId: video, playerVars: ["controls":1,"playsinline":1,"start":millis,"fs":0]) } } override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { modalPresentationStyle = .currentContext super.viewDidLoad() self.view.backgroundColor = UIColor.clear panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureAction(_:))) player.addGestureRecognizer(panGestureRecognizer!) } func panGestureAction(_ panGesture: UIPanGestureRecognizer) { let translation = panGesture.translation(in: view) if panGesture.state == .began { originalPosition = view.center currentPositionTouched = panGesture.location(in: view) } else if panGesture.state == .changed { view.frame.origin = CGPoint( x: translation.x, y: translation.y ) } else if panGesture.state == .ended { let velocity = panGesture.velocity(in: view) if velocity.y >= 1500 { UIView.animate(withDuration: 0.2 , animations: { self.view.frame.origin = CGPoint( x: self.view.frame.origin.x, y: self.view.frame.size.height ) }, completion: { (isCompleted) in if isCompleted { self.dismiss(animated: false, completion: nil) } }) } else { UIView.animate(withDuration: 0.2, animations: { self.view.center = self.originalPosition! }) } } } }
4906b0fb347e121471566f96d2361453
32.012579
131
0.511717
false
false
false
false
nahive/UIColor-WikiColors
refs/heads/master
WikiColors.swift
unlicense
1
// // Created by nahive on 12/20/2016. // Copyright (c) 2016 nahive.io All rights reserved. // import UIKit extension UIColor { convenience init(hex: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if hex.hasPrefix("#") { let index = hex.index(hex.startIndex, offsetBy: 1) let hex = hex.substring(from: index) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after # should be either 3, 4, 6 or 8") } } else { print("Scan hex error") } } else { print("Invalid RGB string, missing # as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } } public extension UIColor { static let absoluteZero = UIColor(hex: "#0048BA") static let acidGreen = UIColor(hex: "#B0BF1A") static let aero = UIColor(hex: "#7CB9E8") static let aeroBlue = UIColor(hex: "#C9FFE5") static let africanViolet = UIColor(hex: "#B284BE") static let airForceBlueRAF = UIColor(hex: "#5D8AA8") static let airForceBlueUSAF = UIColor(hex: "#00308F") static let airSuperiorityBlue = UIColor(hex: "#72A0C1") static let alabamaCrimson = UIColor(hex: "#AF002A") static let alabaster = UIColor(hex: "#F2F0E6") static let aliceBlue = UIColor(hex: "#F0F8FF") static let alienArmpit = UIColor(hex: "#84DE02") static let alizarinCrimson = UIColor(hex: "#E32636") static let alloyOrange = UIColor(hex: "#C46210") static let almond = UIColor(hex: "#EFDECD") static let amaranth = UIColor(hex: "#E52B50") static let amaranthDeepPurple = UIColor(hex: "#9F2B68") static let amaranthPink = UIColor(hex: "#F19CBB") static let amaranthPurple = UIColor(hex: "#AB274F") static let amaranthRed = UIColor(hex: "#D3212D") static let amazon = UIColor(hex: "#3B7A57") static let amazonite = UIColor(hex: "#00C4B0") static let amber = UIColor(hex: "#FFBF00") static let amberSAEECE = UIColor(hex: "#FF7E00") static let americanRose = UIColor(hex: "#FF033E") static let amethyst = UIColor(hex: "#9966CC") static let androidGreen = UIColor(hex: "#A4C639") static let antiFlashWhite = UIColor(hex: "#F2F3F4") static let antiqueBrass = UIColor(hex: "#CD9575") static let antiqueBronze = UIColor(hex: "#665D1E") static let antiqueFuchsia = UIColor(hex: "#915C83") static let antiqueRuby = UIColor(hex: "#841B2D") static let antiqueWhite = UIColor(hex: "#FAEBD7") static let aoEnglish = UIColor(hex: "#008000") static let appleGreen = UIColor(hex: "#8DB600") static let apricot = UIColor(hex: "#FBCEB1") static let aqua = UIColor(hex: "#00FFFF") static let aquamarine = UIColor(hex: "#7FFFD4") static let arcticLime = UIColor(hex: "#D0FF14") static let armyGreen = UIColor(hex: "#4B5320") static let arsenic = UIColor(hex: "#3B444B") static let artichoke = UIColor(hex: "#8F9779") static let arylideYellow = UIColor(hex: "#E9D66B") static let ashGrey = UIColor(hex: "#B2BEB5") static let asparagus = UIColor(hex: "#87A96B") static let atomicTangerine = UIColor(hex: "#FF9966") static let auburn = UIColor(hex: "#A52A2A") static let aureolin = UIColor(hex: "#FDEE00") static let auroMetalSaurus = UIColor(hex: "#6E7F80") static let avocado = UIColor(hex: "#568203") static let awesome = UIColor(hex: "#FF2052") static let aztecGold = UIColor(hex: "#C39953") static let azure = UIColor(hex: "#007FFF") static let azureWebColor = UIColor(hex: "#F0FFFF") static let azureMist = UIColor(hex: "#F0FFFF") static let azureishWhite = UIColor(hex: "#DBE9F4") static let babyBlue = UIColor(hex: "#89CFF0") static let babyBlueEyes = UIColor(hex: "#A1CAF1") static let babyPink = UIColor(hex: "#F4C2C2") static let babyPowder = UIColor(hex: "#FEFEFA") static let bakerMillerPink = UIColor(hex: "#FF91AF") static let ballBlue = UIColor(hex: "#21ABCD") static let bananaMania = UIColor(hex: "#FAE7B5") static let bananaYellow = UIColor(hex: "#FFE135") static let bangladeshGreen = UIColor(hex: "#006A4E") static let barbiePink = UIColor(hex: "#E0218A") static let barnRed = UIColor(hex: "#7C0A02") static let batteryChargedBlue = UIColor(hex: "#1DACD6") static let battleshipGrey = UIColor(hex: "#848482") static let bazaar = UIColor(hex: "#98777B") static let beauBlue = UIColor(hex: "#BCD4E6") static let beaver = UIColor(hex: "#9F8170") static let begonia = UIColor(hex: "#FA6E79") static let beige = UIColor(hex: "#F5F5DC") static let bdazzledBlue = UIColor(hex: "#2E5894") static let bigDipOruby = UIColor(hex: "#9C2542") static let bigFootFeet = UIColor(hex: "#E88E5A") static let bisque = UIColor(hex: "#FFE4C4") static let bistre = UIColor(hex: "#3D2B1F") static let bistreBrown = UIColor(hex: "#967117") static let bitterLemon = UIColor(hex: "#CAE00D") static let bitterLime = UIColor(hex: "#BFFF00") static let bittersweet = UIColor(hex: "#FE6F5E") static let bittersweetShimmer = UIColor(hex: "#BF4F51") static let black = UIColor(hex: "#000000") static let blackBean = UIColor(hex: "#3D0C02") static let blackCoral = UIColor(hex: "#54626F") static let blackLeatherJacket = UIColor(hex: "#253529") static let blackOlive = UIColor(hex: "#3B3C36") static let blackShadows = UIColor(hex: "#BFAFB2") static let blanchedAlmond = UIColor(hex: "#FFEBCD") static let blastOffBronze = UIColor(hex: "#A57164") static let bleuDeFrance = UIColor(hex: "#318CE7") static let blizzardBlue = UIColor(hex: "#ACE5EE") static let blond = UIColor(hex: "#FAF0BE") static let blue = UIColor(hex: "#0000FF") static let blueCrayola = UIColor(hex: "#1F75FE") static let blueMunsell = UIColor(hex: "#0093AF") static let blueNCS = UIColor(hex: "#0087BD") static let bluePantone = UIColor(hex: "#0018A8") static let bluePigment = UIColor(hex: "#333399") static let blueRYB = UIColor(hex: "#0247FE") static let blueBell = UIColor(hex: "#A2A2D0") static let blueBolt = UIColor(hex: "#00B9FB") static let blueGray = UIColor(hex: "#6699CC") static let blueGreen = UIColor(hex: "#0D98BA") static let blueJeans = UIColor(hex: "#5DADEC") static let blueLagoon = UIColor(hex: "#ACE5EE") static let blueMagentaViolet = UIColor(hex: "#553592") static let blueSapphire = UIColor(hex: "#126180") static let blueViolet = UIColor(hex: "#8A2BE2") static let blueYonder = UIColor(hex: "#5072A7") static let blueberry = UIColor(hex: "#4F86F7") static let bluebonnet = UIColor(hex: "#1C1CF0") static let blush = UIColor(hex: "#DE5D83") static let bole = UIColor(hex: "#79443B") static let bondiBlue = UIColor(hex: "#0095B6") static let bone = UIColor(hex: "#E3DAC9") static let boogerBuster = UIColor(hex: "#DDE26A") static let bostonUniversityRed = UIColor(hex: "#CC0000") static let bottleGreen = UIColor(hex: "#006A4E") static let boysenberry = UIColor(hex: "#873260") static let brandeisBlue = UIColor(hex: "#0070FF") static let brass = UIColor(hex: "#B5A642") static let brickRed = UIColor(hex: "#CB4154") static let brightCerulean = UIColor(hex: "#1DACD6") static let brightGreen = UIColor(hex: "#66FF00") static let brightLavender = UIColor(hex: "#BF94E4") static let brightLilac = UIColor(hex: "#D891EF") static let brightMaroon = UIColor(hex: "#C32148") static let brightNavyBlue = UIColor(hex: "#1974D2") static let brightPink = UIColor(hex: "#FF007F") static let brightTurquoise = UIColor(hex: "#08E8DE") static let brightUbe = UIColor(hex: "#D19FE8") static let brightYellowCrayola = UIColor(hex: "#FFAA1D") static let brilliantAzure = UIColor(hex: "#3399FF") static let brilliantLavender = UIColor(hex: "#F4BBFF") static let brilliantRose = UIColor(hex: "#FF55A3") static let brinkPink = UIColor(hex: "#FB607F") static let britishRacingGreen = UIColor(hex: "#004225") static let bronze = UIColor(hex: "#CD7F32") static let bronzeYellow = UIColor(hex: "#737000") static let brownTraditional = UIColor(hex: "#964B00") static let brownWeb = UIColor(hex: "#A52A2A") static let brownNose = UIColor(hex: "#6B4423") static let brownSugar = UIColor(hex: "#AF6E4D") static let brownYellow = UIColor(hex: "#cc9966") static let brunswickGreen = UIColor(hex: "#1B4D3E") static let bubbleGum = UIColor(hex: "#FFC1CC") static let bubbles = UIColor(hex: "#E7FEFF") static let budGreen = UIColor(hex: "#7BB661") static let buff = UIColor(hex: "#F0DC82") static let bulgarianRose = UIColor(hex: "#480607") static let burgundy = UIColor(hex: "#800020") static let burlywood = UIColor(hex: "#DEB887") static let burnishedBrown = UIColor(hex: "#A17A74") static let burntOrange = UIColor(hex: "#CC5500") static let burntSienna = UIColor(hex: "#E97451") static let burntUmber = UIColor(hex: "#8A3324") static let buttonBlue = UIColor(hex: "#24A0ED") static let byzantine = UIColor(hex: "#BD33A4") static let byzantium = UIColor(hex: "#702963") static let cadet = UIColor(hex: "#536872") static let cadetBlue = UIColor(hex: "#5F9EA0") static let cadetGrey = UIColor(hex: "#91A3B0") static let cadmiumGreen = UIColor(hex: "#006B3C") static let cadmiumOrange = UIColor(hex: "#ED872D") static let cadmiumRed = UIColor(hex: "#E30022") static let cadmiumYellow = UIColor(hex: "#FFF600") static let caféAuLait = UIColor(hex: "#A67B5B") static let caféNoir = UIColor(hex: "#4B3621") static let calPolyPomonaGreen = UIColor(hex: "#1E4D2B") static let cambridgeBlue = UIColor(hex: "#A3C1AD") static let camel = UIColor(hex: "#C19A6B") static let cameoPink = UIColor(hex: "#EFBBCC") static let camouflageGreen = UIColor(hex: "#78866B") static let canary = UIColor(hex: "#FFFF99") static let canaryYellow = UIColor(hex: "#FFEF00") static let candyAppleRed = UIColor(hex: "#FF0800") static let candyPink = UIColor(hex: "#E4717A") static let capri = UIColor(hex: "#00BFFF") static let caputMortuum = UIColor(hex: "#592720") static let cardinal = UIColor(hex: "#C41E3A") static let caribbeanGreen = UIColor(hex: "#00CC99") static let carmine = UIColor(hex: "#960018") static let carmineMP = UIColor(hex: "#D70040") static let carminePink = UIColor(hex: "#EB4C42") static let carmineRed = UIColor(hex: "#FF0038") static let carnationPink = UIColor(hex: "#FFA6C9") static let carnelian = UIColor(hex: "#B31B1B") static let carolinaBlue = UIColor(hex: "#56A0D3") static let carrotOrange = UIColor(hex: "#ED9121") static let castletonGreen = UIColor(hex: "#00563F") static let catalinaBlue = UIColor(hex: "#062A78") static let catawba = UIColor(hex: "#703642") static let cedarChest = UIColor(hex: "#C95A49") static let ceil = UIColor(hex: "#92A1CF") static let celadon = UIColor(hex: "#ACE1AF") static let celadonBlue = UIColor(hex: "#007BA7") static let celadonGreen = UIColor(hex: "#2F847C") static let celeste = UIColor(hex: "#B2FFFF") static let celestialBlue = UIColor(hex: "#4997D0") static let cerise = UIColor(hex: "#DE3163") static let cerisePink = UIColor(hex: "#EC3B83") static let cerulean = UIColor(hex: "#007BA7") static let ceruleanBlue = UIColor(hex: "#2A52BE") static let ceruleanFrost = UIColor(hex: "#6D9BC3") static let cGBlue = UIColor(hex: "#007AA5") static let cGRed = UIColor(hex: "#E03C31") static let chamoisee = UIColor(hex: "#A0785A") static let champagne = UIColor(hex: "#F7E7CE") static let champagnePink = UIColor(hex: "#F1DDCF") static let charcoal = UIColor(hex: "#36454F") static let charlestonGreen = UIColor(hex: "#232B2B") static let charmPink = UIColor(hex: "#E68FAC") static let chartreuseTraditional = UIColor(hex: "#DFFF00") static let chartreuseWeb = UIColor(hex: "#7FFF00") static let cherry = UIColor(hex: "#DE3163") static let cherryBlossomPink = UIColor(hex: "#FFB7C5") static let chestnut = UIColor(hex: "#954535") static let chinaPink = UIColor(hex: "#DE6FA1") static let chinaRose = UIColor(hex: "#A8516E") static let chineseRed = UIColor(hex: "#AA381E") static let chineseViolet = UIColor(hex: "#856088") static let chlorophyllGreen = UIColor(hex: "#4AFF00") static let chocolateTraditional = UIColor(hex: "#7B3F00") static let chocolateWeb = UIColor(hex: "#D2691E") static let chromeYellow = UIColor(hex: "#FFA700") static let cinereous = UIColor(hex: "#98817B") static let cinnabar = UIColor(hex: "#E34234") static let cinnamon = UIColor(hex: "#D2691E") static let cinnamonSatin = UIColor(hex: "#CD607E") static let citrine = UIColor(hex: "#E4D00A") static let citron = UIColor(hex: "#9FA91F") static let claret = UIColor(hex: "#7F1734") static let classicRose = UIColor(hex: "#FBCCE7") static let cobaltBlue = UIColor(hex: "#0047AB") static let cocoaBrown = UIColor(hex: "#D2691E") static let coconut = UIColor(hex: "#965A3E") static let coffee = UIColor(hex: "#6F4E37") static let columbiaBlue = UIColor(hex: "#C4D8E2") static let congoPink = UIColor(hex: "#F88379") static let coolBlack = UIColor(hex: "#002E63") static let coolGrey = UIColor(hex: "#8C92AC") static let copper = UIColor(hex: "#B87333") static let copperCrayola = UIColor(hex: "#DA8A67") static let copperPenny = UIColor(hex: "#AD6F69") static let copperRed = UIColor(hex: "#CB6D51") static let copperRose = UIColor(hex: "#996666") static let coquelicot = UIColor(hex: "#FF3800") static let coral = UIColor(hex: "#FF7F50") static let coralPink = UIColor(hex: "#F88379") static let coralRed = UIColor(hex: "#FF4040") static let coralReef = UIColor(hex: "#FD7C6E") static let cordovan = UIColor(hex: "#893F45") static let corn = UIColor(hex: "#FBEC5D") static let cornellRed = UIColor(hex: "#B31B1B") static let cornflowerBlue = UIColor(hex: "#6495ED") static let cornsilk = UIColor(hex: "#FFF8DC") static let cosmicCobalt = UIColor(hex: "#2E2D88") static let cosmicLatte = UIColor(hex: "#FFF8E7") static let coyoteBrown = UIColor(hex: "#81613C") static let cottonCandy = UIColor(hex: "#FFBCD9") static let cream = UIColor(hex: "#FFFDD0") static let crimson = UIColor(hex: "#DC143C") static let crimsonGlory = UIColor(hex: "#BE0032") static let crimsonRed = UIColor(hex: "#990000") static let cultured = UIColor(hex: "#F5F5F5") static let cyan = UIColor(hex: "#00FFFF") static let cyanAzure = UIColor(hex: "#4E82B4") static let cyanBlueAzure = UIColor(hex: "#4682BF") static let cyanCobaltBlue = UIColor(hex: "#28589C") static let cyanCornflowerBlue = UIColor(hex: "#188BC2") static let cyanProcess = UIColor(hex: "#00B7EB") static let cyberGrape = UIColor(hex: "#58427C") static let cyberYellow = UIColor(hex: "#FFD300") static let cyclamen = UIColor(hex: "#F56FA1") static let daffodil = UIColor(hex: "#FFFF31") static let dandelion = UIColor(hex: "#F0E130") static let darkBlue = UIColor(hex: "#00008B") static let darkBlueGray = UIColor(hex: "#666699") static let darkBrown = UIColor(hex: "#654321") static let darkBrownTangelo = UIColor(hex: "#88654E") static let darkByzantium = UIColor(hex: "#5D3954") static let darkCandyAppleRed = UIColor(hex: "#A40000") static let darkCerulean = UIColor(hex: "#08457E") static let darkChestnut = UIColor(hex: "#986960") static let darkCoral = UIColor(hex: "#CD5B45") static let darkCyan = UIColor(hex: "#008B8B") static let darkElectricBlue = UIColor(hex: "#536878") static let darkGoldenrod = UIColor(hex: "#B8860B") static let darkGrayX11 = UIColor(hex: "#A9A9A9") static let darkGreen = UIColor(hex: "#013220") static let darkGreenX11 = UIColor(hex: "#006400") static let darkGunmetal = UIColor(hex: "#1F262A") static let darkImperialBlue = UIColor(hex: "#00416A") static let darkJungleGreen = UIColor(hex: "#1A2421") static let darkKhaki = UIColor(hex: "#BDB76B") static let darkLava = UIColor(hex: "#483C32") static let darkLavender = UIColor(hex: "#734F96") static let darkLiver = UIColor(hex: "#534B4F") static let darkLiverHorses = UIColor(hex: "#543D37") static let darkMagenta = UIColor(hex: "#8B008B") static let darkMediumGray = UIColor(hex: "#A9A9A9") static let darkMidnightBlue = UIColor(hex: "#003366") static let darkMossGreen = UIColor(hex: "#4A5D23") static let darkOliveGreen = UIColor(hex: "#556B2F") static let darkOrange = UIColor(hex: "#FF8C00") static let darkOrchid = UIColor(hex: "#9932CC") static let darkPastelBlue = UIColor(hex: "#779ECB") static let darkPastelGreen = UIColor(hex: "#03C03C") static let darkPastelPurple = UIColor(hex: "#966FD6") static let darkPastelRed = UIColor(hex: "#C23B22") static let darkPink = UIColor(hex: "#E75480") static let darkPowderBlue = UIColor(hex: "#003399") static let darkPuce = UIColor(hex: "#4F3A3C") static let darkPurple = UIColor(hex: "#301934") static let darkRaspberry = UIColor(hex: "#872657") static let darkRed = UIColor(hex: "#8B0000") static let darkSalmon = UIColor(hex: "#E9967A") static let darkScarlet = UIColor(hex: "#560319") static let darkSeaGreen = UIColor(hex: "#8FBC8F") static let darkSienna = UIColor(hex: "#3C1414") static let darkSkyBlue = UIColor(hex: "#8CBED6") static let darkSlateBlue = UIColor(hex: "#483D8B") static let darkSlateGray = UIColor(hex: "#2F4F4F") static let darkSpringGreen = UIColor(hex: "#177245") static let darkTan = UIColor(hex: "#918151") static let darkTangerine = UIColor(hex: "#FFA812") static let darkTaupe = UIColor(hex: "#483C32") static let darkTerraCotta = UIColor(hex: "#CC4E5C") static let darkTurquoise = UIColor(hex: "#00CED1") static let darkVanilla = UIColor(hex: "#D1BEA8") static let darkViolet = UIColor(hex: "#9400D3") static let darkYellow = UIColor(hex: "#9B870C") static let dartmouthGreen = UIColor(hex: "#00703C") static let davysGrey = UIColor(hex: "#555555") static let debianRed = UIColor(hex: "#D70A53") static let deepAquamarine = UIColor(hex: "#40826D") static let deepCarmine = UIColor(hex: "#A9203E") static let deepCarminePink = UIColor(hex: "#EF3038") static let deepCarrotOrange = UIColor(hex: "#E9692C") static let deepCerise = UIColor(hex: "#DA3287") static let deepChampagne = UIColor(hex: "#FAD6A5") static let deepChestnut = UIColor(hex: "#B94E48") static let deepCoffee = UIColor(hex: "#704241") static let deepFuchsia = UIColor(hex: "#C154C1") static let deepGreen = UIColor(hex: "#056608") static let deepGreenCyanTurquoise = UIColor(hex: "#0E7C61") static let deepJungleGreen = UIColor(hex: "#004B49") static let deepKoamaru = UIColor(hex: "#333366") static let deepLemon = UIColor(hex: "#F5C71A") static let deepLilac = UIColor(hex: "#9955BB") static let deepMagenta = UIColor(hex: "#CC00CC") static let deepMaroon = UIColor(hex: "#820000") static let deepMauve = UIColor(hex: "#D473D4") static let deepMossGreen = UIColor(hex: "#355E3B") static let deepPeach = UIColor(hex: "#FFCBA4") static let deepPink = UIColor(hex: "#FF1493") static let deepPuce = UIColor(hex: "#A95C68") static let deepRed = UIColor(hex: "#850101") static let deepRuby = UIColor(hex: "#843F5B") static let deepSaffron = UIColor(hex: "#FF9933") static let deepSkyBlue = UIColor(hex: "#00BFFF") static let deepSpaceSparkle = UIColor(hex: "#4A646C") static let deepSpringBud = UIColor(hex: "#556B2F") static let deepTaupe = UIColor(hex: "#7E5E60") static let deepTuscanRed = UIColor(hex: "#66424D") static let deepViolet = UIColor(hex: "#330066") static let deer = UIColor(hex: "#BA8759") static let denim = UIColor(hex: "#1560BD") static let denimBlue = UIColor(hex: "#2243B6") static let desaturatedCyan = UIColor(hex: "#669999") static let desert = UIColor(hex: "#C19A6B") static let desertSand = UIColor(hex: "#EDC9AF") static let desire = UIColor(hex: "#EA3C53") static let diamond = UIColor(hex: "#B9F2FF") static let dimGray = UIColor(hex: "#696969") static let dingyDungeon = UIColor(hex: "#C53151") static let dirt = UIColor(hex: "#9B7653") static let dodgerBlue = UIColor(hex: "#1E90FF") static let dogwoodRose = UIColor(hex: "#D71868") static let dollarBill = UIColor(hex: "#85BB65") static let dolphinGray = UIColor(hex: "#828E84") static let donkeyBrown = UIColor(hex: "#664C28") static let drab = UIColor(hex: "#967117") static let dukeBlue = UIColor(hex: "#00009C") static let dustStorm = UIColor(hex: "#E5CCC9") static let dutchWhite = UIColor(hex: "#EFDFBB") static let earthYellow = UIColor(hex: "#E1A95F") static let ebony = UIColor(hex: "#555D50") static let ecru = UIColor(hex: "#C2B280") static let eerieBlack = UIColor(hex: "#1B1B1B") static let eggplant = UIColor(hex: "#614051") static let eggshell = UIColor(hex: "#F0EAD6") static let egyptianBlue = UIColor(hex: "#1034A6") static let electricBlue = UIColor(hex: "#7DF9FF") static let electricCrimson = UIColor(hex: "#FF003F") static let electricCyan = UIColor(hex: "#00FFFF") static let electricGreen = UIColor(hex: "#00FF00") static let electricIndigo = UIColor(hex: "#6F00FF") static let electricLavender = UIColor(hex: "#F4BBFF") static let electricLime = UIColor(hex: "#CCFF00") static let electricPurple = UIColor(hex: "#BF00FF") static let electricUltramarine = UIColor(hex: "#3F00FF") static let electricViolet = UIColor(hex: "#8F00FF") static let electricYellow = UIColor(hex: "#FFFF33") static let emerald = UIColor(hex: "#50C878") static let eminence = UIColor(hex: "#6C3082") static let englishGreen = UIColor(hex: "#1B4D3E") static let englishLavender = UIColor(hex: "#B48395") static let englishRed = UIColor(hex: "#AB4B52") static let englishVermillion = UIColor(hex: "#CC474B") static let englishViolet = UIColor(hex: "#563C5C") static let etonBlue = UIColor(hex: "#96C8A2") static let eucalyptus = UIColor(hex: "#44D7A8") static let fallow = UIColor(hex: "#C19A6B") static let faluRed = UIColor(hex: "#801818") static let fandango = UIColor(hex: "#B53389") static let fandangoPink = UIColor(hex: "#DE5285") static let fashionFuchsia = UIColor(hex: "#F400A1") static let fawn = UIColor(hex: "#E5AA70") static let feldgrau = UIColor(hex: "#4D5D53") static let feldspar = UIColor(hex: "#FDD5B1") static let fernGreen = UIColor(hex: "#4F7942") static let ferrariRed = UIColor(hex: "#FF2800") static let fieldDrab = UIColor(hex: "#6C541E") static let fieryRose = UIColor(hex: "#FF5470") static let firebrick = UIColor(hex: "#B22222") static let fireEngineRed = UIColor(hex: "#CE2029") static let flame = UIColor(hex: "#E25822") static let flamingoPink = UIColor(hex: "#FC8EAC") static let flattery = UIColor(hex: "#6B4423") static let flavescent = UIColor(hex: "#F7E98E") static let flax = UIColor(hex: "#EEDC82") static let flirt = UIColor(hex: "#A2006D") static let floralWhite = UIColor(hex: "#FFFAF0") static let fluorescentOrange = UIColor(hex: "#FFBF00") static let fluorescentPink = UIColor(hex: "#FF1493") static let fluorescentYellow = UIColor(hex: "#CCFF00") static let folly = UIColor(hex: "#FF004F") static let forestGreenTraditional = UIColor(hex: "#014421") static let forestGreenWeb = UIColor(hex: "#228B22") static let frenchBeige = UIColor(hex: "#A67B5B") static let frenchBistre = UIColor(hex: "#856D4D") static let frenchBlue = UIColor(hex: "#0072BB") static let frenchFuchsia = UIColor(hex: "#FD3F92") static let frenchLilac = UIColor(hex: "#86608E") static let frenchLime = UIColor(hex: "#9EFD38") static let frenchMauve = UIColor(hex: "#D473D4") static let frenchPink = UIColor(hex: "#FD6C9E") static let frenchPlum = UIColor(hex: "#811453") static let frenchPuce = UIColor(hex: "#4E1609") static let frenchRaspberry = UIColor(hex: "#C72C48") static let frenchRose = UIColor(hex: "#F64A8A") static let frenchSkyBlue = UIColor(hex: "#77B5FE") static let frenchViolet = UIColor(hex: "#8806CE") static let frenchWine = UIColor(hex: "#AC1E44") static let freshAir = UIColor(hex: "#A6E7FF") static let frostbite = UIColor(hex: "#E936A7") static let fuchsia = UIColor(hex: "#FF00FF") static let fuchsiaCrayola = UIColor(hex: "#C154C1") static let fuchsiaPink = UIColor(hex: "#FF77FF") static let fuchsiaPurple = UIColor(hex: "#CC397B") static let fuchsiaRose = UIColor(hex: "#C74375") static let fulvous = UIColor(hex: "#E48400") static let fuzzyWuzzy = UIColor(hex: "#CC6666") static let gainsboro = UIColor(hex: "#DCDCDC") static let gamboge = UIColor(hex: "#E49B0F") static let gambogeOrangeBrown = UIColor(hex: "#996600") static let gargoyleGas = UIColor(hex: "#FFDF46") static let genericViridian = UIColor(hex: "#007F66") static let ghostWhite = UIColor(hex: "#F8F8FF") static let giantsClub = UIColor(hex: "#B05C52") static let giantsOrange = UIColor(hex: "#FE5A1D") static let ginger = UIColor(hex: "#B06500") static let glaucous = UIColor(hex: "#6082B6") static let glitter = UIColor(hex: "#E6E8FA") static let glossyGrape = UIColor(hex: "#AB92B3") static let gOGreen = UIColor(hex: "#00AB66") static let goldMetallic = UIColor(hex: "#D4AF37") static let goldWebGolden = UIColor(hex: "#FFD700") static let goldFusion = UIColor(hex: "#85754E") static let goldenBrown = UIColor(hex: "#996515") static let goldenPoppy = UIColor(hex: "#FCC200") static let goldenYellow = UIColor(hex: "#FFDF00") static let goldenrod = UIColor(hex: "#DAA520") static let graniteGray = UIColor(hex: "#676767") static let grannySmithApple = UIColor(hex: "#A8E4A0") static let grape = UIColor(hex: "#6F2DA8") static let gray = UIColor(hex: "#808080") static let grayHTMLCSSGray = UIColor(hex: "#808080") static let grayX11Gray = UIColor(hex: "#BEBEBE") static let grayAsparagus = UIColor(hex: "#465945") static let grayBlue = UIColor(hex: "#8C92AC") static let greenColorWheelX11Green = UIColor(hex: "#00FF00") static let greenCrayola = UIColor(hex: "#1CAC78") static let greenHTMLCSSColor = UIColor(hex: "#008000") static let greenMunsell = UIColor(hex: "#00A877") static let greenNCS = UIColor(hex: "#009F6B") static let greenPantone = UIColor(hex: "#00AD43") static let greenPigment = UIColor(hex: "#00A550") static let greenRYB = UIColor(hex: "#66B032") static let greenBlue = UIColor(hex: "#1164B4") static let greenCyan = UIColor(hex: "#009966") static let greenLizard = UIColor(hex: "#A7F432") static let greenSheen = UIColor(hex: "#6EAEA1") static let greenYellow = UIColor(hex: "#ADFF2F") static let grizzly = UIColor(hex: "#885818") static let grullo = UIColor(hex: "#A99A86") static let guppieGreen = UIColor(hex: "#00FF7F") static let gunmetal = UIColor(hex: "#2a3439") static let halayàÚbe = UIColor(hex: "#663854") static let hanBlue = UIColor(hex: "#446CCF") static let hanPurple = UIColor(hex: "#5218FA") static let hansaYellow = UIColor(hex: "#E9D66B") static let harlequin = UIColor(hex: "#3FFF00") static let harlequinGreen = UIColor(hex: "#46CB18") static let harletdCrimson = UIColor(hex: "#C90016") static let harvestGold = UIColor(hex: "#DA9100") static let heartGold = UIColor(hex: "#808000") static let heatWave = UIColor(hex: "#FF7A00") static let heidelbergRed = UIColor(hex: "#960018") static let heliotrope = UIColor(hex: "#DF73FF") static let heliotropeGray = UIColor(hex: "#AA98A9") static let heliotropeMagenta = UIColor(hex: "#AA00BB") static let hollywoodCerise = UIColor(hex: "#F400A1") static let honeydew = UIColor(hex: "#F0FFF0") static let honoluluBlue = UIColor(hex: "#006DB0") static let hookersGreen = UIColor(hex: "#49796B") static let hotMagenta = UIColor(hex: "#FF1DCE") static let hotPink = UIColor(hex: "#FF69B4") static let hunterGreen = UIColor(hex: "#355E3B") static let iceberg = UIColor(hex: "#71A6D2") static let icterine = UIColor(hex: "#FCF75E") static let iguanaGreen = UIColor(hex: "#71BC78") static let illuminatingEmerald = UIColor(hex: "#319177") static let imperial = UIColor(hex: "#602F6B") static let imperialBlue = UIColor(hex: "#002395") static let imperialPurple = UIColor(hex: "#66023C") static let imperialRed = UIColor(hex: "#ED2939") static let inchworm = UIColor(hex: "#B2EC5D") static let independence = UIColor(hex: "#4C516D") static let indiaGreen = UIColor(hex: "#138808") static let indianRed = UIColor(hex: "#CD5C5C") static let indianYellow = UIColor(hex: "#E3A857") static let indigo = UIColor(hex: "#4B0082") static let indigoDye = UIColor(hex: "#091F92") static let indigoWeb = UIColor(hex: "#4B0082") static let infraRed = UIColor(hex: "#FF496C") static let interdimensionalBlue = UIColor(hex: "#360CCC") static let internationalKleinBlue = UIColor(hex: "#002FA7") static let internationalOrangeAerospace = UIColor(hex: "#FF4F00") static let internationalOrangeEngineering = UIColor(hex: "#BA160C") static let internationalOrangeGoldenGateBridge = UIColor(hex: "#C0362C") static let iris = UIColor(hex: "#5A4FCF") static let irresistible = UIColor(hex: "#B3446C") static let isabelline = UIColor(hex: "#F4F0EC") static let islamicGreen = UIColor(hex: "#009000") static let italianSkyBlue = UIColor(hex: "#B2FFFF") static let ivory = UIColor(hex: "#FFFFF0") static let jade = UIColor(hex: "#00A86B") static let japaneseCarmine = UIColor(hex: "#9D2933") static let japaneseIndigo = UIColor(hex: "#264348") static let japaneseViolet = UIColor(hex: "#5B3256") static let jasmine = UIColor(hex: "#F8DE7E") static let jasper = UIColor(hex: "#D73B3E") static let jazzberryJam = UIColor(hex: "#A50B5E") static let jellyBean = UIColor(hex: "#DA614E") static let jet = UIColor(hex: "#343434") static let jonquil = UIColor(hex: "#F4CA16") static let jordyBlue = UIColor(hex: "#8AB9F1") static let juneBud = UIColor(hex: "#BDDA57") static let jungleGreen = UIColor(hex: "#29AB87") static let kellyGreen = UIColor(hex: "#4CBB17") static let kenyanCopper = UIColor(hex: "#7C1C05") static let keppel = UIColor(hex: "#3AB09E") static let keyLime = UIColor(hex: "#E8F48C") static let khakiHTMLCSSKhaki = UIColor(hex: "#C3B091") static let khakiX11LightKhaki = UIColor(hex: "#F0E68C") static let kiwi = UIColor(hex: "#8EE53F") static let kobe = UIColor(hex: "#882D17") static let kobi = UIColor(hex: "#E79FC4") static let kobicha = UIColor(hex: "#6B4423") static let kombuGreen = UIColor(hex: "#354230") static let kSUPurple = UIColor(hex: "#512888") static let kUCrimson = UIColor(hex: "#E8000D") static let laSalleGreen = UIColor(hex: "#087830") static let languidLavender = UIColor(hex: "#D6CADD") static let lapisLazuli = UIColor(hex: "#26619C") static let laserLemon = UIColor(hex: "#FFFF66") static let laurelGreen = UIColor(hex: "#A9BA9D") static let lava = UIColor(hex: "#CF1020") static let lavenderFloral = UIColor(hex: "#B57EDC") static let lavenderWeb = UIColor(hex: "#E6E6FA") static let lavenderBlue = UIColor(hex: "#CCCCFF") static let lavenderBlush = UIColor(hex: "#FFF0F5") static let lavenderGray = UIColor(hex: "#C4C3D0") static let lavenderIndigo = UIColor(hex: "#9457EB") static let lavenderMagenta = UIColor(hex: "#EE82EE") static let lavenderMist = UIColor(hex: "#E6E6FA") static let lavenderPink = UIColor(hex: "#FBAED2") static let lavenderPurple = UIColor(hex: "#967BB6") static let lavenderRose = UIColor(hex: "#FBA0E3") static let lawnGreen = UIColor(hex: "#7CFC00") static let lemon = UIColor(hex: "#FFF700") static let lemonChiffon = UIColor(hex: "#FFFACD") static let lemonCurry = UIColor(hex: "#CCA01D") static let lemonGlacier = UIColor(hex: "#FDFF00") static let lemonLime = UIColor(hex: "#E3FF00") static let lemonMeringue = UIColor(hex: "#F6EABE") static let lemonYellow = UIColor(hex: "#FFF44F") static let licorice = UIColor(hex: "#1A1110") static let liberty = UIColor(hex: "#545AA7") static let lightApricot = UIColor(hex: "#FDD5B1") static let lightBlue = UIColor(hex: "#ADD8E6") static let lightBrown = UIColor(hex: "#B5651D") static let lightCarminePink = UIColor(hex: "#E66771") static let lightCobaltBlue = UIColor(hex: "#88ACE0") static let lightCoral = UIColor(hex: "#F08080") static let lightCornflowerBlue = UIColor(hex: "#93CCEA") static let lightCrimson = UIColor(hex: "#F56991") static let lightCyan = UIColor(hex: "#E0FFFF") static let lightDeepPink = UIColor(hex: "#FF5CCD") static let lightFrenchBeige = UIColor(hex: "#C8AD7F") static let lightFuchsiaPink = UIColor(hex: "#F984EF") static let lightGoldenrodYellow = UIColor(hex: "#FAFAD2") static let lightGray = UIColor(hex: "#D3D3D3") static let lightGrayishMagenta = UIColor(hex: "#CC99CC") static let lightGreen = UIColor(hex: "#90EE90") static let lightHotPink = UIColor(hex: "#FFB3DE") static let lightKhaki = UIColor(hex: "#F0E68C") static let lightMediumOrchid = UIColor(hex: "#D39BCB") static let lightMossGreen = UIColor(hex: "#ADDFAD") static let lightOrange = UIColor(hex: "#FED8B1") static let lightOrchid = UIColor(hex: "#E6A8D7") static let lightPastelPurple = UIColor(hex: "#B19CD9") static let lightPink = UIColor(hex: "#FFB6C1") static let lightRedOchre = UIColor(hex: "#E97451") static let lightSalmon = UIColor(hex: "#FFA07A") static let lightSalmonPink = UIColor(hex: "#FF9999") static let lightSeaGreen = UIColor(hex: "#20B2AA") static let lightSkyBlue = UIColor(hex: "#87CEFA") static let lightSlateGray = UIColor(hex: "#778899") static let lightSteelBlue = UIColor(hex: "#B0C4DE") static let lightTaupe = UIColor(hex: "#B38B6D") static let lightThulianPink = UIColor(hex: "#E68FAC") static let lightYellow = UIColor(hex: "#FFFFE0") static let lilac = UIColor(hex: "#C8A2C8") static let lilacLuster = UIColor(hex: "#AE98AA") static let limeColorWheel = UIColor(hex: "#BFFF00") static let limeWebX11Green = UIColor(hex: "#00FF00") static let limeGreen = UIColor(hex: "#32CD32") static let limerick = UIColor(hex: "#9DC209") static let lincolnGreen = UIColor(hex: "#195905") static let linen = UIColor(hex: "#FAF0E6") static let loeen = UIColor(hex: "#15F2FD") static let liseranPurple = UIColor(hex: "#DE6FA1") static let littleBoyBlue = UIColor(hex: "#6CA0DC") static let liver = UIColor(hex: "#674C47") static let liverDogs = UIColor(hex: "#B86D29") static let liverOrgan = UIColor(hex: "#6C2E1F") static let liverChestnut = UIColor(hex: "#987456") static let livid = UIColor(hex: "#6699CC") static let lumber = UIColor(hex: "#FFE4CD") static let lust = UIColor(hex: "#E62020") static let maastrichtBlue = UIColor(hex: "#001C3D") static let macaroniAndCheese = UIColor(hex: "#FFBD88") static let madderLake = UIColor(hex: "#CC3336") static let magenta = UIColor(hex: "#FF00FF") static let magentaCrayola = UIColor(hex: "#FF55A3") static let magentaDye = UIColor(hex: "#CA1F7B") static let magentaPantone = UIColor(hex: "#D0417E") static let magentaProcess = UIColor(hex: "#FF0090") static let magentaHaze = UIColor(hex: "#9F4576") static let magentaPink = UIColor(hex: "#CC338B") static let magicMint = UIColor(hex: "#AAF0D1") static let magicPotion = UIColor(hex: "#FF4466") static let magnolia = UIColor(hex: "#F8F4FF") static let mahogany = UIColor(hex: "#C04000") static let maize = UIColor(hex: "#FBEC5D") static let majorelleBlue = UIColor(hex: "#6050DC") static let malachite = UIColor(hex: "#0BDA51") static let manatee = UIColor(hex: "#979AAA") static let mandarin = UIColor(hex: "#F37A48") static let mangoTango = UIColor(hex: "#FF8243") static let mantis = UIColor(hex: "#74C365") static let mardiGras = UIColor(hex: "#880085") static let marigold = UIColor(hex: "#EAA221") static let maroonCrayola = UIColor(hex: "#C32148") static let maroonHTMLCSS = UIColor(hex: "#800000") static let maroonX11 = UIColor(hex: "#B03060") static let mauve = UIColor(hex: "#E0B0FF") static let mauveTaupe = UIColor(hex: "#915F6D") static let mauvelous = UIColor(hex: "#EF98AA") static let maximumBlue = UIColor(hex: "#47ABCC") static let maximumBlueGreen = UIColor(hex: "#30BFBF") static let maximumBluePurple = UIColor(hex: "#ACACE6") static let maximumGreen = UIColor(hex: "#5E8C31") static let maximumGreenYellow = UIColor(hex: "#D9E650") static let maximumPurple = UIColor(hex: "#733380") static let maximumRed = UIColor(hex: "#D92121") static let maximumRedPurple = UIColor(hex: "#A63A79") static let maximumYellow = UIColor(hex: "#FAFA37") static let maximumYellowRed = UIColor(hex: "#F2BA49") static let mayGreen = UIColor(hex: "#4C9141") static let mayaBlue = UIColor(hex: "#73C2FB") static let meatBrown = UIColor(hex: "#E5B73B") static let mediumAquamarine = UIColor(hex: "#66DDAA") static let mediumBlue = UIColor(hex: "#0000CD") static let mediumCandyAppleRed = UIColor(hex: "#E2062C") static let mediumCarmine = UIColor(hex: "#AF4035") static let mediumChampagne = UIColor(hex: "#F3E5AB") static let mediumElectricBlue = UIColor(hex: "#035096") static let mediumJungleGreen = UIColor(hex: "#1C352D") static let mediumLavenderMagenta = UIColor(hex: "#DDA0DD") static let mediumOrchid = UIColor(hex: "#BA55D3") static let mediumPersianBlue = UIColor(hex: "#0067A5") static let mediumPurple = UIColor(hex: "#9370DB") static let mediumRedViolet = UIColor(hex: "#BB3385") static let mediumRuby = UIColor(hex: "#AA4069") static let mediumSeaGreen = UIColor(hex: "#3CB371") static let mediumSkyBlue = UIColor(hex: "#80DAEB") static let mediumSlateBlue = UIColor(hex: "#7B68EE") static let mediumSpringBud = UIColor(hex: "#C9DC87") static let mediumSpringGreen = UIColor(hex: "#00FA9A") static let mediumTaupe = UIColor(hex: "#674C47") static let mediumTurquoise = UIColor(hex: "#48D1CC") static let mediumTuscanRed = UIColor(hex: "#79443B") static let mediumVermilion = UIColor(hex: "#D9603B") static let mediumVioletRed = UIColor(hex: "#C71585") static let mellowApricot = UIColor(hex: "#F8B878") static let mellowYellow = UIColor(hex: "#F8DE7E") static let melon = UIColor(hex: "#FDBCB4") static let metallicSeaweed = UIColor(hex: "#0A7E8C") static let metallicSunburst = UIColor(hex: "#9C7C38") static let mexicanPink = UIColor(hex: "#E4007C") static let middleBlue = UIColor(hex: "#7ED4E6") static let middleBlueGreen = UIColor(hex: "#8DD9CC") static let middleBluePurple = UIColor(hex: "#8B72BE") static let middleGreen = UIColor(hex: "#4D8C57") static let middleGreenYellow = UIColor(hex: "#ACBF60") static let middlePurple = UIColor(hex: "#D982B5") static let middleRed = UIColor(hex: "#E58E73") static let middleRedPurple = UIColor(hex: "#A55353") static let middleYellow = UIColor(hex: "#FFEB00") static let middleYellowRed = UIColor(hex: "#ECB176") static let midnight = UIColor(hex: "#702670") static let midnightBlue = UIColor(hex: "#191970") static let midnightGreenEagleGreen = UIColor(hex: "#004953") static let mikadoYellow = UIColor(hex: "#FFC40C") static let milk = UIColor(hex: "#FDFFF5") static let mimiPink = UIColor(hex: "#FFDAE9") static let mindaro = UIColor(hex: "#E3F988") static let ming = UIColor(hex: "#36747D") static let minionYellow = UIColor(hex: "#F5E050") static let mint = UIColor(hex: "#3EB489") static let mintCream = UIColor(hex: "#F5FFFA") static let mintGreen = UIColor(hex: "#98FF98") static let mistyMoss = UIColor(hex: "#BBB477") static let mistyRose = UIColor(hex: "#FFE4E1") static let moccasin = UIColor(hex: "#FAEBD7") static let modeBeige = UIColor(hex: "#967117") static let moonstoneBlue = UIColor(hex: "#73A9C2") static let mordantRed19 = UIColor(hex: "#AE0C00") static let morningBlue = UIColor(hex: "#8DA399") static let mossGreen = UIColor(hex: "#8A9A5B") static let mountainMeadow = UIColor(hex: "#30BA8F") static let mountbattenPink = UIColor(hex: "#997A8D") static let mSUGreen = UIColor(hex: "#18453B") static let mughalGreen = UIColor(hex: "#306030") static let mulberry = UIColor(hex: "#C54B8C") static let mummysTomb = UIColor(hex: "#828E84") static let mustard = UIColor(hex: "#FFDB58") static let myrtleGreen = UIColor(hex: "#317873") static let mystic = UIColor(hex: "#D65282") static let mysticMaroon = UIColor(hex: "#AD4379") static let nadeshikoPink = UIColor(hex: "#F6ADC6") static let napierGreen = UIColor(hex: "#2A8000") static let naplesYellow = UIColor(hex: "#FADA5E") static let navajoWhite = UIColor(hex: "#FFDEAD") static let navy = UIColor(hex: "#000080") static let navyPurple = UIColor(hex: "#9457EB") static let neonCarrot = UIColor(hex: "#FFA343") static let neonFuchsia = UIColor(hex: "#FE4164") static let neonGreen = UIColor(hex: "#39FF14") static let newCar = UIColor(hex: "#214FC6") static let newYorkPink = UIColor(hex: "#D7837F") static let nickel = UIColor(hex: "#727472") static let nonPhotoBlue = UIColor(hex: "#A4DDED") static let northTexasGreen = UIColor(hex: "#059033") static let nyanza = UIColor(hex: "#E9FFDB") static let oceanBlue = UIColor(hex: "#4F42B5") static let oceanBoatBlue = UIColor(hex: "#0077BE") static let oceanGreen = UIColor(hex: "#48BF91") static let ochre = UIColor(hex: "#CC7722") static let officeGreen = UIColor(hex: "#008000") static let ogreOdor = UIColor(hex: "#FD5240") static let oldBurgundy = UIColor(hex: "#43302E") static let oldGold = UIColor(hex: "#CFB53B") static let oldHeliotrope = UIColor(hex: "#563C5C") static let oldLace = UIColor(hex: "#FDF5E6") static let oldLavender = UIColor(hex: "#796878") static let oldMauve = UIColor(hex: "#673147") static let oldMossGreen = UIColor(hex: "#867E36") static let oldRose = UIColor(hex: "#C08081") static let oldSilver = UIColor(hex: "#848482") static let olive = UIColor(hex: "#808000") static let oliveDrab3 = UIColor(hex: "#6B8E23") static let oliveDrab7 = UIColor(hex: "#3C341F") static let olivine = UIColor(hex: "#9AB973") static let onyx = UIColor(hex: "#353839") static let operaMauve = UIColor(hex: "#B784A7") static let orangeColorWheel = UIColor(hex: "#FF7F00") static let orangeCrayola = UIColor(hex: "#FF7538") static let orangePantone = UIColor(hex: "#FF5800") static let orangeRYB = UIColor(hex: "#FB9902") static let orangeWeb = UIColor(hex: "#FFA500") static let orangePeel = UIColor(hex: "#FF9F00") static let orangeRed = UIColor(hex: "#FF4500") static let orangeSoda = UIColor(hex: "#FA5B3D") static let orangeYellow = UIColor(hex: "#F8D568") static let orchid = UIColor(hex: "#DA70D6") static let orchidPink = UIColor(hex: "#F2BDCD") static let oriolesOrange = UIColor(hex: "#FB4F14") static let otterBrown = UIColor(hex: "#654321") static let outerSpace = UIColor(hex: "#414A4C") static let outrageousOrange = UIColor(hex: "#FF6E4A") static let oxfordBlue = UIColor(hex: "#002147") static let oUCrimsonRed = UIColor(hex: "#990000") static let pacificBlue = UIColor(hex: "#1CA9C9") static let pakistanGreen = UIColor(hex: "#006600") static let palatinateBlue = UIColor(hex: "#273BE2") static let palatinatePurple = UIColor(hex: "#682860") static let paleAqua = UIColor(hex: "#BCD4E6") static let paleBlue = UIColor(hex: "#AFEEEE") static let paleBrown = UIColor(hex: "#987654") static let paleCarmine = UIColor(hex: "#AF4035") static let paleCerulean = UIColor(hex: "#9BC4E2") static let paleChestnut = UIColor(hex: "#DDADAF") static let paleCopper = UIColor(hex: "#DA8A67") static let paleCornflowerBlue = UIColor(hex: "#ABCDEF") static let paleCyan = UIColor(hex: "#87D3F8") static let paleGold = UIColor(hex: "#E6BE8A") static let paleGoldenrod = UIColor(hex: "#EEE8AA") static let paleGreen = UIColor(hex: "#98FB98") static let paleLavender = UIColor(hex: "#DCD0FF") static let paleMagenta = UIColor(hex: "#F984E5") static let paleMagentaPink = UIColor(hex: "#FF99CC") static let palePink = UIColor(hex: "#FADADD") static let palePlum = UIColor(hex: "#DDA0DD") static let paleRedViolet = UIColor(hex: "#DB7093") static let paleRobinEggBlue = UIColor(hex: "#96DED1") static let paleSilver = UIColor(hex: "#C9C0BB") static let paleSpringBud = UIColor(hex: "#ECEBBD") static let paletaupe = UIColor(hex: "#BC987E") static let paleturquoise = UIColor(hex: "#AFEEEE") static let paleViolet = UIColor(hex: "#CC99FF") static let paleVioletRed = UIColor(hex: "#DB7093") static let palmLeaf = UIColor(hex: "#6F9940") static let pansyPurple = UIColor(hex: "#78184A") static let paoloVeroneseGreen = UIColor(hex: "#009B7D") static let papayaWhip = UIColor(hex: "#FFEFD5") static let paradisePink = UIColor(hex: "#E63E62") static let parisGreen = UIColor(hex: "#50C878") static let parrotPink = UIColor(hex: "#D998A0") static let pastelBlue = UIColor(hex: "#AEC6CF") static let pastelBrown = UIColor(hex: "#836953") static let pastelGray = UIColor(hex: "#CFCFC4") static let pastelGreen = UIColor(hex: "#77DD77") static let pastelMagenta = UIColor(hex: "#F49AC2") static let pastelOrange = UIColor(hex: "#FFB347") static let pastelPink = UIColor(hex: "#DEA5A4") static let pastelPurple = UIColor(hex: "#B39EB5") static let pastelRed = UIColor(hex: "#FF6961") static let pastelViolet = UIColor(hex: "#CB99C9") static let pastelYellow = UIColor(hex: "#FDFD96") static let patriarch = UIColor(hex: "#800080") static let paynesGrey = UIColor(hex: "#536878") static let peach = UIColor(hex: "#FFE5B4") static let peachOrange = UIColor(hex: "#FFCC99") static let peachPuff = UIColor(hex: "#FFDAB9") static let peachYellow = UIColor(hex: "#FADFAD") static let pear = UIColor(hex: "#D1E231") static let pearl = UIColor(hex: "#EAE0C8") static let pearlAqua = UIColor(hex: "#88D8C0") static let pearlyPurple = UIColor(hex: "#B768A2") static let peridot = UIColor(hex: "#E6E200") static let periwinkle = UIColor(hex: "#CCCCFF") static let permanentGeraniumLake = UIColor(hex: "#E12C2C") static let persianBlue = UIColor(hex: "#1C39BB") static let persianGreen = UIColor(hex: "#00A693") static let persianIndigo = UIColor(hex: "#32127A") static let persianOrange = UIColor(hex: "#D99058") static let persianPink = UIColor(hex: "#F77FBE") static let persianPlum = UIColor(hex: "#701C1C") static let persianRed = UIColor(hex: "#CC3333") static let persianRose = UIColor(hex: "#FE28A2") static let persimmon = UIColor(hex: "#EC5800") static let peru = UIColor(hex: "#CD853F") static let pewterBlue = UIColor(hex: "#8BA8B7") static let phlox = UIColor(hex: "#DF00FF") static let phthaloBlue = UIColor(hex: "#000F89") static let phthaloGreen = UIColor(hex: "#123524") static let pictonBlue = UIColor(hex: "#45B1E8") static let pictorialCarmine = UIColor(hex: "#C30B4E") static let piggyPink = UIColor(hex: "#FDDDE6") static let pineGreen = UIColor(hex: "#01796F") static let pineapple = UIColor(hex: "#563C5C") static let pink = UIColor(hex: "#FFC0CB") static let pinkPantone = UIColor(hex: "#D74894") static let pinkFlamingo = UIColor(hex: "#FC74FD") static let pinkLace = UIColor(hex: "#FFDDF4") static let pinkLavender = UIColor(hex: "#D8B2D1") static let pinkOrange = UIColor(hex: "#FF9966") static let pinkPearl = UIColor(hex: "#E7ACCF") static let pinkRaspberry = UIColor(hex: "#980036") static let pinkSherbet = UIColor(hex: "#F78FA7") static let pistachio = UIColor(hex: "#93C572") static let pixiePowder = UIColor(hex: "#391285") static let platinum = UIColor(hex: "#E5E4E2") static let plum = UIColor(hex: "#8E4585") static let plumWeb = UIColor(hex: "#DDA0DD") static let plumpPurple = UIColor(hex: "#5946B2") static let polishedPine = UIColor(hex: "#5DA493") static let pompAndPower = UIColor(hex: "#86608E") static let popstar = UIColor(hex: "#BE4F62") static let portlandOrange = UIColor(hex: "#FF5A36") static let powderBlue = UIColor(hex: "#B0E0E6") static let princessPerfume = UIColor(hex: "#FF85CF") static let princetonOrange = UIColor(hex: "#F58025") static let prune = UIColor(hex: "#701C1C") static let prussianBlue = UIColor(hex: "#003153") static let psychedelicPurple = UIColor(hex: "#DF00FF") static let puce = UIColor(hex: "#CC8899") static let puceRed = UIColor(hex: "#722F37") static let pullmanBrownUPSBrown = UIColor(hex: "#644117") static let pullmanGreen = UIColor(hex: "#3B331C") static let pumpkin = UIColor(hex: "#FF7518") static let purpleHTML = UIColor(hex: "#800080") static let purpleMunsell = UIColor(hex: "#9F00C5") static let purpleX11 = UIColor(hex: "#A020F0") static let purpleHeart = UIColor(hex: "#69359C") static let purpleMountainMajesty = UIColor(hex: "#9678B6") static let purpleNavy = UIColor(hex: "#4E5180") static let purplePizzazz = UIColor(hex: "#FE4EDA") static let purplePlum = UIColor(hex: "#9C51B6") static let purpletaupe = UIColor(hex: "#50404D") static let purpureus = UIColor(hex: "#9A4EAE") static let quartz = UIColor(hex: "#51484F") static let queenBlue = UIColor(hex: "#436B95") static let queenPink = UIColor(hex: "#E8CCD7") static let quickSilver = UIColor(hex: "#A6A6A6") static let quinacridoneMagenta = UIColor(hex: "#8E3A59") static let rackley = UIColor(hex: "#5D8AA8") static let radicalRed = UIColor(hex: "#FF355E") static let raisinBlack = UIColor(hex: "#242124") static let rajah = UIColor(hex: "#FBAB60") static let raspberry = UIColor(hex: "#E30B5D") static let raspberryGlace = UIColor(hex: "#915F6D") static let raspberryPink = UIColor(hex: "#E25098") static let raspberryRose = UIColor(hex: "#B3446C") static let rawSienna = UIColor(hex: "#D68A59") static let rawUmber = UIColor(hex: "#826644") static let razzleDazzleRose = UIColor(hex: "#FF33CC") static let razzmatazz = UIColor(hex: "#E3256B") static let razzmicBerry = UIColor(hex: "#8D4E85") static let rebeccaPurple = UIColor(hex: "#663399") static let red = UIColor(hex: "#FF0000") static let redCrayola = UIColor(hex: "#EE204D") static let redMunsell = UIColor(hex: "#F2003C") static let redNCS = UIColor(hex: "#C40233") static let redPantone = UIColor(hex: "#ED2939") static let redPigment = UIColor(hex: "#ED1C24") static let redRYB = UIColor(hex: "#FE2712") static let redBrown = UIColor(hex: "#A52A2A") static let redDevil = UIColor(hex: "#860111") static let redOrange = UIColor(hex: "#FF5349") static let redPurple = UIColor(hex: "#E40078") static let redSalsa = UIColor(hex: "#FD3A4A") static let redViolet = UIColor(hex: "#C71585") static let redwood = UIColor(hex: "#A45A52") static let regalia = UIColor(hex: "#522D80") static let registrationBlack = UIColor(hex: "#000000") static let resolutionBlue = UIColor(hex: "#002387") static let rhythm = UIColor(hex: "#777696") static let richBlack = UIColor(hex: "#004040") static let richBlackFOGRA29 = UIColor(hex: "#010B13") static let richBlackFOGRA39 = UIColor(hex: "#010203") static let richBrilliantLavender = UIColor(hex: "#F1A7FE") static let richCarmine = UIColor(hex: "#D70040") static let richElectricBlue = UIColor(hex: "#0892D0") static let richLavender = UIColor(hex: "#A76BCF") static let richLilac = UIColor(hex: "#B666D2") static let richMaroon = UIColor(hex: "#B03060") static let rifleGreen = UIColor(hex: "#444C38") static let roastCoffee = UIColor(hex: "#704241") static let robinEggBlue = UIColor(hex: "#00CCCC") static let rocketMetallic = UIColor(hex: "#8A7F80") static let romanSilver = UIColor(hex: "#838996") static let rose = UIColor(hex: "#FF007F") static let roseBonbon = UIColor(hex: "#F9429E") static let roseDust = UIColor(hex: "#9E5E6F") static let roseEbony = UIColor(hex: "#674846") static let roseGold = UIColor(hex: "#B76E79") static let roseMadder = UIColor(hex: "#E32636") static let rosePink = UIColor(hex: "#FF66CC") static let roseQuartz = UIColor(hex: "#AA98A9") static let roseRed = UIColor(hex: "#C21E56") static let roseTaupe = UIColor(hex: "#905D5D") static let roseVale = UIColor(hex: "#AB4E52") static let rosewood = UIColor(hex: "#65000B") static let rossoCorsa = UIColor(hex: "#D40000") static let rosyBrown = UIColor(hex: "#BC8F8F") static let royalAzure = UIColor(hex: "#0038A8") static let royalBlue = UIColor(hex: "#002366") static let royalFuchsia = UIColor(hex: "#CA2C92") static let royalPurple = UIColor(hex: "#7851A9") static let royalYellow = UIColor(hex: "#FADA5E") static let ruber = UIColor(hex: "#CE4676") static let rubineRed = UIColor(hex: "#D10056") static let ruby = UIColor(hex: "#E0115F") static let rubyRed = UIColor(hex: "#9B111E") static let ruddy = UIColor(hex: "#FF0028") static let ruddyBrown = UIColor(hex: "#BB6528") static let ruddyPink = UIColor(hex: "#E18E96") static let rufous = UIColor(hex: "#A81C07") static let russet = UIColor(hex: "#80461B") static let russianGreen = UIColor(hex: "#679267") static let russianViolet = UIColor(hex: "#32174D") static let rust = UIColor(hex: "#B7410E") static let rustyRed = UIColor(hex: "#DA2C43") static let sacramentoStateGreen = UIColor(hex: "#00563F") static let saddleBrown = UIColor(hex: "#8B4513") static let safetyOrange = UIColor(hex: "#FF7800") static let safetyOrangeBlazeOrange = UIColor(hex: "#FF6700") static let safetyYellow = UIColor(hex: "#EED202") static let saffron = UIColor(hex: "#F4C430") static let sage = UIColor(hex: "#BCB88A") static let stPatricksBlue = UIColor(hex: "#23297A") static let salmon = UIColor(hex: "#FA8072") static let salmonPink = UIColor(hex: "#FF91A4") static let sand = UIColor(hex: "#C2B280") static let sandDune = UIColor(hex: "#967117") static let sandstorm = UIColor(hex: "#ECD540") static let sandyBrown = UIColor(hex: "#F4A460") static let sandyTan = UIColor(hex: "#FDD9B5") static let sandyTaupe = UIColor(hex: "#967117") static let sangria = UIColor(hex: "#92000A") static let sapGreen = UIColor(hex: "#507D2A") static let sapphire = UIColor(hex: "#0F52BA") static let sapphireBlue = UIColor(hex: "#0067A5") static let sasquatchSocks = UIColor(hex: "#FF4681") static let satinSheenGold = UIColor(hex: "#CBA135") static let scarlet = UIColor(hex: "#FF2400") static let schaussPink = UIColor(hex: "#FF91AF") static let schoolBusYellow = UIColor(hex: "#FFD800") static let screaminGreen = UIColor(hex: "#66FF66") static let seaBlue = UIColor(hex: "#006994") static let seaFoamGreen = UIColor(hex: "#9FE2BF") static let seaGreen = UIColor(hex: "#2E8B57") static let seaSerpent = UIColor(hex: "#4BC7CF") static let sealBrown = UIColor(hex: "#59260B") static let seashell = UIColor(hex: "#FFF5EE") static let selectiveYellow = UIColor(hex: "#FFBA00") static let sepia = UIColor(hex: "#704214") static let shadow = UIColor(hex: "#8A795D") static let shadowBlue = UIColor(hex: "#778BA5") static let shampoo = UIColor(hex: "#FFCFF1") static let shamrockGreen = UIColor(hex: "#009E60") static let sheenGreen = UIColor(hex: "#8FD400") static let shimmeringBlush = UIColor(hex: "#D98695") static let shinyShamrock = UIColor(hex: "#5FA778") static let shockingPink = UIColor(hex: "#FC0FC0") static let shockingPinkCrayola = UIColor(hex: "#FF6FFF") static let sienna = UIColor(hex: "#882D17") static let silver = UIColor(hex: "#C0C0C0") static let silverChalice = UIColor(hex: "#ACACAC") static let silverLakeBlue = UIColor(hex: "#5D89BA") static let silverPink = UIColor(hex: "#C4AEAD") static let silverSand = UIColor(hex: "#BFC1C2") static let sinopia = UIColor(hex: "#CB410B") static let sizzlingRed = UIColor(hex: "#FF3855") static let sizzlingSunrise = UIColor(hex: "#FFDB00") static let skobeloff = UIColor(hex: "#007474") static let skyBlue = UIColor(hex: "#87CEEB") static let skyMagenta = UIColor(hex: "#CF71AF") static let slateBlue = UIColor(hex: "#6A5ACD") static let slateGray = UIColor(hex: "#708090") static let smaltDarkPowderBlue = UIColor(hex: "#003399") static let slimyGreen = UIColor(hex: "#299617") static let smashedPumpkin = UIColor(hex: "#FF6D3A") static let smitten = UIColor(hex: "#C84186") static let smoke = UIColor(hex: "#738276") static let smokeyTopaz = UIColor(hex: "#832A0D") static let smokyBlack = UIColor(hex: "#100C08") static let smokyTopaz = UIColor(hex: "#933D41") static let snow = UIColor(hex: "#FFFAFA") static let soap = UIColor(hex: "#CEC8EF") static let solidPink = UIColor(hex: "#893843") static let sonicSilver = UIColor(hex: "#757575") static let spartanCrimson = UIColor(hex: "#9E1316") static let spaceCadet = UIColor(hex: "#1D2951") static let spanishBistre = UIColor(hex: "#807532") static let spanishBlue = UIColor(hex: "#0070B8") static let spanishCarmine = UIColor(hex: "#D10047") static let spanishCrimson = UIColor(hex: "#E51A4C") static let spanishGray = UIColor(hex: "#989898") static let spanishGreen = UIColor(hex: "#009150") static let spanishOrange = UIColor(hex: "#E86100") static let spanishPink = UIColor(hex: "#F7BFBE") static let spanishRed = UIColor(hex: "#E60026") static let spanishSkyBlue = UIColor(hex: "#00FFFF") static let spanishViolet = UIColor(hex: "#4C2882") static let spanishViridian = UIColor(hex: "#007F5C") static let spicyMix = UIColor(hex: "#8B5f4D") static let spiroDiscoBall = UIColor(hex: "#0FC0FC") static let springBud = UIColor(hex: "#A7FC00") static let springFrost = UIColor(hex: "#87FF2A") static let springGreen = UIColor(hex: "#00FF7F") static let starCommandBlue = UIColor(hex: "#007BB8") static let steelBlue = UIColor(hex: "#4682B4") static let steelPink = UIColor(hex: "#CC33CC") static let steelTeal = UIColor(hex: "#5F8A8B") static let stilDeGrainYellow = UIColor(hex: "#FADA5E") static let stizza = UIColor(hex: "#990000") static let stormcloud = UIColor(hex: "#4F666A") static let straw = UIColor(hex: "#E4D96F") static let strawberry = UIColor(hex: "#FC5A8D") static let sugarPlum = UIColor(hex: "#914E75") static let sunburntCyclops = UIColor(hex: "#FF404C") static let sunglow = UIColor(hex: "#FFCC33") static let sunny = UIColor(hex: "#F2F27A") static let sunray = UIColor(hex: "#E3AB57") static let sunset = UIColor(hex: "#FAD6A5") static let sunsetOrange = UIColor(hex: "#FD5E53") static let superPink = UIColor(hex: "#CF6BA9") static let sweetBrown = UIColor(hex: "#A83731") static let tan = UIColor(hex: "#D2B48C") static let tangelo = UIColor(hex: "#F94D00") static let tangerine = UIColor(hex: "#F28500") static let tangerineYellow = UIColor(hex: "#FFCC00") static let tangoPink = UIColor(hex: "#E4717A") static let tartOrange = UIColor(hex: "#FB4D46") static let taupe = UIColor(hex: "#483C32") static let taupeGray = UIColor(hex: "#8B8589") static let teaGreen = UIColor(hex: "#D0F0C0") static let teaRose = UIColor(hex: "#F88379") static let teal = UIColor(hex: "#008080") static let tealBlue = UIColor(hex: "#367588") static let tealDeer = UIColor(hex: "#99E6B3") static let tealGreen = UIColor(hex: "#00827F") static let telemagenta = UIColor(hex: "#CF3476") static let tenneTawny = UIColor(hex: "#CD5700") static let terraCotta = UIColor(hex: "#E2725B") static let thistle = UIColor(hex: "#D8BFD8") static let thulianPink = UIColor(hex: "#DE6FA1") static let tickleMePink = UIColor(hex: "#FC89AC") static let tiffanyBlue = UIColor(hex: "#0ABAB5") static let tigersEye = UIColor(hex: "#E08D3C") static let timberwolf = UIColor(hex: "#DBD7D2") static let titaniumYellow = UIColor(hex: "#EEE600") static let tomato = UIColor(hex: "#FF6347") static let toolbox = UIColor(hex: "#746CC0") static let topaz = UIColor(hex: "#FFC87C") static let tractorRed = UIColor(hex: "#FD0E35") static let trolleyGrey = UIColor(hex: "#808080") static let tropicalRainForest = UIColor(hex: "#00755E") static let tropicalViolet = UIColor(hex: "#CDA4DE") static let trueBlue = UIColor(hex: "#0073CF") static let tuftsBlue = UIColor(hex: "#3E8EDE") static let tulip = UIColor(hex: "#FF878D") static let tumbleweed = UIColor(hex: "#DEAA88") static let turkishRose = UIColor(hex: "#B57281") static let turquoise = UIColor(hex: "#40E0D0") static let turquoiseBlue = UIColor(hex: "#00FFEF") static let turquoiseGreen = UIColor(hex: "#A0D6B4") static let turquoiseSurf = UIColor(hex: "#00C5CD") static let turtleGreen = UIColor(hex: "#8A9A5B") static let tuscan = UIColor(hex: "#FAD6A5") static let tuscanBrown = UIColor(hex: "#6F4E37") static let tuscanRed = UIColor(hex: "#7C4848") static let tuscanTan = UIColor(hex: "#A67B5B") static let tuscany = UIColor(hex: "#C09999") static let twilightLavender = UIColor(hex: "#8A496B") static let tyrianPurple = UIColor(hex: "#66023C") static let uABlue = UIColor(hex: "#0033AA") static let uARed = UIColor(hex: "#D9004C") static let ube = UIColor(hex: "#8878C3") static let uCLABlue = UIColor(hex: "#536895") static let uCLAGold = UIColor(hex: "#FFB300") static let uFOGreen = UIColor(hex: "#3CD070") static let ultramarine = UIColor(hex: "#3F00FF") static let ultramarineBlue = UIColor(hex: "#4166F5") static let ultraPink = UIColor(hex: "#FF6FFF") static let ultraRed = UIColor(hex: "#FC6C85") static let umber = UIColor(hex: "#635147") static let unbleachedSilk = UIColor(hex: "#FFDDCA") static let unitedNationsBlue = UIColor(hex: "#5B92E5") static let universityOfCaliforniaGold = UIColor(hex: "#B78727") static let unmellowYellow = UIColor(hex: "#FFFF66") static let uPForestGreen = UIColor(hex: "#014421") static let uPMaroon = UIColor(hex: "#7B1113") static let upsdellRed = UIColor(hex: "#AE2029") static let urobilin = UIColor(hex: "#E1AD21") static let uSAFABlue = UIColor(hex: "#004F98") static let uSCCardinal = UIColor(hex: "#990000") static let uSCGold = UIColor(hex: "#FFCC00") static let universityOfTennesseeOrange = UIColor(hex: "#F77F00") static let utahCrimson = UIColor(hex: "#D3003F") static let vanDykeBrown = UIColor(hex: "#664228") static let vanilla = UIColor(hex: "#F3E5AB") static let vanillaIce = UIColor(hex: "#F38FA9") static let vegasGold = UIColor(hex: "#C5B358") static let venetianRed = UIColor(hex: "#C80815") static let verdigris = UIColor(hex: "#43B3AE") static let vermilion = UIColor(hex: "#E34234") static let veronica = UIColor(hex: "#A020F0") static let veryLightAzure = UIColor(hex: "#74BBFB") static let veryLightBlue = UIColor(hex: "#6666FF") static let veryLightMalachiteGreen = UIColor(hex: "#64E986") static let veryLightTangelo = UIColor(hex: "#FFB077") static let veryPaleOrange = UIColor(hex: "#FFDFBF") static let veryPaleYellow = UIColor(hex: "#FFFFBF") static let violet = UIColor(hex: "#8F00FF") static let violetColorWheel = UIColor(hex: "#7F00FF") static let violetRYB = UIColor(hex: "#8601AF") static let violetWeb = UIColor(hex: "#EE82EE") static let violetBlue = UIColor(hex: "#324AB2") static let violetRed = UIColor(hex: "#F75394") static let viridian = UIColor(hex: "#40826D") static let viridianGreen = UIColor(hex: "#009698") static let vistaBlue = UIColor(hex: "#7C9ED9") static let vividAmber = UIColor(hex: "#CC9900") static let vividAuburn = UIColor(hex: "#922724") static let vividBurgundy = UIColor(hex: "#9F1D35") static let vividCerise = UIColor(hex: "#DA1D81") static let vividCerulean = UIColor(hex: "#00AAEE") static let vividCrimson = UIColor(hex: "#CC0033") static let vividGamboge = UIColor(hex: "#FF9900") static let vividLimeGreen = UIColor(hex: "#A6D608") static let vividMalachite = UIColor(hex: "#00CC33") static let vividMulberry = UIColor(hex: "#B80CE3") static let vividOrange = UIColor(hex: "#FF5F00") static let vividOrangePeel = UIColor(hex: "#FFA000") static let vividOrchid = UIColor(hex: "#CC00FF") static let vividRaspberry = UIColor(hex: "#FF006C") static let vividRed = UIColor(hex: "#F70D1A") static let vividRedTangelo = UIColor(hex: "#DF6124") static let vividSkyBlue = UIColor(hex: "#00CCFF") static let vividTangelo = UIColor(hex: "#F07427") static let vividTangerine = UIColor(hex: "#FFA089") static let vividVermilion = UIColor(hex: "#E56024") static let vividViolet = UIColor(hex: "#9F00FF") static let vividYellow = UIColor(hex: "#FFE302") static let volt = UIColor(hex: "#CEFF00") static let wageningenGreen = UIColor(hex: "#34B233") static let warmBlack = UIColor(hex: "#004242") static let waterspout = UIColor(hex: "#A4F4F9") static let weldonBlue = UIColor(hex: "#7C98AB") static let wenge = UIColor(hex: "#645452") static let wheat = UIColor(hex: "#F5DEB3") static let white = UIColor(hex: "#FFFFFF") static let whiteSmoke = UIColor(hex: "#F5F5F5") static let wildBlueYonder = UIColor(hex: "#A2ADD0") static let wildOrchid = UIColor(hex: "#D470A2") static let wildStrawberry = UIColor(hex: "#FF43A4") static let wildWatermelon = UIColor(hex: "#FC6C85") static let willpowerOrange = UIColor(hex: "#FD5800") static let windsorTan = UIColor(hex: "#A75502") static let wine = UIColor(hex: "#722F37") static let wineDregs = UIColor(hex: "#673147") static let winterSky = UIColor(hex: "#FF007C") static let winterWizard = UIColor(hex: "#A0E6FF") static let wintergreenDream = UIColor(hex: "#56887D") static let wisteria = UIColor(hex: "#C9A0DC") static let woodBrown = UIColor(hex: "#C19A6B") static let xanadu = UIColor(hex: "#738678") static let yaleBlue = UIColor(hex: "#0F4D92") static let yankeesBlue = UIColor(hex: "#1C2841") static let yellow = UIColor(hex: "#FFFF00") static let yellowCrayola = UIColor(hex: "#FCE883") static let yellowMunsell = UIColor(hex: "#EFCC00") static let yellowNCS = UIColor(hex: "#FFD300") static let yellowPantone = UIColor(hex: "#FEDF00") static let yellowProcess = UIColor(hex: "#FFEF00") static let yellowRYB = UIColor(hex: "#FEFE33") static let yellowGreen = UIColor(hex: "#9ACD32") static let yellowOrange = UIColor(hex: "#FFAE42") static let yellowRose = UIColor(hex: "#FFF000") static let yellowSunshine = UIColor(hex: "#FFF700") static let zaffre = UIColor(hex: "#0014A8") static let zinnwalditeBrown = UIColor(hex: "#2C1608") static let zomp = UIColor(hex: "#39A78E") }
b0afcda36eebccf701aad1e93c31d532
51.139362
107
0.670354
false
false
false
false
chanhx/Octogit
refs/heads/master
iGithub/ViewControllers/Detail/OrganizationViewController.swift
gpl-3.0
2
// // OrganizationViewController.swift // iGithub // // Created by Chan Hocheung on 7/29/16. // Copyright © 2016 Hocheung. All rights reserved. // import UIKit import RxSwift class OrganizationViewController: BaseTableViewController { @IBOutlet weak var avatarView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descLabel: UILabel! let statusCell = StatusCell(name: "organization") var viewModel: OrganizationViewModel! { didSet { viewModel.user.asDriver() .drive(onNext: { [unowned self] org in self.tableView.reloadData() self.configureHeader(org: org) self.sizeHeaderToFit(tableView: self.tableView) }) .disposed(by: viewModel.disposeBag) } } class func instantiateFromStoryboard() -> OrganizationViewController { return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OrganizationViewController") as! OrganizationViewController } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = self.viewModel.title self.viewModel.fetchUser() } func configureHeader(org: User) { self.avatarView.setAvatar(with: org.avatarURL) self.descLabel.text = org.orgDescription if let name = org.name?.trimmingCharacters(in: .whitespaces) , name.count > 0 { self.nameLabel.text = name } else { self.nameLabel.text = org.login } } override func numberOfSections(in tableView: UITableView) -> Int { return viewModel.numberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfRowsIn(section: section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard viewModel.userLoaded else { return statusCell } let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) cell.textLabel?.textColor = UIColor(netHex: 0x333333) switch viewModel.sectionTypes[indexPath.section] { case .vcards: switch viewModel.vcardDetails[indexPath.row] { case .company: cell.textLabel?.attributedText = Octicon.organization.iconString(" \(viewModel.user.value.company!)", iconSize: 18, iconColor: .lightGray) case .location: cell.textLabel?.attributedText = Octicon.location.iconString(" \(viewModel.user.value.location!)", iconSize: 18, iconColor: .lightGray) case .email: cell.textLabel?.attributedText = Octicon.mail.iconString(" \(viewModel.user.value.email!)", iconSize: 18, iconColor: .lightGray) case .blog: cell.textLabel?.attributedText = Octicon.link.iconString(" \(viewModel.user.value.blog!)", iconSize: 18, iconColor: .lightGray) cell.accessoryType = .disclosureIndicator } return cell case .general: cell.accessoryType = .disclosureIndicator cell.textLabel?.text = ["Public activity", "Repositories", "Members"][indexPath.row] switch indexPath.row { case 0: cell.textLabel?.attributedText = Octicon.rss.iconString(" Public activity", iconSize: 18, iconColor: .lightGray) case 1: cell.textLabel?.attributedText = Octicon.repo.iconString(" Repositories", iconSize: 18, iconColor: .lightGray) case 2: cell.textLabel?.attributedText = Octicon.organization.iconString(" Members", iconSize: 18, iconColor: .lightGray) default: break } return cell default: return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch viewModel.sectionTypes[indexPath.section] { case .vcards: if viewModel.vcardDetails[indexPath.row] == .blog { navigationController?.pushViewController(URLRouter.viewController(forURL: viewModel.user.value.blog!), animated: true) } case .general: switch indexPath.row { case 0: let eventTVC = EventTableViewController() eventTVC.viewModel = EventTableViewModel(org: viewModel.user.value) self.navigationController?.pushViewController(eventTVC, animated: true) case 1: let repositoryTVC = RepositoryTableViewController() repositoryTVC.viewModel = RepositoryTableViewModel(login: viewModel.user.value.login, type: .organization) self.navigationController?.pushViewController(repositoryTVC, animated: true) case 2: let userTVC = UserTableViewController() userTVC.viewModel = UserTableViewModel(organization: viewModel.user.value) self.navigationController?.pushViewController(userTVC, animated: true) default: break } default: break } } }
cf38ffcae7d9e6029287bdba9a73bfcf
38.460432
157
0.612215
false
false
false
false
Ramotion/reel-search
refs/heads/master
RAMReel/Framework/RAMTextField.swift
mit
1
// // RAMTextField.swift // RAMReel // // Created by Mikhail Stepkin on 4/22/15. // Copyright (c) 2015 Ramotion. All rights reserved. // import UIKit // MARK: - RAMTextField /** RAMTextField -- Textfield with a line in the bottom */ open class RAMTextField: UITextField { /** Overriding UIView's drawRect method to add line in the bottom of the Text Field - parameter rect: Rect that should be updated. This override ignores this parameter and redraws all text field */ override open func draw(_ rect: CGRect) { let rect = self.bounds let ctx = UIGraphicsGetCurrentContext() let lineColor = self.tintColor.withAlphaComponent(0.3) lineColor.set() ctx?.setLineWidth(1) let path = CGMutablePath() // var m = CGAffineTransform.identity // CGPathMoveToPoint(path, &m, 0, rect.height) path.move(to: CGPoint(x: 0, y: rect.height)) path.addLine(to: CGPoint(x: rect.width, y: rect.height)) // CGPathAddLineToPoint(path, &m, rect.width, rect.height) ctx?.addPath(path) ctx?.strokePath() } } // MARK: - UITextField extensions extension UITextField { /** Overriding `UITextField` `tintColor` property to make it affect close image tint color. */ open override var tintColor: UIColor! { get { return super.tintColor } set { super.tintColor = newValue let subviews = self.subviews for view in subviews { guard let button = view as? UIButton else { break } let states: [UIControl.State] = [.highlighted] states.forEach { state -> Void in let image = button.image(for: state)?.tintedImage(self.tintColor) button.setImage(image, for: state) } } } } } // MARK: - UIImage extensions private extension UIImage { /** Create new image by applying a tint. - parameter color: New image tint color. */ func tintedImage(_ color: UIColor) -> UIImage { let size = self.size UIGraphicsBeginImageContextWithOptions(size, false, self.scale) let context = UIGraphicsGetCurrentContext() self.draw(at: CGPoint.zero, blendMode: CGBlendMode.normal, alpha: 1.0) context?.setFillColor(color.cgColor) context?.setBlendMode(CGBlendMode.sourceIn) context?.setAlpha(1.0) let rect = CGRect( x: CGPoint.zero.x, y: CGPoint.zero.y, width: size.width, height: size.height) UIGraphicsGetCurrentContext()?.fill(rect) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage ?? self } }
396cacc6abaa1e43dcc1c25c93df1261
25.681416
115
0.571808
false
false
false
false
apple/swift-format
refs/heads/main
Sources/SwiftFormatRules/NoBlockComments.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftFormatCore import SwiftSyntax /// Block comments should be avoided in favor of line comments. /// /// Lint: If a block comment appears, a lint error is raised. public final class NoBlockComments: SyntaxLintRule { public override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind { for triviaIndex in token.leadingTrivia.indices { let piece = token.leadingTrivia[triviaIndex] if case .blockComment = piece { diagnose(.avoidBlockComment, on: token, leadingTriviaIndex: triviaIndex) } } return .skipChildren } } extension Finding.Message { public static let avoidBlockComment: Finding.Message = "replace block comment with line comments" }
79851ea00f5139909206673770b89a3b
35.205882
81
0.641755
false
false
false
false
Arthraim/ENIL
refs/heads/master
ENIL/AppDelegate.swift
mit
1
// // AppDelegate.swift // ENIL // // Created by Arthur Wang on 2/20/17. // Copyright © 2017 YANGAPP. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var viewController: ViewController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) viewController = ViewController() window?.rootViewController = UINavigationController.init(rootViewController: viewController!) window?.makeKeyAndVisible() if let url: URL = launchOptions?[UIApplication.LaunchOptionsKey.url] as? URL { updateUI(content: extractTextFromURL(url: url), shouldDelay: true) } else { updateUI(content: "NO AVAILABLE LINK\n\nClick link below to go back to MONSTER STRIKE, then send invitation link via LINE. It will automatically go back to this app.", shouldDelay: true) } return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { updateUI(content: extractTextFromURL(url: url), shouldDelay: false) return true } func extractTextFromURL(url: URL) -> String { return url.path.replacingOccurrences(of: "/text/", with: "") } // IMPORTANT // by the time didFinishLaunchingWithOptions invoked, self.viewController might not created yet // so add a delay here before update text if needed func updateUI(content: String, shouldDelay: Bool) { let deadline = shouldDelay ? DispatchTime.now() + 1 : DispatchTime.now() DispatchQueue.main.asyncAfter(deadline: deadline) { [unowned self] in self.viewController?.updateText(text: content) if let presented = self.viewController?.presentedViewController { presented.dismiss(animated: false, completion: nil) } } } }
fefc9ba278336965cf7f9f9e926e103a
36.052632
179
0.668087
false
false
false
false
FedeGens/WeePager
refs/heads/master
WeePager/WeePager.swift
mit
1
// // MyPager.swift // MyPager // // Created by Federico Gentile on 02/01/17. // Copyright © 2017 Federico Gentile. All rights reserved. // import UIKit public class WeePager: UIView { internal var menu: MenuView! internal var body: BodyView! private var separator: UIView = UIView() internal var page: Int = 0 internal var bodyOldIndex: Int = 0 public var delegate: MyPagerDelegate? public var isLoaded: Bool = false public var bodyInteractable: Bool = true { didSet { body?.isUserInteractionEnabled = bodyInteractable } } public var menuInteractable: Bool = true { didSet { menu?.isUserInteractionEnabled = menuInteractable } } private var menuLeftConst: NSLayoutConstraint! private var bodyTopConst: NSLayoutConstraint! @IBInspectable public var loadAllPages : Bool = true @IBInspectable public var pagesOffLimit : Int = 5 @IBInspectable public var initialPage : Int = 0 @IBInspectable public var animateMenuSelectionScroll : Bool = true @IBInspectable public var menuVisible : Bool = true @IBInspectable public var menuHeight : CGFloat = 50 public var menuPosition : menuPosition = .top @IBInspectable public var menuBackgroundColor : UIColor = .white @IBInspectable public var menuInset : CGFloat = 32 @IBInspectable public var menuShadowEnabled : Bool = false @IBInspectable public var menuShadowOpacity : Float = 0.4 @IBInspectable public var menuShadowRadius : CGFloat = 1.5 @IBInspectable public var menuShadowWidth : CGFloat = 0 @IBInspectable public var menuShadowHeight : CGFloat = 2.5 @IBInspectable public var menuFillItems : Bool = true @IBInspectable public var separatorHeight : CGFloat = 0 @IBInspectable public var separatorColor : UIColor = .black @IBInspectable public var separatorInset : CGFloat = 0 @IBInspectable public var separatorMarginTop : CGFloat = 0 @IBInspectable public var separatorMarginBottom : CGFloat = 0 @IBInspectable public var itemMaxLines : Int = 1 @IBInspectable public var itemMinWidth : CGFloat = 50 @IBInspectable public var itemMaxWidth : CGFloat = 150 @IBInspectable public var itemInset : CGFloat = 16 @IBInspectable public var itemAlignment : UIControl.ContentHorizontalAlignment = .center @IBInspectable public var itemBoldSelected : Bool = true @IBInspectable public var itemCanColor : Bool = true @IBInspectable public var itemColor : UIColor = .gray @IBInspectable public var itemSelectedColor : UIColor = .black @IBInspectable public var itemFont : UIFont = UIFont.systemFont(ofSize: 17) @IBInspectable public var itemBoldFont : UIFont = UIFont.boldSystemFont(ofSize: 17) @IBInspectable public var indicatorView : UIView = UIView() @IBInspectable public var indicatorColor : UIColor = .black @IBInspectable public var indicatorWidthAnimated : Bool = true @IBInspectable public var indicatorWidth : CGFloat = 50 @IBInspectable public var indicatorHeight : CGFloat = 3 @IBInspectable public var indicatorCornerRadius : CGFloat = 2 public var indicatorAlign : indicatorAlignment = .bottom @IBInspectable public var indicatorAlpha : CGFloat = 1.0 @IBInspectable public var indicatorOffsetY : CGFloat = 0.0 @IBInspectable public var bodyScrollable : Bool = true @IBInspectable public var bodyBounceable : Bool = true @IBInspectable public var menuScrollable : Bool = true { didSet { menu?.isScrollEnabled = menuScrollable } } @IBInspectable public var infiniteScroll : Bool = false public func set(viewControllers: [UIViewController], titles: [String]?, images: [UIImage]?) { guard viewControllers.count > 0 else { print("WeePager WARNING: - add at least one viewController to init the pager") return } if body != nil { menu?.removeFromSuperview() body.removeFromSuperview() separator.removeFromSuperview() } //body setup body = BodyView(frame: CGRect(x: 0, y: (self.menuPosition == .top) ? self.menuHeight : 0, width:self.frame.width, height: self.frame.height-self.menuHeight), viewControllers: viewControllers, pagerReference: self) body.translatesAutoresizingMaskIntoConstraints = false body.isUserInteractionEnabled = bodyInteractable self.addSubview(body) if menuVisible { //menu setup var titleArray = [String]() if titles == nil || titles?.count != viewControllers.count { for elem in viewControllers { let title = (elem.title != nil) ? elem.title! : "" titleArray.append(title) } } else { titleArray = titles! } menu = MenuView(frame: CGRect(x: 0, y: (self.menuPosition == .top) ? 0 : self.frame.height-self.menuHeight, width:self.frame.width, height: self.menuHeight), titles: titleArray, images: images, pagerReference: self) menu.translatesAutoresizingMaskIntoConstraints = false body.menuReference = menu menu?.bodyReference = body menu.setSelected(index: page) menu.isUserInteractionEnabled = menuInteractable menu.isScrollEnabled = menuScrollable self.addSubview(menu) //separator setup separator.backgroundColor = separatorColor separator.translatesAutoresizingMaskIntoConstraints = false self.addSubview(separator) } setConstraints() isLoaded = true didSetPage(index: initialPage) } private func setConstraints() { guard let menu = menu, let body = body else { return } menuLeftConst = NSLayoutConstraint(item: menu, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0) self.addConstraint(menuLeftConst) let rightConst = NSLayoutConstraint(item: menu, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0) rightConst.priority = UILayoutPriority(rawValue: 750) self.addConstraint(rightConst) self.addConstraint(NSLayoutConstraint(item: menu, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.menuHeight)) self.addConstraint(NSLayoutConstraint(item: separator, attribute: .leading, relatedBy: .equal, toItem: menu, attribute: .leading, multiplier: 1.0, constant: self.separatorInset)) self.addConstraint(NSLayoutConstraint(item: separator, attribute: .trailing, relatedBy: .equal, toItem: menu, attribute: .trailing, multiplier: 1.0, constant: -self.separatorInset)) self.addConstraint(NSLayoutConstraint(item: separator, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.separatorHeight)) self.addConstraint(NSLayoutConstraint(item: body, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: body, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0)) if self.menuPosition == .top { self.addConstraint(NSLayoutConstraint(item: menu, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: menu, attribute: .bottom, relatedBy: .equal, toItem: separator, attribute: .top, multiplier: 1.0, constant: -separatorMarginTop)) bodyTopConst = NSLayoutConstraint(item: separator, attribute: .bottom, relatedBy: .equal, toItem: body, attribute: .top, multiplier: 1.0, constant: -separatorMarginBottom) self.addConstraint(bodyTopConst) let bodyBotConst = NSLayoutConstraint(item: body, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0) bodyBotConst.priority = UILayoutPriority(rawValue: 750) self.addConstraint(bodyBotConst) } else { self.addConstraint(NSLayoutConstraint(item: menu, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: menu, attribute: .top, relatedBy: .equal, toItem: separator, attribute: .bottom, multiplier: 1.0, constant: separatorMarginBottom)) self.addConstraint(NSLayoutConstraint(item: separator, attribute: .top, relatedBy: .equal, toItem: body, attribute: .bottom, multiplier: 1.0, constant: separatorMarginTop)) self.addConstraint(NSLayoutConstraint(item: body, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0)) } } override public func layoutSubviews() { guard body != nil else { return } body.delegate = nil super.layoutSubviews() body.updateLayout() menu?.updateLayout() body.delegate = body } internal func didSetPage(index: Int) { page = index delegate?.pagerDidMoveToPage?(index: page) } internal func isSettingPage(index: Int) { guard !infiniteScroll else { if bodyOldIndex != index { body.updateInfiniteViewControllersPosition(forward: (index > bodyOldIndex)) page += (index > bodyOldIndex) ? 1 : -1 bodyOldIndex = index if page == body.viewControllers.count { page = 0 } else if page < 0 { page = body.viewControllers.count-1 } delegate?.pagerIsMovingToPage?(index: page) } return } if page != index { page = index menu?.setSelected(index: page) delegate?.pagerIsMovingToPage?(index: page) } } public func setPage(forIndex index: Int, animated: Bool) { guard !infiniteScroll else { page = index body.updateLayout() page = index return } body.moveToPage(index: index, animated: animated) } public func getPage() -> Int { return page } public func setIndicatorImage(withName name: String) { let myImage = UIImage(named: name)! setIndicatorImage(withImage: myImage) } public func setIndicatorImage(withImage image: UIImage) { let myImageView = UIImageView(image: image) indicatorView = myImageView indicatorColor = .clear } public func setMenuElementTitle(forIndex index: Int, title: String) { menu.setMenuElement(title: title, index: index) } public func reloadData() { for vc in body.viewControllers { vc.viewWillAppear(true) vc.viewDidAppear(true) } } public func prepareToAnimate(show: Bool) { menuLeftConst.constant = (show) ? UIScreen.main.bounds.width : 0 bodyTopConst.constant = (show) ? -self.frame.height : 0 } public func animate(show: Bool, time: Double, options: UIView.AnimationOptions, completion: (()->())? = nil ) { menuLeftConst.constant = (show) ? 0 : UIScreen.main.bounds.width+16 bodyTopConst.constant = (show) ? 0 : -self.frame.height UIView.animate(withDuration: time, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0, options: options, animations: { self.layoutIfNeeded() }, completion: { _ in completion?() if show { self.layoutSubviews() } }) } public func set(menuShadowVisible visible: Bool) { self.menuShadowEnabled = visible self.menu?.setShadow() } public func refreshMenuProperties() { menu?.refreshMenuProperties() } } public enum indicatorAlignment : String { case top = "top" case middle = "middle" case bottom = "bottom" } public enum menuPosition : String { case top = "top" case bottom = "bottom" } @objc public protocol MyPagerDelegate { @objc optional func pagerWillBeginMoving(fromIndex index: Int) @objc optional func pagerDidMoveToPage(index: Int) @objc optional func pagerIsMovingToPage(index: Int) @objc optional func percentageScrolled(percentage: Double) @objc optional func pagerMenuSelected(index: Int) }
d38a87c0b6a960425111dd57e9613232
42.585859
227
0.650985
false
false
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
Carthage/Checkouts/CocoaLumberjack/Sources/CocoaLumberjackSwift/DDLog+Combine.swift
apache-2.0
2
// Software License Agreement (BSD License) // // Copyright (c) 2010-2020, Deusty, LLC // All rights reserved. // // Redistribution and use of this software in source and binary forms, // with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Neither the name of Deusty nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission of Deusty, LLC. #if canImport(Combine) import Combine #if SWIFT_PACKAGE import CocoaLumberjack import CocoaLumberjackSwiftSupport #endif @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension DDLog { /** * Creates a message publisher. * * The publisher will add and remove loggers as subscriptions are added and removed. * * The level that you provide here is a preemptive filter (for performance). * That is, the level specified here will be used to filter out logMessages so that * the logger is never even invoked for the messages. * * More information: * See -[DDLog addLogger:with:] * * - Parameter logLevel: preemptive filter of the message returned by the publisher. All levels are sent by default * - Returns: A MessagePublisher that emits LogMessages filtered by the specified logLevel **/ public func messagePublisher(with logLevel: DDLogLevel = .all) -> MessagePublisher { return MessagePublisher(log: self, with: logLevel) } // MARK: - MessagePublisher @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public struct MessagePublisher: Combine.Publisher { public typealias Output = DDLogMessage public typealias Failure = Never private let log: DDLog private let logLevel: DDLogLevel public init(log: DDLog, with logLevel: DDLogLevel) { self.log = log self.logLevel = logLevel } public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, S.Input == Output { let subscription = Subscription(log: self.log, with: logLevel, subscriber: subscriber) subscriber.receive(subscription: subscription) } } // MARK: - Subscription private final class Subscription<S: Subscriber>: NSObject, DDLogger, Combine.Subscription where S.Input == DDLogMessage { private var subscriber: S? private weak var log: DDLog? //Not used but DDLogger requires it. The preferred way to achieve this is to use the `map()` Combine operator of the publisher. //ie: // DDLog.sharedInstance.messagePublisher() // .map { [format log message] } // .sink(receiveValue: { [process log message] }) // var logFormatter: DDLogFormatter? = nil let combineIdentifier = CombineIdentifier() init(log: DDLog, with logLevel: DDLogLevel, subscriber: S) { self.subscriber = subscriber self.log = log super.init() log.add(self, with: logLevel) } func request(_ demand: Subscribers.Demand) { //The log messages are endless until canceled, so we won't do any demand management. //Combine operators can be used to deal with it as needed. } func cancel() { self.log?.remove(self) self.subscriber = nil } func log(message logMessage: DDLogMessage) { _ = self.subscriber?.receive(logMessage) } } } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension Publisher where Output == DDLogMessage { public func formatted(with formatter: DDLogFormatter) -> Publishers.CompactMap<Self, String> { return compactMap { formatter.format(message: $0) } } } #endif
d0081886866f653367ddfe7da5844820
31.991803
135
0.654161
false
false
false
false
hackersatcambridge/hac-website
refs/heads/master
Sources/HaCWebsiteLib/Config.swift
mit
2
import Foundation public struct Config { public static func envVar(forKey key: String) -> String? { return ProcessInfo.processInfo.environment[key] } public static var listeningPort: Int { if let portString = envVar(forKey: "PORT"), let port = Int(portString) { return port } return 8090 } private static func checkEnvVarsExist(for keys: String...) { for key in keys { guard envVar(forKey: key) != nil else { fatalError("Missing environment variable: \(key)") } } } public static func checkEnvVars() { checkEnvVarsExist(for: "DATA_DIR", "DATABASE_URL", "API_PASSWORD" ) } public static var isProduction: Bool { // We use NODE_ENV to check for production as that's what our build tooling uses return envVar(forKey: "NODE_ENV") == "production" } }
3c8ebeab1fd520b8a9610398e6dc23b7
23.823529
84
0.652844
false
false
false
false
davidkobilnyk/Pitch-Perfect
refs/heads/master
Pitch Perfect/RecordSoundsViewController.swift
mit
1
// // RecordSoundsViewController.swift // Pitch Perfect // // Created by David Kobilnyk on 5/9/15. // Copyright (c) 2015 David Kobilnyk. All rights reserved. // // Code concepts and portions adapted from Udacity course "Intro to iOS App Development with Swift" // import UIKit import AVFoundation final class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate { // MARK: - IBOutlets /** Tapped to start the recording, during which the button is disabled. */ @IBOutlet private weak var recordButton: UIButton! /** Gives the user direction or clarification regarding the recording process. */ @IBOutlet private weak var recordingLabel: UILabel! /** Visible when a recording is in process, during which it can be tapped to pause the recording. */ @IBOutlet private weak var pauseButton: UIButton! /** Visible when a recording is paused, during which it can be tapped to resume with recording. */ @IBOutlet private weak var resumeButton: UIButton! /** Visible when a recording is in process, during which it can be tapped to complete the recording and push the next screen for adding effects. */ @IBOutlet private weak var stopButton: UIButton! // MARK: - Private properties /** An object from AVFoundation used for performing all of the recording operations. */ private var audioRecorder: AVAudioRecorder? /** A simple object for passing audio information to the next screen for replay. */ private var recordedAudio: RecordedAudio! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) setUIModeToInitial() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier != "stopRecording") { return } if let playSoundsVC: PlaySoundsViewController = segue.destinationViewController as? PlaySoundsViewController { playSoundsVC.receivedAudio = sender as? RecordedAudio } } // MARK: - UI Events @IBAction func touchUpRecordButton(sender: UIButton) { setUIModeToRecord() startRecording() } @IBAction func touchUpPauseButton(sender: UIButton) { setUIModeToPause() pauseRecording() } @IBAction func touchUpResumeButton(sender: UIButton) { setUIModeToRecord() resumeRecording() } @IBAction func touchUpStopButton(sender: UIButton) { setUIModeToInitial() stopRecording() } // MARK: - AVAudioRecorderDelegate func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) { if (!flag) { setUIModeToFailed() println("Recording was not successful") return } recordedAudio = RecordedAudio(filePathUrl: recorder.url, title: recorder.url.lastPathComponent) performSegueWithIdentifier("stopRecording", sender: recordedAudio) } // MARK: - Audio Control func startRecording() { if let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String { // Determine file name for audio recording let currentDateTime = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "ddMMyyyy-HHmmss" let recordingName = formatter.stringFromDate(currentDateTime)+".wav" // Determine file path let pathArray = [dirPath, recordingName] let filePath = NSURL.fileURLWithPathComponents(pathArray) // Configure the audio session let session = AVAudioSession.sharedInstance() var error: NSError? if !session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: &error) { setUIModeToFailed() println("audio session configuration failed: \(error?.description)") return } // Perform recording audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: &error) if let error = error { setUIModeToFailed() println("error preparing audio recorder: \(error.description)") return } if let audioRecorder = self.audioRecorder { audioRecorder.delegate = self audioRecorder.meteringEnabled = true audioRecorder.prepareToRecord() audioRecorder.record() } else { setUIModeToFailed() } } else { setUIModeToFailed() println("could not save audio because document directory was not found") } } func pauseRecording() { audioRecorder?.pause() } func resumeRecording() { audioRecorder?.record() } func stopRecording() { audioRecorder?.stop() let audioSession = AVAudioSession.sharedInstance() var error: NSError? if !audioSession.setActive(false, error: &error) { setUIModeToFailed() println("audio session deactivation failed: \(error?.description)") } } // MARK: - View Model func setUIModeToInitial() { recordButton.enabled = true recordingLabel.text = "Tap to Record" pauseButton.hidden = true resumeButton.hidden = true stopButton.hidden = true } func setUIModeToRecord() { recordButton.enabled = false recordingLabel.text = "Recording" pauseButton.hidden = false resumeButton.hidden = true stopButton.hidden = false } func setUIModeToPause() { recordButton.enabled = false recordingLabel.text = "Paused" pauseButton.hidden = true resumeButton.hidden = false stopButton.hidden = false } func setUIModeToFailed() { recordButton.enabled = true recordingLabel.text = "Record Failed. Tap to Re-Attempt Record" pauseButton.hidden = true resumeButton.hidden = true stopButton.hidden = true } }
95b46eaf3c002b1f6b861f4b0d702d0a
31.756345
122
0.636448
false
false
false
false
internetarchive/wayback-machine-chrome
refs/heads/master
safari/Wayback Machine/ViewController.swift
agpl-3.0
1
// // ViewController.swift // Wayback Machine // // Created by Carl on 9/4/21. // import Cocoa import SafariServices.SFSafariApplication import SafariServices.SFSafariExtensionManager let appName = "Wayback Machine" let extensionBundleIdentifier = "archive.org.waybackmachine.mac.extension" let APP_VERSION = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0" class ViewController: NSViewController { @IBOutlet weak var statusLabel: NSTextField! @IBOutlet weak var versionLabel: NSTextField! @IBOutlet weak var activateButton: NSButton! override func viewDidLoad() { super.viewDidLoad() versionLabel.stringValue = "\(APP_VERSION)" SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: extensionBundleIdentifier) { (state, error) in guard let state = state, error == nil else { // Insert code to inform the user that something went wrong. return } DispatchQueue.main.async { if (state.isEnabled) { self.statusLabel.stringValue = "Extension is On" self.activateButton.title = "Open Preferences" } else { self.statusLabel.stringValue = "Extension is Off" } } } } @IBAction func openSafariExtensionPreferences(_ sender: AnyObject?) { SFSafariApplication.showPreferencesForExtension(withIdentifier: extensionBundleIdentifier) { error in guard error == nil else { // Insert code to inform the user that something went wrong. return } //DispatchQueue.main.async { // NSApplication.shared.terminate(nil) //} } } }
5ea6b1ee43bf56cb73929b29ec8e13a2
31.571429
121
0.624452
false
false
false
false
superman-coder/pakr
refs/heads/master
pakr/pakr/UserInterface/Login/view/LoginController.swift
apache-2.0
1
// // LoginController.swift // pakr // // Created by Huynh Quang Thao on 4/16/16. // Copyright © 2016 Pakr. All rights reserved. // import Foundation import UIKit import FBSDKLoginKit import Google import Parse class LoginController: UIViewController, LoginView, GIDSignInUIDelegate { @IBOutlet weak var googleLoginButton: GIDSignInButton! @IBOutlet weak var facebookLoginButton: FBSDKLoginButton! var presenter: LoginPresenter! override func viewDidLoad() { super.viewDidLoad() let loginDataManager = LoginDataManagerImpl() let loginTracker = LoginTrackerImpl() let router = LoginRouterImpl() presenter = LoginPresenterImpl(view: self, manager: loginDataManager, router: router, tracker: loginTracker) presenter.initViews() } override func viewDidAppear(animated: Bool) { presenter.presentView() } func getFacebookLoginButton() -> FBSDKLoginButton { return facebookLoginButton } func initViews() { googleLoginButton.colorScheme = GIDSignInButtonColorScheme.Light GIDSignIn.sharedInstance().uiDelegate = self } }
423dcf5d9cc515f5d397d74d96235a13
25.840909
116
0.692373
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureCoin/Sources/FeatureCoinDomain/Watchlist/WatchlistRepositoryAPI.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors public protocol WatchlistRepositoryAPI { func addToWatchlist( _ assetCode: String ) -> AnyPublisher<Void, NetworkError> func removeFromWatchlist( _ assetCode: String ) -> AnyPublisher<Void, NetworkError> func getWatchlist() -> AnyPublisher<Set<String>, NetworkError> } // MARK: - Preview Helper public class PreviewWatchlistRepository: WatchlistRepositoryAPI { private let add: AnyPublisher<Void, NetworkError> private let remove: AnyPublisher<Void, NetworkError> private let get: AnyPublisher<Set<String>, NetworkError> public init( _ add: AnyPublisher<Void, NetworkError> = .empty(), _ remove: AnyPublisher<Void, NetworkError> = .empty(), _ get: AnyPublisher<Set<String>, NetworkError> = .empty() ) { self.add = add self.remove = remove self.get = get } public func addToWatchlist( _ assetCode: String ) -> AnyPublisher<Void, NetworkError> { add } public func removeFromWatchlist( _ assetCode: String ) -> AnyPublisher<Void, NetworkError> { remove } public func getWatchlist() -> AnyPublisher<Set<String>, NetworkError> { get } }
6c1ab389a5da34e58f46cc308cc42aee
24.307692
75
0.653495
false
false
false
false
attaswift/Attabench
refs/heads/master
OptimizingCollections.attabench/Sources/main.swift
mit
2
// Copyright © 2017 Károly Lőrentey. // This file is part of Attabench: https://github.com/attaswift/Attabench // For licensing information, see the file LICENSE.md in the Git repository above. import Benchmarking let benchmark = Benchmark<([Int], [Int])>(title: "SortedSet") benchmark.descriptiveTitle = "SortedSet operations" benchmark.descriptiveAmortizedTitle = "SortedSet operations (amortized)" benchmark.addTask(title: "SortedArray.insert") { input, lookups in return { timer in var set = SortedArray<Int>() timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "SortedArray.contains") { input, lookups in let set = SortedArray<Int>(sortedElements: 0 ..< input.count) // Cheating return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "SortedArray.contains2") { input, lookups in let set = SortedArray<Int>(sortedElements: 0 ..< input.count) // Cheating return { timer in for element in lookups { guard set.contains2(element) else { fatalError() } } } } benchmark.addTask(title: "SortedArray.contains3") { input, lookups in let set = SortedArray<Int>(sortedElements: 0 ..< input.count) // Cheating return { timer in for element in lookups { guard set.contains3(element) else { fatalError() } } } } benchmark.addTask(title: "SortedArray.forEach") { input, lookups in let set = SortedArray<Int>(sortedElements: 0 ..< input.count) // Cheating return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "SortedArray.for-in") { input, lookups in let set = SortedArray<Int>(sortedElements: 0 ..< input.count) // Cheating return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "SortedArray.sharedInsert") { input, lookups in return { timer in var set = SortedArray<Int>() timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } benchmark.addTask(title: "OrderedSet.insert") { input, lookups in return { timer in var set = OrderedSet<Int>() timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "OrderedSet.contains") { input, lookups in var set = OrderedSet<Int>() for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "OrderedSet.contains2") { input, lookups in var set = OrderedSet<Int>() for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains2(element) else { fatalError() } } } } benchmark.addTask(title: "OrderedSet.forEach") { input, lookups in var set = OrderedSet<Int>() for value in input { set.insert(value) } return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "OrderedSet.for-in") { input, lookups in var set = OrderedSet<Int>() for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "OrderedSet.sharedInsert") { input, lookups in return { timer in var set = OrderedSet<Int>() timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } benchmark.addTask(title: "RedBlackTree.insert") { input, lookups in return { timer in var set = RedBlackTree<Int>() timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "RedBlackTree.contains") { input, lookups in var set = RedBlackTree<Int>() for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "RedBlackTree.forEach") { input, lookups in var set = RedBlackTree<Int>() for value in input { set.insert(value) } return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "RedBlackTree.for-in") { input, lookups in var set = RedBlackTree<Int>() for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "RedBlackTree.sharedInsert") { input, lookups in return { timer in var set = RedBlackTree<Int>() timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } benchmark.addTask(title: "RedBlackTree2.insert") { input, lookups in return { timer in var set = RedBlackTree2<Int>() timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "RedBlackTree2.contains") { input, lookups in var set = RedBlackTree2<Int>() for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "RedBlackTree2.forEach") { input, lookups in var set = RedBlackTree2<Int>() for value in input { set.insert(value) } return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "RedBlackTree2.for-in") { input, lookups in var set = RedBlackTree2<Int>() for value in input { set.insert(value) } return { timer in var i = 0 var index = set.startIndex while index != set.endIndex { let element = set[index] guard element == i else { fatalError() } i += 1 set.formIndex(after: &index) } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "RedBlackTree2.for-in2") { input, lookups in var set = RedBlackTree2<Int>() for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "RedBlackTree2.for-in3") { input, lookups in var set = RedBlackTree2b<Int>() for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "RedBlackTree2.sharedInsert") { input, lookups in return { timer in var set = RedBlackTree2<Int>() timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } benchmark.addTask(title: "BTree.insert") { input, lookups in return { timer in var set = BTree<Int>(order: 1024) timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "BTree.contains") { input, lookups in var set = BTree<Int>(order: 1024) for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "BTree.forEach") { input, lookups in var set = BTree<Int>(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "BTree.for-in") { input, lookups in var set = BTree<Int>(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "BTree.sharedInsert") { input, lookups in return { timer in var set = BTree<Int>(order: 1024) timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } benchmark.addTask(title: "BTree2.insert") { input, lookups in return { timer in var set = BTree2<Int>(order: 1024) timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "BTree2.contains") { input, lookups in var set = BTree2<Int>(order: 1024) for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "BTree2.forEach") { input, lookups in var set = BTree2<Int>(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "BTree2.for-in") { input, lookups in var set = BTree2<Int>(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError("\(i) vs \(input.count)") } } } benchmark.addTask(title: "BTree2.sharedInsert") { input, lookups in return { timer in var set = BTree2<Int>(order: 1024) timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } benchmark.addTask(title: "BTree3.insert") { input, lookups in return { timer in var set = BTree3<Int>(order: 1024) timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "BTree3.contains") { input, lookups in var set = BTree3<Int>(order: 1024) for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "BTree3.forEach") { input, lookups in var set = BTree3<Int>(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "BTree3.for-in") { input, lookups in var set = BTree3<Int>(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "BTree3.sharedInsert") { input, lookups in return { timer in var set = BTree3<Int>(order: 1024) timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } #if false benchmark.addTask(title: "BTree4.insert") { input, lookups in return { timer in var set = BTree4<Int>(order: 1024) timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "BTree4.contains") { input, lookups in var set = BTree4<Int>(order: 1024) for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "BTree4.forEach") { input, lookups in var set = BTree4<Int>(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "BTree4.for-in") { input, lookups in var set = BTree4<Int>(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "BTree4.sharedInsert") { input, lookups in return { timer in var set = BTree4<Int>(order: 1024) timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } benchmark.addTask(title: "IntBTree3.insert") { input, lookups in return { timer in var set = IntBTree3(order: 1024) timer.measure { for value in input { set.insert(value) } } } } benchmark.addTask(title: "IntBTree3.contains") { input, lookups in var set = IntBTree3(order: 1024) for value in input { set.insert(value) } return { timer in for element in lookups { guard set.contains(element) else { fatalError() } } } } benchmark.addTask(title: "IntBTree3.forEach") { input, lookups in var set = IntBTree3(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 set.forEach { element in guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "IntBTree3.for-in") { input, lookups in var set = IntBTree3(order: 1024) for value in input { set.insert(value) } return { timer in var i = 0 for element in set { guard element == i else { fatalError() } i += 1 } guard i == input.count else { fatalError() } } } benchmark.addTask(title: "IntBTree3.sharedInsert") { input, lookups in return { timer in var set = IntBTree3(order: 1024) timer.measure { var clone = set for value in input { set.insert(value) clone = set } noop(clone) } } } #endif benchmark.addTask(title: "Array.sort") { input, lookups in return { timer in noop(input.sorted()) } } benchmark.start()
34724f0dbe41dc7508ad3957b1a6b81d
24.014749
82
0.534139
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/stdlib/Accelerate_Quadrature.swift
apache-2.0
8
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: rdar50301438 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Accelerate var AccelerateQuadratureTests = TestSuite("Accelerate_Quadrature") //===----------------------------------------------------------------------===// // // Quadrature Tests // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { func vectorExp(x: UnsafeBufferPointer<Double>, y: UnsafeMutableBufferPointer<Double>) { let radius: Double = 12.5 for i in 0 ..< x.count { y[i] = sqrt(radius * radius - pow(x[i] - radius, 2)) } } AccelerateQuadratureTests.test("Quadrature/QNG") { var diameter: Double = 25 // New API: Scalar let quadrature = Quadrature(integrator: .nonAdaptive, absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let result = quadrature.integrate(over: 0.0 ... diameter) { x in let radius = diameter * 0.5 return sqrt(radius * radius - pow(x - radius, 2)) } // New API: Vectorized let vQuadrature = Quadrature(integrator: .nonAdaptive, absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, integrand: vectorExp) // Legacy API var integrateFunction: quadrature_integrate_function = { return quadrature_integrate_function( fun: { (arg: UnsafeMutableRawPointer?, n: Int, x: UnsafePointer<Double>, y: UnsafeMutablePointer<Double> ) in guard let diameter = arg?.load(as: Double.self) else { return } let r = diameter * 0.5 (0 ..< n).forEach { i in y[i] = sqrt(r * r - pow(x[i] - r, 2)) } }, fun_arg: &diameter) }() var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QNG, abs_tolerance: 1.0e-8, rel_tolerance: 1.0e-2, qag_points_per_interval: 0, max_intervals: 0) var status = QUADRATURE_SUCCESS var legacyEstimatedAbsoluteError: Double = 0 let legacyResult = quadrature_integrate(&integrateFunction, 0.0, diameter, &options, &status, &legacyEstimatedAbsoluteError, 0, nil) switch result { case .success(let integralResult, let estimatedAbsoluteError): expectEqual(integralResult, legacyResult) expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) switch vRresult { case .success(let vIntegralResult, let vEstimatedAbsoluteError): expectEqual(integralResult, vIntegralResult) expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) case .failure(_): expectationFailure("Vectorized non-adaptive integration failed.", trace: "", stackTrace: SourceLocStack()) } case .failure( _): expectationFailure("Non-adaptive integration failed.", trace: "", stackTrace: SourceLocStack()) } } AccelerateQuadratureTests.test("Quadrature/QAGS") { var diameter: Double = 25 // New API let quadrature = Quadrature(integrator: .adaptiveWithSingularities(maxIntervals: 11), absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let result = quadrature.integrate(over: 0.0 ... diameter) { x in let radius = diameter * 0.5 return sqrt(radius * radius - pow(x - radius, 2)) } // New API: Vectorized let vQuadrature = Quadrature(integrator: .adaptiveWithSingularities(maxIntervals: 11), absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, integrand: vectorExp) // Legacy API var integrateFunction: quadrature_integrate_function = { return quadrature_integrate_function( fun: { (arg: UnsafeMutableRawPointer?, n: Int, x: UnsafePointer<Double>, y: UnsafeMutablePointer<Double> ) in guard let diameter = arg?.load(as: Double.self) else { return } let r = diameter * 0.5 (0 ..< n).forEach { i in y[i] = sqrt(r * r - pow(x[i] - r, 2)) } }, fun_arg: &diameter) }() var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QAGS, abs_tolerance: 1.0e-8, rel_tolerance: 1.0e-2, qag_points_per_interval: 0, max_intervals: 11) var status = QUADRATURE_SUCCESS var legacyEstimatedAbsoluteError = Double(0) let legacyResult = quadrature_integrate(&integrateFunction, 0, diameter, &options, &status, &legacyEstimatedAbsoluteError, 0, nil) switch result { case .success(let integralResult, let estimatedAbsoluteError): expectEqual(integralResult, legacyResult) expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) switch vRresult { case .success(let vIntegralResult, let vEstimatedAbsoluteError): expectEqual(integralResult, vIntegralResult) expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) case .failure(_): expectationFailure("Vectorized adaptive with singularities integration failed.", trace: "", stackTrace: SourceLocStack()) } case .failure( _): expectationFailure("Adaptive with singularities integration failed.", trace: "", stackTrace: SourceLocStack()) } } AccelerateQuadratureTests.test("Quadrature/QAG") { var diameter: Double = 25 // New API let quadrature = Quadrature(integrator: .adaptive(pointsPerInterval: .sixtyOne, maxIntervals: 7), absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let result = quadrature.integrate(over: 0.0 ... diameter) { x in let radius: Double = diameter * 0.5 return sqrt(radius * radius - pow(x - radius, 2)) } // New API: Vectorized let vQuadrature = Quadrature(integrator: .adaptive(pointsPerInterval: .sixtyOne, maxIntervals: 7), absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, integrand: vectorExp) // Legacy API var integrateFunction: quadrature_integrate_function = { return quadrature_integrate_function( fun: { (arg: UnsafeMutableRawPointer?, n: Int, x: UnsafePointer<Double>, y: UnsafeMutablePointer<Double> ) in guard let diameter = arg?.load(as: Double.self) else { return } let r = diameter * 0.5 (0 ..< n).forEach { i in y[i] = sqrt(r * r - pow(x[i] - r, 2)) } }, fun_arg: &diameter) }() var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QAG, abs_tolerance: 1.0e-8, rel_tolerance: 1.0e-2, qag_points_per_interval: 61, max_intervals: 7) var status = QUADRATURE_SUCCESS var legacyEstimatedAbsoluteError = Double(0) let legacyResult = quadrature_integrate(&integrateFunction, 0, diameter, &options, &status, &legacyEstimatedAbsoluteError, 0, nil) switch result { case .success(let integralResult, let estimatedAbsoluteError): expectEqual(integralResult, legacyResult) expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) switch vRresult { case .success(let vIntegralResult, let vEstimatedAbsoluteError): expectEqual(integralResult, vIntegralResult) expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) case .failure(_): expectationFailure("Vectorized adaptive integration failed.", trace: "", stackTrace: SourceLocStack()) } case .failure( _): expectationFailure("Adaptive integration failed.", trace: "", stackTrace: SourceLocStack()) } } AccelerateQuadratureTests.test("Quadrature/ToleranceProperties") { var quadrature = Quadrature(integrator: .qng, absoluteTolerance: 1, relativeTolerance: 2) expectEqual(quadrature.absoluteTolerance, 1) expectEqual(quadrature.relativeTolerance, 2) quadrature.absoluteTolerance = 101 quadrature.relativeTolerance = 102 expectEqual(quadrature.absoluteTolerance, 101) expectEqual(quadrature.relativeTolerance, 102) } AccelerateQuadratureTests.test("Quadrature/QAGPointsPerInterval") { expectEqual(Quadrature.QAGPointsPerInterval.fifteen.points, 15) expectEqual(Quadrature.QAGPointsPerInterval.twentyOne.points, 21) expectEqual(Quadrature.QAGPointsPerInterval.thirtyOne.points, 31) expectEqual(Quadrature.QAGPointsPerInterval.fortyOne.points, 41) expectEqual(Quadrature.QAGPointsPerInterval.fiftyOne.points, 51) expectEqual(Quadrature.QAGPointsPerInterval.sixtyOne.points, 61) } AccelerateQuadratureTests.test("Quadrature/ErrorDescription") { let a = Quadrature.Error(quadratureStatus: QUADRATURE_ERROR) expectEqual(a.errorDescription, "Generic error.") let b = Quadrature.Error(quadratureStatus: QUADRATURE_INVALID_ARG_ERROR) expectEqual(b.errorDescription, "Invalid Argument.") let c = Quadrature.Error(quadratureStatus: QUADRATURE_INTERNAL_ERROR) expectEqual(c.errorDescription, "This is a bug in the Quadrature code, please file a bug report.") let d = Quadrature.Error(quadratureStatus: QUADRATURE_INTEGRATE_MAX_EVAL_ERROR) expectEqual(d.errorDescription, "The requested accuracy limit could not be reached with the allowed number of evals/subdivisions.") let e = Quadrature.Error(quadratureStatus: QUADRATURE_INTEGRATE_BAD_BEHAVIOUR_ERROR) expectEqual(e.errorDescription, "Extremely bad integrand behaviour, or excessive roundoff error occurs at some points of the integration interval.") } } runAllTests()
599c8541b134cf89eca71325cc7e51c3
43.390323
156
0.477291
false
true
false
false
MTTHWBSH/Short-Daily-Devotions
refs/heads/master
Short Daily Devotions/View Models/MoreInfoViewModel.swift
mit
1
// // MoreInfoViewModel.swift // Short Daily Devotions // // Created by Matt Bush on 12/20/16. // Copyright © 2016 Matt Bush. All rights reserved. // import UIKit enum InfoOptions: Int { case about, support, beliefs, contact, social, count } class MoreInfoViewModel: ViewModel { private let kAboutPageID = "49" private let kBeliefsPageID = "1981" let kFacebookURL = URL(string: "https://www.facebook.com/shortdailydevotions") let kTwitterURL = URL(string: "https://www.twitter.com/shortdevotions") let kInstagramURL = URL(string: "https://www.instagram.com/shortdailydevotions") func numberOfOptions() -> Int { return InfoOptions.count.rawValue } func cell(forIndexPath indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case InfoOptions.about.rawValue: return InfoCell(title: "About") case InfoOptions.support.rawValue: return InfoCell(title: "Support") case InfoOptions.beliefs.rawValue: return InfoCell(title: "Beliefs") case InfoOptions.contact.rawValue: return InfoCell(title: "Contact") case InfoOptions.social.rawValue: return SocialCell(viewModel: self) default: return UITableViewCell() } } func heightForRow(atIndexPath indexPath: IndexPath) -> CGFloat { switch indexPath.row { case InfoOptions.about.rawValue, InfoOptions.support.rawValue, InfoOptions.beliefs.rawValue, InfoOptions.contact.rawValue: return 80 case InfoOptions.social.rawValue: return 120 default: return 0 } } func viewController(forIndexPath indexPath: IndexPath) -> UIViewController? { switch indexPath.row { case InfoOptions.about.rawValue: return PageViewController(viewModel: PageViewModel(pageID: kAboutPageID)) case InfoOptions.support.rawValue: return SupportViewController(viewModel: SupportViewModel()) case InfoOptions.beliefs.rawValue: return PageViewController(viewModel: PageViewModel(pageID: kBeliefsPageID)) case InfoOptions.contact.rawValue: return ContactViewController(viewModel: ContactViewModel()) default: return nil } } }
d056f00a342180c75a8509a66d306efe
38.474576
118
0.66681
false
false
false
false
TG908/iOS
refs/heads/master
TUM Campus App/Map.swift
gpl-3.0
1
// // Map.swift // TUM Campus App // // Created by Mathias Quintero on 12/11/15. // Copyright © 2015 LS1 TUM. All rights reserved. // import Foundation import SwiftyJSON final class Map: ImageDownloader, DataElement { let roomID: String let mapID: String let description: String let scale: Int init(roomID: String, mapID: String, description: String, scale: Int) { self.roomID = roomID self.mapID = mapID self.description = description self.scale = scale let url = RoomFinderApi.BaseUrl.rawValue + RoomFinderApi.MapImage.rawValue + roomID + "/" + mapID super.init() if let sanitizedURL = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed) { getImage(sanitizedURL) } } convenience init?(roomID: String, from json: JSON) { guard let description = json["description"].string, let id = json["map_id"].int, let scale = json["scale"].int else { return nil } self.init(roomID: roomID, mapID: id.description, description: description, scale: scale) } func getCellIdentifier() -> String { return "map" } var text: String { return description } }
b4f952f8104f97b80407099fc637073a
26.744681
113
0.614264
false
false
false
false
teambition/GrowingTextView
refs/heads/master
GrowingTextView/GrowingInternalTextView.swift
mit
1
// // GrowingInternalTextView.swift // GrowingTextView // // Created by Xin Hong on 16/2/16. // Copyright © 2016年 Teambition. All rights reserved. // import UIKit internal class GrowingInternalTextView: UITextView, NSCopying { var placeholder: NSAttributedString? { didSet { setNeedsDisplay() } } var shouldDisplayPlaceholder = true { didSet { if shouldDisplayPlaceholder != oldValue { setNeedsDisplay() } } } var isCaretHidden = false fileprivate var isScrollEnabledTemp = false override var text: String! { willSet { // If one of GrowingTextView's superviews is a scrollView, and self.scrollEnabled is false, setting the text programatically will cause UIKit to search upwards until it finds a scrollView with scrollEnabled true, then scroll it erratically. Setting scrollEnabled temporarily to true prevents this. isScrollEnabledTemp = isScrollEnabled isScrollEnabled = true } didSet { isScrollEnabled = isScrollEnabledTemp } } override func draw(_ rect: CGRect) { super.draw(rect) guard let placeholder = placeholder, shouldDisplayPlaceholder else { return } let placeholderSize = sizeForAttributedString(placeholder) let xPosition: CGFloat = textContainer.lineFragmentPadding + textContainerInset.left let yPosition: CGFloat = (textContainerInset.top - textContainerInset.bottom) / 2 let rect = CGRect(origin: CGPoint(x: xPosition, y: yPosition), size: placeholderSize) placeholder.draw(in: rect) } override func caretRect(for position: UITextPosition) -> CGRect { if isCaretHidden { return .zero } return super.caretRect(for: position) } func copy(with zone: NSZone?) -> Any { let textView = GrowingInternalTextView(frame: frame) textView.isScrollEnabled = isScrollEnabled textView.shouldDisplayPlaceholder = shouldDisplayPlaceholder textView.isCaretHidden = isCaretHidden textView.placeholder = placeholder textView.text = text textView.font = font textView.textColor = textColor textView.textAlignment = textAlignment textView.isEditable = isEditable textView.selectedRange = selectedRange textView.dataDetectorTypes = dataDetectorTypes textView.returnKeyType = returnKeyType textView.keyboardType = keyboardType textView.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically textView.textContainerInset = textContainerInset textView.textContainer.lineFragmentPadding = textContainer.lineFragmentPadding textView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator textView.contentInset = contentInset textView.contentMode = contentMode return textView } fileprivate func sizeForAttributedString(_ attributedString: NSAttributedString) -> CGSize { let size = attributedString.size() return CGRect(origin: .zero, size: size).integral.size } }
7bbb81547b17f89c6c9415cdc81d427c
35.454545
309
0.682045
false
false
false
false
atrick/swift
refs/heads/main
test/decl/protocol/existential_member_accesses_self_assoctype_exec.swift
apache-2.0
3
// RUN: %target-run-simple-swift // REQUIRES: executable_test // Temporarily disabled due to a runtime crash. // REQUIRES: rdar83066987 import StdlibUnittest let Tests = TestSuite(#file) protocol P { associatedtype Assoc = Self func getString() -> String func covariantSelfSimple() -> Self func covariantSelfArray() -> Array<Self> func covariantSelfDictionary() -> [String : Self] func covariantSelfClosure(_: (Self) -> Void) var covariantSelfPropSimple: Self { get } var covariantSelfPropArray: Array<Self> { get } var covariantSelfPropDictionary: [String : Self] { get } var covariantSelfPropClosure: ((Self) -> Void) -> Void { get } subscript(covariantSelfSubscriptSimple _: Void) -> Self { get } subscript(covariantSelfSubscriptArray _: Void) -> Array<Self> { get } subscript(covariantSelfSubscriptDictionary _: Void) -> [String : Self] { get } subscript(covariantSelfSubscriptClosure _: (Self) -> Void) -> Void { get } } extension P { func covariantSelfSimple() -> Self { self } func covariantSelfArray() -> Array<Self> { [self] } func covariantSelfDictionary() -> [String : Self] { [#file : self] } func covariantSelfClosure(_ arg: (Self) -> Void) { arg(self) } var covariantSelfPropSimple: Self { self } var covariantSelfPropArray: Array<Self> { [self] } var covariantSelfPropDictionary: [String : Self] { [#file : self] } var covariantSelfPropClosure: ((Self) -> Void) -> Void { { $0(self) } } subscript(covariantSelfSubscriptSimple _: Void) -> Self { self } subscript(covariantSelfSubscriptArray _: Void) -> Array<Self> { [self] } subscript(covariantSelfSubscriptDictionary _: Void) -> [String : Self] { [#file : self] } subscript(covariantSelfSubscriptClosure arg: (Self) -> Void) -> Void { arg(self) } } Tests.test("Basic") { let collection: Collection = [0, 0, 0] expectEqual(3, collection.count) } Tests.test("Covariant 'Self' erasure") { struct S: P { static let str = "Success" func getString() -> String { Self.str } } let p: P = S() // Partial Application do { let covariantSelfSimplePartialApp = p.covariantSelfSimple let covariantSelfArrayPartialApp = p.covariantSelfArray let covariantSelfDictionaryPartialApp = p.covariantSelfDictionary let covariantSelfClosurePartialApp = p.covariantSelfClosure expectEqual(S.str, covariantSelfSimplePartialApp().getString()) expectEqual(S.str, covariantSelfArrayPartialApp().first.unsafelyUnwrapped.getString()) expectEqual(S.str, covariantSelfDictionaryPartialApp()[#file].unsafelyUnwrapped.getString()) covariantSelfClosurePartialApp { expectEqual(S.str, $0.getString()) } } // Instance method reference on metatype do { let covariantSelfSimpleRef = P.covariantSelfSimple let covariantSelfArrayRef = P.covariantSelfArray let covariantSelfDictionaryRef = P.covariantSelfDictionary let covariantSelfClosureRef = P.covariantSelfClosure expectEqual(S.str, covariantSelfSimpleRef(p)().getString()) expectEqual(S.str, covariantSelfArrayRef(p)().first.unsafelyUnwrapped.getString()) expectEqual(S.str, covariantSelfDictionaryRef(p)()[#file].unsafelyUnwrapped.getString()) covariantSelfClosureRef(p)({ expectEqual(S.str, $0.getString()) }) } // Regular calls expectEqual(S.str, p.covariantSelfSimple().getString()) expectEqual(S.str, p.covariantSelfArray().first.unsafelyUnwrapped.getString()) expectEqual(S.str, p.covariantSelfDictionary()[#file].unsafelyUnwrapped.getString()) p.covariantSelfClosure { expectEqual(S.str, $0.getString()) } expectEqual(S.str, p.covariantSelfPropSimple.getString()) expectEqual(S.str, p.covariantSelfPropArray.first.unsafelyUnwrapped.getString()) expectEqual(S.str, p.covariantSelfPropDictionary[#file].unsafelyUnwrapped.getString()) p.covariantSelfPropClosure { expectEqual(S.str, $0.getString()) } expectEqual(S.str, p[covariantSelfSubscriptSimple: ()].getString()) expectEqual(S.str, p[covariantSelfSubscriptArray: ()].first.unsafelyUnwrapped.getString()) expectEqual(S.str, p[covariantSelfSubscriptDictionary: ()][#file].unsafelyUnwrapped.getString()) p[covariantSelfSubscriptClosure: { expectEqual(S.str, $0.getString()) }] expectEqual(S.str, (S() as P).getString()) expectEqual(true, p is P) expectEqual(true, S() is P) } protocol MyIntCollection: BidirectionalCollection where Element == Int, SubSequence == ArraySlice<Element>, Index == Int {} extension Array: MyIntCollection where Element == Int {} Tests.test("Known associated types") { let erasedIntArr: MyIntCollection = [5, 8, 1, 9, 3, 8] expectEqual(6, erasedIntArr.count) expectEqual(5, erasedIntArr[Int.zero]) expectEqual(8, erasedIntArr.last.unsafelyUnwrapped) expectEqual([5, 8, 1, 9, 3], erasedIntArr.dropLast()) expectEqual([8, 3, 9, 1, 8, 5], erasedIntArr.reversed()) expectEqual(9, erasedIntArr.max().unsafelyUnwrapped) expectEqual([1, 3, 5, 8, 8, 9], erasedIntArr.sorted()) expectEqual(false, erasedIntArr.contains(Int.zero)) expectEqual([5, 8], erasedIntArr[ erasedIntArr.startIndex...erasedIntArr.firstIndex( of: erasedIntArr.last.unsafelyUnwrapped ).unsafelyUnwrapped ] ) } runAllTests()
e0b77bda3c633e1ca69ef5e385ec64d5
37.75
98
0.718975
false
true
false
false
rickzonhagos/CirrenaFramework
refs/heads/master
Pod/Classes/MyPlayground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play //: Playground - noun: a place where people can play import UIKit protocol GenericProtocol { typealias AbstractType func magic() -> AbstractType } struct GenericProtocolThunk<T> : GenericProtocol { // closure which will be used to implement `magic()` as declared in the protocol private let _magic : () -> T // `T` is effectively a handle for `AbstractType` in the protocol init<P : GenericProtocol where P.AbstractType == T>(_ dep : P) { // requires Swift 2, otherwise create explicit closure _magic = dep.magic } func magic() -> T { // any protocol methods are implemented by forwarding return _magic() } } struct StringMagic : GenericProtocol { typealias AbstractType = String func magic() -> String { return "Magic!" } } let magic : GenericProtocolThunk<String> = GenericProtocolThunk(StringMagic()) magic.magic() protocol URLProtocol { typealias AbstractType func getURLPath()->AbstractType } struct URLModule<T> : URLProtocol { private let _url : () -> T init<P : URLProtocol where P.AbstractType == T>(_ dep : P){ _url = dep.getURLPath } func getURLPath() -> T { return _url() } } enum GroupURL : URLProtocol{ typealias AbstractType = String case GroupList case GroupJoin func getURLPath() -> String { switch self{ case .GroupList: return "/list" case .GroupJoin: return "/join" } } } URLModule(GroupURL.GroupJoin) class Testing{ func tae<T : URLProtocol>(type : T){ let magic : URLModule<String> = URLModule(type) } } let test = Testing() test.tae(GroupURL.GroupJoin) protocol AnimalProtocol { typealias EdibleFood typealias SupplementKind func eat(f:EdibleFood) func supplement(s:SupplementKind) } class Cow : AnimalProtocol { func eat(f: String) { print("the Animal eats "+f) } func supplement(s: String) { print("the Animal supplement "+s) } } let myCow = Cow() myCow.eat("tae") /* struct GenericURL<T> : URLProtocol { private let _base : () -> T private let _sub : () -> T init<U : URLProtocol where U.AbstractType == T>(_ dep : U) { _base } func getBaseModule() -> T { return "sdsd" } func getSubModule() -> T { return "sdsd" } } struct Test : URLProtocol { typealias AbstractType = String func getBaseModule() -> String { return "sdsd" } func getSubModule() -> String { return "sdsd" } } */
e5a3b8a8afdd19161802912df074125b
17.862319
84
0.622743
false
false
false
false
DonMag/ScratchPad
refs/heads/master
Swift3/CustomBarButton/CustomBarButton/ClassAC.swift
mit
1
// // ClassAC.swift // CustomBarButton // // Created by Don Mag on 3/22/17. // Copyright © 2017 DonMag. All rights reserved. // import UIKit class ClassAC: UIViewController, ClassCDelegate { override func viewDidLoad() { super.viewDidLoad() setNavbarButtons() } private func setNavbarButtons() { let myBarButton = classC() myBarButton.setup("Press Me AC") myBarButton.delegate = self self.navigationItem.rightBarButtonItem = myBarButton } func PressedButtonForMethodAC(theSender: classC) { NSLog("Method AC in Class AC fired!") } } protocol ClassCDelegate { func PressedButtonForMethodAC(theSender: classC) } class classC: UIBarButtonItem { var delegate: ClassCDelegate? func setup(_ title: String) { let shadow = NSShadow() shadow.shadowColor = UIColor.clear let attributesNormal = [ NSForegroundColorAttributeName : UIColor.white, NSShadowAttributeName : shadow, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 12.0) ] let button = UIButton(type: .custom) let buttonTitleAttributesNormal = NSAttributedString(string: title, attributes: attributesNormal) button.setAttributedTitle(buttonTitleAttributesNormal, for: UIControlState.normal) let buttonTextSize = button.intrinsicContentSize button.frame = CGRect(x: 0, y: 0, width: buttonTextSize.width, height: buttonTextSize.height) // my navbar is white... button.backgroundColor = UIColor.blue // target is self, selector action is inside self... *that* is where we'll call back to the delegate button.addTarget(self, action: #selector(classC.classCTap), for: .touchUpInside) customView = button } func classCTap() { NSLog("tap inside ClassC ... call back to delegate method") delegate?.PressedButtonForMethodAC(theSender: self) } }
b1aadd9592dd5bde90e1386e60362c17
22.584416
102
0.730176
false
false
false
false
creisterer-db/Dwifft
refs/heads/master
DwifftExample/DwifftExample/StuffTableViewController.swift
mit
3
// // StuffTableViewController.swift // DwifftExample // // Created by Jack Flintermann on 8/23/15. // Copyright (c) 2015 jflinter. All rights reserved. // import UIKit import Dwifft class StuffTableViewController: UITableViewController { static let possibleStuff = [ "Cats", "Onions", "A used lobster", "Splinters", "Mud", "Pineapples", "Fish legs", "Duck panties", "Adam's apple", "Igloo cream", "Self-flying car" ] // I shamelessly stole this list of things from my friend Pasquale's blog post because I thought it was funny. You can see it at https://medium.com/elepath-exports/spatial-interfaces-886bccc5d1e9 static func randomArrayOfStuff() -> [String] { var possibleStuff = self.possibleStuff for i in 0..<possibleStuff.count - 1 { let j = Int(arc4random_uniform(UInt32(possibleStuff.count - i))) + i swap(&possibleStuff[i], &possibleStuff[j]) } let subsetCount: Int = Int(arc4random_uniform(3)) + 5 return Array(possibleStuff[0...subsetCount]) } required init!(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Shuffle", style: .Plain, target: self, action: "shuffle") } @objc func shuffle() { self.stuff = StuffTableViewController.randomArrayOfStuff() } // MARK: - Dwifft stuff // This is the stuff that's relevant to actually using Dwifft. The rest is just boilerplate to get the app working. var diffCalculator: TableViewDiffCalculator<String>? var stuff: [String] = StuffTableViewController.randomArrayOfStuff() { // So, whenever your datasource's array of things changes, just let the diffCalculator know and it'll do the rest. didSet { self.diffCalculator?.rows = stuff } } override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") self.diffCalculator = TableViewDiffCalculator<String>(tableView: self.tableView, initialRows: self.stuff) // You can change insertion/deletion animations like this! Fade works well. So does Top/Bottom. Left/Right/Middle are a little weird, but hey, do your thing. self.diffCalculator?.insertionAnimation = .Fade self.diffCalculator?.deletionAnimation = .Fade } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.stuff.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = self.stuff[indexPath.row] return cell } }
baa1f2594b5bfff128c2ef0773274cd7
36.604938
199
0.666776
false
false
false
false
groue/RxGRDB
refs/heads/master
Sources/RxGRDB/DatabaseRegionObservation+Rx.swift
mit
1
import GRDB import RxSwift extension DatabaseRegionObservation { /// Reactive extensions. public var rx: GRDBReactive<Self> { GRDBReactive(self) } } extension GRDBReactive where Base == DatabaseRegionObservation { /// Returns an Observable that emits the same elements as /// a DatabaseRegionObservation. /// /// All elements are emitted in a protected database dispatch queue, /// serialized with all database updates. If you set *startImmediately* to /// true (the default value), the first element is emitted synchronously /// upon subscription. See [GRDB Concurrency Guide](https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency) /// for more information. /// /// let dbQueue = DatabaseQueue() /// try dbQueue.write { db in /// try db.create(table: "player") { t in /// t.column("id", .integer).primaryKey() /// t.column("name", .text) /// } /// } /// /// struct Player: Encodable, PersistableRecord { /// var id: Int64 /// var name: String /// } /// /// let request = Player.all() /// let observation = DatabaseRegionObservation(tracking: request) /// observation.rx /// .changes(in: dbQueue) /// .subscribe(onNext: { db in /// let count = try! Player.fetchCount(db) /// print("Number of players: \(count)") /// }) /// // Prints "Number of players: 0" /// /// try dbQueue.write { db in /// try Player(id: 1, name: "Arthur").insert(db) /// try Player(id: 2, name: "Barbara").insert(db) /// } /// // Prints "Number of players: 2" /// /// try dbQueue.inDatabase { db in /// try Player(id: 3, name: "Craig").insert(db) /// // Prints "Number of players: 3" /// try Player(id: 4, name: "David").insert(db) /// // Prints "Number of players: 4" /// } /// /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool). public func changes(in writer: DatabaseWriter) -> Observable<Database> { Observable.create { observer -> Disposable in do { let transactionObserver = try self.base.start(in: writer, onChange: observer.onNext) return Disposables.create { writer.remove(transactionObserver: transactionObserver) } } catch { observer.onError(error) return Disposables.create() } } } }
b0a5846e6efb6f326fe3e716f6d8c70e
37.666667
126
0.547601
false
false
false
false
gribozavr/swift
refs/heads/master
test/Sema/type_join.swift
apache-2.0
3
// RUN: %target-typecheck-verify-swift -parse-stdlib import Swift class C {} class D : C {} protocol L {} protocol M : L {} protocol N : L {} protocol P : M {} protocol Q : M {} protocol R : L {} protocol Y {} protocol FakeEquatable {} protocol FakeHashable : FakeEquatable {} protocol FakeExpressibleByIntegerLiteral {} protocol FakeNumeric : FakeEquatable, FakeExpressibleByIntegerLiteral {} protocol FakeSignedNumeric : FakeNumeric {} protocol FakeComparable : FakeEquatable {} protocol FakeStrideable : FakeComparable {} protocol FakeCustomStringConvertible {} protocol FakeBinaryInteger : FakeHashable, FakeNumeric, FakeCustomStringConvertible, FakeStrideable {} protocol FakeLosslessStringConvertible {} protocol FakeFixedWidthInteger : FakeBinaryInteger, FakeLosslessStringConvertible {} protocol FakeUnsignedInteger : FakeBinaryInteger {} protocol FakeSignedInteger : FakeBinaryInteger, FakeSignedNumeric {} protocol FakeFloatingPoint : FakeSignedNumeric, FakeStrideable, FakeHashable {} protocol FakeExpressibleByFloatLiteral {} protocol FakeBinaryFloatingPoint : FakeFloatingPoint, FakeExpressibleByFloatLiteral {} func expectEqualType<T>(_: T.Type, _: T.Type) {} func commonSupertype<T>(_: T, _: T) -> T {} // expected-note 2 {{generic parameters are always considered '@escaping'}} expectEqualType(Builtin.type_join(Int.self, Int.self), Int.self) expectEqualType(Builtin.type_join_meta(D.self, C.self), C.self) expectEqualType(Builtin.type_join(Int?.self, Int?.self), Int?.self) expectEqualType(Builtin.type_join(Int.self, Int?.self), Int?.self) expectEqualType(Builtin.type_join(Int?.self, Int.self), Int?.self) expectEqualType(Builtin.type_join(Int.self, Int??.self), Int??.self) expectEqualType(Builtin.type_join(Int??.self, Int.self), Int??.self) expectEqualType(Builtin.type_join(Int?.self, Int??.self), Int??.self) expectEqualType(Builtin.type_join(Int??.self, Int?.self), Int??.self) expectEqualType(Builtin.type_join(D?.self, D?.self), D?.self) expectEqualType(Builtin.type_join(C?.self, D?.self), C?.self) expectEqualType(Builtin.type_join(D?.self, C?.self), C?.self) expectEqualType(Builtin.type_join(D.self, D?.self), D?.self) expectEqualType(Builtin.type_join(D?.self, D.self), D?.self) expectEqualType(Builtin.type_join(C.self, D?.self), C?.self) expectEqualType(Builtin.type_join(D?.self, C.self), C?.self) expectEqualType(Builtin.type_join(D.self, C?.self), C?.self) expectEqualType(Builtin.type_join(C?.self, D.self), C?.self) expectEqualType(Builtin.type_join(Any?.self, D.self), Any?.self) expectEqualType(Builtin.type_join(D.self, Any?.self), Any?.self) expectEqualType(Builtin.type_join(Any.self, D?.self), Any?.self) expectEqualType(Builtin.type_join(D?.self, Any.self), Any?.self) expectEqualType(Builtin.type_join(Any?.self, Any.self), Any?.self) expectEqualType(Builtin.type_join(Any.self, Any?.self), Any?.self) expectEqualType(Builtin.type_join(Builtin.Int1.self, Builtin.Int1.self), Builtin.Int1.self) expectEqualType(Builtin.type_join(Builtin.Int32.self, Builtin.Int1.self), Any.self) expectEqualType(Builtin.type_join(Builtin.Int1.self, Builtin.Int32.self), Any.self) expectEqualType(Builtin.type_join(L.self, L.self), L.self) expectEqualType(Builtin.type_join(L.self, M.self), L.self) expectEqualType(Builtin.type_join(L.self, P.self), L.self) expectEqualType(Builtin.type_join(L.self, Y.self), Any.self) expectEqualType(Builtin.type_join(N.self, P.self), L.self) expectEqualType(Builtin.type_join(Q.self, P.self), M.self) expectEqualType(Builtin.type_join((N & P).self, (Q & R).self), M.self) expectEqualType(Builtin.type_join((Q & P).self, (Y & R).self), L.self) expectEqualType(Builtin.type_join(FakeEquatable.self, FakeEquatable.self), FakeEquatable.self) expectEqualType(Builtin.type_join(FakeHashable.self, FakeEquatable.self), FakeEquatable.self) expectEqualType(Builtin.type_join(FakeEquatable.self, FakeHashable.self), FakeEquatable.self) expectEqualType(Builtin.type_join(FakeNumeric.self, FakeHashable.self), FakeEquatable.self) expectEqualType(Builtin.type_join((FakeHashable & FakeStrideable).self, (FakeHashable & FakeNumeric).self), FakeHashable.self) expectEqualType(Builtin.type_join((FakeNumeric & FakeStrideable).self, (FakeHashable & FakeNumeric).self), FakeNumeric.self) expectEqualType(Builtin.type_join(FakeBinaryInteger.self, FakeFloatingPoint.self), (FakeHashable & FakeNumeric & FakeStrideable).self) expectEqualType(Builtin.type_join(FakeFloatingPoint.self, FakeBinaryInteger.self), (FakeHashable & FakeNumeric & FakeStrideable).self) func joinFunctions( _ escaping: @escaping () -> (), _ nonescaping: () -> () ) { _ = commonSupertype(escaping, escaping) _ = commonSupertype(nonescaping, escaping) // expected-error@-1 {{converting non-escaping parameter 'nonescaping' to generic parameter 'T' may allow it to escape}} _ = commonSupertype(escaping, nonescaping) // expected-error@-1 {{converting non-escaping parameter 'nonescaping' to generic parameter 'T' may allow it to escape}} let x: Int = 1 // FIXME: We emit these diagnostics here because we refuse to allow // Any to be inferred for the generic type. That's pretty // arbitrary. _ = commonSupertype(escaping, x) // expected-error@-1 {{cannot convert value of type 'Int' to expected argument type '() -> ()'}} _ = commonSupertype(x, escaping) // expected-error@-1 {{cannot convert value of type '() -> ()' to expected argument type 'Int'}} let a: Any = 1 _ = commonSupertype(nonescaping, a) // expected-error@-1 {{converting non-escaping value to 'Any' may allow it to escape}} _ = commonSupertype(a, nonescaping) // expected-error@-1 {{converting non-escaping value to 'Any' may allow it to escape}} _ = commonSupertype(escaping, a) _ = commonSupertype(a, escaping) expectEqualType(Builtin.type_join(((C) -> C).self, ((C) -> D).self), ((C) -> C).self) } func rdar37241221(_ a: C?, _ b: D?) { let c: C? = C() let array_c_opt = [c] let inferred = [a!, b] expectEqualType(type(of: array_c_opt).self, type(of: inferred).self) }
18154db5ef40f4e82d83fea93e70f843
49.598361
122
0.731249
false
false
false
false
QueryKit/TodoExample
refs/heads/master
Todo/TaskListViewController.swift
bsd-2-clause
1
// // ViewController.swift // Todo // // Created by Kyle Fuller on 28/01/2015. // Copyright (c) 2015 Cocode. All rights reserved. // import UIKit import KFData import QueryKit class TaskListViewController: KFDataTableViewController { var dataStore:KFDataStore! var querySet:QuerySet<Task>! { didSet { if let querySet = querySet { setManagedObjectContext(querySet.context, fetchRequest: querySet.fetchRequest, sectionNameKeyPath: nil, cacheName: nil) } else { setManagedObjectContext(nil, fetchRequest: nil, sectionNameKeyPath: nil, cacheName: nil) } } } var context:NSManagedObjectContext? { return querySet.context } override func viewDidLoad() { super.viewDidLoad() dataStore = try! KFDataStore.standardLocalDataStore() let context = dataStore.managedObjectContext() querySet = Task.queryset(context).orderBy { $0.createdAt.descending() } if let count = try? querySet.count() { if count == 0 { createTask("Hit add to create your first task.") } } } func createTask(name:String) { let task = Task.create(context!) task.name = name task.createdAt = NSDate() try! context?.save() } // MARK: UITableViewDataSource override func tableView(tableView: UITableView!, cellForManagedObject managedObject: NSManagedObject!, atIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let task = managedObject as! Task let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell! cell.textLabel?.text = task.name cell.accessoryType = task.complete!.boolValue ? .Checkmark : .None return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let task = dataSource.objectAtIndexPath(indexPath) as! Task task.complete = !task.complete!.boolValue } // MARK: Actions @IBAction func handleCreate() { let alertController = UIAlertController(title: "Create Task", message: nil, preferredStyle: .Alert) alertController.addTextFieldWithConfigurationHandler { textField in } alertController.addAction(UIAlertAction(title: "Add", style: .Default) { _ in let textField = alertController.textFields![0] as UITextField if let text = textField.text { if !text.isEmpty { self.createTask(text) } } }) alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(alertController, animated: true, completion: nil) } }
ef05e76ec2b022925f04d8e24d024453
30.243902
163
0.703747
false
false
false
false
GatorNation/HackGT
refs/heads/master
HackGT2016/HackGT2016 WatchKit Extension/InterfaceController.swift
mit
1
// // InterfaceController.swift // HackGT2016 WatchKit Extension // // Created by David Yeung on 9/24/16. // // import WatchKit import Foundation import WatchConnectivity class InterfaceController: WKInterfaceController, WCSessionDelegate { @IBOutlet var counterLabel: WKInterfaceLabel! var counter = 0 var session : WCSession! @IBAction func incrementCounter() { counter += 1 setCounterLabelText() } @IBAction func clearCounter() { counter = 0 setCounterLabelText() } @IBAction func saveCounter() { let applicationData = ["counterValue":String(counter)] session.sendMessage(applicationData, replyHandler: { (_: [String : Any]) in }) { (Error) in } } func setCounterLabelText() { counterLabel.setText(String(counter)) } override func willActivate() { super.willActivate() if (WCSession.isSupported()) { session = WCSession.default() session.delegate = self session.activate() } } override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?){ } }
627f6015cb1fc0c804387f71372e2ccc
21.054795
123
0.601242
false
false
false
false
CaiMiao/CGSSGuide
refs/heads/master
DereGuide/Toolbox/BirthdayNotification/BirthdayCenter.swift
mit
1
// // BirthdayCenter.swift // DereGuide // // Created by zzk on 16/8/16. // Copyright © 2016年 zzk. All rights reserved. // import UIKit import UserNotifications import SDWebImage extension CGSSChar { var nextBirthday: Date! { let timeZone = UserDefaults.standard.birthdayTimeZone var gregorian = Calendar(identifier: .gregorian) gregorian.timeZone = timeZone let now = Date() var dateComp = gregorian.dateComponents([Calendar.Component.year, Calendar.Component.month, Calendar.Component.day], from: now) if (birthMonth, birthDay) < (dateComp.month!, dateComp.day!) { dateComp.year = dateComp.year! + 1 } dateComp.month = birthMonth dateComp.day = birthDay return gregorian.date(from: dateComp) } var nextBirthdayComponents: DateComponents { // var calendar = Calendar(identifier: .gregorian) // calendar.timeZone = UserDefaults.standard.birthdayTimeZone // // let now = Date() // var dateComponents = calendar.dateComponents([.year, .month, .day], from: now) // if (birthMonth, birthDay) < (dateComponents.month!, dateComponents.day!) { // dateComponents.year = dateComponents.year! + 1 // } // dateComponents.month = birthMonth // dateComponents.day = birthDay // // dateComponents.timeZone = UserDefaults.standard.birthdayTimeZone // return dateComponents let date = self.nextBirthday var gregorian = Calendar(identifier: .gregorian) gregorian.timeZone = TimeZone.current return gregorian.dateComponents([.year, .month, .day, .hour, .minute], from: date!) } } class BirthdayCenter { static let `default` = BirthdayCenter() var chars: [CGSSChar]! var lastSortDate: Date! private init() { prepare() NotificationCenter.default.addObserver(self, selector: #selector(prepare), name: .updateEnd, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc func prepare() { let dao = CGSSDAO.shared chars = dao.charDict.allValues as! [CGSSChar] chars.sort { (char1, char2) -> Bool in char1.nextBirthday < char2.nextBirthday } lastSortDate = Date() } @objc func scheduleNotifications() { removeBirthdayNotifications() DispatchQueue.global(qos: .userInitiated).async { [weak self] in if let strongSelf = self { for char in strongSelf.getRecent(1, endDays: 30) { if #available(iOS 10.0, *) { // 1. 创建通知内容 let content = UNMutableNotificationContent() content.title = NSLocalizedString("偶像生日提醒", comment: "") let body = NSLocalizedString("今天是%@的生日(%d月%d日)", comment: "生日通知正文") content.body = String.init(format: body, char.name!, char.birthMonth!, char.birthDay!) // 2. 创建发送触发 let trigger = UNCalendarNotificationTrigger(dateMatching: char.nextBirthdayComponents, repeats: false) // 3. 发送请求标识符 let requestIdentifier = Config.bundleID + ".\(char.name!)" content.categoryIdentifier = NotificationHandler.UserNotificationCategoryType.birthday let relatedCards = CGSSDAO.shared.findCardsByCharId(char.charaId).sorted { $0.albumId > $1.albumId } var userInfo: [String: Any] = ["charName": char.name!, "charaId": char.charaId!] if let spriteImageRef = relatedCards.first?.spriteImageRef { // 注意: userInfo 中只能存属性列表 userInfo["cardSpriteImageRef"] = spriteImageRef } content.userInfo = userInfo let url = URL.images.appendingPathComponent("/icon_char/\(char.charaId!).png") if let key = SDWebImageManager.shared().cacheKey(for: url) { if let path = SDImageCache.shared().defaultCachePath(forKey: key) { let imageURL = URL(fileURLWithPath: path) // by adding into a notification, the attachment will be moved to a new location so you need to copy it first let fileManager = FileManager.default let newURL = URL(fileURLWithPath: Path.temporary + "\(char.charaId!).png") do { try fileManager.copyItem(at: imageURL, to: newURL) } catch { print(error.localizedDescription) } if let attachment = try? UNNotificationAttachment(identifier: "imageAttachment", url: newURL, options: nil) { content.attachments = [attachment] } } } // 4. 创建一个发送请求 let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger) // 将请求添加到发送中心 // print("notification scheduling: \(requestIdentifier)") UNUserNotificationCenter.current().add(request) { error in if error == nil { // print("notification scheduled: \(requestIdentifier)") } else { // if userinfo is not property list, this closure will not be executed, no errors here print("notification falied in scheduling: \(requestIdentifier)") } } } else { // Fallback on earlier versions let localNotification = UILocalNotification() localNotification.fireDate = char.nextBirthday let body = NSLocalizedString("今天是%@的生日(%d月%d日)", comment: "生日通知正文") localNotification.alertBody = String.init(format: body, char.name!, char.birthMonth!, char.birthDay!) localNotification.category = NotificationCategory.birthday localNotification.userInfo = ["chara_id": char.charaId] UIApplication.shared.scheduleLocalNotification(localNotification) } } } } } func getRecent(_ startDays: Int, endDays: Int) -> [CGSSChar] { let timeZone = UserDefaults.standard.birthdayTimeZone var gregorian = Calendar(identifier: .gregorian) gregorian.timeZone = timeZone let now = Date() // 因为用户修改日期或自然时间变动时 重新排序 if lastSortDate.truncateHours(timeZone: timeZone) != now.truncateHours(timeZone: timeZone) { prepare() } let start = now.addingTimeInterval(TimeInterval(startDays) * 3600 * 24).truncateHours(timeZone: timeZone) let end = now.addingTimeInterval(TimeInterval(endDays) * 3600 * 24).truncateHours(timeZone: timeZone) var arr = [CGSSChar]() for char in chars { if char.nextBirthday < start { continue } if char.nextBirthday > end { break } arr.append(char) } return arr } func removeBirthdayNotifications() { if #available(iOS 10.0, *) { // UNUserNotificationCenter.current().removeAllDeliveredNotifications() UNUserNotificationCenter.current().removeAllPendingNotificationRequests() } else { } if let notifications = UIApplication.shared.scheduledLocalNotifications { for notification in notifications { if notification.category == "Birthday" { UIApplication.shared.cancelLocalNotification(notification) } } } } }
bfa8845f3ba60c45b3e523d99cf03155
42.984615
141
0.533054
false
false
false
false
angelopino/APJExtensions
refs/heads/master
Source/String+extension.swift
mit
1
// // String+extension.swift // APJExtensionsiOS // // Created by Pino, Angelo on 13/01/2018. // Copyright © 2018 Pino, Angelo. All rights reserved. // import UIKit public extension String { func count(regex: String) -> Int { guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return 0 } let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: count)) return matches.count } func test(regex: String) -> Bool { return self.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil } var isNotEmpty: Bool { return !isEmpty } var toImage: UIImage? { return UIImage(named: self) } var storyboard: UIStoryboard { return UIStoryboard(name: self, bundle: nil) } var toInt: Int? { return Int(self) } func toDate(_ format: String) -> Date? { guard !isEmpty else { return nil } let dateFormatter = DateFormatter() dateFormatter.dateFormat = format dateFormatter.locale = Locale(identifier: "en_US") return dateFormatter.date(from: self) } }
a9e6fa800e6bc0042603bac5d2a6c0ac
24.702128
102
0.605132
false
false
false
false
salesawagner/wascar
refs/heads/master
Pods/SwiftLocation/src/HeadingRequest.swift
mit
1
// // SwiftLocation.swift // SwiftLocations // // Copyright (c) 2016 Daniele Margutti // Web: http://www.danielemargutti.com // Mail: [email protected] // Twitter: @danielemargutti // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreLocation fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } open class HeadingRequest: Request { /// Unique identifier of the heading request open var UUID: String = Foundation.UUID().uuidString /// Handler to call when a new heading value is received internal var onReceiveUpdates: HeadingHandlerSuccess? /// Handler to call when an error has occurred internal var onError: HeadingHandlerError? /// Authorization did change open var onAuthorizationDidChange: LocationHandlerAuthDidChange? /// Last heading received fileprivate(set) var lastHeading: CLHeading? internal weak var locator: LocationManager? open var rState: RequestState = .pending { didSet { self.locator?.updateHeadingService() } } /// Frequency value to receive new events open var frequency: HeadingFrequency { didSet { self.locator?.updateHeadingService() } } /// The maximum deviation (measured in degrees) between the reported heading and the true geomagnetic heading. open var accuracy: CLLocationDirection { didSet { self.locator?.updateHeadingService() } } /// True if system calibration tool can be opened if necessary. open var allowsCalibration: Bool = true /** Create a new request to receive heading values from device's motion sensors about the orientation of the device - parameter withInterval: The minimum angular change (measured in degrees) required to generate new heading events.If nil is specified you will receive any new value - parameter sHandler: handler to call when a new heading value is received - parameter eHandler: error handler to call when something goes bad. request is automatically stopped and removed from queue. - returns: the request instance you can add to the queue */ internal init(withFrequency frequency: HeadingFrequency, accuracy: CLLocationDirection, allowsCalibration: Bool = true) { self.frequency = frequency self.accuracy = accuracy self.allowsCalibration = allowsCalibration } /** Use this function to change the handler to call when a new heading value is received - parameter handler: handler to call - returns: self, used to make the function chainable */ open func onReceiveUpdates(_ handler :@escaping HeadingHandlerSuccess) -> HeadingRequest { self.onReceiveUpdates = handler return self } /** Use this function to change the handler to call when something bad occours while receiving data from server - parameter handler: handler to call - returns: self, used to make the function chainable */ open func onError(_ handler :@escaping HeadingHandlerError) -> HeadingRequest { self.onError = handler return self } /** Put the request in queue and starts it */ open func start() { guard let locator = self.locator else { return } let previousState = self.rState self.rState = .running if locator.add(self) == false { self.rState = previousState } } /** Temporary pause request (not removed) */ open func pause() { if self.rState.isRunning { guard let locator = self.locator else { return } self.rState = .paused locator.updateHeadingService() } } /** Terminate request */ open func cancel(_ error: LocationError?) { guard let locator = self.locator else { return } if locator.remove(self) { self.rState = .cancelled(error: error) } } /** Terminate request (no error passing) */ open func cancel() { self.cancel(nil) } //MARK: - Private internal func didReceiveEventFromManager(_ error: NSError?, heading: CLHeading?) { if error != nil { let err = LocationError.locationManager(error: error!) self.onError?(err) self.cancel(err) return } if self.validateHeading(heading!) == true { self.lastHeading = heading if self.rState.isRunning == true { self.onReceiveUpdates?(self.lastHeading!) } } } fileprivate func validateHeading(_ heading: CLHeading) -> Bool { guard let lastHeading = self.lastHeading else { return true } switch self.frequency { case .continuous(let interval): let elapsedTime = (heading.timestamp.timeIntervalSince1970 - lastHeading.timestamp.timeIntervalSince1970) return (elapsedTime > interval) case .magneticNorth(let minChange): let degreeDiff = fabs(heading.magneticHeading - lastHeading.magneticHeading) return (degreeDiff > minChange) case .trueNorth(let minChange): let degreeDiff = fabs(heading.trueHeading - lastHeading.trueHeading) return (degreeDiff > minChange) } } }
04f686be76a41db3c822af66897ebe0a
28.478261
166
0.724189
false
false
false
false
vchuo/Photoasis
refs/heads/master
Photoasis/Classes/Views/Views/ImageViewer/POImageViewerZoomHintToastView.swift
mit
1
// // POImageViewerZoomHintToastView.swift // イメージビューアーの「ダブルクリックかピンチでズームができる」ヒントトーストビュー。 // // Created by Vernon Chuo Chian Khye on 2017/02/27. // Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved. // import UIKit import ChuoUtil class POImageViewerZoomHintToastView: UIView { // MARK: - Views private let hintLabel = UILabel() // MARK: - Init override init(frame: CGRect) { super.init(frame: CGRectZero) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: - Public Functions /** ヒントを表示。 */ func displayHint() { CUHelper.animateKeyframes( POConstants.ImageViewerHintToastViewDisplayDuration, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.02) { self.alpha = 0.9 } UIView.addKeyframeWithRelativeStartTime(0.98, relativeDuration: 0.02) { self.alpha = 0 } } ) { _ in self.removeFromSuperview() } } // MARK: - Private Functions /** ビューのセットアップ。 */ private func setup() { self.bounds.size = POConstants.ImageViewerZoomHintToastViewContainerViewSize self.layer.cornerRadius = POConstants.ImageViewerHintToastViewContainerViewCornerRadius self.clipsToBounds = true self.backgroundColor = POColors.ImageViewerHintToastViewContainerBackgroundColor self.userInteractionEnabled = false self.alpha = 0 // ヒントラベル hintLabel.text = POStrings.ImageViewerZoomHintToastViewLabelText hintLabel.font = POFonts.ImageViewerHintToastViewLabelFont hintLabel.textColor = POColors.ImageViewerHintToastViewLabelTextColor hintLabel.textAlignment = .Center hintLabel.numberOfLines = 0 hintLabel.bounds.size.width = self.bounds.width - POConstants.ImageViewerHintToastViewContainerViewHorizontalContentInset * 2 hintLabel.sizeToFit() hintLabel.center = CUHelper.centerPointOf(self) self.addSubview(hintLabel) } }
be99aac82b84d3bf14872d17b723b12c
29.152778
133
0.657761
false
false
false
false
Pyroh/SwiftMark
refs/heads/master
Sources/SwiftMark/SwiftMarkConvertToHTMLOperation.swift
mit
4
// // SMarkConvertToHTMLOperation.swift // SwiftMark // // Created by Pierre TACCHI on 20/12/15. // Copyright © 2015 Pierre TACCHI. All rights reserved. // import Foundation /// A `SwiftMarkToHTMLOperation` converts any valid *CommonMark* text to HTML. Use this class if you want to convert *CommonMark* text to HTML asynchronously. /// /// The blocks you assign to process the fetched records are executed serially on an internal queue managed by the operation. Your blocks must be capable of executing on a background thread, so any tasks that require access to the main thread must be redirected accordingly. public class SwiftMarkToHTMLOperation: SwiftMarkOperation { /** Returns on initialized `SwiftMarkToHTMLOperation` object ready to convert the given *CommonMark* text using given options. - parameter text: The *CommonMark* text. - parameter options: The options passed to the parser. - returns: An initialized `SwiftMarkToHTMLOperation` object ready to execute. */ public override init(text: String, options: SwiftMarkOptions = .Default) { super.init(text: text, options: options) } /** Returns on initialized `SwiftMarkToHTMLOperation` object ready to convert the given *CommonMark* text using given options. Once the conversion is complete the given block will be executed. - parameter text: The *CommonMark* text. - parameter options: The options passed to the parser. - parameter conversionCompleteBlock: The block to execute once de conversion is complete. - returns: An initialized `SwiftMarkToHTMLOperation` object ready to execute. */ public convenience init(text: String, options: SwiftMarkOptions = .Default, conversionCompleteBlock: @escaping ConversionCompleteBlock) { self.init(text: text, options: options) self.conversionCompleteBlock = conversionCompleteBlock } /** Returns on initialized `SwiftMarkToHTMLOperation` object ready to convert the given *CommonMark* text using given options. Once the conversion is complete the given block will be executed. If an error occurs the given block will execute. - parameter text: The *CommonMark* text. - parameter options: The options passed to the parser. - parameter conversionCompleteBlock: The block to execute once de conversion is complete. - parameter failureBlock: The block to execute if an error occurs. - returns: An initialized `SwiftMarkToHTMLOperation` object ready to execute. */ public convenience init(text: String, options: SwiftMarkOptions = .Default, conversionCompleteBlock: @escaping ConversionCompleteBlock, failureBlock: @escaping FailureBlock) { self.init(text: text, options: options) self.conversionCompleteBlock = conversionCompleteBlock self.failureBlock = failureBlock } /** Returns on initialized `SwiftMarkToHTMLOperation` object ready to convert *CommonMark* text read for the given file URL using given options and reading text using given encoding. - parameter text: The *CommonMark* text. - parameter options: The options passed to the parser. - parameter encoding: The text file encoding - returns: An initialized `SwiftMarkToHTMLOperation` object ready to execute. */ public override init(url: URL, options: SwiftMarkOptions = .Default, encoding: String.Encoding = String.Encoding.utf8) { super.init(url: url, options: options, encoding: encoding) } /** Returns on initialized `SwiftMarkToHTMLOperation` object ready to convert *CommonMark* text read for the given file URL using given options and reading text using given encoding. Once the conversion is complete the given block will be executed. - parameter text: The *CommonMark* text. - parameter options: The options passed to the parser. - parameter encoding: The text file encoding - parameter conversionCompleteBlock: The block to execute once de conversion is complete. - returns: An initialized `SwiftMarkToHTMLOperation` object ready to execute. */ public convenience init(url: URL, options: SwiftMarkOptions = .Default, encoding: String.Encoding = String.Encoding.utf8, conversionCompleteBlock: @escaping ConversionCompleteBlock) { self.init(url: url, options: options) self.conversionCompleteBlock = conversionCompleteBlock } /** Returns on initialized `SwiftMarkToHTMLOperation` object ready to convert *CommonMark* text read for the given file URL using given options and reading text using given encoding. Once the conversion is complete the given block will be executed. If an error occurs the given block will execute. - parameter text: The *CommonMark* text. - parameter options: The options passed to the parser. - parameter encoding: The text file encoding - parameter conversionCompleteBlock: The block to execute once de conversion is complete. - parameter failureBlock: The block to execute if an error occurs. - returns: An initialized `SwiftMarkToHTMLOperation` object ready to execute. */ public convenience init(url: URL, options: SwiftMarkOptions = .Default, encoding: String.Encoding = String.Encoding.utf8, conversionCompleteBlock: @escaping ConversionCompleteBlock, failureBlock: @escaping FailureBlock) { self.init(url: url, options: options) self.conversionCompleteBlock = conversionCompleteBlock self.failureBlock = failureBlock } override func convert(_ commonMarkString: String) throws -> String { return try commonMarkToHTML(commonMarkString, options: self.options) } }
f8ac6a94505d70acb3b3fae088c929b3
55.704762
298
0.709271
false
false
false
false
WuAlan/SwiftPractice-TodoList
refs/heads/master
Todo/DetailViewController.swift
gpl-3.0
1
// // DetailViewController.swift // Todo // // Created by WuYanlin on 15/4/11. // Copyright (c) 2015年 AllenWu. All rights reserved. // import UIKit class DetailViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var childButton: UIButton! @IBOutlet weak var phoneButton: UIButton! @IBOutlet weak var shoppingButton: UIButton! @IBOutlet weak var travelButton: UIButton! @IBOutlet weak var todoItem: UITextField! @IBOutlet weak var todoDate: UIDatePicker! var todo: TodoModel? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. todoItem.delegate=self if todo == nil { childButton.selected=true navigationItem.title = "新增Todo" } else { navigationItem.title = "修改Todo" if todo?.image == "selectChild" { childButton.selected=true } else if todo?.image == "selectShop" { shoppingButton.selected=true } else if todo?.image == "selectPhone" { phoneButton.selected=true } else if todo?.image == "selectTravel" { travelButton.selected=true } todoItem.text=todo?.title todoDate.setDate((todo?.date)!, animated: false) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { todoItem.resignFirstResponder() } func resetButton() { childButton.selected=false shoppingButton.selected=false travelButton.selected=false phoneButton.selected=false } @IBAction func childTapped(sender: AnyObject) { resetButton() childButton.selected=true } @IBAction func phoneTapped(sender: AnyObject) { resetButton() phoneButton.selected=true } @IBAction func shoppingTapped(sender: AnyObject) { resetButton() shoppingButton.selected=true } @IBAction func travelTapped(sender: AnyObject) { resetButton() travelButton.selected=true } @IBAction func OKTapped(sender: AnyObject) { var image="" if childButton.selected { image = "selectChild" } else if phoneButton.selected { image = "selectPhone" } else if shoppingButton.selected { image = "selectShop" } else if travelButton.selected { image = "selectTravel" } if todo==nil { let uuid = NSUUID().UUIDString var todo=TodoModel(id: uuid, image: image, title: todoItem.text, date: todoDate.date) todos.append(todo) } else { todo?.image=image todo?.title=todoItem.text todo?.date=todoDate.date } } /* // 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. } */ }
6628b89892574543420d82f916d632f1
26.095588
106
0.585346
false
false
false
false
brunomorgado/ScrollableAnimation
refs/heads/master
ScrollableAnimation/Source/Animation/Interpolators/BasicInterpolator/BasicValueInterpolator.swift
mit
1
// // BasicValueInterpolator.swift // ScrollableMovie // // Created by Bruno Morgado on 25/12/14. // Copyright (c) 2014 kocomputer. 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 class BasicValueInterpolator: BasicInterpolator { var animatable: CALayer required init(animatable: CALayer) { self.animatable = animatable } private func interpolatedPoint(offset: Float, animation: ScrollableBasicAnimation) -> CGPoint { var point = CGPointZero if let animation = animation as ScrollableBasicAnimation? { let offsetPercentage = BasicInterpolator.getPercentageForOffset(offset, animation: animation) if let fromValue = animation.fromValue as NSValue? { if let toValue = animation.toValue as NSValue? { if (offsetPercentage <= 0) { point = fromValue.CGPointValue() } else if (offsetPercentage > 1) { point = toValue.CGPointValue() } else { let verticalDeltaX = Double(toValue.CGPointValue().x - fromValue.CGPointValue().x) let verticalDeltaY = Double(toValue.CGPointValue().y - fromValue.CGPointValue().y) var valueX: Float var valueY: Float var tween = animation.offsetFunction if let tween = tween as TweenBlock? { valueX = Float(fromValue.CGPointValue().x) + Float(tween(Double(offsetPercentage))) * Float(verticalDeltaX) valueY = Float(fromValue.CGPointValue().y) + Float(tween(Double(offsetPercentage))) * Float(verticalDeltaY) } else { valueX = Float(fromValue.CGPointValue().x) + (offsetPercentage * Float(verticalDeltaX)) valueY = Float(fromValue.CGPointValue().y) + offsetPercentage * Float(verticalDeltaY) } point = CGPoint(x: CGFloat(valueX), y: CGFloat(valueY)) } } } } return point } private func interpolatedSize(offset: Float, animation: ScrollableBasicAnimation) -> CGSize { var size = CGSizeZero if let animation = animation as ScrollableBasicAnimation? { let offsetPercentage = BasicInterpolator.getPercentageForOffset(offset, animation: animation) if let fromValue = animation.fromValue as NSValue? { if let toValue = animation.toValue as NSValue? { let verticalDeltaWidth = Double(toValue.CGSizeValue().width - fromValue.CGSizeValue().width) let verticalDeltaHeight = Double(toValue.CGSizeValue().height - fromValue.CGSizeValue().height) var valueWidth: Float var valueHeight: Float var tween = animation.offsetFunction if let tween = tween as TweenBlock? { valueWidth = Float(fromValue.CGSizeValue().width) + Float(tween(Double(offsetPercentage))) * Float(verticalDeltaWidth) valueHeight = Float(fromValue.CGSizeValue().height) + Float(tween(Double(offsetPercentage))) * Float(verticalDeltaHeight) } else { valueWidth = Float(fromValue.CGSizeValue().width) + offsetPercentage * Float(verticalDeltaWidth) valueHeight = Float(fromValue.CGSizeValue().height) + offsetPercentage * Float(verticalDeltaHeight) } size = CGSize(width: CGFloat(valueWidth), height: CGFloat(valueHeight)) } } } return size } } extension BasicValueInterpolator: BasicInterpolatorProtocol { func interpolateAnimation(animation: ScrollableAnimation, forAnimatable animatable: CALayer, forOffset offset: Float) { if let animation = animation as? ScrollableBasicAnimation { if let fromValue = animation.fromValue as NSValue? { if let toValue = animation.toValue as NSValue? { let type = String.fromCString(toValue.objCType) ?? "" switch true { case type.hasPrefix("{CGPoint"): let point = self.interpolatedPoint(offset, animation: animation) self.animatable.setValue(NSValue(CGPoint: point), forKeyPath: animation.keyPath) case type.hasPrefix("{CGSize"): let size = self.interpolatedSize(offset, animation: animation) self.animatable.setValue(NSValue(CGSize: size), forKeyPath: animation.keyPath) default: return } } else { println("Warning!! Invalid value type when expecting NSValue") } } else { println("Warning!! Invalid value type when expecting NSValue") } } else { println("Warning!! Invalid value type when expecting NSValue") } } }
c19d884ef2239b7bbb88179fe42e399b
50.532258
145
0.596494
false
false
false
false
trident10/TDMediaPicker
refs/heads/master
TDMediaPicker/Classes/Controller/ChildViewControllers/TDAlbumListViewController.swift
mit
1
// // TDAlbumPickerViewController.swift // ImagePicker // // Created by Abhimanu Jindal on 25/06/17. // Copyright © 2017 Abhimanu Jindal. All rights reserved. // import UIKit import Photos protocol TDAlbumListViewControllerDataSource: class{ func albumController(_ controller: TDAlbumListViewController, selectedAlbumAtInitialLoad albums: [TDAlbum])-> TDAlbum? func albumController(_ picker: TDAlbumListViewController, textFormatForAlbum album: TDAlbum, mediaCount: Int)-> TDConfigText? } protocol TDAlbumListViewControllerDelegate: class{ func albumControllerDidTapCancel(_ controller: TDAlbumListViewController) func albumControllerDidTapDone(_ controller: TDAlbumListViewController) func albumController(_ controller: TDAlbumListViewController, didSelectAlbum album: TDAlbum, animation:Bool) } class TDAlbumListViewController: UIViewController, TDAlbumListViewDelegate, TDAlbumListServiceManagerDelegate, TDAlbumListViewDataSource{ // MARK: - Variables weak var delegate: TDAlbumListViewControllerDelegate? weak var dataSource: TDAlbumListViewControllerDataSource? lazy fileprivate var serviceManager: TDAlbumListServiceManager = TDAlbumListServiceManager() lazy fileprivate var isFirstTime = false // MARK: - Init public required init() { super.init(nibName: "TDAlbumList", bundle: TDMediaUtil.xibBundle()) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Life cycle public override func viewDidLoad() { super.viewDidLoad() // 2. View Setup let albumView = self.view as! TDAlbumListView albumView.setupView() albumView.delegate = self albumView.dataSource = self // 3. Service Manager Setup serviceManager.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNavigationTheme() setupConfig() serviceManager.fetchAlbums(getAlbumFetchResults()) { (albums) in self.handleFetchedAlbums(albums) } } override func viewDidDisappear(_ animated: Bool) { serviceManager.purgeData() let albumView = self.view as! TDAlbumListView albumView.purgeData() } // MARK: - Private Method(s) private func handleFetchedAlbums(_ albums:[TDAlbum]){ if !isFirstTime{ isFirstTime = true if let selectedInitialAlbum = self.dataSource?.albumController(self, selectedAlbumAtInitialLoad: albums){ self.delegate?.albumController(self, didSelectAlbum: selectedInitialAlbum, animation: false) } } var albumViewModels: [TDAlbumViewModel] = [] for(_,album) in albums.enumerated(){ let albumViewModel = map(album) if albumViewModel != nil{ let albumView = albumViewModel as! TDAlbumViewModel albumViewModels.append(albumView) } } let albumView = self.view as! TDAlbumListView albumView.reload(albumViewModels) } private func map<T>(_ from: T) -> AnyObject?{ if from is TDAlbum{ let album = from as! TDAlbum var title = "" if album.collection.localizedTitle != nil{ title = album.collection.localizedTitle! } let countText = "\(album.itemsCount)" let asset = album.albumMedia?.asset let imageSize = CGSize(width: 65, height: 65) if asset != nil{ return TDAlbumViewModel.init(id: album.id, asset: asset!, title: title, countTitle: countText, imageSize: imageSize) as AnyObject } } return nil } //MARK: - Album View Datasource Method(s) func albumListView(_ view: TDAlbumListView, textForAlbum album: TDAlbumViewModel)->TDConfigText?{ let albums = serviceManager.fetchAlbum(album.id) let selectedAlbum: TDAlbum? if albums.count > 0{ selectedAlbum = albums[0] } else{ return nil } let currentCount = selectedAlbum?.itemsCount return self.dataSource?.albumController(self, textFormatForAlbum: selectedAlbum!, mediaCount: currentCount!) } // MARK: - Album View Delegate Method(s) func albumListView(_ view:TDAlbumListView, didSelectAlbum album:TDAlbumViewModel){ serviceManager.fetchAlbum(album.id, completion: { (albumData) in if albumData != nil{ self.delegate?.albumController(self, didSelectAlbum: albumData!, animation: true) } }) } func albumListViewDidTapBack(_ view:TDAlbumListView){ self.delegate?.albumControllerDidTapCancel(self) } func albumListViewDidTapNext(_ view:TDAlbumListView){ self.delegate?.albumControllerDidTapDone(self) } } // MARK: - Configurations extension TDAlbumListViewController{ func setupNavigationTheme(){ let config = serviceManager.getNavigationThemeConfig() let albumView = self.view as! TDAlbumListView albumView.setupNavigationTheme(config.backgroundColor) } func setupConfig(){ let albumView = self.view as! TDAlbumListView let config = serviceManager.getAlbumScreenConfig() if let title = config.navigationBar?.screenTitle{ albumView.setupScreenTitle(title) } if let btnConfig = config.navigationBar?.backButton{ albumView.setupBackButton(btnConfig) } if let btnConfig = config.navigationBar?.nextButton{ albumView.setupNextButton(btnConfig) } if let color = config.navigationBar?.navigationBarView?.backgroundColor{ albumView.setupNavigationTheme(color) } if let size = config.imageSize{ albumView.setupAlbumImageSize(size) } } func getAlbumFetchResults()->[PHFetchResult<PHAssetCollection>]?{ let config = serviceManager.getAlbumScreenConfig() return config.fetchResults } }
24590093ce5295e63f347a0cf94be2ce
32.246073
145
0.645197
false
true
false
false
alexlivenson/BlueLibrarySwift
refs/heads/master
BlueLibrarySwift/AlbumView.swift
mit
1
// // AlbumView.swift // BlueLibrarySwift // // Created by alex livenson on 9/23/15. // Copyright © 2015 alex livenson. All rights reserved. // import UIKit class AlbumView: UIView { private var coverImage: UIImageView! private var indicator: UIActivityIndicatorView! private let notificationCenter = NSNotificationCenter.defaultCenter() private let imageKeyPath = "image" init(frame: CGRect, albumCover: String) { super.init(frame: frame) commonInit() notificationCenter.postNotificationName( "BLDownloadImageNotification", object: self, userInfo: ["imageView": coverImage, "coverUrl": albumCover]) } // NOTE: Required because UIView conforms to NSCoding required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = UIColor.blackColor() coverImage = UIImageView(frame: CGRectMake(5, 5, frame.size.width - 10, frame.size.height - 10)) addSubview(coverImage) indicator = UIActivityIndicatorView() indicator.center = center indicator.activityIndicatorViewStyle = .WhiteLarge indicator.startAnimating() addSubview(indicator) // KVO -> Should come before notification center coverImage.addObserver(self, forKeyPath: imageKeyPath, options: .Prior, context: nil) } func highlightAlbum(didHighlightView: Bool) { if didHighlightView { backgroundColor = UIColor.whiteColor() } else { backgroundColor = UIColor.blackColor() } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == imageKeyPath { indicator.stopAnimating() } } deinit { coverImage.removeObserver(self, forKeyPath: imageKeyPath) } }
f2ff2d9ad598ec7171df7cc5d55f2b54
28.097222
157
0.627208
false
false
false
false
masbog/HiBeacons
refs/heads/swift
HiBeacons/NATViewController.swift
mit
1
// // NATViewController.swift // HiBeacons // // Created by Nick Toumpelis on 2015-07-22. // Copyright (c) 2015 Nick Toumpelis. // // 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 UIKit import CoreLocation /// The main view controller, which basically manages the UI, triggers operations and updates its views. class NATViewController: UIViewController { // Outlets /// The main table view containing the operation cells, and optionally the ranged beacons. @IBOutlet weak var beaconTableView: UITableView? // Constants /// The maximum number of table view sections (when ranged beacons are included). private let kMaxNumberOfSections = 2 /// The number of possible operations. private let kNumberOfAvailableOperations = 3 /// The title for the beacon ranging table view section. private let kBeaconSectionTitle = "Looking for beacons..." /// The position of the activity indicator in the ranging table view header. private let kActivityIndicatorPosition = CGPoint(x: 205, y: 12) /// The identifier for the beacon ranging table view header. private let kBeaconsHeaderViewIdentifier = "BeaconsHeader" // Enumerations /** The type of the table view section. - Operations: The first section contains the cells that can perform operations, and have switches. - DetectedBeacons: The second section lists cells, each with a ranged beacon. */ private enum NTSectionType: Int { case Operations = 0 case DetectedBeacons /** Returns the table view cell identifier that corresponds to the section type. :returns: The table view cell identifier. */ func cellIdentifier() -> String { switch self { case .Operations: return "OperationCell" case .DetectedBeacons: return "BeaconCell" } } /** Returns the table view cell height that corresponds to the section type. :returns: The table view cell height. */ func tableViewCellHeight() -> CGFloat { switch self { case .Operations: return 44.0 case .DetectedBeacons: return 52.0 } } } /** The rows contained in the operations table view section. - Monitoring: The monitoring cell row. - Advertising: The advertising cell row. - Ranging: The ranging cell row. */ private enum NTOperationsRow: Int { case Monitoring = 0 case Advertising case Ranging /** Returns the table view cell title that corresponds to the specific operations row. :returns: A title for the table view cell label. */ func tableViewCellTitle() -> String { switch self { case .Monitoring: return "Monitoring" case .Advertising: return "Advertising" case .Ranging: return "Ranging" } } } // The Operation objects /// The monitoring operation object. private var monitoringOperation = NATMonitoringOperation() /// The advertising operation object. private var advertisingOperation = NATAdvertisingOperation() /// The ranging operation object. private var rangingOperation = NATRangingOperation() // Other /// An array of CLBeacon objects, typically those detected through ranging. private var detectedBeacons = [CLBeacon]() /// The UISwitch instance associated with the monitoring cell. private var monitoringSwitch: UISwitch? /// The UISwitch instance associated with the advertising cell. private var advertisingSwitch: UISwitch? /// The UISwitch instance associated with the ranging cell. private var rangingSwitch: UISwitch? /// The UIActivityIndicatorView that shows whether monitoring is active. private var monitoringActivityIndicator: UIActivityIndicatorView? /// The UIActivityIndicatorView that shows whether advertising is active. private var advertisingActivityIndicator: UIActivityIndicatorView? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "performWatchAction:", name: NATHiBeaconsDelegate.NATHiBeaconsWatchNotificationName, object: nil) // We need to assign self as a delegate here. monitoringOperation.delegate = self advertisingOperation.delegate = self rangingOperation.delegate = self } deinit { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self) } } // MARK: - Index path management extension NATViewController { /** Returns an array of NSIndexPath instances for the given beacons, which are to be removed from the table view. Not all of the given beacons will actually be removed. It will be determined by comparing with the currently detected beacons. :param: beacons An array of CLBeacon objects. :returns: An array of NSIndexPaths corresponding to positions in the table view where these beacons are. */ func indexPathsOfRemovedBeacons(beacons: [CLBeacon]) -> [NSIndexPath]? { var indexPaths: [NSIndexPath]? var row = 0 for existingBeacon in detectedBeacons { var stillExists = false for beacon in beacons { if existingBeacon.major?.integerValue == beacon.major?.integerValue && existingBeacon.minor?.integerValue == beacon.minor?.integerValue { stillExists = true break } } if stillExists == false { indexPaths = indexPaths ?? [] indexPaths!.append(NSIndexPath(forRow: row, inSection: NTSectionType.DetectedBeacons.rawValue)) } row++ } return indexPaths } /** Returns an array of NSIndexPath instances for the given beacons, which are to be inserted in the table view. Not all of the given beacons will actually be inserted. It will be determined by comparing with all the currently detected beacons. :param: beacons An array of CLBeacon objects. :returns: An array of NSIndexPaths corresponding to positions in the table view where these beacons are. */ func indexPathsOfInsertedBeacons(beacons: [CLBeacon]) -> [NSIndexPath]? { var indexPaths: [NSIndexPath]? var row = 0 for beacon in beacons { var isNewBeacon = true for existingBeacon in detectedBeacons { if existingBeacon.major?.integerValue == beacon.major?.integerValue && existingBeacon.minor?.integerValue == beacon.minor?.integerValue { isNewBeacon = false break } } if isNewBeacon == true { indexPaths = indexPaths ?? [] indexPaths!.append(NSIndexPath(forRow: row, inSection: NTSectionType.DetectedBeacons.rawValue)) } row++ } return indexPaths } /** Returns an array of NSIndexPath instances for the given beacons. :param: beacons An array of CLBeacon objects. :returns: An array of NSIndexPaths corresponding to positions in the table view. */ func indexPathsForBeacons(beacons: [CLBeacon]) -> [NSIndexPath] { var indexPaths = [NSIndexPath]() for row in 0..<beacons.count { indexPaths.append(NSIndexPath(forRow: row, inSection: NTSectionType.DetectedBeacons.rawValue)) } return indexPaths } /** Returns an NSIndexSet instance of the inserted sections in the table view or nil. :returns: An NSIndexSet instance or nil. */ func insertedSections() -> NSIndexSet? { if rangingSwitch?.on == true && beaconTableView?.numberOfSections() == kMaxNumberOfSections - 1 { return NSIndexSet(index: 1) } else { return nil } } /** Returns an NSIndexSet instance of the deleted sections in the table view or nil. :returns: An NSIndexSet instance or nil. */ func deletedSections() -> NSIndexSet? { if rangingSwitch?.on == false && beaconTableView?.numberOfSections() == kMaxNumberOfSections { return NSIndexSet(index: 1) } else { return nil } } /** Returns an array of CLBeacon instances that has been all its duplicates filtered out. Duplicates may appear during ranging; this may happen temporarily if the originating device changes its Bluetooth ID. :param: beacons An array of CLBeacon objects. :returns: An array of CLBeacon objects. */ func filteredBeacons(beacons: [CLBeacon]) -> [CLBeacon] { var filteredBeacons = beacons // Copy var lookup = Set<String>() for index in 0..<beacons.count { var currentBeacon = beacons[index] var identifier = "\(currentBeacon.major)/\(currentBeacon.minor)" if lookup.contains(identifier) { filteredBeacons.removeAtIndex(index) } else { lookup.insert(identifier) } } return filteredBeacons } } // MARK: - Table view functionality extension NATViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = NTSectionType(rawValue: indexPath.section)?.cellIdentifier() var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier!) as? UITableViewCell switch indexPath.section { case NTSectionType.Operations.rawValue: var operationCell = cell as! NATOperationCell cell?.textLabel?.text = NTOperationsRow(rawValue: indexPath.row)?.tableViewCellTitle() switch indexPath.row { case NTOperationsRow.Monitoring.rawValue: monitoringSwitch = operationCell.accessoryView as? UISwitch monitoringActivityIndicator = operationCell.activityIndicator monitoringSwitch?.addTarget(self, action: "changeMonitoringState:", forControlEvents: UIControlEvents.ValueChanged) if (monitoringSwitch!.on) { monitoringActivityIndicator?.startAnimating() } case NTOperationsRow.Advertising.rawValue: advertisingSwitch = operationCell.accessoryView as? UISwitch advertisingActivityIndicator = operationCell.activityIndicator advertisingSwitch?.addTarget(self, action: "changeAdvertisingState:", forControlEvents: UIControlEvents.ValueChanged) if (advertisingSwitch!.on) { advertisingActivityIndicator?.startAnimating() } case NTOperationsRow.Ranging.rawValue: rangingSwitch = cell?.accessoryView as? UISwitch rangingSwitch?.addTarget(self, action: "changeRangingState:", forControlEvents: UIControlEvents.ValueChanged) default: break } case NTSectionType.DetectedBeacons.rawValue: var beacon = detectedBeacons[indexPath.row] cell = cell ?? UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier) cell!.textLabel?.text = beacon.proximityUUID.UUIDString cell!.detailTextLabel?.text = beacon.fullDetails() cell!.detailTextLabel?.textColor = UIColor.grayColor() default: break } // We wouldn't normally need this, since constraints can be set in Interface Builder. However, there seems // to be a bug that removes all constraints from our cells upon dequeueing, so we need to trigger re-adding // them here. (See also NATOperationCell.swift). cell?.updateConstraintsIfNeeded() return cell! } func numberOfSectionsInTableView(tableView: UITableView) -> Int { if rangingSwitch?.on == true { return kMaxNumberOfSections // All sections visible } else { return kMaxNumberOfSections - 1 // Beacons section not visible } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case NTSectionType.Operations.rawValue: return kNumberOfAvailableOperations case NTSectionType.DetectedBeacons.rawValue: return self.detectedBeacons.count default: return 0 } } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch (section) { case NTSectionType.Operations.rawValue: return nil case NTSectionType.DetectedBeacons.rawValue: return kBeaconSectionTitle default: return nil } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return NTSectionType(rawValue: indexPath.section)!.tableViewCellHeight() } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UITableViewHeaderFooterView(reuseIdentifier: kBeaconsHeaderViewIdentifier) // Adds an activity indicator view to the section header let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) headerView.addSubview(indicatorView) indicatorView.frame = CGRect(origin: kActivityIndicatorPosition, size: indicatorView.frame.size) indicatorView.startAnimating() return headerView } } // MARK: - Operation methods extension NATViewController { /** Starts/stops the monitoring operation, depending on the state of the given switch. :param: monitoringSwitch The monitoring UISwitch instance. */ func changeMonitoringState(monitoringSwitch: UISwitch) { if monitoringSwitch.on { monitoringOperation.startMonitoringForBeacons() } else { monitoringOperation.stopMonitoringForBeacons() } } /** Starts/stops the advertising operation, depending on the state of the given switch. :param: advertisingSwitch The advertising UISwitch instance. */ func changeAdvertisingState(advertisingSwitch: UISwitch) { if advertisingSwitch.on { advertisingOperation.startAdvertisingBeacon() } else { advertisingOperation.stopAdvertisingBeacon() } } /** Starts/stops the ranging operation, depending on the state of the given switch. :param: rangingSwitch The ranging UISwitch instance. */ func changeRangingState(rangingSwitch: UISwitch) { if rangingSwitch.on { rangingOperation.startRangingForBeacons() } else { rangingOperation.stopRangingForBeacons() } } } // MARK: - Monitoring delegate methods and helpers extension NATViewController: NATMonitoringOperationDelegate { /** Triggered by the monitoring operation when it has started successfully and turns the monitoring switch and activity indicator on. */ func monitoringOperationDidStartSuccessfully() { monitoringSwitch?.on = true monitoringActivityIndicator?.startAnimating() } /** Triggered by the monitoring operation when it has stopped successfully and turns the activity indicator off. */ func monitoringOperationDidStopSuccessfully() { monitoringActivityIndicator?.stopAnimating() } /** Triggered by the monitoring operation whe it has failed to start and turns the monitoring switch off. */ func monitoringOperationDidFailToStart() { monitoringSwitch?.on = false } /** Triggered by the monitoring operation when it has failed to start due to the last authorization denial. It turns the monitoring switch off and presents a UIAlertView to prompt the user to change their location access settings. */ func monitoringOperationDidFailToStartDueToAuthorization() { let title = "Missing Location Access" let message = "Location Access (Always) is required. Click Settings to update the location access settings." let cancelButtonTitle = "Cancel" let settingsButtonTitle = "Settings" let alert = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: settingsButtonTitle) alert.show() monitoringSwitch?.on = false } /** Triggered by the monitoring operation when it has detected entering the provided region. It emits a local notification. :param: region The provided region that the monitoring operation detected. */ func monitoringOperationDidDetectEnteringRegion(region: CLBeaconRegion) { sendLocalNotificationForBeaconRegion(region) } /** Emits a UILocalNotification with information about the given region. Note that major and minor are not available at the monitoring stage. :param: region The given CLBeaconRegion instance. */ func sendLocalNotificationForBeaconRegion(region: CLBeaconRegion) { let notification = UILocalNotification() notification.alertBody = "Entered beacon region for UUID: " + region.proximityUUID.UUIDString notification.alertAction = "View Details" notification.soundName = UILocalNotificationDefaultSoundName UIApplication.sharedApplication().presentLocalNotificationNow(notification) } } // MARK: - Advertising delegate methods extension NATViewController: NATAdvertisingOperationDelegate { /** Triggered by the advertising operation when it has started successfully and turns the advertising switch and the activity indicator on. */ func advertisingOperationDidStartSuccessfully() { advertisingSwitch?.on = true advertisingActivityIndicator?.startAnimating() } /** Triggered by the advertising operation when it has stopped successfully and turns the activity indicator off. */ func advertisingOperationDidStopSuccessfully() { advertisingActivityIndicator?.stopAnimating() } /** Triggered by the advertising operation when ithas failed to start and turns the advertising switch off. */ func advertisingOperationDidFailToStart() { let title = "Bluetooth is off" let message = "It seems that Bluetooth is off. For advertising to work, please turn Bluetooth on." let cancelButtonTitle = "OK" let alert = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: cancelButtonTitle) alert.show() advertisingSwitch?.on = false } } // MARK: - Ranging delegate methods extension NATViewController: NATRangingOperationDelegate { /** Triggered by the ranging operation when it has started successfully. It turns the ranging switch on and resets the detectedBeacons array. */ func rangingOperationDidStartSuccessfully() { detectedBeacons = [] rangingSwitch?.on = true } /** Triggered by the ranging operation when it has failed to start and turns the ranging switch off. */ func rangingOperationDidFailToStart() { rangingSwitch?.on = false } /** Triggered by the ranging operation when it has failed to start due to the last authorization denial. It turns the ranging switch off and presents a UIAlertView to prompt the user to change their location access settings. */ func rangingOperationDidFailToStartDueToAuthorization() { let title = "Missing Location Access" let message = "Location Access (When In Use) is required. Click Settings to update the location access settings." let cancelButtonTitle = "Cancel" let settingsButtonTitle = "Settings" let alert = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: settingsButtonTitle) alert.show() rangingSwitch?.on = false } /** Triggered by the ranging operation when it has stopped successfully. It updates the beacon table view to reflect that the ranging has stopped. */ func rangingOperationDidStopSuccessfully() { detectedBeacons = [] beaconTableView?.beginUpdates() if let deletedSections = self.deletedSections() { beaconTableView?.deleteSections(deletedSections, withRowAnimation: UITableViewRowAnimation.Fade) } beaconTableView?.endUpdates() } /** Triggered by the ranging operation when it has detected beacons belonging to a specific given beacon region. It updates the table view to show the newly-found beacons. :param: beacons An array of provided beacons that the ranging operation detected. :param: region A provided region whose beacons the operation is trying to range. */ func rangingOperationDidRangeBeacons(beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { let filteredBeacons = self.filteredBeacons(beacons as! [CLBeacon]) if filteredBeacons.isEmpty { println("No beacons found nearby.") } else { let beaconsString: String if filteredBeacons.count > 1 { beaconsString = "beacons" } else { beaconsString = "beacon" } println("Found \(filteredBeacons.count) \(beaconsString).") } var insertedRows = indexPathsOfInsertedBeacons(filteredBeacons) var deletedRows = indexPathsOfRemovedBeacons(filteredBeacons) var reloadedRows: [NSIndexPath]? if deletedRows == nil && insertedRows == nil { reloadedRows = indexPathsForBeacons(filteredBeacons) } detectedBeacons = filteredBeacons beaconTableView?.beginUpdates() if insertedSections() != nil { beaconTableView?.insertSections(insertedSections()!, withRowAnimation: UITableViewRowAnimation.Fade) } if deletedSections() != nil { beaconTableView?.deleteSections(deletedSections()!, withRowAnimation: UITableViewRowAnimation.Fade) } if insertedRows != nil { beaconTableView?.insertRowsAtIndexPaths(insertedRows!, withRowAnimation: UITableViewRowAnimation.Fade) } if deletedRows != nil { beaconTableView?.deleteRowsAtIndexPaths(deletedRows!, withRowAnimation: UITableViewRowAnimation.Fade) } if reloadedRows != nil { beaconTableView?.reloadRowsAtIndexPaths(reloadedRows!, withRowAnimation: UITableViewRowAnimation.Fade) } beaconTableView?.endUpdates() } } // MARK: - Alert view delegate methods extension NATViewController: UIAlertViewDelegate { func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if buttonIndex == 1 { UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) } } } // MARK: Notifications extension NATViewController { /** Triggers any of the three operations in the app. It effectively reflects the actions taken on the watch by updating the action UI and triggering the operations, based on the updated UI. :param: notification The notification object that caused this method to be called. */ func performWatchAction(notification: NSNotification) { var payload = notification.userInfo as! [String : NSNumber] if let monitoringState = payload["Monitoring"] { monitoringSwitch?.on = monitoringState.boolValue changeMonitoringState(monitoringSwitch!) } else if let advertisingState = payload["Advertising"] { advertisingSwitch?.on = advertisingState.boolValue changeAdvertisingState(advertisingSwitch!) } else if let rangingState = payload["Ranging"] { rangingSwitch?.on = rangingState.boolValue changeRangingState(rangingSwitch!) } } } // MARK: - CLBeacon extension extension CLBeacon { /** Returns a specially-formatted description of the beacon's characteristics. :returns: The beacon's description. */ func fullDetails() -> String { let proximityText: String switch proximity { case .Near: proximityText = "Near" case .Immediate: proximityText = "Immediate" case .Far: proximityText = "Far" case .Unknown: proximityText = "Unknown" } return "\(major), \(minor) • \(proximityText) • \(accuracy) • \(rssi)" } }
54c9f9b7dfb7ebceb530a83704f97dcc
35.84116
157
0.662618
false
false
false
false
gogunskiy/The-Name
refs/heads/master
NameMe/Classes/UserInterface/ViewControllers/NMNameDetailsViewController/views/NMNameDetailsRecommendedCell.swift
mit
1
// // NMNameDetailsRecommendedCell.swift // NameMe // // Created by Vladimir Gogunsky on 1/9/15. // Copyright (c) 2015 Volodymyr Hohunskyi. All rights reserved. // import UIKit class NMNameDetailsRecommendedCell : NMNameDetailsBaseCell, GETagListViewDataSource { @IBOutlet weak var tagListView : GETagListView! weak var delegate : NMNameDetailsRecommendedCellDelegate! var items : NSArray = [] override func awakeFromNib() { tagListView.dataSource = self } override func update(nameDetails: NMNameItem?) { NEDataManager.sharedInstance.fetchRecommendedItems(nameDetails!.recommended!, completion: { (result) -> () in self.items = result dispatch_async(dispatch_get_main_queue(), { self.tagListView.reloadData() }) }) } func numberOfItemsInTagListView(tagListView: GETagListView) -> Int { return items.count } func tagListView(tagListView: GETagListView, itemAtIndex index: Int) -> String { return items[index].name as NSString } func tagListView(tagListView: GETagListView, didSelectItemAtIndex index: Int) { if let wDelegate = delegate { wDelegate.didSelectRecommendedCellItemAtIndex(items[index] as NMNameItem) } } func tagListViewDidReloadItems(tagListView: GETagListView) { self.height = tagListView.frame.size.height delegate.didReloadRecommendedCellItem() } } protocol NMNameDetailsRecommendedCellDelegate : NSObjectProtocol { func didReloadRecommendedCellItem(); func didSelectRecommendedCellItemAtIndex(item: NMNameItem); }
f597a4ff6dd9c44ef4c1da2b6a513256
27.416667
117
0.676246
false
false
false
false
strivingboy/CocoaChinaPlus
refs/heads/master
Code/CocoaChinaPlus/Application/Business/CocoaChina/Search/CCSearchViewController.swift
mit
1
// // CCAboutViewController.swift // CocoaChinaPlus // // Created by zixun on 15/10/3. // Copyright © 2015年 zixun. All rights reserved. // import UIKit import RxSwift import RxCocoa import Alamofire class CCSearchViewController: CCArticleTableViewController { //搜索条 private var searchfiled:UISearchBar! //取消按钮 private var cancelButton:UIButton! //RxSwift资源回收包 private let disposeBag = DisposeBag() required init(navigatorURL URL: NSURL, query: Dictionary<String, String>) { super.init(navigatorURL: URL, query: query) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge.None self.cancelButton = UIButton(frame: CGRectMake(0, 0, 44, 44)) self.cancelButton.setImage(UIImage.Asset.NavCancel.image, forState: UIControlState.Normal) self.navigationItem.rightBarButtonItemFixedSpace(UIBarButtonItem(customView: cancelButton)) self.searchfiled = UISearchBar() self.searchfiled.placeholder = "关键字必需大于2个字符哦" self.navigationItem.titleView = self.searchfiled self.subscribes() } private func subscribes() { //取消按钮点击Observable self.cancelButton.rx_tap .subscribeNext { [weak self] x in guard let sself = self else { return } sself.dismissViewControllerAnimated(true, completion: nil) } .addDisposableTo(disposeBag) //tableView滚动偏移量Observable self.tableView.rx_contentOffset .subscribe { [weak self] _ in guard let control = self else { return } if control.searchfiled.isFirstResponder() { _ = control.searchfiled.resignFirstResponder() } } .addDisposableTo(disposeBag) //搜索框搜索按钮点击Observable self.searchfiled.rx_delegate .observe("searchBarSearchButtonClicked:") .map { [weak self] (field) -> PublishSubject<[CCArticleModel]> in guard let sself = self else { return PublishSubject<[CCArticleModel]>() } sself.tableView.clean() return CCHTMLModelHandler.sharedHandler .handleSearchPage(sself.searchfiled.text!, loadNextPageTrigger: sself.loadNextPageTrigger) } .switchLatest() .subscribeNext { [weak self] (models) -> Void in guard let sself = self else { return } sself.tableView.append(models) sself.tableView.infiniteScrollingView.stopAnimating() } .addDisposableTo(disposeBag) } }
ea0eef0327776d8b037e144ebdb99b0d
30.222222
110
0.567777
false
false
false
false
apple/swift-system
refs/heads/main
Sources/System/Internals/CInterop.swift
apache-2.0
1
/* This source file is part of the Swift System open source project Copyright (c) 2020 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ // MARK: - Public typealiases /// The C `mode_t` type. /*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ @available(*, deprecated, renamed: "CInterop.Mode") public typealias CModeT = CInterop.Mode #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android) @_implementationOnly import CSystem import Glibc #elseif os(Windows) import CSystem import ucrt #else #error("Unsupported Platform") #endif /// A namespace for C and platform types /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ public enum CInterop { #if os(Windows) public typealias Mode = CInt #else public typealias Mode = mode_t #endif /// The C `char` type public typealias Char = CChar #if os(Windows) /// The platform's preferred character type. On Unix, this is an 8-bit C /// `char` (which may be signed or unsigned, depending on platform). On /// Windows, this is `UInt16` (a "wide" character). public typealias PlatformChar = UInt16 #else /// The platform's preferred character type. On Unix, this is an 8-bit C /// `char` (which may be signed or unsigned, depending on platform). On /// Windows, this is `UInt16` (a "wide" character). public typealias PlatformChar = CInterop.Char #endif #if os(Windows) /// The platform's preferred Unicode encoding. On Unix this is UTF-8 and on /// Windows it is UTF-16. Native strings may contain invalid Unicode, /// which will be handled by either error-correction or failing, depending /// on API. public typealias PlatformUnicodeEncoding = UTF16 #else /// The platform's preferred Unicode encoding. On Unix this is UTF-8 and on /// Windows it is UTF-16. Native strings may contain invalid Unicode, /// which will be handled by either error-correction or failing, depending /// on API. public typealias PlatformUnicodeEncoding = UTF8 #endif }
1e9a3af7cfb1a01912e083456208b84c
32.5
77
0.711895
false
false
false
false
postmanlabs/httpsnippet
refs/heads/master
test/fixtures/output/swift/nsurlsession/multipart-file.swift
mit
2
import Foundation let headers = ["content-type": "multipart/form-data; boundary=---011000010111000001101001"] let parameters = [ [ "name": "foo", "fileName": "test/fixtures/files/hello.txt", "contentType": "text/plain" ] ] let boundary = "---011000010111000001101001" var body = "" var error: NSError? = nil for param in parameters { let paramName = param["name"]! body += "--\(boundary)\r\n" body += "Content-Disposition:form-data; name=\"\(paramName)\"" if let filename = param["fileName"] { let contentType = param["content-type"]! let fileContent = String(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: &error) if (error != nil) { println(error) } body += "; filename=\"\(filename)\"\r\n" body += "Content-Type: \(contentType)\r\n\r\n" body += fileContent! } else if let paramValue = param["value"] { body += "\r\n\r\n\(paramValue)" } } var request = NSMutableURLRequest(URL: NSURL(string: "http://mockbin.com/har")!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10.0) request.HTTPMethod = "POST" request.allHTTPHeaderFields = headers request.HTTPBody = postData let session = NSURLSession.sharedSession() let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if (error != nil) { println(error) } else { let httpResponse = response as? NSHTTPURLResponse println(httpResponse) } }) dataTask.resume()
1b24b82447466cb25e50943bf22137da
29.411765
107
0.642811
false
false
false
false
Shivol/Swift-CS333
refs/heads/master
examples/swift/Swift Standard Library 2.playground/Pages/Understanding Collection Protocols.xcplaygroundpage/Sources/FinishedTimeline.swift
mit
3
import UIKit private let calendar = Calendar.current private var dateFormatter: DateFormatter? private struct DateIndex: CustomDebugStringConvertible, Comparable { typealias Distance = Int let date: Date init (_ date: Date) { self.date = calendar.startOfDay(for: date) } var debugDescription: String { if dateFormatter == nil { dateFormatter = DateFormatter() dateFormatter!.dateFormat = "MMMM d" } return dateFormatter!.string(from: date) } public static func == (lhs: DateIndex, rhs: DateIndex) -> Bool { return lhs.date == rhs.date } public static func < (lhs: DateIndex, rhs: DateIndex) -> Bool { return lhs.date.compare(rhs.date) == .orderedAscending } } private func dateIsOrderedBefore(lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == .orderedAscending } private struct ImageTimeline: RandomAccessCollection { private var storage: [Date: UIImage] = [:] var startIndex = DateIndex(Date.distantPast) var endIndex = DateIndex(Date.distantPast) subscript (i: DateIndex) -> UIImage? { get { return storage[i.date] } set { if let value = newValue { // Adding a value storage[i.date] = value if isEmpty { startIndex = i endIndex = index(after: i) } else if i < startIndex { startIndex = i } else if i >= endIndex { endIndex = index(after: i) } } else { // Removing a value storage[i.date] = nil // Update start and/or end index if we've removed the first/last item if i == startIndex { if let newStartDate = storage.keys.sorted(by: dateIsOrderedBefore).first { startIndex = DateIndex(newStartDate) } else { startIndex = DateIndex(Date.distantPast) endIndex = startIndex } } else if i == endIndex { if let newEndDate = storage.keys.sorted(by: dateIsOrderedBefore).last { endIndex = index(after: DateIndex(newEndDate)) } else { startIndex = DateIndex(Date.distantPast) endIndex = startIndex } } } } } subscript (date: Date) -> UIImage? { get { return self[DateIndex(date)] } set { self[DateIndex(date)] = newValue } } func index(after i: DateIndex) -> DateIndex { let nextDay = calendar.date(byAdding: .day, value: 1, to: i.date)! return DateIndex(nextDay) } func index(before i: DateIndex) -> DateIndex { let previousDay = calendar.date(byAdding: .day, value: -1, to: i.date)! return DateIndex(previousDay) } func distance(from start: DateIndex, to end: DateIndex) -> Int { return calendar.dateComponents([.day], from: start.date, to: end.date).day! } func index(_ i: DateIndex, offsetBy n: Int) -> DateIndex { let offsetDate = calendar.date(byAdding: .day, value: n, to: i.date)! return DateIndex(offsetDate) } } public var finishedApp: UIView = { var dates = ImageTimeline() for elem in loadElements() { dates[elem.date] = elem.image } return visualize(dates) }()
566e82197533f5ba859710413e1efebe
28.709677
94
0.53013
false
false
false
false
eddiekaiger/SwiftyDate
refs/heads/master
SwiftyDate/SwiftyDate.swift
mit
1
/** The MIT License (MIT) Copyright (c) 2015 Eddie Kaiger 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 /** This class is used as the middleman for easily constructing a relative date based on extensions from Swift number types. It is not intended to be used independently. Instead, use SwiftyDate's extensions to construct statements such as `12.days.ago()`. */ public struct SwiftyDate { let seconds: TimeInterval /** Initializes a new SwiftyDate object. - parameter seconds: The total number of seconds to be used as a relative timestamp. */ public init(seconds: TimeInterval) { self.seconds = seconds } /** Returns a `Date` that represents the specified amount of time ahead of the current date. */ public func fromNow() -> Date { return Date(timeIntervalSinceNow: seconds) } /** Returns a `Date` that represents the specified amount of time before the current date. */ public func ago() -> Date { return before(Date()) } /** Returns an `Date` that represents the specified amount of time after a certain date. - parameter date: The date of comparison. */ public func after(_ date: Date) -> Date { return Date(timeInterval: seconds, since: date) } /** Returns a `Date` that represents the specified amount of time before a certain date. - parameter date: The date of comparison. */ public func before(_ date: Date) -> Date { return Date(timeInterval: -seconds, since: date) } } /** Constants */ private let secondsInMinute: TimeInterval = 60 private let secondsInHour: TimeInterval = 3600 private let secondsInDay: TimeInterval = 86400 private let secondsInWeek: TimeInterval = 604800 public protocol TimeNumber { var timeValue: TimeInterval { get } } extension TimeNumber { private func swiftDate(_ secondsInUnit: TimeInterval) -> SwiftyDate { return SwiftyDate(seconds: timeValue * secondsInUnit) } public var seconds: SwiftyDate { return swiftDate(1) } public var minutes: SwiftyDate { return swiftDate(secondsInMinute) } public var hours: SwiftyDate { return swiftDate(secondsInHour) } public var days: SwiftyDate { return swiftDate(secondsInDay) } public var weeks: SwiftyDate { return swiftDate(secondsInWeek) } } extension UInt8: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension Int8: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension UInt16: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension Int16: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension UInt32: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension Int32: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension UInt64: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension Int64: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension UInt: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension Int: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension Float: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } } extension NSNumber: TimeNumber { public var timeValue: TimeInterval { return doubleValue } } extension TimeInterval: TimeNumber { public var timeValue: TimeInterval { return self } } extension CGFloat: TimeNumber { public var timeValue: TimeInterval { return TimeInterval(self) } }
7d2e5f127940ac9cfefdfea28967860d
30.057692
99
0.719298
false
false
false
false
peigen/iLife
refs/heads/master
iLife/AppItem.swift
gpl-3.0
1
// // AppItem.swift // iLife // // Created by peigen on 14-6-29. // Copyright (c) 2014年 Peigen.info. All rights reserved. // import Foundation class AppItem{ var name: String = "" var openURL: String = "" var icon : String = "" var lastOpenDate : NSDate? var openTimes : Int16? func toString() { println("AppItem[name=\(name) , openURL=\(openURL) , icon=\(icon), lastOpenDate=\(lastOpenDate),openTimes=\(openTimes)]") } init(name:String,openURL:String) { self.name = name self.openURL = openURL } init(name:String,openURL:String,icon:String,lastOpenDate:NSDate?,openTimes:Int16?) { self.name = name self.openURL = openURL } }
813162c8ee43990dd8cc7936187c6899
19.060606
123
0.670197
false
false
false
false
ReactiveKit/ReactiveGitter
refs/heads/master
Carthage/Checkouts/Bond/Sources/Bond/AppKit/NSButton.swift
gpl-3.0
2
// // The MIT License (MIT) // // Copyright (c) 2016 Tony Arnold (@tonyarnold) // // 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. // #if os(macOS) import AppKit import ReactiveKit public extension ReactiveExtensions where Base: NSButton { public var state: DynamicSubject<Int> { return dynamicSubject( signal: controlEvent.eraseType(), get: { $0.state }, set: { $0.state = $1 } ) } public var title: Bond<String> { return bond { $0.title = $1 } } public var alternateTitle: Bond<String> { return bond { $0.alternateTitle = $1 } } public var image: Bond<NSImage?> { return bond { $0.image = $1 } } public var alternateImage: Bond<NSImage?> { return bond { $0.alternateImage = $1 } } public var imagePosition: Bond<NSCellImagePosition> { return bond { $0.imagePosition = $1 } } public var imageScaling: Bond<NSImageScaling> { return bond { $0.imageScaling = $1 } } @available(macOS 10.12, *) public var imageHugsTitle: Bond<Bool> { return bond { $0.imageHugsTitle = $1 } } public var isBordered: Bond<Bool> { return bond { $0.isBordered = $1 } } public var isTransparent: Bond<Bool> { return bond { $0.isTransparent = $1 } } public var keyEquivalent: Bond<String> { return bond { $0.keyEquivalent = $1 } } public var keyEquivalentModifierMask: Bond<NSEventModifierFlags> { return bond { $0.keyEquivalentModifierMask = $1 } } @available(macOS 10.10.3, *) public var isSpringLoaded: Bond<Bool> { return bond { $0.isSpringLoaded = $1 } } @available(macOS 10.10.3, *) public var maxAcceleratorLevel: Bond<Int> { return bond { $0.maxAcceleratorLevel = $1 } } @available(macOS 10.12.2, *) public var bezelColor: Bond<NSColor?> { return bond { $0.bezelColor = $1 } } public var attributedTitle: Bond<NSAttributedString> { return bond { $0.attributedTitle = $1 } } public var attributedAlternateTitle: Bond<NSAttributedString> { return bond { $0.attributedAlternateTitle = $1 } } public var bezelStyle: Bond<NSBezelStyle> { return bond { $0.bezelStyle = $1 } } public var allowsMixedState: Bond<Bool> { return bond { $0.allowsMixedState = $1 } } public var showsBorderOnlyWhileMouseInside: Bond<Bool> { return bond { $0.showsBorderOnlyWhileMouseInside = $1 } } public var sound: Bond<NSSound?> { return bond { $0.sound = $1 } } } #endif
094c6ebdc2791a1c114aeabbfa7478a8
26.944
81
0.681076
false
false
false
false
Binlogo/One3-iOS-Swift
refs/heads/master
One3-iOS/Extensions/UI/UIImageExtensions.swift
mit
2
// // UIImageExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/6/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import UIKit // MARK: - Properties public extension UIImage { /// SwifterSwift: Size in bytes of UIImage public var bytesSize: Int { return UIImageJPEGRepresentation(self, 1)?.count ?? 0 } /// SwifterSwift: Size in kilo bytes of UIImage public var kilobytesSize: Int { return bytesSize / 1024 } } // MARK: - Methods public extension UIImage { /// SwifterSwift: Compressed UIImage from original UIImage. /// /// - Parameter quality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality), (default is 0.5). /// - Returns: optional UIImage (if applicable). public func compressed(quality: CGFloat = 0.5) -> UIImage? { guard let data = compressedData(quality: quality) else { return nil } return UIImage(data: data) } /// SwifterSwift: Compressed UIImage data from original UIImage. /// /// - Parameter quality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality), (default is 0.5). /// - Returns: optional Data (if applicable). public func compressedData(quality: CGFloat = 0.5) -> Data? { return UIImageJPEGRepresentation(self, quality) } /// SwifterSwift: UIImage Cropped to CGRect. /// /// - Parameter rect: CGRect to crop UIImage to. /// - Returns: cropped UIImage public func cropped(to rect: CGRect) -> UIImage { guard rect.size.height < self.size.height && rect.size.height < self.size.height else { return self } guard let cgImage: CGImage = self.cgImage?.cropping(to: rect) else { return self } return UIImage(cgImage: cgImage) } /// SwifterSwift: UIImage scaled to height with respect to aspect ratio. /// /// - Parameters: /// - toHeight: new height. /// - orientation: optional UIImage orientation (default is nil). /// - Returns: optional scaled UIImage (if applicable). public func scaled(toHeight: CGFloat, with orientation: UIImageOrientation? = nil) -> UIImage? { let scale = toHeight / self.size.height let newWidth = self.size.width * scale UIGraphicsBeginImageContext(CGSize(width: newWidth, height: toHeight)) self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: toHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /// SwifterSwift: UIImage scaled to width with respect to aspect ratio. /// /// - Parameters: /// - toWidth: new width. /// - orientation: optional UIImage orientation (default is nil). /// - Returns: optional scaled UIImage (if applicable). public func scaled(toWidth: CGFloat, with orientation: UIImageOrientation? = nil) -> UIImage? { let scale = toWidth / self.size.width let newHeight = self.size.height * scale UIGraphicsBeginImageContext(CGSize(width: toWidth, height: newHeight)) self.draw(in: CGRect(x: 0, y: 0, width: toWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /// SwifterSwift: UIImage filled with color /// /// - Parameter color: color to fill image with. /// - Returns: UIImage filled with given color. public func filled(withColor color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) color.setFill() guard let context = UIGraphicsGetCurrentContext() else { return self } context.translateBy(x: 0, y: self.size.height) context.scaleBy(x: 1.0, y: -1.0); context.setBlendMode(CGBlendMode.normal) let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) guard let mask = self.cgImage else { return self } context.clip(to: rect, mask: mask) context.fill(rect) guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return self } UIGraphicsEndImageContext() return newImage } } // MARK: - Initializers public extension UIImage { /// SwifterSwift: Create UIImage from color and size. /// /// - Parameters: /// - color: image fill color. /// - size: image size. public convenience init(color: UIColor, size: CGSize) { UIGraphicsBeginImageContextWithOptions(size, false, 1) color.setFill() UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() self.init(cgImage: image.cgImage!) } }
111467f1b06dd695789ec5dab86d5460
31.951389
263
0.715701
false
false
false
false
ws4715535/WSWeiBo
refs/heads/master
Weibo/Weibo/Classes/Home(首页)/HomeViewController.swift
apache-2.0
1
// // HomeViewController.swift // Weibo // // Created by Ws on 16/1/7. // Copyright © 2016年 Ws. All rights reserved. // import UIKit class HomeViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
29fcdab447189fc011fc476d5c2257a0
32.778947
157
0.684949
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/MainClass/Mine/CWPersonalInfoController.swift
mit
2
// // CWPersonalInfoController.swift // CWWeChat // // Created by chenwei on 2017/4/12. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit /// 个人信息 class CWPersonalInfoController: CWBaseTableViewController { var contactManager = CWChatClient.share.contactManager lazy var tableViewManager: CWTableViewManager = { let tableViewManager = CWTableViewManager(tableView: self.tableView) tableViewManager.delegate = self return tableViewManager }() override func viewDidLoad() { super.viewDidLoad() self.title = "个人信息" setupItemData() let currentUser = contactManager.userInfo(with: CWChatClient.share.userId) log.debug(currentUser.userInfo) let rightItem = UIBarButtonItem(title: "提交", style: .done, target: self, action: #selector(updateUserInfo)) self.navigationItem.rightBarButtonItem = rightItem contactManager.addContactDelegate(self, delegateQueue: DispatchQueue.main) } @objc func updateUserInfo() { contactManager.updateMyUserInfo([CWUserInfoUpdateTag.sign: "我是一个好的开发者"]) } deinit { contactManager.removeContactDelegate(self) } } extension CWPersonalInfoController { func setupItemData() { let avatarItem = CWTableViewItem(title: "头像") avatarItem.cellHeight = 87 avatarItem.rightImageURL = URL(string: "\(kImageBaseURLString)chenwei.jpg") let nikename = "武藤游戏boy" let nikenameItem = CWTableViewItem(title: "名字", subTitle: nikename) let usernameItem = CWTableViewItem(title: "微信号", subTitle: "chenwei") usernameItem.showDisclosureIndicator = false let qrCodeItem = CWTableViewItem(title: "我的二维码") let locationItem = CWTableViewItem(title: "我的地址") let section1 = CWTableViewSection(items: [avatarItem, nikenameItem, usernameItem, qrCodeItem, locationItem]) let sexItem = CWTableViewItem(title: "性别", subTitle: "男") let cityItem = CWTableViewItem(title: "地区", subTitle: "中国") let mottoItem = CWTableViewItem(title: "个性签名", subTitle: "hello world") let section2 = CWTableViewSection(items: [sexItem, cityItem, mottoItem]) tableViewManager.addSection(contentsOf: [section1, section2]) } } extension CWPersonalInfoController: CWTableViewManagerDelegate { } extension CWPersonalInfoController: CWContactManagerDelegate { func onUserInfoChanged(user: CWUser) { log.debug(user.userInfo.sign ?? "未设置签名") } }
7be4b892c71af5d05f517b9ba53e1310
28.931818
116
0.670463
false
false
false
false
Acidburn0zzz/firefox-ios
refs/heads/main
Client/Frontend/Theme/ThemedWidgets.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class ThemedTableViewCell: UITableViewCell, Themeable { var detailTextColor = UIColor.theme.tableView.disabledRowText override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { textLabel?.textColor = UIColor.theme.tableView.rowText detailTextLabel?.textColor = detailTextColor backgroundColor = UIColor.theme.tableView.rowBackground tintColor = UIColor.theme.general.controlTint } } class ThemedTableViewController: UITableViewController, Themeable { override init(style: UITableView.Style = .grouped) { super.init(style: style) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = ThemedTableViewCell(style: .subtitle, reuseIdentifier: nil) return cell } override func viewDidLoad() { super.viewDidLoad() applyTheme() } func applyTheme() { tableView.separatorColor = UIColor.theme.tableView.separator tableView.backgroundColor = UIColor.theme.tableView.headerBackground tableView.reloadData() (tableView.tableHeaderView as? Themeable)?.applyTheme() } } class ThemedTableSectionHeaderFooterView: UITableViewHeaderFooterView, Themeable { private struct UX { static let titleHorizontalPadding: CGFloat = 15 static let titleVerticalPadding: CGFloat = 6 static let titleVerticalLongPadding: CGFloat = 20 } enum TitleAlignment { case top case bottom } var titleAlignment: TitleAlignment = .bottom { didSet { remakeTitleAlignmentConstraints() } } lazy var titleLabel: UILabel = { var headerLabel = UILabel() headerLabel.font = UIFont.systemFont(ofSize: 12.0, weight: UIFont.Weight.regular) headerLabel.numberOfLines = 0 return headerLabel }() fileprivate lazy var bordersHelper = ThemedHeaderFooterViewBordersHelper() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.addSubview(titleLabel) bordersHelper.initBorders(view: self.contentView) setDefaultBordersValues() setupInitialConstraints() applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { bordersHelper.applyTheme() contentView.backgroundColor = UIColor.theme.tableView.headerBackground titleLabel.textColor = UIColor.theme.tableView.headerTextLight } func setupInitialConstraints() { remakeTitleAlignmentConstraints() } func showBorder(for location: ThemedHeaderFooterViewBordersHelper.BorderLocation, _ show: Bool) { bordersHelper.showBorder(for: location, show) } func setDefaultBordersValues() { bordersHelper.showBorder(for: .top, false) bordersHelper.showBorder(for: .bottom, false) } override func prepareForReuse() { super.prepareForReuse() setDefaultBordersValues() titleLabel.text = nil titleAlignment = .bottom applyTheme() } fileprivate func remakeTitleAlignmentConstraints() { switch titleAlignment { case .top: titleLabel.snp.remakeConstraints { make in make.left.right.equalTo(self.contentView).inset(UX.titleHorizontalPadding) make.top.equalTo(self.contentView).offset(UX.titleVerticalPadding) make.bottom.equalTo(self.contentView).offset(-UX.titleVerticalLongPadding) } case .bottom: titleLabel.snp.remakeConstraints { make in make.left.right.equalTo(self.contentView).inset(UX.titleHorizontalPadding) make.bottom.equalTo(self.contentView).offset(-UX.titleVerticalPadding) make.top.equalTo(self.contentView).offset(UX.titleVerticalLongPadding) } } } } class ThemedHeaderFooterViewBordersHelper: Themeable { enum BorderLocation { case top case bottom } fileprivate lazy var topBorder: UIView = { let topBorder = UIView() return topBorder }() fileprivate lazy var bottomBorder: UIView = { let bottomBorder = UIView() return bottomBorder }() func showBorder(for location: BorderLocation, _ show: Bool) { switch location { case .top: topBorder.isHidden = !show case .bottom: bottomBorder.isHidden = !show } } func initBorders(view: UIView) { view.addSubview(topBorder) view.addSubview(bottomBorder) topBorder.snp.makeConstraints { make in make.left.right.top.equalTo(view) make.height.equalTo(0.25) } bottomBorder.snp.makeConstraints { make in make.left.right.bottom.equalTo(view) make.height.equalTo(0.5) } } func applyTheme() { topBorder.backgroundColor = UIColor.theme.tableView.separator bottomBorder.backgroundColor = UIColor.theme.tableView.separator } } class UISwitchThemed: UISwitch { override func layoutSubviews() { super.layoutSubviews() onTintColor = UIColor.theme.general.controlTint } }
5030861336c14de89c78c38cc0acae7f
29.937173
109
0.66221
false
false
false
false
banDedo/BDModules
refs/heads/master
Harness/HarnessTests/Networking/OAuth2SessionManagerTests.swift
apache-2.0
1
// // OAuth2AuthorizationTests.swift // BDModules // // Created by Patrick Hogan on 1/11/15. // Copyright (c) 2015 bandedo. All rights reserved. // import BDModules import Foundation import XCTest class OAuth2AuthorizationTests: XCTestCase { var mockTask = MockURLSessionDataTask() lazy var mockAccountUserProvider = MockAccountUserProvider() lazy var mockSessionManager = MockOAuth2SessionManager() lazy var oAuth2Authorization = OAuth2Authorization() override func setUp() { super.setUp() mockTask = MockURLSessionDataTask() mockAccountUserProvider = MockAccountUserProvider() mockAccountUserProvider.backingOAuth2Credential = OAuth2Credential( accessToken: "access_token", refreshToken: "refresh_token" ) mockSessionManager = MockOAuth2SessionManager() oAuth2Authorization = OAuth2Authorization( jsonSerializer: JSONSerializer(), oAuth2SessionManager: mockSessionManager, oAuth2CredentialHandler: { self.mockAccountUserProvider.oAuth2Credential } ) } func testShouldNotHandleResponseInAbsenceOfError() { var didCallback = false oAuth2Authorization.performAuthenticatedRequest( requestHandler: { handler in }) { urlSessionDataTask, responseObject, error in didCallback = true } XCTAssertFalse(didCallback) } func testShouldNotHandleResponseIfStatusCodeIsNot401() { var didCallback = false mockTask.mockResponse.code = 403 oAuth2Authorization.performAuthenticatedRequest( requestHandler: { handler in }) { urlSessionDataTask, responseObject, error in didCallback = true } XCTAssertFalse(didCallback) } func testShouldCallHandlerOnSuccessfulRefresh() { var requestCounter = 0 var didCallback = false oAuth2Authorization.performAuthenticatedRequest( requestHandler: { handler in handler(self.mockTask, nil, requestCounter++ == 0 ? NSError() : nil) }) { urlSessionDataTask, responseObject, error in if error == nil { didCallback = true } } XCTAssertTrue(didCallback) } func testAuthorizationHandlerShouldNotRetryRequestOnFailedRefresh() { mockSessionManager.shouldRefreshSuccessfully = false var didReturnError = false oAuth2Authorization.performAuthenticatedRequest( requestHandler: { handler in handler(self.mockTask, nil, NSError()) }) { urlSessionDataTask, responseObject, error in if error != nil { didReturnError = true } } XCTAssertTrue(didReturnError) XCTAssertEqual(mockSessionManager.refreshRetryCounter, 1) } }
29d247a89902e1036dd704349b4fa9f8
27.75
90
0.615459
false
true
false
false
AlanJN/ios-charts
refs/heads/master
Charts/Classes/Charts/ChartViewBase.swift
apache-2.0
12
// // ChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // // Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880 import Foundation import UIKit @objc public protocol ChartViewDelegate { /// Called when a value has been selected inside the chart. /// - parameter entry: The selected Entry. /// - parameter dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in. optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight) // Called when nothing has been selected or an "un-select" has been made. optional func chartValueNothingSelected(chartView: ChartViewBase) // Callbacks when the chart is scaled / zoomed via pinch zoom gesture. optional func chartScaled(chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) // Callbacks when the chart is moved / translated via drag gesture. optional func chartTranslated(chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) } public class ChartViewBase: UIView, ChartAnimatorDelegate { // MARK: - Properties /// custom formatter that is used instead of the auto-formatter if set internal var _valueFormatter = NSNumberFormatter() /// the default value formatter internal var _defaultValueFormatter = NSNumberFormatter() /// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied internal var _data: ChartData! /// If set to true, chart continues to scroll after touch up public var dragDecelerationEnabled = true /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. private var _dragDecelerationFrictionCoef: CGFloat = 0.9 /// font object used for drawing the description text in the bottom right corner of the chart public var descriptionFont: UIFont? = UIFont(name: "HelveticaNeue", size: 9.0) public var descriptionTextColor: UIColor! = UIColor.blackColor() /// font object for drawing the information text when there are no values in the chart public var infoFont: UIFont! = UIFont(name: "HelveticaNeue", size: 12.0) public var infoTextColor: UIColor! = UIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange /// description text that appears in the bottom right corner of the chart public var descriptionText = "Description" /// flag that indicates if the chart has been fed with data yet internal var _dataNotSet = true /// if true, units are drawn next to the values in the chart internal var _drawUnitInChart = false /// the number of x-values the chart displays internal var _deltaX = CGFloat(1.0) internal var _chartXMin = Double(0.0) internal var _chartXMax = Double(0.0) /// the legend object containing all data associated with the legend internal var _legend: ChartLegend! /// delegate to receive chart events public weak var delegate: ChartViewDelegate? /// text that is displayed when the chart is empty public var noDataText = "No chart data available." /// text that is displayed when the chart is empty that describes why the chart is empty public var noDataTextDescription: String? internal var _legendRenderer: ChartLegendRenderer! /// object responsible for rendering the data public var renderer: ChartDataRendererBase? internal var _highlighter: ChartHighlighter? /// object that manages the bounds and drawing constraints of the chart internal var _viewPortHandler: ChartViewPortHandler! /// object responsible for animations internal var _animator: ChartAnimator! /// flag that indicates if offsets calculation has already been done or not private var _offsetsCalculated = false /// array of Highlight objects that reference the highlighted slices in the chart internal var _indicesToHightlight = [ChartHighlight]() /// if set to true, the marker is drawn when a value is clicked public var drawMarkers = true /// the view that represents the marker public var marker: ChartMarker? private var _interceptTouchEvents = false /// An extra offset to be appended to the viewport's top public var extraTopOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's right public var extraRightOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's bottom public var extraBottomOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's left public var extraLeftOffset: CGFloat = 0.0 public func setExtraOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { extraLeftOffset = left extraTopOffset = top extraRightOffset = right extraBottomOffset = bottom } // MARK: - Initializers public override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } deinit { self.removeObserver(self, forKeyPath: "bounds") self.removeObserver(self, forKeyPath: "frame") } internal func initialize() { _animator = ChartAnimator() _animator.delegate = self _viewPortHandler = ChartViewPortHandler() _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height) _legend = ChartLegend() _legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend) _defaultValueFormatter.minimumIntegerDigits = 1 _defaultValueFormatter.maximumFractionDigits = 1 _defaultValueFormatter.minimumFractionDigits = 1 _defaultValueFormatter.usesGroupingSeparator = true _valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil) self.addObserver(self, forKeyPath: "frame", options: .New, context: nil) } // MARK: - ChartViewBase /// The data for the chart public var data: ChartData? { get { return _data } set { if (newValue == nil || newValue?.yValCount == 0) { print("Charts: data argument is nil on setData()", terminator: "\n") return } _dataNotSet = false _offsetsCalculated = false _data = newValue // calculate how many digits are needed calculateFormatter(min: _data.getYMin(), max: _data.getYMax()) notifyDataSetChanged() } } /// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()). public func clear() { _data = nil _dataNotSet = true _indicesToHightlight.removeAll() setNeedsDisplay() } /// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay(). public func clearValues() { if (_data !== nil) { _data.clearValues() } setNeedsDisplay() } /// - returns: true if the chart is empty (meaning it's data object is either null or contains no entries). public func isEmpty() -> Bool { if (_data == nil) { return true } else { if (_data.yValCount <= 0) { return true } else { return false } } } /// Lets the chart know its underlying data has changed and should perform all necessary recalculations. /// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour. public func notifyDataSetChanged() { fatalError("notifyDataSetChanged() cannot be called on ChartViewBase") } /// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position internal func calculateOffsets() { fatalError("calculateOffsets() cannot be called on ChartViewBase") } /// calcualtes the y-min and y-max value and the y-delta and x-delta value internal func calcMinMax() { fatalError("calcMinMax() cannot be called on ChartViewBase") } /// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter internal func calculateFormatter(min min: Double, max: Double) { // check if a custom formatter is set or not var reference = Double(0.0) if (_data == nil || _data.xValCount < 2) { let absMin = fabs(min) let absMax = fabs(max) reference = absMin > absMax ? absMin : absMax } else { reference = fabs(max - min) } let digits = ChartUtils.decimals(reference) _defaultValueFormatter.maximumFractionDigits = digits _defaultValueFormatter.minimumFractionDigits = digits } public override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() let frame = self.bounds if (_dataNotSet || _data === nil || _data.yValCount == 0) { // check if there is data CGContextSaveGState(context) // if no data, inform the user ChartUtils.drawText(context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor]) if (noDataTextDescription != nil && (noDataTextDescription!).characters.count > 0) { let textOffset = -infoFont.lineHeight / 2.0 ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0 + textOffset), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor]) } return } if (!_offsetsCalculated) { calculateOffsets() _offsetsCalculated = true } } /// draws the description text in the bottom right corner of the chart internal func drawDescription(context context: CGContext?) { if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0) { return } let frame = self.bounds var attrs = [String : AnyObject]() var font = descriptionFont if (font == nil) { font = UIFont.systemFontOfSize(UIFont.systemFontSize()) } attrs[NSFontAttributeName] = font attrs[NSForegroundColorAttributeName] = descriptionTextColor ChartUtils.drawText(context: context, text: descriptionText, point: CGPoint(x: frame.width - _viewPortHandler.offsetRight - 10.0, y: frame.height - _viewPortHandler.offsetBottom - 10.0 - font!.lineHeight), align: .Right, attributes: attrs) } // MARK: - Highlighting /// - returns: the array of currently highlighted values. This might an empty if nothing is highlighted. public var highlighted: [ChartHighlight] { return _indicesToHightlight } /// Checks if the highlight array is null, has a length of zero or if the first object is null. /// - returns: true if there are values to highlight, false if there are no values to highlight. public func valuesToHighlight() -> Bool { return _indicesToHightlight.count > 0 } /// Highlights the values at the given indices in the given DataSets. Provide /// null or an empty array to undo all highlighting. /// This should be used to programmatically highlight values. /// This DOES NOT generate a callback to the delegate. public func highlightValues(highs: [ChartHighlight]?) { // set the indices to highlight _indicesToHightlight = highs ?? [ChartHighlight]() if (_indicesToHightlight.isEmpty) { self.lastHighlighted = nil } // redraw the chart setNeedsDisplay() } /// Highlights the value at the given x-index in the given DataSet. /// Provide -1 as the x-index to undo all highlighting. public func highlightValue(xIndex xIndex: Int, dataSetIndex: Int, callDelegate: Bool) { if (xIndex < 0 || dataSetIndex < 0 || xIndex >= _data.xValCount || dataSetIndex >= _data.dataSetCount) { highlightValue(highlight: nil, callDelegate: callDelegate) } else { highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate) } } /// Highlights the value selected by touch gesture. public func highlightValue(highlight highlight: ChartHighlight?, callDelegate: Bool) { var entry: ChartDataEntry? var h = highlight if (h == nil) { _indicesToHightlight.removeAll(keepCapacity: false) } else { // set the indices to highlight entry = _data.getEntryForHighlight(h!) if (entry === nil || entry!.xIndex != h?.xIndex) { h = nil entry = nil _indicesToHightlight.removeAll(keepCapacity: false) } else { _indicesToHightlight = [h!] } } // redraw the chart setNeedsDisplay() if (callDelegate && delegate != nil) { if (h == nil) { delegate!.chartValueNothingSelected?(self) } else { // notify the listener delegate!.chartValueSelected?(self, entry: entry!, dataSetIndex: h!.dataSetIndex, highlight: h!) } } } /// The last value that was highlighted via touch. public var lastHighlighted: ChartHighlight? // MARK: - Markers /// draws all MarkerViews on the highlighted positions internal func drawMarkers(context context: CGContext?) { // if there is no marker view or drawing marker is disabled if (marker === nil || !drawMarkers || !valuesToHighlight()) { return } for (var i = 0, count = _indicesToHightlight.count; i < count; i++) { let highlight = _indicesToHightlight[i] let xIndex = highlight.xIndex if (xIndex <= Int(_deltaX) && xIndex <= Int(_deltaX * _animator.phaseX)) { let e = _data.getEntryForHighlight(highlight) if (e === nil || e!.xIndex != highlight.xIndex) { continue } let pos = getMarkerPosition(entry: e!, highlight: highlight) // check bounds if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y)) { continue } // callbacks to update the content marker!.refreshContent(entry: e!, highlight: highlight) let markerSize = marker!.size if (pos.y - markerSize.height <= 0.0) { let y = markerSize.height - pos.y marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y)) } else { marker!.draw(context: context, point: pos) } } } } /// - returns: the actual position in pixels of the MarkerView for the given Entry in the given DataSet. public func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { fatalError("getMarkerPosition() cannot be called on ChartViewBase") } // MARK: - Animation /// - returns: the animator responsible for animating chart values. public var animator: ChartAnimator! { return _animator } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingX: an easing function for the animation on the x axis /// - parameter easingY: an easing function for the animation on the y axis public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOptionX: the easing function for the animation on the x axis /// - parameter easingOptionY: the easing function for the animation on the y axis public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easing: an easing function for the animation public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easingOption: the easing function for the animation public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis public func animate(xAxisDuration xAxisDuration: NSTimeInterval) { _animator.animate(xAxisDuration: xAxisDuration) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis public func animate(yAxisDuration yAxisDuration: NSTimeInterval) { _animator.animate(yAxisDuration: yAxisDuration) } // MARK: - Accessors /// - returns: the current y-max value across all DataSets public var chartYMax: Double { return _data.yMax } /// - returns: the current y-min value across all DataSets public var chartYMin: Double { return _data.yMin } public var chartXMax: Double { return _chartXMax } public var chartXMin: Double { return _chartXMin } /// - returns: the total number of (y) values the chart holds (across all DataSets) public var getValueCount: Int { return _data.yValCount } /// *Note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)* /// - returns: the center point of the chart (the whole View) in pixels. public var midPoint: CGPoint { let bounds = self.bounds return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0) } /// - returns: the center of the chart taking offsets under consideration. (returns the center of the content rectangle) public var centerOffsets: CGPoint { return _viewPortHandler.contentCenter } /// - returns: the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend. public var legend: ChartLegend { return _legend } /// - returns: the renderer object responsible for rendering / drawing the Legend. public var legendRenderer: ChartLegendRenderer! { return _legendRenderer } /// - returns: the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn). public var contentRect: CGRect { return _viewPortHandler.contentRect } /// Sets the formatter to be used for drawing the values inside the chart. /// If no formatter is set, the chart will automatically determine a reasonable /// formatting (concerning decimals) for all the values that are drawn inside /// the chart. Set this to nil to re-enable auto formatting. public var valueFormatter: NSNumberFormatter! { get { return _valueFormatter } set { if (newValue === nil) { _valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter } else { _valueFormatter = newValue } } } /// - returns: the x-value at the given index public func getXValue(index: Int) -> String! { if (_data == nil || _data.xValCount <= index) { return nil } else { return _data.xVals[index] } } /// Get all Entry objects at the given index across all DataSets. public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry] { var vals = [ChartDataEntry]() for (var i = 0, count = _data.dataSetCount; i < count; i++) { let set = _data.getDataSetByIndex(i) let e = set.entryForXIndex(xIndex) if (e !== nil) { vals.append(e!) } } return vals } /// - returns: the percentage the given value has of the total y-value sum public func percentOfTotal(val: Double) -> Double { return val / _data.yValueSum * 100.0 } /// - returns: the ViewPortHandler of the chart that is responsible for the /// content area of the chart and its offsets and dimensions. public var viewPortHandler: ChartViewPortHandler! { return _viewPortHandler } /// - returns: the bitmap that represents the chart. public func getChartImage(transparent transparent: Bool) -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, opaque || !transparent, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size) if (opaque || !transparent) { // Background color may be partially transparent, we must fill with white if we want to output an opaque image CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextFillRect(context, rect) if (self.backgroundColor !== nil) { CGContextSetFillColorWithColor(context, self.backgroundColor?.CGColor) CGContextFillRect(context, rect) } } layer.renderInOptionalContext(context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public enum ImageFormat { case JPEG case PNG } /// Saves the current chart state with the given name to the given path on /// the sdcard leaving the path empty "" will put the saved file directly on /// the SD card chart is saved as a PNG image, example: /// saveToPath("myfilename", "foldername1/foldername2") /// /// - parameter filePath: path to the image to save /// - parameter format: the format to save /// - parameter compressionQuality: compression quality for lossless formats (JPEG) /// /// - returns: true if the image was saved successfully public func saveToPath(path: String, format: ImageFormat, compressionQuality: Double) -> Bool { let image = getChartImage(transparent: format != .JPEG) var imageData: NSData! switch (format) { case .PNG: imageData = UIImagePNGRepresentation(image) break case .JPEG: imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality)) break } return imageData.writeToFile(path, atomically: true) } /// Saves the current state of the chart to the camera roll public func saveToCameraRoll() { UIImageWriteToSavedPhotosAlbum(getChartImage(transparent: false), nil, nil, nil) } internal typealias VoidClosureType = () -> () internal var _sizeChangeEventActions = [VoidClosureType]() public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (keyPath == "bounds" || keyPath == "frame") { let bounds = self.bounds if (_viewPortHandler !== nil && (bounds.size.width != _viewPortHandler.chartWidth || bounds.size.height != _viewPortHandler.chartHeight)) { _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height) // Finish any pending viewport changes while (!_sizeChangeEventActions.isEmpty) { _sizeChangeEventActions.removeAtIndex(0)() } notifyDataSetChanged() } } } public func clearPendingViewPortChanges() { _sizeChangeEventActions.removeAll(keepCapacity: false) } /// if true, value highlighting is enabled public var highlightEnabled: Bool { get { return _data === nil ? true : _data.highlightEnabled } set { if (_data !== nil) { _data.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// **default**: true /// - returns: true if chart continues to scroll after touch up, false if not. public var isDragDecelerationEnabled: Bool { return dragDecelerationEnabled } /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. /// /// **default**: true public var dragDecelerationFrictionCoef: CGFloat { get { return _dragDecelerationFrictionCoef } set { var val = newValue if (val < 0.0) { val = 0.0 } if (val >= 1.0) { val = 0.999 } _dragDecelerationFrictionCoef = val } } // MARK: - ChartAnimatorDelegate public func chartAnimatorUpdated(chartAnimator: ChartAnimator) { setNeedsDisplay() } public func chartAnimatorStopped(chartAnimator: ChartAnimator) { } // MARK: - Touches public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if (!_interceptTouchEvents) { super.touchesBegan(touches, withEvent: event) } } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if (!_interceptTouchEvents) { super.touchesMoved(touches, withEvent: event) } } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if (!_interceptTouchEvents) { super.touchesEnded(touches, withEvent: event) } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { if (!_interceptTouchEvents) { super.touchesCancelled(touches, withEvent: event) } } }
a313690afe48dea8d938723b687f14a8
35.703743
265
0.62453
false
false
false
false
sunlubo/TicTacToe
refs/heads/master
TiCTacToe/Board.swift
apache-2.0
1
// // Board.swift // TiCTacToe // // Created by sunlubo on 2017/2/9. // Copyright © 2017年 slb. All rights reserved. // import Foundation final class Board { enum GameState { case inProgress case finished } var cells = Array(repeating: Array(repeating: Cell(), count: 3), count: 3) var winner: Player! var currentTurn: Player! var state: GameState! init() { restart() } /// Restart or start a new game, will clear the board and win status. func restart() { clearCells() winner = nil currentTurn = .x state = .inProgress } /// Mark the current row for the player who's current turn it is. /// Will perform no-op if the arguments are out of range or if that position is already played. /// Will also perform a no-op if the game is already over. /// /// - Parameters: /// - row: 0..2 /// - col: 0..2 /// - Returns: the player that moved or nil if we did not move anything. func mark(row: Int, col: Int) -> Player? { guard isValid(row, col) else { return nil } let playerThatMoved = currentTurn cells[row][col].value = playerThatMoved if isWinningMoveByPlayer(currentTurn, row, col) { state = .finished winner = currentTurn } else { // flip the current turn and continue flipCurrentTurn() } return playerThatMoved } private func clearCells() { for i in 0..<3 { for j in 0..<3 { cells[i][j].value = nil } } } private func isValid(_ row: Int, _ col: Int) -> Bool { guard state != .finished else { return false } if isOutOfBounds(row) || isOutOfBounds(row) { return false } else if isCellValueAlreadySet(row, col) { return false } return true } private func isOutOfBounds(_ idx: Int) -> Bool { return idx < 0 || idx > 2 } private func isCellValueAlreadySet(_ row: Int, _ col: Int) -> Bool { return cells[row][col].value != nil } /// Algorithm adapted from http://www.ntu.edu.sg/home/ehchua/programming/java/JavaGame_TicTacToe.html /// /// - Parameters: /// - player: player /// - currentRow: currentRow /// - currentCol: currentCol /// - Returns: true if `player` who just played the move at the `currentRow`, `currentCol` has a tic tac toe. private func isWinningMoveByPlayer(_ player: Player, _ currentRow: Int, _ currentCol: Int) -> Bool { return (cells[currentRow][0].value == player // 3-in-the-row && cells[currentRow][1].value == player && cells[currentRow][2].value == player || cells[0][currentCol].value == player // 3-in-the-column && cells[1][currentCol].value == player && cells[2][currentCol].value == player || currentRow == currentCol // 3-in-the-diagonal && cells[0][0].value == player && cells[1][1].value == player && cells[2][2].value == player || currentRow + currentCol == 2 // 3-in-the-opposite-diagonal && cells[0][2].value == player && cells[1][1].value == player && cells[2][0].value == player) } private func flipCurrentTurn() { currentTurn = currentTurn == .x ? .o : .x } }
58ee295148e9b9827da7de6d91332ffe
29.577586
113
0.541021
false
false
false
false
google/iosched-ios
refs/heads/master
Source/Platform/Repository/Mapping/User+GIDSignIn.swift
apache-2.0
1
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import GoogleSignIn extension User { public init?(user googleUser: GIDGoogleUser) { // GIDGoogleUser's header doesn't have nullability annotations, // so this code is excessively cautious to avoid crashing. guard let id = googleUser.userID, let profile = googleUser.profile, let name = profile.name, let email = profile.email, // Set dimension to 3x the largest place we use it to account for high dpi screens. let imageURLString = profile.imageURL(withDimension: 72 * 3)?.absoluteString else { return nil } self.init(id: id, name: name, email: email, thumbnailURL: imageURLString) } }
b2bca4c09b119a54c0dc3bb8680f0c9b
36.647059
91
0.708594
false
false
false
false
yakirlee/TwitterDemo
refs/heads/master
TwitterDemo/TwitterDemo/TableViewCell.swift
mit
1
// // TableViewCell.swift // TwitterDemo // // Created by 李 on 16/4/24. // Copyright © 2016年 李. All rights reserved. // import UIKit import SnapKit private let margin = 10.0 class TableViewCell: UITableViewCell { var user: User? { didSet { statusView.user = user actionView.user = user } } // MARK: - 私有控件 private lazy var statusView = CellStatusView(frame: CGRectZero) private lazy var actionView = CellActionsView(frame: CGRectZero) override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI设计 extension TableViewCell { func setupUI() { contentView.addSubview(statusView) contentView.addSubview(actionView) statusView.snp_makeConstraints { (make) in make.left.equalTo(contentView) make.right.equalTo(contentView) make.top.equalTo(contentView) } actionView.snp_makeConstraints { (make) in make.left.equalTo(statusView).offset(8 * margin) make.top.equalTo(statusView.snp_bottom).offset(margin) make.right.equalTo(statusView) make.bottom.equalTo(contentView) } actionView.userInteractionEnabled = true // 性能调优 关键 异步绘制栅格化 layer.drawsAsynchronously = true layer.shouldRasterize = true layer.rasterizationScale = UIScreen.mainScreen().scale } }
0eb59f78e2578cba5d5a89b84e1dbec1
26.52459
74
0.620012
false
false
false
false
zoeyzhong520/SlidingMenu
refs/heads/master
SlidingMenu/SlidingMenu/SlidingMenuKit/View/SlidingMenuHeaderViewCell.swift
mit
1
// // SlidingMenuHeaderViewCell.swift // SlidingMenu // // Created by JOE on 2017/10/12. // Copyright © 2017年 Hongyear Information Technology (Shanghai) Co.,Ltd. All rights reserved. // import UIKit class SlidingMenuHeaderViewCell: UITableViewCell { var model:ChapterListModel? { didSet { showData() } } var noteModel:NoteListModel? { didSet { showNoteData() } } fileprivate func showNoteData() { for view in self.contentView.subviews { view.removeFromSuperview() } let detailView = UIView() self.contentView.addSubview(detailView) detailView.snp.makeConstraints { (make) in make.edges.equalTo(self.contentView) } let bookImgView = UIImageView() guard let imageUrl = noteModel?.bookPicture else { return } bookImgView.kf.setImage(with: zzj_URLWithString(BaseURL + imageUrl)) detailView.addSubview(bookImgView) bookImgView.snp.makeConstraints { (make) in make.centerY.equalTo(detailView) make.left.equalTo(detailView).offset(fontSizeScale(20)) make.width.equalTo(fontSizeScale(60)) make.height.equalTo(fontSizeScale(80)) } let bookNameLabel = UILabel() bookNameLabel.text = noteModel?.bookName bookNameLabel.font = zzj_SystemFontWithSize(15) bookNameLabel.textColor = UIColor.black bookNameLabel.textAlignment = .left detailView.addSubview(bookNameLabel) bookNameLabel.snp.makeConstraints { (make) in make.left.equalTo(bookImgView.snp.right).offset(fontSizeScale(10)) make.top.equalTo(detailView).offset(fontSizeScale(20)) make.right.equalTo(detailView) } let authorLabel = UILabel() authorLabel.text = noteModel?.author authorLabel.font = zzj_SystemFontWithSize(13) authorLabel.textColor = UIColor.gray authorLabel.textAlignment = .left detailView.addSubview(authorLabel) authorLabel.snp.makeConstraints { (make) in make.left.equalTo(bookImgView.snp.right).offset(fontSizeScale(10)) make.top.equalTo(bookNameLabel.snp.bottom).offset(fontSizeScale(20)) make.right.equalTo(detailView) } } fileprivate func showData() { for view in self.contentView.subviews { view.removeFromSuperview() } let detailView = UIView() self.contentView.addSubview(detailView) detailView.snp.makeConstraints { (make) in make.edges.equalTo(self.contentView) } let bookImgView = UIImageView() guard let imageUrl = model?.bookPicture else { return } bookImgView.kf.setImage(with: zzj_URLWithString(BaseURL + imageUrl)) detailView.addSubview(bookImgView) bookImgView.snp.makeConstraints { (make) in make.centerY.equalTo(detailView) make.left.equalTo(detailView).offset(fontSizeScale(20)) make.width.equalTo(fontSizeScale(60)) make.height.equalTo(fontSizeScale(80)) } let bookNameLabel = UILabel() bookNameLabel.text = model?.bookName bookNameLabel.font = zzj_SystemFontWithSize(15) bookNameLabel.textColor = UIColor.black bookNameLabel.textAlignment = .left detailView.addSubview(bookNameLabel) bookNameLabel.snp.makeConstraints { (make) in make.left.equalTo(bookImgView.snp.right).offset(fontSizeScale(10)) make.top.equalTo(detailView).offset(fontSizeScale(20)) make.right.equalTo(detailView) } let authorLabel = UILabel() authorLabel.text = model?.author authorLabel.font = zzj_SystemFontWithSize(13) authorLabel.textColor = UIColor.gray authorLabel.textAlignment = .left detailView.addSubview(authorLabel) authorLabel.snp.makeConstraints { (make) in make.left.equalTo(bookImgView.snp.right).offset(fontSizeScale(10)) make.top.equalTo(bookNameLabel.snp.bottom).offset(fontSizeScale(20)) make.right.equalTo(detailView) } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension SlidingMenuHeaderViewCell { ///创建cell的方法 class func createSlidingMenuCell(tableView: UITableView, atIndexPath indexPath: IndexPath, model: ChapterListModel?) -> SlidingMenuHeaderViewCell { let cellId = "SlidingMenuHeaderViewCellId" let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? SlidingMenuHeaderViewCell if cell == nil { printLog(message: "创建cell失败") } cell?.model = model return cell! } //NoteListModel class func createSlidingMenuCell(tableView: UITableView, atIndexPath indexPath: IndexPath, model: NoteListModel?) -> SlidingMenuHeaderViewCell { let cellId = "SlidingMenuHeaderViewCellId" let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? SlidingMenuHeaderViewCell if cell == nil { printLog(message: "创建cell失败") } cell?.noteModel = model return cell! } }
bf786688dd3ae0b75a4acee8729e9417
33.310976
151
0.639239
false
false
false
false
justindarc/firefox-ios
refs/heads/master
Client/Frontend/Library/HistoryPanel.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import XCGLogger import WebKit private struct HistoryPanelUX { static let WelcomeScreenItemWidth = 170 static let IconSize = 23 static let IconBorderColor = UIColor.Photon.Grey30 static let IconBorderWidth: CGFloat = 0.5 static let actionIconColor = UIColor.Photon.Grey40 // Works for light and dark theme. } private class FetchInProgressError: MaybeErrorType { internal var description: String { return "Fetch is already in-progress" } } @objcMembers class HistoryPanel: SiteTableViewController, LibraryPanel { enum Section: Int { // Showing synced tabs, showing recently closed, and clearing recent history are action rows of this type. case additionalHistoryActions case today case yesterday case lastWeek case lastMonth static let count = 5 var title: String? { switch self { case .today: return Strings.TableDateSectionTitleToday case .yesterday: return Strings.TableDateSectionTitleYesterday case .lastWeek: return Strings.TableDateSectionTitleLastWeek case .lastMonth: return Strings.TableDateSectionTitleLastMonth default: return nil } } } enum AdditionalHistoryActionRow: Int { case clearRecent case showRecentlyClosedTabs case showSyncTabs // Use to enable/disable the additional history action rows. static func setStyle(enabled: Bool, forCell cell: UITableViewCell) { if enabled { cell.textLabel?.alpha = 1.0 cell.imageView?.alpha = 1.0 cell.selectionStyle = .default cell.isUserInteractionEnabled = true } else { cell.textLabel?.alpha = 0.5 cell.imageView?.alpha = 0.5 cell.selectionStyle = .none cell.isUserInteractionEnabled = false } } } let QueryLimitPerFetch = 100 var libraryPanelDelegate: LibraryPanelDelegate? var groupedSites = DateGroupedTableData<Site>() var refreshControl: UIRefreshControl? var syncDetailText = "" var currentSyncedDevicesCount = 0 var currentFetchOffset = 0 var isFetchInProgress = false var clearHistoryCell: UITableViewCell? var hasRecentlyClosed: Bool { return profile.recentlyClosedTabs.tabs.count > 0 } lazy var emptyStateOverlayView: UIView = createEmptyStateOverlayView() lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(onLongPressGestureRecognized)) }() // MARK: - Lifecycle override init(profile: Profile) { super.init(profile: profile) [ Notification.Name.FirefoxAccountChanged, Notification.Name.PrivateDataClearedHistory, Notification.Name.DynamicFontChanged, Notification.Name.DatabaseWasReopened ].forEach { NotificationCenter.default.addObserver(self, selector: #selector(onNotificationReceived), name: $0, object: nil) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "History List" tableView.prefetchDataSource = self updateSyncedDevicesCount().uponQueue(.main) { result in self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Add a refresh control if the user is logged in and the control was not added before. If the user is not // logged in, remove any existing control. if profile.hasSyncableAccount() && refreshControl == nil { addRefreshControl() } else if !profile.hasSyncableAccount() && refreshControl != nil { removeRefreshControl() } if profile.hasSyncableAccount() { syncDetailText = " " updateSyncedDevicesCount().uponQueue(.main) { result in self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) } } else { syncDetailText = "" } } // MARK: - Refreshing TableView func addRefreshControl() { let control = UIRefreshControl() control.addTarget(self, action: #selector(onRefreshPulled), for: .valueChanged) refreshControl = control tableView.refreshControl = control } func removeRefreshControl() { tableView.refreshControl = nil refreshControl = nil } func endRefreshing() { // Always end refreshing, even if we failed! refreshControl?.endRefreshing() // Remove the refresh control if the user has logged out in the meantime if !profile.hasSyncableAccount() { removeRefreshControl() } } // MARK: - Loading data override func reloadData() { guard !isFetchInProgress else { return } groupedSites = DateGroupedTableData<Site>() currentFetchOffset = 0 fetchData().uponQueue(.main) { result in if let sites = result.successValue { for site in sites { if let site = site, let latestVisit = site.latestVisit { self.groupedSites.add(site, timestamp: TimeInterval.fromMicrosecondTimestamp(latestVisit.date)) } } self.tableView.reloadData() self.updateEmptyPanelState() if let cell = self.clearHistoryCell { AdditionalHistoryActionRow.setStyle(enabled: !self.groupedSites.isEmpty, forCell: cell) } } } } func fetchData() -> Deferred<Maybe<Cursor<Site>>> { guard !isFetchInProgress else { return deferMaybe(FetchInProgressError()) } isFetchInProgress = true return profile.history.getSitesByLastVisit(limit: QueryLimitPerFetch, offset: currentFetchOffset) >>== { result in // Force 100ms delay between resolution of the last batch of results // and the next time `fetchData()` can be called. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) { self.currentFetchOffset += self.QueryLimitPerFetch self.isFetchInProgress = false } return deferMaybe(result) } } func resyncHistory() { profile.syncManager.syncHistory().uponQueue(.main) { syncResult in self.updateSyncedDevicesCount().uponQueue(.main) { result in self.endRefreshing() self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) if syncResult.isSuccess { self.reloadData() } } } } func updateNumberOfSyncedDevices(_ count: Int) { if count > 0 { syncDetailText = String.localizedStringWithFormat(Strings.SyncedTabsTableViewCellDescription, count) } else { syncDetailText = "" } tableView.reloadData() } func updateSyncedDevicesCount() -> Success { guard profile.hasSyncableAccount() else { currentSyncedDevicesCount = 0 return succeed() } return chainDeferred(profile.getCachedClientsAndTabs()) { tabsAndClients in self.currentSyncedDevicesCount = tabsAndClients.count return succeed() } } // MARK: - Actions func removeHistoryForURLAtIndexPath(indexPath: IndexPath) { guard let site = siteForIndexPath(indexPath) else { return } profile.history.removeHistoryForURL(site.url).uponQueue(.main) { result in guard site == self.siteForIndexPath(indexPath) else { self.reloadData() return } self.tableView.beginUpdates() self.groupedSites.remove(site) self.tableView.deleteRows(at: [indexPath], with: .right) self.tableView.endUpdates() self.updateEmptyPanelState() if let cell = self.clearHistoryCell { AdditionalHistoryActionRow.setStyle(enabled: !self.groupedSites.isEmpty, forCell: cell) } } } func pinToTopSites(_ site: Site) { _ = profile.history.addPinnedTopSite(site).value } func navigateToSyncedTabs() { let nextController = RemoteTabsPanel(profile: profile) nextController.title = Strings.SyncedTabsTableViewCellTitle nextController.libraryPanelDelegate = libraryPanelDelegate refreshControl?.endRefreshing() navigationController?.pushViewController(nextController, animated: true) } func navigateToRecentlyClosed() { guard hasRecentlyClosed else { return } let nextController = RecentlyClosedTabsPanel(profile: profile) nextController.title = Strings.RecentlyClosedTabsButtonTitle nextController.libraryPanelDelegate = libraryPanelDelegate refreshControl?.endRefreshing() navigationController?.pushViewController(nextController, animated: true) } func showClearRecentHistory() { func remove(hoursAgo: Int) { if let date = Calendar.current.date(byAdding: .hour, value: -hoursAgo, to: Date()) { let types = WKWebsiteDataStore.allWebsiteDataTypes() WKWebsiteDataStore.default().removeData(ofTypes: types, modifiedSince: date, completionHandler: {}) self.profile.history.removeHistoryFromDate(date).uponQueue(.main) { _ in self.reloadData() } } } let alert = UIAlertController(title: Strings.ClearHistoryMenuTitle, message: nil, preferredStyle: .actionSheet) // This will run on the iPad-only, and sets the alert to be centered with no arrow. if let popoverController = alert.popoverPresentationController { popoverController.sourceView = view popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) popoverController.permittedArrowDirections = [] } [(Strings.ClearHistoryMenuOptionTheLastHour, 1), (Strings.ClearHistoryMenuOptionToday, 24), (Strings.ClearHistoryMenuOptionTodayAndYesterday, 48)].forEach { (name, time) in let action = UIAlertAction(title: name, style: .destructive) { _ in remove(hoursAgo: time) } alert.addAction(action) } let cancelAction = UIAlertAction(title: Strings.CancelString, style: .cancel) alert.addAction(cancelAction) present(alert, animated: true) } // MARK: - Cell configuration func siteForIndexPath(_ indexPath: IndexPath) -> Site? { // First section is reserved for Sync. guard indexPath.section > Section.additionalHistoryActions.rawValue else { return nil } let sitesInSection = groupedSites.itemsForSection(indexPath.section - 1) return sitesInSection[safe: indexPath.row] } func configureClearHistory(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { clearHistoryCell = cell cell.textLabel?.text = Strings.HistoryPanelClearHistoryButtonTitle cell.detailTextLabel?.text = "" cell.imageView?.image = UIImage.templateImageNamed("forget") cell.imageView?.tintColor = HistoryPanelUX.actionIconColor cell.imageView?.backgroundColor = UIColor.theme.homePanel.historyHeaderIconsBackground cell.accessibilityIdentifier = "HistoryPanel.clearHistory" var isEmpty = true for i in Section.today.rawValue..<tableView.numberOfSections { if tableView.numberOfRows(inSection: i) > 0 { isEmpty = false } } AdditionalHistoryActionRow.setStyle(enabled: !isEmpty, forCell: cell) return cell } func configureRecentlyClosed(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { cell.accessoryType = .disclosureIndicator cell.textLabel?.text = Strings.RecentlyClosedTabsButtonTitle cell.detailTextLabel?.text = "" cell.imageView?.image = UIImage.templateImageNamed("recently_closed") cell.imageView?.tintColor = HistoryPanelUX.actionIconColor cell.imageView?.backgroundColor = UIColor.theme.homePanel.historyHeaderIconsBackground AdditionalHistoryActionRow.setStyle(enabled: hasRecentlyClosed, forCell: cell) cell.accessibilityIdentifier = "HistoryPanel.recentlyClosedCell" return cell } func configureSyncedTabs(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { cell.accessoryType = .disclosureIndicator cell.textLabel?.text = Strings.SyncedTabsTableViewCellTitle cell.detailTextLabel?.text = syncDetailText cell.imageView?.image = UIImage.templateImageNamed("synced_devices") cell.imageView?.tintColor = HistoryPanelUX.actionIconColor cell.imageView?.backgroundColor = UIColor.theme.homePanel.historyHeaderIconsBackground cell.imageView?.backgroundColor = UIColor.theme.homePanel.historyHeaderIconsBackground cell.accessibilityIdentifier = "HistoryPanel.syncedDevicesCell" return cell } func configureSite(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { if let site = siteForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell { cell.setLines(site.title, detailText: site.url) cell.imageView?.layer.borderColor = HistoryPanelUX.IconBorderColor.cgColor cell.imageView?.layer.borderWidth = HistoryPanelUX.IconBorderWidth cell.imageView?.setIcon(site.icon, forURL: site.tileURL, completed: { (color, url) in if site.tileURL == url { cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: HistoryPanelUX.IconSize, height: HistoryPanelUX.IconSize)) cell.imageView?.backgroundColor = color cell.imageView?.contentMode = .center } }) } return cell } // MARK: - Selector callbacks func onNotificationReceived(_ notification: Notification) { switch notification.name { case .FirefoxAccountChanged, .PrivateDataClearedHistory: reloadData() if profile.hasSyncableAccount() { resyncHistory() } break case .DynamicFontChanged: reloadData() if emptyStateOverlayView.superview != nil { emptyStateOverlayView.removeFromSuperview() } emptyStateOverlayView = createEmptyStateOverlayView() resyncHistory() break case .DatabaseWasReopened: if let dbName = notification.object as? String, dbName == "browser.db" { reloadData() } default: // no need to do anything at all print("Error: Received unexpected notification \(notification.name)") break } } func onLongPressGestureRecognized(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } if indexPath.section != Section.additionalHistoryActions.rawValue { presentContextMenu(for: indexPath) } } func onRefreshPulled() { refreshControl?.beginRefreshing() resyncHistory() } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return Section.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // First section is for Sync/recently closed and always has 2 rows. guard section > Section.additionalHistoryActions.rawValue else { return 3 } return groupedSites.numberOfItemsForSection(section - 1) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // First section is for Sync/recently closed and has no title. guard section > Section.additionalHistoryActions.rawValue else { return nil } // Ensure there are rows in this section. guard groupedSites.numberOfItemsForSection(section - 1) > 0 else { return nil } return Section(rawValue: section)?.title } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) cell.accessoryType = .none // First section is reserved for Sync/recently closed. guard indexPath.section > Section.additionalHistoryActions.rawValue else { cell.imageView?.layer.borderWidth = 0 guard let row = AdditionalHistoryActionRow(rawValue: indexPath.row) else { assertionFailure("Bad row number") return cell } switch row { case .clearRecent: return configureClearHistory(cell, for: indexPath) case .showRecentlyClosedTabs: return configureRecentlyClosed(cell, for: indexPath) case .showSyncTabs: return configureSyncedTabs(cell, for: indexPath) } } return configureSite(cell, for: indexPath) } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // First section is reserved for Sync/recently closed. defer { tableView.deselectRow(at: indexPath, animated: true) } guard indexPath.section > Section.additionalHistoryActions.rawValue else { switch indexPath.row { case 0: showClearRecentHistory() case 1: navigateToRecentlyClosed() default: navigateToSyncedTabs() } return } if let site = siteForIndexPath(indexPath), let url = URL(string: site.url) { if let libraryPanelDelegate = libraryPanelDelegate { libraryPanelDelegate.libraryPanel(didSelectURL: url, visitType: VisitType.typed) } return } print("Error: No site or no URL when selecting row.") } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? UITableViewHeaderFooterView { header.textLabel?.textColor = UIColor.theme.tableView.headerTextDark header.contentView.backgroundColor = UIColor.theme.tableView.headerBackground } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // First section is for Sync/recently closed and its header has no view. guard section > Section.additionalHistoryActions.rawValue else { return nil } // Ensure there are rows in this section. guard groupedSites.numberOfItemsForSection(section - 1) > 0 else { return nil } return super.tableView(tableView, viewForHeaderInSection: section) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // First section is for Sync/recently closed and its header has no height. guard section > Section.additionalHistoryActions.rawValue else { return 0 } // Ensure there are rows in this section. guard groupedSites.numberOfItemsForSection(section - 1) > 0 else { return 0 } return super.tableView(tableView, heightForHeaderInSection: section) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Intentionally blank. Required to use UITableViewRowActions } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if indexPath.section == Section.additionalHistoryActions.rawValue { return [] } let title = NSLocalizedString("Delete", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.") let delete = UITableViewRowAction(style: .default, title: title, handler: { (action, indexPath) in self.removeHistoryForURLAtIndexPath(indexPath: indexPath) }) return [delete] } // MARK: - Empty State func updateEmptyPanelState() { if groupedSites.isEmpty { if emptyStateOverlayView.superview == nil { tableView.tableFooterView = emptyStateOverlayView } } else { tableView.alwaysBounceVertical = true tableView.tableFooterView = nil } } func createEmptyStateOverlayView() -> UIView { let overlayView = UIView() // overlayView becomes the footer view, and for unknown reason, setting the bgcolor is ignored. // Create an explicit view for setting the color. let bgColor = UIView() bgColor.backgroundColor = UIColor.theme.homePanel.panelBackground overlayView.addSubview(bgColor) bgColor.snp.makeConstraints { make in // Height behaves oddly: equalToSuperview fails in this case, as does setting top.equalToSuperview(), simply setting this to ample height works. make.height.equalTo(UIScreen.main.bounds.height) make.width.equalToSuperview() } let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = Strings.HistoryPanelEmptyStateTitle welcomeLabel.textAlignment = .center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight welcomeLabel.textColor = UIColor.theme.homePanel.welcomeScreenText welcomeLabel.numberOfLines = 0 welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(overlayView) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(overlayView).offset(LibraryPanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView).offset(50) make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth) } return overlayView } override func applyTheme() { emptyStateOverlayView.removeFromSuperview() emptyStateOverlayView = createEmptyStateOverlayView() updateEmptyPanelState() super.applyTheme() } } extension HistoryPanel: UITableViewDataSourcePrefetching { func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { guard !isFetchInProgress, indexPaths.contains(where: shouldLoadRow) else { return } fetchData().uponQueue(.main) { result in if let sites = result.successValue { let indexPaths: [IndexPath] = sites.compactMap({ site in guard let site = site, let latestVisit = site.latestVisit else { return nil } let indexPath = self.groupedSites.add(site, timestamp: TimeInterval.fromMicrosecondTimestamp(latestVisit.date)) return IndexPath(row: indexPath.row, section: indexPath.section + 1) }) self.tableView.insertRows(at: indexPaths, with: .automatic) } } } func shouldLoadRow(for indexPath: IndexPath) -> Bool { guard indexPath.section > Section.additionalHistoryActions.rawValue else { return false } return indexPath.row >= groupedSites.numberOfItemsForSection(indexPath.section - 1) - 1 } } extension HistoryPanel: LibraryPanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { return siteForIndexPath(indexPath) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard var actions = getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate) else { return nil } let removeAction = PhotonActionSheetItem(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in self.removeHistoryForURLAtIndexPath(indexPath: indexPath) }) let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in self.pinToTopSites(site) }) actions.append(pinTopSite) actions.append(removeAction) return actions } }
80d4d883780f87ca285eac23553d624f
36.862464
156
0.646057
false
false
false
false
goblinr/omim
refs/heads/master
iphone/Maps/UI/Search/Filters/FilterCheckCell.swift
apache-2.0
3
@objc(MWMFilterCheckCellDelegate) protocol FilterCheckCellDelegate { func checkCellButtonTap(_ button: UIButton) } @objc(MWMFilterCheckCell) final class FilterCheckCell: MWMTableViewCell { @IBOutlet private var checkButtons: [UIButton]! @IBOutlet private var checkLabels: [UILabel]! @IBOutlet weak var checkInLabel: UILabel! { didSet { checkInLabel.text = L("booking_filters_check_in") } } @IBOutlet weak var checkOutLabel: UILabel! { didSet { checkOutLabel.text = L("booking_filters_check_out") } } @IBOutlet weak var checkIn: UIButton! @IBOutlet weak var checkOut: UIButton! @IBOutlet private weak var offlineLabel: UILabel! { didSet { offlineLabel.font = UIFont.regular12() offlineLabel.textColor = UIColor.red offlineLabel.text = L("booking_filters_offline") } } @IBOutlet private weak var offlineLabelBottomOffset: NSLayoutConstraint! @objc var isOffline = false { didSet { offlineLabel.isHidden = !isOffline offlineLabelBottomOffset.priority = isOffline ? .defaultHigh : .defaultLow checkLabels.forEach { $0.isEnabled = !isOffline } checkButtons.forEach { $0.isEnabled = !isOffline } } } @objc weak var delegate: FilterCheckCellDelegate? @IBAction private func tap(sender: UIButton!) { delegate?.checkCellButtonTap(sender) } fileprivate func setupButton(_ button: UIButton) { button.setTitleColor(UIColor.blackPrimaryText(), for: .normal) button.setTitleColor(UIColor.blackDividers(), for: .disabled) button.setBackgroundColor(UIColor.white(), for: .normal) let label = button.titleLabel! label.textAlignment = .natural label.font = UIFont.regular14() let layer = button.layer layer.cornerRadius = 4 layer.borderWidth = 1 layer.borderColor = UIColor.blackDividers().cgColor } @objc func refreshButtonsAppearance() { checkButtons.forEach { setupButton($0) } } fileprivate func setupLabel(_ label: UILabel) { label.font = UIFont.bold12() label.textColor = UIColor.blackSecondaryText() } @objc func refreshLabelsAppearance() { checkLabels.forEach { setupLabel($0) } } override func awakeFromNib() { super.awakeFromNib() isSeparatorHidden = true backgroundColor = UIColor.clear } }
0c64be6b48b34b73d94ae8751e0b9920
27.85
80
0.707539
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureCardIssuing/Sources/FeatureCardIssuingUI/Manage/Activity/Transaction+Activity.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import BlockchainComponentLibrary import FeatureCardIssuingDomain import Localization import MoneyKit import SwiftUI import ToolKit extension Card.Transaction { var displayDateTime: String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short return dateFormatter.string(from: userTransactionTime) } var displayTime: String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .none dateFormatter.timeStyle = .short return dateFormatter.string(from: userTransactionTime) } var displayDate: String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short return dateFormatter.string(from: userTransactionTime) } var displayTitle: String { typealias L10n = LocalizationConstants.CardIssuing.Manage.Transaction.TransactionType switch transactionType { case .payment: return merchantName case .cashback: return [L10n.cashback, merchantName].joined(separator: " ") case .refund: return [L10n.refund, merchantName].joined(separator: " ") case .chargeback: return [L10n.chargeback, merchantName].joined(separator: " ") case .funding: return [L10n.payment, merchantName].joined(separator: " ") } } var displayStatus: String { typealias L10n = LocalizationConstants.CardIssuing.Manage.Transaction.Status switch state { case .pending: return L10n.pending case .cancelled: return L10n.cancelled case .declined: return L10n.declined case .completed: return L10n.completed } } var statusColor: Color { switch state { case .pending: return .WalletSemantic.muted case .cancelled: return .WalletSemantic.muted case .declined: return .WalletSemantic.error case .completed: return .WalletSemantic.success } } var icon: Icon { switch (state, transactionType) { case (.pending, _): return Icon.pending case (.cancelled, _): return Icon.error case (.declined, _): return Icon.error case (.completed, .chargeback), (.completed, .refund), (.completed, .cashback): return Icon.arrowDown case (.completed, _): return Icon.creditcard } } var tag: TagView { switch state { case .pending: return TagView(text: displayStatus, variant: .infoAlt) case .cancelled: return TagView(text: displayStatus, variant: .default) case .declined: return TagView(text: displayStatus, variant: .error) case .completed: return TagView(text: displayStatus, variant: .success) } } } extension FeatureCardIssuingDomain.Money { var displayString: String { guard let currency = try? CurrencyType(code: symbol), let decimal = Decimal(string: value) else { return "" } return MoneyValue.create(major: decimal, currency: currency).displayString } var isZero: Bool { guard let decimal = Decimal(string: value) else { return true } return decimal.isZero || decimal.isNaN } }
13e8d77afb425875b0d578acf957b86a
27.650794
93
0.603324
false
false
false
false
playstones/NEKit
refs/heads/master
src/ProxyServer/ProxyServer.swift
bsd-3-clause
1
import Foundation import CocoaAsyncSocket import Resolver /** The base proxy server class. This proxy does not listen on any port. */ open class ProxyServer: NSObject, TunnelDelegate { typealias TunnelArray = [Tunnel] /// The port of proxy server. open let port: Port /// The address of proxy server. open let address: IPAddress? /// The type of the proxy server. /// /// This can be set to anything describing the proxy server. open let type: String /// The description of proxy server. open override var description: String { return "<\(type) address:\(String(describing: address)) port:\(port)>" } open var observer: Observer<ProxyServerEvent>? var tunnels: TunnelArray = [] /** Create an instance of proxy server. - parameter address: The address of proxy server. - parameter port: The port of proxy server. - warning: If you are using Network Extension, you have to set address or you may not able to connect to the proxy server. */ public init(address: IPAddress?, port: Port) { self.address = address self.port = port type = "\(Swift.type(of: self))" super.init() self.observer = ObserverFactory.currentFactory?.getObserverForProxyServer(self) } /** Start the proxy server. - throws: The error occured when starting the proxy server. */ open func start() throws { QueueFactory.executeOnQueueSynchronizedly { GlobalIntializer.initalize() self.observer?.signal(.started(self)) } } /** Stop the proxy server. */ open func stop() { QueueFactory.executeOnQueueSynchronizedly { for tunnel in tunnels { tunnel.forceClose() } observer?.signal(.stopped(self)) } } /** Delegate method when the proxy server accepts a new ProxySocket from local. When implementing a concrete proxy server, e.g., HTTP proxy server, the server should listen on some port and then wrap the raw socket in a corresponding ProxySocket subclass, then call this method. - parameter socket: The accepted proxy socket. */ func didAcceptNewSocket(_ socket: ProxySocket) { observer?.signal(.newSocketAccepted(socket, onServer: self)) let tunnel = Tunnel(proxySocket: socket) tunnel.delegate = self tunnels.append(tunnel) tunnel.openTunnel() } // MARK: TunnelDelegate implementation /** Delegate method when a tunnel closed. The server will remote it internally. - parameter tunnel: The closed tunnel. */ func tunnelDidClose(_ tunnel: Tunnel) { observer?.signal(.tunnelClosed(tunnel, onServer: self)) guard let index = tunnels.index(of: tunnel) else { // things went strange return } tunnels.remove(at: index) } }
298f84daf20a53afa53a7c53906118a3
27.018692
203
0.628753
false
false
false
false
zapdroid/RXWeather
refs/heads/master
Pods/Nimble/Sources/Nimble/Matchers/PostNotification.swift
mit
1
import Foundation internal class NotificationCollector { private(set) var observedNotifications: [Notification] private let notificationCenter: NotificationCenter #if _runtime(_ObjC) private var token: AnyObject? #else private var token: NSObjectProtocol? #endif required init(notificationCenter: NotificationCenter) { self.notificationCenter = notificationCenter observedNotifications = [] } func startObserving() { token = notificationCenter.addObserver(forName: nil, object: nil, queue: nil) { [weak self] n in // linux-swift gets confused by .append(n) self?.observedNotifications.append(n) } } deinit { #if _runtime(_ObjC) if let token = self.token { self.notificationCenter.removeObserver(token) } #else if let token = self.token as? AnyObject { self.notificationCenter.removeObserver(token) } #endif } } private let mainThread = pthread_self() let notificationCenterDefault = NotificationCenter.default public func postNotifications<T>( _ notificationsMatcher: T, fromNotificationCenter center: NotificationCenter = notificationCenterDefault) -> MatcherFunc<Any> where T: Matcher, T.ValueType == [Notification] { _ = mainThread // Force lazy-loading of this value let collector = NotificationCollector(notificationCenter: center) collector.startObserving() var once: Bool = false return MatcherFunc { actualExpression, failureMessage in let collectorNotificationsExpression = Expression(memoizedExpression: { _ in collector.observedNotifications }, location: actualExpression.location, withoutCaching: true) assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.") if !once { once = true _ = try actualExpression.evaluate() } let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage) if collector.observedNotifications.isEmpty { failureMessage.actualValue = "no notifications" } else { failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>" } return match } }
fb84cae352c56ff3b7144382a62fb39b
33.913043
120
0.665006
false
false
false
false
justinvyu/SwiftyDictionary
refs/heads/master
Pod/Classes/SwiftyDictionary.swift
mit
1
// // SwiftyDictionary.swift // Pods // // Created by Justin Yu on 11/25/15. // // import Foundation import Alamofire import AEXML public enum SwiftyDictionaryType { case Dictionary case Thesaurus } public typealias DictionaryRequestCallback = (AEXMLDocument) -> Void public typealias ArrayCallback = ([String]) -> Void public typealias SeparatedArrayCallback = ([[String]]) -> Void struct SwiftyDictionaryConstants { static let API_ROOT_PATH = NSURL(string: "http://www.dictionaryapi.com/api/v1/references/") static let OBSOLETE = "obsolete" } func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] { var buffer = [T]() var added = Set<T>() for elem in source { if !added.contains(elem) { buffer.append(elem) added.insert(elem) } } return buffer }
988924a09f23cfa4b251675fc5a3cb8a
22.486486
95
0.663594
false
false
false
false
CodaFi/swift-compiler-crashes
refs/heads/master
crashes-duplicates/13451-swift-type-walk.swift
mit
11
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } } struct B<b: a { if true { func f(T) -> { class A : a<b class A { func f.c: P { } class a class A : d = b: Int { func f(f(n: d = a<T where g: BooleanType) init(T) -> { } func f.c func a<T where g: b var e) init(T] { } class a<T where I.B<Int> protocol A { protocol P { } class A : S(v: P { init(") protocol A { func a<T : a { protocol P { class a<T] { class b typealias f : e() } } func a<b<T where g: Any, e(n: U : C { init(f<T where I.c: a { protocol P { typealias f : S<T where I.B) class c { } init(f<Int> func a<T : b(T.B) if true { struct A { protocol d : a { } func a<b protocol P { func b func b func b: a { } let c { } typealias f : C { init(f<T : C { } } class func a let start = A class A { } assert(sel assert(sel class func b protocol d = { class b: C { let c : C { class func a<T.B) init(sel func a: a<b: a { struct A : a class a<b: A protocol d : Any, f.B<T) -> { func a struct S<T where I.c class A { typealias e : BooleanType) class A { protocol A : d : Int { struct A { typealias f : C { let start = b: C { typealias f : Any, e(f(sel class A { func b: U : Int { protocol A { func a: d = A if true { protocol A { struct S(T) -> { struct B<Int> protocol A : AnyObject, e) protocol A : Any, f.B) class A { let start = A protocol A { protocol A { typealias e = A let c : b<T where I.c: AnyObject, f(T.c: S<b: b: S(f(T.c: S<T where g: Any, e(") class c { func a<T where I.c: a { typealias e = { class func a<T where I.c: d : C { typealias f : AnyObject, e(n: C { } class func a class A { protocol A { func a<b: BooleanType) } class A : a { struct B<b struct S(n: C { typealias f : S<T] { [() init(") func a class c { var e(v: b() var d : AnyObject, e(v: U : P { func f(T) -> { var d = b(sel let start = a: Int { class func a protocol A : d = A protocol A { func f<T : S() struct B) protocol A { if true { var e(T.c func f.B<T where I.B<T : BooleanType) init(n: A if true { class A : Any, f.c: C { protocol P { if true { class func a: d : e) class b class c : S<T : P { init(sel var e(sel typealias f : b: C { var e() func a<T where g: S<b } if true { struct S<T where g: U : a { protocol a { class func f(T] { class A : S<T : d = b } var e) protocol P { protocol d = { protocol A { [(T.c: U : C { class c { protocol A {
bec8ebf9895e2e274d890de8b76bfbaf
13.754601
87
0.604574
false
false
false
false
Ahyufei/DouYuTV
refs/heads/master
DYTV/DYTV/Classes/Home/View/RecommendCycleView.swift
mit
1
// // RecommendCycleView.swift // DYTV // // Created by Yufei on 2017/1/16. // Copyright © 2017年 张玉飞. All rights reserved. // import UIKit fileprivate let kCycleID = "kCycleID" class RecommendCycleView: UIView { // MARK:- 控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! // 定义属性 var cycleTimer : Timer? var cycleModels : [CycleModel]?{ didSet{ collectionView.reloadData() pageControl.numberOfPages = cycleModels?.count ?? 0 // 默认滚动到中间某一位置 let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 100, section: 0) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) // 4.添加定时器 removeCycleTimer() addCycleTimer() } } // MARK:- 系统回调 override func awakeFromNib() { super.awakeFromNib() autoresizingMask = UIViewAutoresizing() // 注册cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleID) } override func layoutSubviews() { // 设置layput let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true } } extension RecommendCycleView { class func recommendCycleView() -> RecommendCycleView { return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } // MARK:- UICollectionViewDataSource extension RecommendCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleID, for: indexPath) as! CollectionCycleCell // cell.backgroundColor = UIColor.randomColor() cell.cycleModel = cycleModels![indexPath.item % cycleModels!.count] return cell } } // MARK:- UICollectionViewDelegate extension RecommendCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } // MARK:- 定时器 extension RecommendCycleView { fileprivate func addCycleTimer() { cycleTimer = Timer(timeInterval: 2.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes) } fileprivate func removeCycleTimer() { cycleTimer?.invalidate() // 从运行循环中移除 cycleTimer = nil } @objc fileprivate func scrollToNext() { let offsetX = collectionView.contentOffset.x + collectionView.bounds.width // 2.滚动该位置 collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } }
2447a154242b628ea1996950927d2c5f
29.511811
129
0.650065
false
false
false
false
igormatyushkin014/Eternal
refs/heads/master
Eternal/Dispatcher/ETDispatcher.swift
mit
1
// // ETDispatcher.swift // Eternal // // Created by Igor Matyushkin on 24.09.15. // Copyright © 2015 Igor Matyushkin. All rights reserved. // import Foundation public class ETDispatcher: NSObject { // MARK: Class variables & properties // MARK: Class methods @discardableResult public class func dispatch(onQueue queue: DispatchQueue, asynchronously runAsynchronously: Bool, withBlock block: @escaping () -> Void) -> ETDispatcher.Type { // Start dispatch if runAsynchronously { queue.async { block() } } else { queue.sync { block() } } // Return result return self } @discardableResult public class func dispatch(onQueue queue: DispatchQueue, asynchronously runAsynchronously: Bool, afterTimeInterval timeInterval: TimeInterval, withBlock block: @escaping () -> Void) -> ETDispatcher.Type { // Start dispatch if timeInterval > 0.0 { let delayTime = DispatchTime(uptimeNanoseconds: UInt64(timeInterval * Double(NSEC_PER_SEC))) queue.asyncAfter(deadline: delayTime, execute: { block() }) } else { queue.async { block() } } // Return result return self } @discardableResult public class func dispatch(onBackgroundQueueAsynchronously runAsynchronously: Bool, withBlock block: @escaping () -> Void) -> ETDispatcher.Type { // Obtain queue let queue = DispatchQueue.global(qos: .background) // Start dispatch dispatch(onQueue: queue, asynchronously: runAsynchronously) { block() } // Return result return self } @discardableResult public class func dispatch(onBackgroundQueueAfterTimeInterval timeInterval: TimeInterval, asynchronously runAsynchronously: Bool, withBlock block: @escaping () -> Void) -> ETDispatcher.Type { // Obtain queue let queue = DispatchQueue.global(qos: .background) // Start dispatch dispatch(onQueue: queue, asynchronously: runAsynchronously, afterTimeInterval: timeInterval) { block() } // Return result return self } @discardableResult public class func dispatch(onMainQueueAsynchronously runAsynchronously: Bool, withBlock block: @escaping () -> Void) -> ETDispatcher.Type { // Obtain queue let queue = DispatchQueue.main // Start dispatch dispatch(onQueue: queue, asynchronously: runAsynchronously) { block() } // Return result return self } @discardableResult public class func dispatch(onMainQueueAsynchronously runAsynchronously: Bool, afterTimeInterval timeInterval: TimeInterval, withBlock block: @escaping () -> Void) -> ETDispatcher.Type { // Obtain queue let queue = DispatchQueue.main // Start dispatch dispatch(onQueue: queue, asynchronously: runAsynchronously, afterTimeInterval: timeInterval) { block() } // Return result return self } // MARK: Initializers public override init() { super.init() } // MARK: Deinitializer deinit { } // MARK: Variables & properties // MARK: Public methods // MARK: Private methods // MARK: Protocol methods }
8d2337a9024a27cfc6f2b31965f0c21c
23.104938
208
0.546991
false
false
false
false
darrinhenein/firefox-ios
refs/heads/master
Providers/ProfilePrefs.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation public protocol ProfilePrefs { func setObject(value: AnyObject?, forKey defaultName: String) func stringForKey(defaultName: String) -> String? func boolForKey(defaultName: String) -> Bool? func stringArrayForKey(defaultName: String) -> [String]? func arrayForKey(defaultName: String) -> [AnyObject]? func dictionaryForKey(defaultName: String) -> [String : AnyObject]? func removeObjectForKey(defaultName: String) func clearAll() } public class MockProfilePrefs : ProfilePrefs { var things: NSMutableDictionary = NSMutableDictionary() public func setObject(value: AnyObject?, forKey defaultName: String) { things[defaultName] = value } public func stringForKey(defaultName: String) -> String? { return things[defaultName] as? String } public func boolForKey(defaultName: String) -> Bool? { return things[defaultName] as? Bool } public func stringArrayForKey(defaultName: String) -> [String]? { return self.arrayForKey(defaultName) as [String]? } public func arrayForKey(defaultName: String) -> [AnyObject]? { let r: AnyObject? = things.objectForKey(defaultName) if (r == nil) { return nil } if let arr = r as? [AnyObject] { return arr } return nil } public func dictionaryForKey(defaultName: String) -> [String : AnyObject]? { return things.objectForKey(defaultName) as? [String: AnyObject] } public func removeObjectForKey(defaultName: String) { self.things[defaultName] = nil } public func clearAll() { self.things.removeAllObjects() } } public class NSUserDefaultsProfilePrefs : ProfilePrefs { private let profile: Profile private let prefix: String private let userDefaults: NSUserDefaults init(profile: Profile) { self.profile = profile self.prefix = profile.localName() + "." self.userDefaults = NSUserDefaults(suiteName: ExtensionUtils.sharedContainerIdentifier())! } // Preferences are qualified by the profile's local name. // Connecting a profile to a Firefox Account, or changing to another, won't alter this. private func qualifyKey(key: String) -> String { return self.prefix + key } public func setObject(value: AnyObject?, forKey defaultName: String) { userDefaults.setObject(value, forKey: qualifyKey(defaultName)) } public func stringForKey(defaultName: String) -> String? { // stringForKey converts numbers to strings, which is almost always a bug. return userDefaults.objectForKey(qualifyKey(defaultName)) as? String } public func boolForKey(defaultName: String) -> Bool? { // boolForKey just returns false if the key doesn't exist. We need to // distinguish between false and non-existent keys, so use objectForKey // and cast the result instead. return userDefaults.objectForKey(qualifyKey(defaultName)) as? Bool } public func stringArrayForKey(defaultName: String) -> [String]? { return userDefaults.stringArrayForKey(qualifyKey(defaultName)) as [String]? } public func arrayForKey(defaultName: String) -> [AnyObject]? { return userDefaults.arrayForKey(qualifyKey(defaultName)) } public func dictionaryForKey(defaultName: String) -> [String : AnyObject]? { return userDefaults.dictionaryForKey(qualifyKey(defaultName)) as? [String:AnyObject] } public func removeObjectForKey(defaultName: String) { userDefaults.removeObjectForKey(qualifyKey(defaultName)) } public func clearAll() { // TODO: userDefaults.removePersistentDomainForName() has no effect for app group suites. // iOS Bug? Iterate and remove each manually for now. for key in userDefaults.dictionaryRepresentation().keys { userDefaults.removeObjectForKey(key as NSString) } } }
2c4778f8dc1052fe517176ab2666ecdc
34.871795
98
0.68263
false
false
false
false
DeveloperLx/LxProjectTemplate
refs/heads/develop
Example/Pods/PromiseKit/Sources/join.swift
apache-2.0
12
import Dispatch /** Waits on all provided promises. `when` rejects as soon as one of the provided promises rejects. `join` waits on all provided promises, then rejects if any of those promises rejected, otherwise it fulfills with values from the provided promises. join(promise1, promise2, promise3).then { results in //… }.error { error in switch error { case Error.Join(let promises): //… } } - Returns: A new promise that resolves once all the provided promises resolve. */ public func join<T>(promises: Promise<T>...) -> Promise<[T]> { var countdown = promises.count let barrier = dispatch_queue_create("org.promisekit.barrier.join", DISPATCH_QUEUE_CONCURRENT) var rejected = false return Promise { fulfill, reject in for promise in promises { promise.pipe { resolution in dispatch_barrier_sync(barrier) { if case .Rejected(_, let token) = resolution { token.consumed = true // the parent Error.Join consumes all rejected = true } if --countdown == 0 { if rejected { reject(Error.Join(promises)) } else { fulfill(promises.map{ $0.value! }) } } } } } } }
8a297f2724f779098a063fcf7188c4e5
32.636364
213
0.525676
false
false
false
false
fellipecaetano/Democracy-iOS
refs/heads/develop
Aestheticam/Vendor/RandomKit/Sources/RandomKit/Extensions/Swift/FloatingPoint+RandomKit.swift
mit
3
// // FloatingPoint+RandomKit.swift // RandomKit // // The MIT License (MIT) // // Copyright (c) 2015-2017 Nikolai Vazquez // // 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. // extension FloatingPoint where Self: RandomInRange { /// Returns a random value of `Self` inside of the unchecked range using `randomGenerator`. public static func uncheckedRandom<R: RandomGenerator>(in range: Range<Self>, using randomGenerator: inout R) -> Self { let random = UInt.random(using: &randomGenerator) if random == 0 { return range.lowerBound } else { let multiplier = range.upperBound - range.lowerBound return range.lowerBound + multiplier * (Self(random - 1) / Self(UInt.max)) } } } extension FloatingPoint where Self: RandomInClosedRange { /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> Self { let multiplier = closedRange.upperBound - closedRange.lowerBound return closedRange.lowerBound + multiplier * (Self(UInt.random(using: &randomGenerator)) / Self(UInt.max)) } } extension FloatingPoint where Self: Random & RandomInClosedRange { /// Generates a random value of `Self`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Self { return random(in: 0...1, using: &randomGenerator) } } extension FloatingPoint where Self: RandomToValue & RandomThroughValue { /// The random base from which to generate. public static var randomBase: Self { return 0 } } extension FloatingPoint where Self: RandomInClosedRange & RandomThroughValue { /// Generates a random value of `Self` from `Self.randomBase` through `value` using `randomGenerator`. public static func random<R: RandomGenerator>(through value: Self, using randomGenerator: inout R) -> Self { let range: ClosedRange<Self> if value < randomBase { range = value...randomBase } else { range = randomBase...value } return random(in: range, using: &randomGenerator) } } extension FloatingPoint where Self: RandomInRange & RandomToValue { /// Generates a random value of `Self` from `Self.randomBase` to `value` using `randomGenerator`. public static func random<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { let negate = value < randomBase let newValue = negate ? -value : value let randomRange = Range(uncheckedBounds: (randomBase, newValue)) guard let random = self.random(in: randomRange, using: &randomGenerator) else { return randomBase } return negate ? -random : random } } extension Double: Random, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange { /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Double { return randomGenerator.randomClosed64() } } extension Float: Random, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange { /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Float { return randomGenerator.randomClosed32() } } #if arch(i386) || arch(x86_64) extension Float80: Random, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange { } #endif
02223bd4071a1191ca1666f8e94e8d02
37.131148
126
0.704213
false
false
false
false