repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
charliewilliams/CWNotificationBanner
CWNotificationBanner/Classes/NotificationBanner.swift
1
13435
// // NotificationBanner.swift // CWNotificationBanner // // Created by Charlie Williams on 12/04/2016. // Copyright © 2016 Charlie Robert Williams, Ltd. All rights reserved. // import UIKit import SwiftyTimer public let NotificationBannerShouldDisplayErrorNotification = "NotificationBannerShouldDisplayErrorNotification" public func ==(lhs: Message, rhs: Message) -> Bool { return lhs.text == rhs.text && (lhs.date == rhs.date || (lhs.isError && rhs.isError)) } public enum MessageType: String { case NoConnection = "No network connection." case ServerError = "Error connecting to the server." case Unspecified = "We couldn't complete that request." case NotLoggedIn = "Error: Please log out and log in again to continue." } public enum PushPayloadKey: String { case aps = "aps" case alert = "alert" case action = "a" case duration = "d" } public typealias MessageAction = (() -> ()) public struct Message: Equatable { public let text: String private let date: NSDate public let duration: NSTimeInterval public var actionKey: String? private let isError: Bool private static let defaultDisplayTime: NSTimeInterval = 5 private static var actions = [String:MessageAction]() public init(text: String, displayDuration: NSTimeInterval = defaultDisplayTime, actionKey: String? = nil, isError error: Bool = false) { self.text = text self.date = NSDate() self.duration = displayDuration self.actionKey = actionKey self.isError = error } public init?(pushPayload: [NSObject : AnyObject]) { guard let text = pushPayload[PushPayloadKey.aps.rawValue]?[PushPayloadKey.alert.rawValue] as? String else { return nil } self.text = text self.date = NSDate() self.actionKey = pushPayload[PushPayloadKey.action.rawValue] as? String self.duration = pushPayload[PushPayloadKey.duration.rawValue] as? NSTimeInterval ?? Message.defaultDisplayTime self.isError = false } public static func registerAction(action: MessageAction, forKey key: String) { actions[key] = action } public static func registerActionsAndKeys(actionsAndKeys:[String:MessageAction]) { for (key, action) in actionsAndKeys { actions[key] = action } } public static func unregisterActionForKey(key: String) { actions.removeValueForKey(key) } public func isEqual(other: AnyObject?) -> Bool { guard let o = other as? Message else { return false } return o.text == text && o.date == date } } public class NotificationBanner: UIView { public static var animateDuration: NSTimeInterval = 0.3 public static var fallbackToBannerOnMainWindow: Bool = true public static var errorBackgroundColor = UIColor(white: 0.2, alpha: 1.0) public static var regularBackgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.2) override public var backgroundColor: UIColor! { didSet { underStatusBarView?.backgroundColor = backgroundColor?.colorWithAlphaComponent(0.85) } } public static func showMessage(message: Message) { guard NSThread.mainThread() == NSThread.currentThread() else { NSOperationQueue.mainQueue().addOperationWithBlock { showMessage(message) } return } // Don't interrupt an error to show a non-error if let currentMessage = pendingMessages.last where currentMessage.isError { let index = pendingMessages.count >= 2 ? pendingMessages.count - 2 : 0 pendingMessages.insert(message, atIndex: index) return } // If we're interrupting a message to show an error, re-insert the old message so we show it again if let timer = currentMessageTimer, let interruptedMessage = pendingMessages.last where timer.valid { let index = pendingMessages.count >= 2 ? pendingMessages.count - 2 : 0 pendingMessages.insert(interruptedMessage, atIndex: index) } if !pendingMessages.contains(message) { pendingMessages.append(message) } sharedToolbar.styleForError(message.isError) sharedToolbar.frame = messageHiddenFrame sharedToolbar.messageLabel.text = message.text var translucentNavBar: Bool = false if let navController = activeNavigationController, let navBar = navController.navigationBar as? NavigationBar { translucentNavBar = navBar.translucent navBar.extraView = sharedToolbar navController.navigationBar.insertSubview(sharedToolbar, atIndex: 0) } else if fallbackToBannerOnMainWindow { keyWindow.rootViewController?.view.addSubview(sharedToolbar) } else { return } currentMessage = message UIView.animateWithDuration(animateDuration) { sharedToolbar.frame = messageShownFrame sharedToolbar.alpha = 1 } currentMessageTimer?.invalidate() currentMessageTimer = NSTimer.after(message.duration) { pendingMessages = pendingMessages.filter { $0 != message } hideCurrentMessage(true, fadeOpacity: translucentNavBar, alreadyRemoved: true) { if let next = pendingMessages.last { showMessage(next) } } } } public static func showErrorMessage(messageType: MessageType, code: Int? = nil, duration: NSTimeInterval = Message.defaultDisplayTime) -> Message { if messageType == .Unspecified { return showErrorMessage(messageType.rawValue, code: code, duration: duration) } else { return showErrorMessage(messageType.rawValue, code: nil, duration: duration) } } public static func showErrorMessage(text: String, code: Int? = nil, duration: NSTimeInterval = Message.defaultDisplayTime) -> Message { var text = text if let code = code where code != 0 { text = String(text.characters.dropLast()) + ": \(code)" } let message = Message(text: text, displayDuration: duration, isError: true) showMessage(message) return message } public static func cancelMessage(toCancel: Message, animated: Bool = true) { guard NSThread.mainThread() == NSThread.currentThread() else { NSOperationQueue.mainQueue().addOperationWithBlock { cancelMessage(toCancel, animated: animated) } return } if let current = currentMessage where toCancel == current { hideCurrentMessage(animated) } else { pendingMessages = pendingMessages.filter { $0 != toCancel } } } public static func cancelAllMessages(animated: Bool) { guard NSThread.mainThread() == NSThread.currentThread() else { NSOperationQueue.mainQueue().addOperationWithBlock { cancelAllMessages(animated) } return } hideCurrentMessage(animated) pendingMessages = [] } private static var keyWindow: UIWindow { return UIApplication.sharedApplication().keyWindow! } private static var activeNavigationController: UINavigationController? { let rootVC = keyWindow.rootViewController! if let navController = rootVC as? UINavigationController { return navController } else if let navController = rootVC.navigationController { return navController } else if let tabBarController = rootVC as? UITabBarController { let selectedVC = tabBarController.selectedViewController! if let navController = selectedVC as? UINavigationController { if let visibleViewController = navController.visibleViewController, let visibleNavController = visibleViewController.navigationController { return visibleNavController } else { return navController } } else if let navController = selectedVC.navigationController { return navController } } else if let navController = rootVC.childViewControllers.first?.navigationController { return navController } return nil } @IBOutlet private weak var messageLabel: UILabel! @IBOutlet weak var messageButton: UIButton! @IBOutlet weak var closeButton: UIButton! private var underStatusBarView: UIView? private static var sharedToolbar: NotificationBanner = { let b = NSBundle(forClass: NotificationBanner.classForCoder()) let t = b.loadNibNamed(String(NotificationBanner), owner: nil, options: nil).first as! NotificationBanner t.messageButton.addTarget(t, action: #selector(NotificationBanner.messageLabelTapped(_:)), forControlEvents: .TouchUpInside) t.closeButton.addTarget(t, action: #selector(NotificationBanner.closeButtonTapped(_:)), forControlEvents: .TouchUpInside) NSNotificationCenter.defaultCenter().addObserverForName(NotificationBannerShouldDisplayErrorNotification, object: nil, queue: .mainQueue(), usingBlock: { (notification:NSNotification) in if let error = notification.object as? NSError { NotificationBanner.showErrorMessage(error.localizedDescription) } else if let errorText = notification.object as? String { NotificationBanner.showErrorMessage(errorText) } else { NotificationBanner.showErrorMessage(.Unspecified) } }) return t }() private static var currentMessageTimer: NSTimer? private static var currentMessage: Message? private static var pendingMessages = [Message]() private class var messageShownFrame: CGRect { let y: CGFloat if let navigationBar = activeNavigationController?.navigationBar where sharedToolbar.superview == navigationBar { y = navigationBar.frame.height } else { y = UIApplication.sharedApplication().statusBarHidden ? 0 : UIApplication.sharedApplication().statusBarFrame.height } return CGRect(x: 0, y: y, width: UIScreen.mainScreen().bounds.width, height: sharedToolbar.frame.height) } private class var messageHiddenFrame: CGRect { return CGRect(x: 0, y: -sharedToolbar.frame.height, width: UIScreen.mainScreen().bounds.width, height: sharedToolbar.frame.height) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private static func hideCurrentMessage(animated: Bool, fadeOpacity: Bool = false, alreadyRemoved: Bool = false, completion: (()->())? = nil) { if !alreadyRemoved && pendingMessages.count > 0 { pendingMessages.removeLast() } if animated { UIView.animateWithDuration(animateDuration, animations: { sharedToolbar.frame = messageHiddenFrame if fadeOpacity { sharedToolbar.alpha = 0 } }, completion: { finished in sharedToolbar.alpha = 0 completion?() }) } else { sharedToolbar.frame = messageHiddenFrame completion?() } currentMessageTimer?.invalidate() currentMessageTimer = nil currentMessage = nil } @IBAction @objc private func messageLabelTapped(sender: UIButton) { if let key = NotificationBanner.currentMessage?.actionKey, let action = Message.actions[key] { action() } } @IBAction @objc private func closeButtonTapped(sender: UIButton) { NotificationBanner.hideCurrentMessage(true) { if let next = NotificationBanner.pendingMessages.last { NotificationBanner.showMessage(next) } } } private func styleForError(isError: Bool) { backgroundColor = isError ? NotificationBanner.errorBackgroundColor : NotificationBanner.regularBackgroundColor messageLabel.textColor = .whiteColor() } private func addStatusBarBackingView() { let underStatusBar = UIView(frame: CGRectZero) underStatusBar.backgroundColor = backgroundColor.colorWithAlphaComponent(0.85) //UIColor(white: 0.2, alpha: 0.85) underStatusBar.translatesAutoresizingMaskIntoConstraints = false addSubview(underStatusBar) let views = ["underStatusBar":underStatusBar] addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[underStatusBar]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(-20)-[underStatusBar(20)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) underStatusBarView = underStatusBar } }
mit
66ce62df0a62e6b3c532e87e2d6059c3
37.603448
194
0.643963
5.489988
false
false
false
false
matthewpurcell/firefox-ios
Client/Frontend/Reader/ReadabilityService.swift
9
4233
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit private let ReadabilityServiceSharedInstance = ReadabilityService() private let ReadabilityTaskDefaultTimeout = 15 private let ReadabilityServiceDefaultConcurrency = 1 enum ReadabilityOperationResult { case Success(ReadabilityResult) case Error(NSError) case Timeout } class ReadabilityOperation: NSOperation, WKNavigationDelegate, ReadabilityBrowserHelperDelegate { var url: NSURL var semaphore: dispatch_semaphore_t var result: ReadabilityOperationResult? var browser: Browser! var readerModeCache: ReaderModeCache init(url: NSURL, readerModeCache: ReaderModeCache) { self.url = url self.semaphore = dispatch_semaphore_create(0) self.readerModeCache = readerModeCache } override func main() { if self.cancelled { return } // Setup a browser, attach a Readability helper. Kick all this off on the main thread since UIKit // and WebKit are not safe from other threads. dispatch_async(dispatch_get_main_queue(), { () -> Void in let configuration = WKWebViewConfiguration() self.browser = Browser(configuration: configuration) self.browser.createWebview() self.browser.navigationDelegate = self if let readabilityBrowserHelper = ReadabilityBrowserHelper(browser: self.browser) { readabilityBrowserHelper.delegate = self self.browser.addHelper(readabilityBrowserHelper, name: ReadabilityBrowserHelper.name()) } // Load the page in the webview. This either fails with a navigation error, or we get a readability // callback. Or it takes too long, in which case the semaphore times out. self.browser.loadRequest(NSURLRequest(URL: self.url)) }) if dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, Int64(Double(ReadabilityTaskDefaultTimeout) * Double(NSEC_PER_SEC)))) != 0 { result = ReadabilityOperationResult.Timeout } // Maybe this is where we should store stuff in the cache / run a callback? if let result = self.result { switch result { case .Timeout: // Don't do anything on timeout break case .Success(let readabilityResult): do { try readerModeCache.put(url, readabilityResult) } catch let error as NSError { print("Failed to store readability results in the cache: \(error.localizedDescription)") // TODO Fail } case .Error(_): // TODO Not entitely sure what to do on error. Needs UX discussion and followup bug. break } } } func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { result = ReadabilityOperationResult.Error(error) dispatch_semaphore_signal(semaphore) } func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { result = ReadabilityOperationResult.Error(error) dispatch_semaphore_signal(semaphore) } func readabilityBrowserHelper(readabilityBrowserHelper: ReadabilityBrowserHelper, didFinishWithReadabilityResult readabilityResult: ReadabilityResult) { result = ReadabilityOperationResult.Success(readabilityResult) dispatch_semaphore_signal(semaphore) } } class ReadabilityService { class var sharedInstance: ReadabilityService { return ReadabilityServiceSharedInstance } var queue: NSOperationQueue init() { queue = NSOperationQueue() queue.maxConcurrentOperationCount = ReadabilityServiceDefaultConcurrency } func process(url: NSURL, cache: ReaderModeCache) { queue.addOperation(ReadabilityOperation(url: url, readerModeCache: cache)) } }
mpl-2.0
d9119b8153ee2149a65cf144a98a3f66
36.803571
156
0.672336
5.569737
false
false
false
false
maranas/activityindicators
activityindicators/Classes/GLSImageRotationsActivityIndicatorView.swift
1
3223
// // GLSImageRotationsActivityIndicatorView.swift // activityindicators // // Created by Moises Anthony Aranas on 7/13/15. // Copyright © 2015 ganglion software. All rights reserved. // import UIKit /** **GLSImageRotationsActivityIndicatorView** A view that displays a rotating image activity indicator. */ class GLSImageRotationsActivityIndicatorView: UIView { fileprivate var animating : Bool = false fileprivate weak var imageView : UIImageView? fileprivate var yAnimation : CAKeyframeAnimation? fileprivate var xAnimation : CAKeyframeAnimation? /** If true, the activity indicator becomes hidden when stopped. */ var hidesWhenStopped : Bool = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override required init(frame: CGRect) { super.init(frame: frame) commonInit() } /** Common initializer logic for the spin indicator. */ fileprivate func commonInit() { let imageView = UIImageView(frame: self.bounds) self.addSubview(imageView) self.imageView = imageView } /** Sets the image to use for the progress indicator. *image* - A UIImage to use for the progress indicator. */ func setImage(_ image:UIImage) { self.imageView?.image = image } /** Starts the image rotation animation. */ func startAnimating() { if self.isAnimating() { return } self.layer.isHidden = false self.animating = true self.layer.transform.m34 = 1.0 / -300 self.yAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.y") self.yAnimation?.values = [0, Double.pi, Double.pi, 2*Double.pi, 2*Double.pi] self.yAnimation?.keyTimes = [0, 0.2, 0.4, 0.8, 1.0] self.yAnimation?.calculationMode = kCAAnimationLinear self.xAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.x") self.xAnimation?.values = [0, 0, Double.pi, Double.pi, 2*Double.pi] self.xAnimation?.keyTimes = [0, 0.2, 0.4, 0.8, 1.0] self.xAnimation?.calculationMode = kCAAnimationLinear let animationGroup = CAAnimationGroup() animationGroup.animations = [self.yAnimation!, self.xAnimation!] animationGroup.duration = 3.0 animationGroup.repeatCount = Float.infinity self.layer.add(animationGroup, forKey: "rotation") } /** Stops the image rotation animation. */ func stopAnimating() { if !self.isAnimating() { return } self.animating = false self.layer.isHidden = self.hidesWhenStopped self.layer.removeAllAnimations() } /** Returns if the rotation indicator is animating. *returns* - A boolean indicator if the animation is in progress. */ func isAnimating() -> Bool { return self.animating } override func layoutSubviews() { super.layoutSubviews() self.imageView?.frame = self.layer.bounds self.imageView?.frame = self.layer.bounds } }
mit
583f65514663207271e64ef4e036d0d0
27.017391
85
0.624767
4.557284
false
false
false
false
Romdeau4/16POOPS
Helps_Kitchen_iOS/Help's Kitchen/TableInfoViewController.swift
1
6937
// // TableInfoViewController.swift // Help's Kitchen // // Created by Stephen Ulmer on 2/23/17. // Copyright © 2017 Stephen Ulmer. All rights reserved. // import UIKit import Firebase class TableInfoViewController: CustomTableViewController { let ref = FIRDatabase.database().reference(fromURL: DataAccess.URL) var selectedTable: Table? struct OrderStatus { var keys: [String]! var status: String! var orders: [Order]! } var placedOrders = OrderStatus() var inProgressOrders = OrderStatus() var readyOrders = OrderStatus() var seeKitchenOrders = OrderStatus() var orderArray = [OrderStatus]() override func viewDidLoad() { super.viewDidLoad() tableView.register(CustomTableCell.self, forCellReuseIdentifier: "cell") navigationItem.title = "Tables" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add Order", style: .plain, target: self, action: #selector(handleNewOrder)) // Do any additional setup after loading the view. fetchTableOrders() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) fetchTableOrders() } func initOrderArrays(){ orderArray = [OrderStatus]() placedOrders.status = "Placed" inProgressOrders.status = "In Progress" readyOrders.status = "Ready" seeKitchenOrders.status = "See Kitchen" placedOrders.orders = [Order]() inProgressOrders.orders = [Order]() readyOrders.orders = [Order]() seeKitchenOrders.orders = [Order]() } func fetchTableOrders() { ref.child("Orders").observeSingleEvent(of: .value, with: { (snapshot) in self.initOrderArrays() let orderListSnapshot = snapshot.childSnapshot(forPath: "OrderList") for eachOrderStatus in snapshot.children { let thisOrderStatus = eachOrderStatus as! FIRDataSnapshot if thisOrderStatus.key != "OrderList" { if let keyArray = (thisOrderStatus.value as! [AnyObject]?) { var stringArray = [String]() for key in keyArray { if let str = key as? String{ stringArray.append(str) }else if let num = key as? Int{ stringArray.append(String(describing: num)) } } switch thisOrderStatus.key { case "Placed": self.placedOrders.keys = stringArray self.placedOrders.orders = self.getOrdersWith(keyArray: stringArray, orderListSnapshot: orderListSnapshot) case "InProgress": self.inProgressOrders.keys = stringArray self.inProgressOrders.orders = self.getOrdersWith(keyArray: stringArray, orderListSnapshot: orderListSnapshot) case "SeeKitchen": self.seeKitchenOrders.keys = stringArray self.seeKitchenOrders.orders = self.getOrdersWith(keyArray: stringArray, orderListSnapshot: orderListSnapshot) case "Ready": self.readyOrders.keys = stringArray self.readyOrders.orders = self.getOrdersWith(keyArray: stringArray, orderListSnapshot: orderListSnapshot) default: print("not one of those") } } } } self.orderArray.append(self.readyOrders) self.orderArray.append(self.seeKitchenOrders) self.orderArray.append(self.inProgressOrders) self.orderArray.append(self.placedOrders) DispatchQueue.main.async { self.tableView.reloadData() } }) } func getOrdersWith(keyArray: [String], orderListSnapshot: FIRDataSnapshot) -> [Order] { var orders = [Order]() for key in keyArray{ if key != "" { if let tableKey = orderListSnapshot.childSnapshot(forPath: key).childSnapshot(forPath: "tableKey").value as? String { if key != "" && selectedTable?.key == tableKey { if let dict = orderListSnapshot.childSnapshot(forPath: String( describing:key)).value as! [String : AnyObject]? { let order = Order() order.setValuesForKeys(dict) orders.append(order) } } } } } return orders } func handleCancel() { dismiss(animated: true, completion: nil) } func handleNewOrder() { let orderController = NewOrderViewController() orderController.selectedTable = self.selectedTable present(orderController, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> CustomTableCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableCell cell.textLabel?.text = orderArray[indexPath.section].orders[indexPath.row].item cell.setColors() return cell } override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return orderArray.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return orderArray[section].status } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { view.tintColor = CustomColor.Yellow500 (view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.black } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return orderArray[section].orders.count } }
mit
ab6aeabe73cef3a64a71cd24747ce4cb
35.893617
143
0.553057
5.685246
false
false
false
false
yeziahehe/Gank
Pods/Kingfisher/Sources/General/Deprecated.swift
1
28492
// // Deprecated.swift // Kingfisher // // Created by onevcat on 2018/09/28. // // Copyright (c) 2019 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 canImport(AppKit) import AppKit #elseif canImport(UIKit) import UIKit #endif // MARK: - Deprecated extension KingfisherWrapper where Base: Image { @available(*, deprecated, message: "Will be removed soon. Pass parameters with `ImageCreatingOptions`, use `image(with:options:)` instead.") public static func image( data: Data, scale: CGFloat, preloadAllAnimationData: Bool, onlyFirstFrame: Bool) -> Image? { let options = ImageCreatingOptions( scale: scale, duration: 0.0, preloadAll: preloadAllAnimationData, onlyFirstFrame: onlyFirstFrame) return KingfisherWrapper.image(data: data, options: options) } @available(*, deprecated, message: "Will be removed soon. Pass parameters with `ImageCreatingOptions`, use `animatedImage(with:options:)` instead.") public static func animated( with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? { let options = ImageCreatingOptions( scale: scale, duration: duration, preloadAll: preloadAll, onlyFirstFrame: onlyFirstFrame) return animatedImage(data: data, options: options) } } @available(*, deprecated, message: "Will be removed soon. Use `Result<RetrieveImageResult>` based callback instead") public typealias CompletionHandler = ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> Void) @available(*, deprecated, message: "Will be removed soon. Use `Result<ImageLoadingResult>` based callback instead") public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> Void) // MARK: - Deprecated @available(*, deprecated, message: "Will be removed soon. Use `DownloadTask` to cancel a task.") extension RetrieveImageTask { @available(*, deprecated, message: "RetrieveImageTask.empty will be removed soon. Use `nil` to represent a no task.") public static let empty = RetrieveImageTask() } // MARK: - Deprecated extension KingfisherManager { /// Get an image with resource. /// If `.empty` is used as `options`, Kingfisher will seek the image in memory and disk first. /// If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`. /// These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more. /// /// - Parameters: /// - resource: Resource object contains information such as `cacheKey` and `downloadURL`. /// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called every time downloaded data changed. This could be used as a progress UI. /// - completionHandler: Called when the whole retrieving process finished. /// - Returns: A `RetrieveImageTask` task object. You can use this object to cancel the task. @available(*, deprecated, message: "Use `Result` based callback instead.") @discardableResult public func retrieveImage(with resource: Resource, options: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> DownloadTask? { return retrieveImage(with: resource, options: options, progressBlock: progressBlock) { result in switch result { case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url) case .failure(let error): completionHandler?(nil, error as NSError, .none, resource.downloadURL) } } } } // MARK: - Deprecated extension ImageDownloader { @available(*, deprecated, message: "Use `Result` based callback instead.") @discardableResult open func downloadImage(with url: URL, retrieveImageTask: RetrieveImageTask? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: ImageDownloaderProgressBlock? = nil, completionHandler: ImageDownloaderCompletionHandler?) -> DownloadTask? { return downloadImage(with: url, options: options, progressBlock: progressBlock) { result in switch result { case .success(let value): completionHandler?(value.image, nil, value.url, value.originalData) case .failure(let error): completionHandler?(nil, error as NSError, nil, nil) } } } } @available(*, deprecated, message: "RetrieveImageDownloadTask is removed. Use `DownloadTask` to cancel a task.") public struct RetrieveImageDownloadTask { } @available(*, deprecated, message: "RetrieveImageTask is removed. Use `DownloadTask` to cancel a task.") public final class RetrieveImageTask { } @available(*, deprecated, message: "Use `DownloadProgressBlock` instead.", renamed: "DownloadProgressBlock") public typealias ImageDownloaderProgressBlock = DownloadProgressBlock #if !os(watchOS) // MARK: - Deprecated extension KingfisherWrapper where Base: ImageView { @available(*, deprecated, message: "Use `Result` based callback instead.") @discardableResult public func setImage(with resource: Resource?, placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler?) -> DownloadTask? { return setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock) { result in switch result { case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url) case .failure(let error): completionHandler?(nil, error as NSError, .none, nil) } } } } #endif #if canImport(UIKit) && !os(watchOS) // MARK: - Deprecated extension KingfisherWrapper where Base: UIButton { @available(*, deprecated, message: "Use `Result` based callback instead.") @discardableResult public func setImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler?) -> DownloadTask? { return setImage( with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock) { result in switch result { case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url) case .failure(let error): completionHandler?(nil, error as NSError, .none, nil) } } } @available(*, deprecated, message: "Use `Result` based callback instead.") @discardableResult public func setBackgroundImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler?) -> DownloadTask? { return setBackgroundImage( with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock) { result in switch result { case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url) case .failure(let error): completionHandler?(nil, error as NSError, .none, nil) } } } } #endif #if os(watchOS) import WatchKit // MARK: - Deprecated extension KingfisherWrapper where Base: WKInterfaceImage { @available(*, deprecated, message: "Use `Result` based callback instead.") @discardableResult public func setImage(_ resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler?) -> DownloadTask? { return setImage( with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock) { result in switch result { case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url) case .failure(let error): completionHandler?(nil, error as NSError, .none, nil) } } } } #endif #if os(macOS) // MARK: - Deprecated extension KingfisherWrapper where Base: NSButton { @discardableResult @available(*, deprecated, message: "Use `Result` based callback instead.") public func setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler?) -> DownloadTask? { return setImage( with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock) { result in switch result { case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url) case .failure(let error): completionHandler?(nil, error as NSError, .none, nil) } } } @discardableResult @available(*, deprecated, message: "Use `Result` based callback instead.") public func setAlternateImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler?) -> DownloadTask? { return setAlternateImage( with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock) { result in switch result { case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url) case .failure(let error): completionHandler?(nil, error as NSError, .none, nil) } } } } #endif // MARK: - Deprecated extension ImageCache { /// The largest cache cost of memory cache. The total cost is pixel count of /// all cached images in memory. /// Default is unlimited. Memory cache will be purged automatically when a /// memory warning notification is received. @available(*, deprecated, message: "Use `memoryStorage.config.totalCostLimit` instead.", renamed: "memoryStorage.config.totalCostLimit") open var maxMemoryCost: Int { get { return memoryStorage.config.totalCostLimit } set { memoryStorage.config.totalCostLimit = newValue } } /// The default DiskCachePathClosure @available(*, deprecated, message: "Not needed anymore.") public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String { let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! return (dstPath as NSString).appendingPathComponent(cacheName) } /// The default file extension appended to cached files. @available(*, deprecated, message: "Use `diskStorage.config.pathExtension` instead.", renamed: "diskStorage.config.pathExtension") open var pathExtension: String? { get { return diskStorage.config.pathExtension } set { diskStorage.config.pathExtension = newValue } } ///The disk cache location. @available(*, deprecated, message: "Use `diskStorage.directoryURL.absoluteString` instead.", renamed: "diskStorage.directoryURL.absoluteString") public var diskCachePath: String { return diskStorage.directoryURL.absoluteString } /// The largest disk size can be taken for the cache. It is the total /// allocated size of cached files in bytes. /// Default is no limit. @available(*, deprecated, message: "Use `diskStorage.config.sizeLimit` instead.", renamed: "diskStorage.config.sizeLimit") open var maxDiskCacheSize: UInt { get { return UInt(diskStorage.config.sizeLimit) } set { diskStorage.config.sizeLimit = newValue } } @available(*, deprecated, message: "Use `diskStorage.cacheFileURL(forKey:).path` instead.", renamed: "diskStorage.cacheFileURL(forKey:)") open func cachePath(forComputedKey key: String) -> String { return diskStorage.cacheFileURL(forKey: key).path } /** Get an image for a key from disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. If you need to retrieve an image which was stored with a specified `ImageProcessor`, pass the processor in the option too. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ @available(*, deprecated, message: "Use `Result` based `retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:)` instead.", renamed: "retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:)") open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? { let options = options ?? .empty let computedKey = key.computedKey(with: options.processor.identifier) do { if let data = try diskStorage.value(forKey: computedKey) { return options.cacheSerializer.image(with: data, options: options) } } catch {} return nil } @available(*, deprecated, message: "Use `Result` based `retrieveImage(forKey:options:callbackQueue:completionHandler:)` instead.", renamed: "retrieveImage(forKey:options:callbackQueue:completionHandler:)") open func retrieveImage(forKey key: String, options: KingfisherOptionsInfo?, completionHandler: ((Image?, CacheType) -> Void)?) { retrieveImage( forKey: key, options: options, callbackQueue: .dispatch((options ?? .empty).callbackDispatchQueue)) { result in do { let value = try result.get() completionHandler?(value.image, value.cacheType) } catch { completionHandler?(nil, .none) } } } /// The longest time duration in second of the cache being stored in disk. /// Default is 1 week (60 * 60 * 24 * 7 seconds). /// Setting this to a negative value will make the disk cache never expiring. @available(*, deprecated, message: "Deprecated. Use `diskStorage.config.expiration` instead") open var maxCachePeriodInSecond: TimeInterval { get { return diskStorage.config.expiration.timeInterval } set { diskStorage.config.expiration = .seconds(newValue) } } @available(*, deprecated, message: "Use `Result` based callback instead.") open func store(_ image: Image, original: Data? = nil, forKey key: String, processorIdentifier identifier: String = "", cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, toDisk: Bool = true, completionHandler: (() -> Void)?) { store( image, original: original, forKey: key, processorIdentifier: identifier, cacheSerializer: serializer, toDisk: toDisk) { _ in completionHandler?() } } @available(*, deprecated, message: "Use the `Result`-based `calculateDiskStorageSize` instead.") open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> Void)) { calculateDiskStorageSize { result in let size: UInt? = try? result.get() handler(size ?? 0) } } } // MARK: - Deprecated extension Collection where Iterator.Element == KingfisherOptionsInfoItem { /// The queue of callbacks should happen from Kingfisher. @available(*, deprecated, message: "Use `callbackQueue` instead.", renamed: "callbackQueue") public var callbackDispatchQueue: DispatchQueue { return KingfisherParsedOptionsInfo(Array(self)).callbackQueue.queue } } /// Error domain of Kingfisher @available(*, deprecated, message: "Use `KingfisherError.domain` instead.", renamed: "KingfisherError.domain") public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error" /// Key will be used in the `userInfo` of `.invalidStatusCode` @available(*, unavailable, message: "Use `.invalidHTTPStatusCode` or `isInvalidResponseStatusCode` of `KingfisherError` instead for the status code.") public let KingfisherErrorStatusCodeKey = "statusCode" // MARK: - Deprecated extension Collection where Iterator.Element == KingfisherOptionsInfoItem { /// The target `ImageCache` which is used. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `targetCache` instead.") public var targetCache: ImageCache? { return KingfisherParsedOptionsInfo(Array(self)).targetCache } /// The original `ImageCache` which is used. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `originalCache` instead.") public var originalCache: ImageCache? { return KingfisherParsedOptionsInfo(Array(self)).originalCache } /// The `ImageDownloader` which is specified. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `downloader` instead.") public var downloader: ImageDownloader? { return KingfisherParsedOptionsInfo(Array(self)).downloader } /// Member for animation transition when using UIImageView. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `transition` instead.") public var transition: ImageTransition { return KingfisherParsedOptionsInfo(Array(self)).transition } /// A `Float` value set as the priority of image download task. The value for it should be /// between 0.0~1.0. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `downloadPriority` instead.") public var downloadPriority: Float { return KingfisherParsedOptionsInfo(Array(self)).downloadPriority } /// Whether an image will be always downloaded again or not. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `forceRefresh` instead.") public var forceRefresh: Bool { return KingfisherParsedOptionsInfo(Array(self)).forceRefresh } /// Whether an image should be got only from memory cache or download. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `fromMemoryCacheOrRefresh` instead.") public var fromMemoryCacheOrRefresh: Bool { return KingfisherParsedOptionsInfo(Array(self)).fromMemoryCacheOrRefresh } /// Whether the transition should always happen or not. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `forceTransition` instead.") public var forceTransition: Bool { return KingfisherParsedOptionsInfo(Array(self)).forceTransition } /// Whether cache the image only in memory or not. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheMemoryOnly` instead.") public var cacheMemoryOnly: Bool { return KingfisherParsedOptionsInfo(Array(self)).cacheMemoryOnly } /// Whether the caching operation will be waited or not. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `waitForCache` instead.") public var waitForCache: Bool { return KingfisherParsedOptionsInfo(Array(self)).waitForCache } /// Whether only load the images from cache or not. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onlyFromCache` instead.") public var onlyFromCache: Bool { return KingfisherParsedOptionsInfo(Array(self)).onlyFromCache } /// Whether the image should be decoded in background or not. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `backgroundDecode` instead.") public var backgroundDecode: Bool { return KingfisherParsedOptionsInfo(Array(self)).backgroundDecode } /// Whether the image data should be all loaded at once if it is an animated image. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `preloadAllAnimationData` instead.") public var preloadAllAnimationData: Bool { return KingfisherParsedOptionsInfo(Array(self)).preloadAllAnimationData } /// The `CallbackQueue` on which completion handler should be invoked. /// If not set in the options, `.mainCurrentOrAsync` will be used. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `callbackQueue` instead.") public var callbackQueue: CallbackQueue { return KingfisherParsedOptionsInfo(Array(self)).callbackQueue } /// The scale factor which should be used for the image. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `scaleFactor` instead.") public var scaleFactor: CGFloat { return KingfisherParsedOptionsInfo(Array(self)).scaleFactor } /// The `ImageDownloadRequestModifier` will be used before sending a download request. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `requestModifier` instead.") public var modifier: ImageDownloadRequestModifier? { return KingfisherParsedOptionsInfo(Array(self)).requestModifier } /// `ImageProcessor` for processing when the downloading finishes. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `processor` instead.") public var processor: ImageProcessor { return KingfisherParsedOptionsInfo(Array(self)).processor } /// `ImageModifier` for modifying right before the image is displayed. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `imageModifier` instead.") public var imageModifier: ImageModifier? { return KingfisherParsedOptionsInfo(Array(self)).imageModifier } /// `CacheSerializer` to convert image to data for storing in cache. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheSerializer` instead.") public var cacheSerializer: CacheSerializer { return KingfisherParsedOptionsInfo(Array(self)).cacheSerializer } /// Keep the existing image while setting another image to an image view. /// Or the placeholder will be used while downloading. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `keepCurrentImageWhileLoading` instead.") public var keepCurrentImageWhileLoading: Bool { return KingfisherParsedOptionsInfo(Array(self)).keepCurrentImageWhileLoading } /// Whether the options contains `.onlyLoadFirstFrame`. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onlyLoadFirstFrame` instead.") public var onlyLoadFirstFrame: Bool { return KingfisherParsedOptionsInfo(Array(self)).onlyLoadFirstFrame } /// Whether the options contains `.cacheOriginalImage`. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheOriginalImage` instead.") public var cacheOriginalImage: Bool { return KingfisherParsedOptionsInfo(Array(self)).cacheOriginalImage } /// The image which should be used when download image request fails. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onFailureImage` instead.") public var onFailureImage: Optional<Image?> { return KingfisherParsedOptionsInfo(Array(self)).onFailureImage } /// Whether the `ImagePrefetcher` should load images to memory in an aggressive way or not. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `alsoPrefetchToMemory` instead.") public var alsoPrefetchToMemory: Bool { return KingfisherParsedOptionsInfo(Array(self)).alsoPrefetchToMemory } /// Whether the disk storage file loading should happen in a synchronous behavior or not. @available(*, deprecated, message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `loadDiskFileSynchronously` instead.") public var loadDiskFileSynchronously: Bool { return KingfisherParsedOptionsInfo(Array(self)).loadDiskFileSynchronously } } /// The default modifier. /// It does nothing and returns the image as is. @available(*, deprecated, message: "Use `nil` in KingfisherOptionsInfo to indicate no modifier.") public struct DefaultImageModifier: ImageModifier { /// A default `DefaultImageModifier` which can be used everywhere. public static let `default` = DefaultImageModifier() private init() {} /// Modifies an input `Image`. See `ImageModifier` protocol for more. public func modify(_ image: Image) -> Image { return image } }
gpl-3.0
a7aaabffe114768003ad3f8273a08221
42.565749
131
0.670609
5.33658
false
false
false
false
lvnyk/BezierString
BezierString/Bezier.swift
1
9030
// // BezierPath.swift // // Created by Luka on 26/12/15. // Copyright (c) 2015 lvnyk. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // MARK: Helpers extension CGPath { typealias Applier = @convention(block) (UnsafePointer<CGPathElement>) -> () func forEach(_ applier: Applier) { let callback: CGPathApplierFunction = { (info, element) in let applier = unsafeBitCast(info, to: Applier.self) applier(element) } self.apply(info: unsafeBitCast(applier, to: UnsafeMutableRawPointer.self), function: callback) } } class Box<T> { var value: T init(value: T) { self.value = value } } // MARK: - Bezier Path /// Contains a list of Bezier Curves struct Bezier { /// Bezier Curve of the n-th order struct Curve { typealias Value = (value: CGFloat, at: CGFloat) let points: [CGPoint] fileprivate let diffs: [CGPoint] fileprivate let cache = Box(value: [Value(0, 0)]) init(point: CGPoint...) { points = point diffs = zip(point.dropFirst(), point).map(-) } } let path: CGPath // CGPath used instead of UIBezierPath for its immutability fileprivate let curves: [Curve] /// - parameter path: UIBezierPath - preferably continuous init(path: CGPath) { self.path = path var curves = [Curve]() var last: CGPoint? path.forEach({ let p = $0.pointee switch p.type { case .moveToPoint: last = p.points[0] case .addLineToPoint: if let first = last { last = p.points[0] curves.append(Curve(point: first, last!)) } case .addQuadCurveToPoint: if let first = last { last = p.points[1] curves.append(Curve(point: first, p.points[0], last!)) } case .addCurveToPoint: if let first = last { last = p.points[2] curves.append(Curve(point: first, p.points[0], p.points[1], last!)) } case .closeSubpath: last = nil break; } }) self.curves = curves } } // MARK: - BezierCurve extension Bezier.Curve { struct Binomial { private static var c = [[1]] /// - returns: Binomial Coefficients for the order n static func coefficients(for n: Int) -> [Int] { if n < Binomial.c.count { return Binomial.c[n] } let prev = coefficients(for: (n - 1)) let new = zip([0]+prev, prev+[0]).map(+) Binomial.c.append(new) return new } /// Sums up the list of items static func sum(_ list: [CGPoint], t: CGFloat) -> CGPoint { let count = CGFloat(list.count) return zip(Binomial.coefficients(for: list.count - 1), list).enumerated().reduce(CGPoint.zero) { sum, d in let i = CGFloat(d.offset) let b = CGFloat(d.element.0) return sum + pow(t, i)*pow(1-t, count-1-i) * b * d.element.1 } } } /** Finds the parameter t for given length - parameter length: length along the path - parameter left: left value for initial bisection (only used if no values have been previously cached) - returns: parameter t */ func t(at length: CGFloat, left: Value=(0,0)) -> Value { let length = max(0, min(length, self.length())) if let t = cache.value.lazy.filter({$0.value == length}).first { return t } let left = cache.value.lazy.filter({$0.value < length}).last ?? left let right = cache.value.lazy.filter({$0.value > length}).first ?? (self.length(), 1) return bisect(length, left: left, right: right) } /** Recursive bisection step while searching for the parameter t - parameter find: length for which we're searching t for - parameter left: left boundary - parameter right: right boundary - parameter depth: bisection step number - returns: final value */ func bisect(_ find: CGFloat, left: Value, right: Value, depth: Int = 0) -> Value { let split = (find-left.value)/(right.value-left.value) // 0...1 let t = (left.at*(1-split) + right.at*(split)) // search for the solution closer to the boundary that it is nearer to let guess = Value(self.length(at: t), t) if abs(find-guess.value) < 0.15 || depth > 10 { return guess } if guess.value < find { return bisect(find, left: guess, right: right, depth: (depth + 1)) } else { return bisect(find, left: left, right: guess, depth: (depth + 1)) } } /// - returns: Derivative of the curve at t func d(at t:CGFloat) -> CGPoint { return Binomial.sum(diffs, t: t) * CGFloat(diffs.count) } /// - returns: Location on the curve at t func position(at t: CGFloat) -> CGPoint { return Binomial.sum(points, t: t) } /// Calculated using the [Gauss-Legendre quadrature](http://pomax.github.io/bezierinfo/legendre-gauss.html) /// - returns: Length of the curve at t func length(at t: CGFloat=1) -> CGFloat { let t = max(0, min(t, 1)) if let length = cache.value.lazy.filter({$0.at==t}).first { return length.value } // Gauss-Legendre quadrature let length = Bezier.Curve.glvalues[(diffs.count - 1)].reduce(CGFloat(0.0)) { sum, table in let tt = t/2 * (table.abscissa + 1) return sum + t/2 * table.weight * self.d(at: tt).distanceTo(.zero) } cache.value.insert((length, t), at: cache.value.index { $0.at>t } ?? cache.value.endIndex) // keep it sorted return length } /// [Weight and abscissa](http://pomax.github.io/bezierinfo/legendre-gauss.html) values private static let glvalues:[[(weight: CGFloat, abscissa: CGFloat)]] = [ [ // line - 2 (1.0000000000000000, -0.5773502691896257), (1.0000000000000000, 0.5773502691896257) ], [ // quadratic - 16 (0.1894506104550685, -0.0950125098376374), (0.1894506104550685, 0.0950125098376374), (0.1826034150449236, -0.2816035507792589), (0.1826034150449236, 0.2816035507792589), (0.1691565193950025, -0.4580167776572274), (0.1691565193950025, 0.4580167776572274), (0.1495959888165767, -0.6178762444026438), (0.1495959888165767, 0.6178762444026438), (0.1246289712555339, -0.7554044083550030), (0.1246289712555339, 0.7554044083550030), (0.0951585116824928, -0.8656312023878318), (0.0951585116824928, 0.8656312023878318), (0.0622535239386479, -0.9445750230732326), (0.0622535239386479, 0.9445750230732326), (0.0271524594117541, -0.9894009349916499), (0.0271524594117541, 0.9894009349916499) ], [ // cubic - 24 (0.1279381953467522, -0.0640568928626056), (0.1279381953467522, 0.0640568928626056), (0.1258374563468283, -0.1911188674736163), (0.1258374563468283, 0.1911188674736163), (0.1216704729278034, -0.3150426796961634), (0.1216704729278034, 0.3150426796961634), (0.1155056680537256, -0.4337935076260451), (0.1155056680537256, 0.4337935076260451), (0.1074442701159656, -0.5454214713888396), (0.1074442701159656, 0.5454214713888396), (0.0976186521041139, -0.6480936519369755), (0.0976186521041139, 0.6480936519369755), (0.0861901615319533, -0.7401241915785544), (0.0861901615319533, 0.7401241915785544), (0.0733464814110803, -0.8200019859739029), (0.0733464814110803, 0.8200019859739029), (0.0592985849154368, -0.8864155270044011), (0.0592985849154368, 0.8864155270044011), (0.0442774388174198, -0.9382745520027328), (0.0442774388174198, 0.9382745520027328), (0.0285313886289337, -0.9747285559713095), (0.0285313886289337, 0.9747285559713095), (0.0123412297999872, -0.9951872199970213), (0.0123412297999872, 0.9951872199970213) ] ] } // MARK: - API extension Bezier { /// - returns: Total length of the path func length() -> CGFloat { return self.curves.reduce(CGFloat(0)) { sum, c in return sum + c.length() } } /// - returns: Path properties (position and normal) at given length. /// nil if out of bounds func properties(at length: CGFloat) -> (position: CGPoint, normal: CGFloat)? { var length = length for curve in curves { let l = curve.length() if length <= l { let t = curve.t(at: length).at let pos = curve.position(at: t) let rot = curve.d(at: t) return (pos, atan2(rot.y, rot.x)) } length -= l } return nil } }
mit
0ad28ed9b812a717a0d3d1e1b5b2ac8d
28.80198
124
0.671429
2.887752
false
false
false
false
GuyKahlon/CloneYO
YO/ServerUtility.swift
1
4120
// // AppDelegate.swift // YO // // Created by Guy Kahlon on 1/14/15. // Copyright (c) 2015 GuyKahlon. All rights reserved. // let kUserNotFound : Int = 999 let kErrorMessageKey : String = "error" class ServerUtility { class func registerUserToPushNotification(){ if let user = PFUser.currentUser(){ var installation = PFInstallation.currentInstallation() installation.setObject(user, forKey: "user") installation.saveInBackgroundWithBlock(nil) } } class func signUp(username:String, password:String,email: String, successClosure:()->(), failureClosure:(error: NSError) -> ()){ var user = PFUser() user.username = username user.password = password user.email = email user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError!) -> Void in if error == nil { successClosure() self.registerUserToPushNotification() } else { failureClosure(error: error) } } } class func login(username:String, password:String, successClosure:()->(), failureClosure:(error: NSError) -> ()){ PFUser.logInWithUsernameInBackground(username, password:password) { (user: PFUser!, error: NSError!) -> Void in if let loginError = error { failureClosure(error: error) } else { successClosure() self.registerUserToPushNotification() } } } class func sentYO(username: String, callbackClosure:(error: NSError?)->()){ var userQuery = PFUser.query() userQuery.whereKey("username", equalTo: username) userQuery.findObjectsInBackgroundWithBlock { (users: [AnyObject]!, error: NSError!) -> Void in if error != nil { callbackClosure(error: error) } else if users.count < 1{ callbackClosure( error: NSError(domain: "Send YO", code: kUserNotFound, userInfo: [kErrorMessageKey: "The username '\(username)' not found"])) } else{ // Find devices associated with these users let pushInstallationQuery = PFInstallation.query() pushInstallationQuery.whereKey("user", matchesQuery: userQuery) // Send push notification to query let push = PFPush() push.setQuery(pushInstallationQuery) // Set our Installation query // Set push notification data let data = ["alert" : "YO FROM \(PFUser.currentUser().username)", "sound" : "YO.caf"] push.setData(data) push.sendPushInBackgroundWithBlock({ (succeeded: Bool, error:NSError!) -> Void in if succeeded{ callbackClosure(error: nil) } else{ callbackClosure(error: error) } }) } } } class func logout(){ PFUser.logOut() } class func currentUser() -> PFUser?{ return PFUser.currentUser() } class func sendResetPasswordMail(username: String, callbackClosure:(succeeded : Bool, error: NSError!)->()){ var userQuery = PFUser.query() userQuery.whereKey("username", equalTo: username) userQuery.findObjectsInBackgroundWithBlock({ (users: [AnyObject]!, error: NSError!) -> Void in if let user = users.first as? PFUser where user.email != nil{ PFUser.requestPasswordResetForEmailInBackground(user.email, block:callbackClosure) } else{ callbackClosure(succeeded: false, error: NSError(domain: "ResetPassword", code: kUserNotFound, userInfo: ["user" : "User not found"])) } }) } }
mit
50c0934787cdd41aaedb3da4fd4cd59d
35.469027
149
0.542718
5.406824
false
false
false
false
andrea-prearo/SwiftExamples
AutolayoutScrollView/AutolayoutScrollView/LoginViewController.swift
1
3556
// // LoginViewController.swift // AutoLayoutScrollView // // Created by Andrea Prearo on 5/24/15. // Copyright (c) 2015 Andrea Prearo. All rights reserved. // import UIKit let LoginToFirstSegue = "LoginToFirstSegue" class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signInButton: UIButton! var didLayoutSubviews = false var initialContentSizeHeight: CGFloat = 0.0 override func viewDidLoad() { super.viewDidLoad() usernameTextField.delegate = self passwordTextField.delegate = self let defaultCenter = NotificationCenter.default defaultCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) defaultCenter.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if (didLayoutSubviews || scrollView.contentSize.height == 0.0) { return; } didLayoutSubviews = true initialContentSizeHeight = scrollView.contentSize.height } // MARK: UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == usernameTextField { passwordTextField.becomeFirstResponder() return false } else if textField == passwordTextField { passwordTextField.resignFirstResponder() signInButtonTapped(textField) } return true } // MARK: Keyboard Events @objc func keyboardWillShow(_ notification: Notification) { guard let userInfo = (notification as NSNotification).userInfo, let end = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } let keyboardHeight = end.cgRectValue.size.height var contentSize = scrollView.contentSize contentSize.height = initialContentSizeHeight + keyboardHeight scrollView.contentSize = contentSize scrollView.setContentOffset(CGPoint(x: 0, y: keyboardHeight), animated: true) } @objc func keyboardWillHide(_ notification: Notification) { var contentSize = scrollView.contentSize contentSize.height = initialContentSizeHeight scrollView.contentSize = contentSize scrollView.setContentOffset(CGPoint.zero, animated: true) } // MARK: Actions @IBAction func signInButtonTapped(_ sender: AnyObject) { if let username = usernameTextField.text, let password = passwordTextField.text, !username.isEmpty && !password.isEmpty { performSegue(withIdentifier: LoginToFirstSegue, sender: self) } else { let alert = UIAlertView(title: "Error", message: "Any non-empty username/password combination works!", delegate: nil, cancelButtonTitle: "OK") alert.show() } } // MARK: Orientation Changes override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) didLayoutSubviews = false } }
mit
752735bd675606f6cf0368c4a7609cb4
34.56
143
0.666479
5.791531
false
false
false
false
eonil/toolbox.swift
EonilToolbox/LayoutBox/SilentBoxSplitExtensions.swift
1
6886
// // SilentBoxSplitExtensions.swift // EonilToolbox // // Created by Hoon H. on 2016/06/16. // Copyright © 2016 Eonil. All rights reserved. // import CoreGraphics //postfix operator * { //} //postfix func *(p: Int) -> SilentBoxPartition { // return SilentBoxPartition.soft(proportion: CGFloat(p)) //} postfix operator % public postfix func %(p: Int) -> SilentBoxPartition { return SilentBoxPartition.soft(proportion: CGFloat(p) / 100) } /// - TODO: Figure out why `SilentBox.Scalar` causes some error and /// replace `CGFloat` to `SilentBox.Scalar`. public enum SilentBoxPartition { case rigid(length: CGFloat) case soft(proportion: CGFloat) } extension SilentBoxPartition: ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral { public typealias IntegerLiteralType = Int public typealias FloatLiteralType = Double public init(integerLiteral value: IntegerLiteralType) { self = .rigid(length: CGFloat(value)) } public init(floatLiteral value: FloatLiteralType) { self = .rigid(length: CGFloat(value)) } } private extension SilentBoxPartition { var rigidLength: SilentBox.Scalar? { switch self { case let .rigid(length): return length default: return nil } } var softProportion: SilentBox.Scalar? { switch self { case let .soft(proportion): return proportion default: return nil } } } public extension SilentBox { fileprivate func splitInX<S: Sequence>(_ partitions: S) -> AnySequence<SilentBox> where S.Iterator.Element == CGFloat { assert(size.x - partitions.reduce(0, +) > -0.1) return AnySequence { () -> AnyIterator<SilentBox> in var pg = partitions.makeIterator() var budget = self return AnyIterator { () -> SilentBox? in guard let p = pg.next() else { return nil } let (a, b) = budget.splitAtX(budget.min.x + p) budget = b return a } } } fileprivate func splitInY<S: Sequence>(_ partitions: S) -> AnySequence<SilentBox> where S.Iterator.Element == CGFloat { assert(size.y - partitions.reduce(0, +) > -0.1) return AnySequence { () -> AnyIterator<SilentBox> in var pg = partitions.makeIterator() var budget = self return AnyIterator { () -> SilentBox? in guard let p = pg.next() else { return nil } let (a, b) = budget.splitAtY(budget.min.y + p) budget = b return a } } } public func splitInX(_ partitions: [SilentBoxPartition]) -> [SilentBox] { assert(size.x >= 0) let totalRigidLength = partitions.map({ $0.rigidLength ?? 0 }).reduce(0, +) let totalProportion = partitions.map({ $0.softProportion ?? 0 }).reduce(0, +) let finalTotalCompressedRigidLength = Swift.min(totalRigidLength, size.x) let finalRigidCompressionRatio = (finalTotalCompressedRigidLength == 0) ? 0 : (finalTotalCompressedRigidLength / totalRigidLength) let softAvailableLength = (totalProportion == 0) ? 0 : ((size.x - finalTotalCompressedRigidLength) / totalProportion) let partitionLengths = partitions.map({ (partition: SilentBoxPartition) -> CGFloat in switch partition { case let .rigid(length): return length * finalRigidCompressionRatio case let .soft(proportion): return proportion * softAvailableLength } }) let occupyingLength = finalTotalCompressedRigidLength + softAvailableLength let startingPoint = min.x + (size.x - occupyingLength) / 2 let budgetArea = splitAtX(startingPoint).max return Array(budgetArea.splitInX(partitionLengths)) } public func splitInY(_ partitions: [SilentBoxPartition]) -> [SilentBox] { assert(size.y >= 0) let totalRigidLength = partitions.map({ $0.rigidLength ?? 0 }).reduce(0, +) let totalProportion = partitions.map({ $0.softProportion ?? 0 }).reduce(0, +) let finalTotalCompressedRigidLength = Swift.min(totalRigidLength, size.y) let finalRigidCompressionRatio = (finalTotalCompressedRigidLength == 0) ? 0 : (finalTotalCompressedRigidLength / totalRigidLength) let softAvailableLength = (totalProportion == 0) ? 0 : ((size.y - finalTotalCompressedRigidLength) / totalProportion) let partitionLengths = partitions.map({ (partition: SilentBoxPartition) -> CGFloat in switch partition { case let .rigid(length): return length * finalRigidCompressionRatio case let .soft(proportion): return proportion * softAvailableLength } }) let occupyingLength = finalTotalCompressedRigidLength + softAvailableLength let startingPoint = min.y + (size.y - occupyingLength) / 2 let budgetArea = splitAtY(startingPoint).max return Array(budgetArea.splitInY(partitionLengths)) } } public extension SilentBox { public func splitInX(_ min: SilentBoxPartition, _ mid: SilentBoxPartition, _ max: SilentBoxPartition) -> (SilentBox, SilentBox, SilentBox) { let a = splitInX([min, mid, max]) return (a[0], a[1], a[2]) } public func splitInY(_ min: SilentBoxPartition, _ mid: SilentBoxPartition, _ max: SilentBoxPartition) -> (SilentBox, SilentBox, SilentBox) { let a = splitInY([min, mid, max]) return (a[0], a[1], a[2]) } // public func splitInY(_ min: SilentBoxPartition, _ max: SilentBoxPartition) -> (min: SilentBox, max: SilentBox) { // let a = splitInY([min, max]) // return (a[0], a[1]) // } } public extension SilentBox { public func splitInX<A: SilentBoxPartitionType, B: SilentBoxPartitionType, C: SilentBoxPartitionType>(_ min: A, _ mid: B, _ max: C) -> (min: SilentBox, mid: SilentBox, max: SilentBox) { return splitInX(min.toPartition(), mid.toPartition(), max.toPartition()) } public func splitInY<A: SilentBoxPartitionType, B: SilentBoxPartitionType, C: SilentBoxPartitionType>(_ min: A, _ mid: B, _ max: C) -> (min: SilentBox, mid: SilentBox, max: SilentBox) { return splitInY(min.toPartition(), mid.toPartition(), max.toPartition()) } } public protocol SilentBoxPartitionType { func toPartition() -> SilentBoxPartition } extension SilentBoxPartition: SilentBoxPartitionType { public func toPartition() -> SilentBoxPartition { return self } } extension Int: SilentBoxPartitionType { public func toPartition() -> SilentBoxPartition { return .rigid(length: CGFloat(self)) } } extension CGFloat: SilentBoxPartitionType { public func toPartition() -> SilentBoxPartition { return .rigid(length: self) } }
mit
82cd9ee917faba9afe13a7ba2815c736
39.5
189
0.644299
4.016919
false
false
false
false
inaturalist/INaturalistIOS
INaturalistIOS/Controllers/Media Picker/MediaPickerSegue.swift
1
760
// // MediaPickerSegue.swift // iNaturalist // // Created by Alex Shepard on 5/24/20. // Copyright © 2020 iNaturalist. All rights reserved. // import UIKit class MediaPickerSegue: UIStoryboardSegue { private var selfRetainer: MediaPickerSegue? = nil lazy var slideInTransitioningDelegate = SlideInPresentationManager() override func perform() { destination.transitioningDelegate = slideInTransitioningDelegate // hold a strong reference to self so that the the transitioning delegate // doesn't get dealloced while we're running the dismiss animation(s) selfRetainer = self destination.modalPresentationStyle = .custom source.present(destination, animated: true, completion: nil) } }
mit
9cebf83768a6922b67e880eae2540d0e
32
81
0.720685
4.773585
false
false
false
false
onevcat/Kingfisher
Sources/SwiftUI/KFImageRenderer.swift
2
4605
// // KFImageRenderer.swift // Kingfisher // // Created by onevcat on 2021/05/08. // // Copyright (c) 2021 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 canImport(SwiftUI) && canImport(Combine) import SwiftUI import Combine /// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`. /// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`. @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) struct KFImageRenderer<HoldingView> : View where HoldingView: KFImageHoldingView { @StateObject var binder: KFImage.ImageBinder = .init() let context: KFImage.Context<HoldingView> var body: some View { ZStack { context.configurations .reduce(HoldingView.created(from: binder.loadedImage, context: context)) { current, config in config(current) } .opacity(binder.loaded ? 1.0 : 0.0) if binder.loadedImage == nil { ZStack { if let placeholder = context.placeholder, let view = placeholder(binder.progress) { view } else { Color.clear } } .onAppear { [weak binder = self.binder] in guard let binder = binder else { return } if !binder.loadingOrSucceeded { binder.start(context: context) } } .onDisappear { [weak binder = self.binder] in guard let binder = binder else { return } if context.cancelOnDisappear { binder.cancel() } } } } // Workaround for https://github.com/onevcat/Kingfisher/issues/1988 // on iOS 16 there seems to be a bug that when in a List, the `onAppear` of the `ZStack` above in the // `binder.loadedImage == nil` not get called. Adding this empty `onAppear` fixes it and the life cycle can // work again. // // There is another "fix": adding an `else` clause and put a `Color.clear` there. But I believe this `onAppear` // should work better. // // It should be a bug in iOS 16, I guess it is some kinds of over-optimization in list cell loading caused it. .onAppear() } } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) extension Image { // Creates an Image with either UIImage or NSImage. init(crossPlatformImage: KFCrossPlatformImage?) { #if canImport(UIKit) self.init(uiImage: crossPlatformImage ?? KFCrossPlatformImage()) #elseif canImport(AppKit) self.init(nsImage: crossPlatformImage ?? KFCrossPlatformImage()) #endif } } #if canImport(UIKit) @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) extension UIImage.Orientation { func toSwiftUI() -> Image.Orientation { switch self { case .down: return .down case .up: return .up case .left: return .left case .right: return .right case .upMirrored: return .upMirrored case .downMirrored: return .downMirrored case .leftMirrored: return .leftMirrored case .rightMirrored: return .rightMirrored @unknown default: return .up } } } #endif #endif
mit
da16449a4971ec4ac728c344aba46f43
39.043478
119
0.608252
4.54142
false
false
false
false
Stjng/StingLibrary
StingLibrary/String+Date.swift
1
990
// // String+Date.swift // Football App // // Created by Thua Ha on 8/3/15. // Copyright (c) 2015 Thua Ha. All rights reserved. // import Foundation extension String { func toDate() -> String { var formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm" var date = formatter.dateFromString(self) formatter.dateFormat = "dd MMM yyyy - HH:mm" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) if let newDate = date { return formatter.stringFromDate(newDate) } return "" } func toDateWithoutHours() -> String { var formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" var date = formatter.dateFromString(self) formatter.dateFormat = "dd MMM yyyy" if let date = date { return formatter.stringFromDate(date) } return "" } }
mit
9a56d81fabbae3c4dbef8e50f5cac5b8
22.046512
61
0.559596
4.583333
false
false
false
false
kamleshgk/iOSStarterTemplate
foodcolors/Classes/ViewControllers/BookDetailViewController.swift
1
11369
// // BookDetailViewController.swift // foodcolors // // Created by kamyFCMacBook on 1/18/17. // Copyright © 2017 foodcolors. All rights reserved. // import UIKit class BookDetailViewController: UIViewController { @IBOutlet weak var bookImage: UIImageView! @IBOutlet weak var subTitleLabel: UILabel! @IBOutlet weak var costLabel: UILabel! @IBOutlet weak var productDescription: UITextView! @IBOutlet var pickerViewBox: UIView! @IBOutlet weak var pickerShowButton1: UIButton! @IBOutlet weak var pickerShowButton2: UIButton! @IBOutlet weak var quantityLabel: UILabel! @IBOutlet weak var totalCostLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var addCartButton: UIButton! var quantitySelected:Int = -1 var bookDetailObject : BookDetails? = nil @IBOutlet weak var textViewHeightContraint: NSLayoutConstraint! @IBOutlet weak var scrollBarHeightConstraint: NSLayoutConstraint! @IBOutlet weak var messageView: UIView! @IBOutlet weak var messageLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() pickerViewBox.layer.cornerRadius = 10 let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor(red: 0.42, green: 0.81, blue: 0.023, alpha: 1.0)] self.navigationController!.navigationBar.titleTextAttributes = titleDict as? [String : AnyObject] view.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true self.messageView.layer.borderWidth = 1 self.messageView.layer.borderColor = UIColor(red: 0.42, green: 0.81, blue: 0.023, alpha: 1.0).cgColor } override func viewWillAppear(_ animated: Bool) { if ((bookDetailObject) != nil) { quantitySelected = -1 var image = UIImage(named: "Placeholder") if (bookDetailObject?.bookImage != nil) { image = (bookDetailObject?.bookImage)! as UIImage } else { image = UIImage(named: "Placeholder") } bookImage.image = image let label = UILabel(frame: CGRect(x:0, y:0, width:400, height:50)) label.backgroundColor = UIColor.clear label.numberOfLines = 2 label.font = UIFont.boldSystemFont(ofSize: 16.0) label.textAlignment = .center label.textColor = UIColor(red: 0.42, green: 0.81, blue: 0.023, alpha: 1.0) label.text = bookDetailObject?.productTitle self.navigationItem.titleView = label subTitleLabel.text = bookDetailObject?.productSubTitle costLabel.text = (bookDetailObject?.price)! + " €" productDescription.text = bookDetailObject?.description textViewHeightContraint.constant = productDescription.sizeThatFits(CGSize(width: CGFloat(productDescription.frame.size.width), height: CGFloat(CGFloat.greatestFiniteMagnitude))).height quantityLabel.text = "1" let priceInt:Float? = Float((bookDetailObject?.price)!) //let quantityInt:Float? = Float((bookDetailObject?.quantityAvailable)!) let totalCost:Float? = Float(priceInt! * 1) let myStringToTwoDecimals = String(format:"%.2f", totalCost!) totalCostLabel.text = "Total: " + myStringToTwoDecimals + " €" } self.navigationItem.rightBarButtonItem = nil let session = UserSessionInfo.sharedUser() as UserSessionInfo let cartImage = UIImage(named: "carts") let myBarButtonItem = UIBarButtonItem(badge: "0", image: cartImage!, target: self, action: #selector(self.goKart)) messageView.isHidden = true messageLabel.isHidden = true if (session.cartList.count == 0) { myBarButtonItem.badgeString = "0" } else { myBarButtonItem.badgeString = String(session.cartList.count) var bookExistsInCart:Bool bookExistsInCart = false var quantityInCart:Int32 = 0 var index:Int index = 0 for item in session.cartList { let cartItem:CartDetails cartItem = item as! CartDetails if (cartItem.cartType == Music) { index = index + 1 continue } let bookDetailInfo:BookDetails bookDetailInfo = cartItem.itemDetails as! BookDetails if (bookDetailInfo.idelement == self.bookDetailObject?.idelement) { quantityInCart = cartItem.quantity //Book already exists in Cart bookExistsInCart = true break } index = index + 1 } if (bookExistsInCart == true) { //update the quantity of that product in the cart self.showDodo(quantity: Int(quantityInCart)) } } self.navigationItem.rightBarButtonItem = myBarButtonItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Button Handlers @IBAction func pickerShow(_ sender: Any) { self.showPicker(sender) } @IBAction func pickerShowAgain(_ sender: Any) { self.showPicker(sender) } @IBAction func addCartACtion(_ sender: Any) { self.navigationItem.rightBarButtonItem = nil let session = UserSessionInfo.sharedUser() as UserSessionInfo let cartImage = UIImage(named: "carts") let myBarButtonItem = UIBarButtonItem(badge: "0", image: cartImage!, target: self, action: #selector(self.goKart)) let cartObject = CartDetails() cartObject.cartType = Books cartObject.itemDetails = self.bookDetailObject let price:Float? = Float((self.bookDetailObject?.price)!) let quantityString = self.quantityLabel.text let totalCost:Float? = Float(price! * Float(quantityString!)!) if (session.cartList.count == 0) { //If there are no products in Cart, blindly add it cartObject.quantity = Int32(quantityString!)! cartObject.cost = totalCost! session.cartList.add(cartObject) self.showDodo(quantity: Int(quantityString!)!) } else { //Else make checks :-| var bookExistsInCart:Bool bookExistsInCart = false var index:Int index = 0 for item in session.cartList { let cartItem:CartDetails cartItem = item as! CartDetails if (cartItem.cartType == Music) { index = index + 1 continue } let bookDetailInfo:BookDetails bookDetailInfo = cartItem.itemDetails as! BookDetails if (bookDetailInfo.idelement == self.bookDetailObject?.idelement) { //Book already exists in Cart bookExistsInCart = true break } index = index + 1 } if (bookExistsInCart == true) { //update the quantity of that product in the cart cartObject.quantity = Int32(quantityString!)! cartObject.cost = totalCost! //Update our session cart with new object session.cartList[index] = cartObject self.showDodo(quantity: Int(cartObject.quantity)) } else { cartObject.quantity = Int32(quantityString!)! cartObject.cost = totalCost! session.cartList.add(cartObject) self.showDodo(quantity: Int(quantityString!)!) } } myBarButtonItem.badgeString = String(session.cartList.count) self.navigationItem.rightBarButtonItem = myBarButtonItem } // MARK: - Private Methods func goKart() { self.performSegue(withIdentifier: "showCart", sender: self) } func showPicker(_ sender: Any) { var stringArray : [String] = [] let quantityInt:Int? = Int((bookDetailObject?.quantityAvailable)!) if (self.quantitySelected == -1) { self.quantitySelected = 1 } for index in 0 ..< (quantityInt!) { let stringVal = String((index+1)) stringArray.append(stringVal) //stringArray[index] = stringVal } ActionSheetStringPicker.show(withTitle: "Select Quantity", rows: stringArray, initialSelection: (self.quantitySelected - 1), doneBlock: { picker, value, index in print("value = \(value)") print("index = \(index)") print("picker = \(picker)") let priceInt:Float? = Float((self.bookDetailObject?.price)!) let quantityString = index as! String let totalCost:Float? = Float(priceInt! * Float(quantityString)!) let myStringToTwoDecimals = String(format:"%.2f", totalCost!) self.totalCostLabel.text = "Total: " + myStringToTwoDecimals + " €" self.quantityLabel.text = quantityString self.quantitySelected = Int(quantityString)! return }, cancel: { ActionStringCancelBlock in return }, origin: sender) } private func showDodo(quantity:Int) { let stringVal = " The product is present in the basket with a quantity of " + String(quantity) + " elements" messageLabel.text = stringVal messageView.isHidden = false messageLabel.isHidden = false } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
10999928905ab598cf15cd6abb6749d8
30.473684
196
0.541454
5.331769
false
false
false
false
sakebook/CallbackSample
CallbackSample/WebViewController.swift
1
1943
// // WebViewController.swift // CallbackSample // // Created by 酒本 伸也 on 2015/07/28. // Copyright (c) 2015年 酒本 伸也. All rights reserved. // import Foundation import UIKit final class WebViewController: UIViewController { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var customNavigationItem: UINavigationItem! var article: QiitaArticle? override func viewDidLoad() { super.viewDidLoad() if let article = article { customNavigationItem.title = article.title let url = NSURL(string: article.url) let request = NSURLRequest(URL: url!) webView.loadRequest(request) } // TODO: else urlがなかった場合の処理 } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) println("WebViewController: viewWillAppear") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) println("WebViewController: viewDidAppear") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) println("WebViewController: viewWillDisappear") } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) println("WebViewController: viewDidDisappear") NSNotificationCenter.defaultCenter().postNotificationName(NOTIFICATION_COMEBACK_WEB_VIEW, object: nil) } @IBAction func clickClose(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } } extension WebViewController { internal static func getController(board: UIStoryboard, article: QiitaArticle) -> UIViewController { let controller = board.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController controller.article = article return controller } }
apache-2.0
cf9393b40062a1d5c1dc572b084a688a
29.253968
113
0.686089
5.247934
false
false
false
false
913868456/DropDownList
GFDropDown.swift
1
5144
// // GFDropDown.swift // GFDropDownDemo // // Created by ECHINACOOP1 on 2017/4/1. // Copyright © 2017年 蔺国防. All rights reserved. // import UIKit let cellId = "cellID" class GFDropDown: UIView, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { var tableView : UITableView? var textField : UITextField? ///textFiled高度&&控件的高度 var textFieldH: CGFloat? ///tableView高度 var tableViewH: CGFloat? = 120 ///tableView的cell高度 var rowH : CGFloat? = 50 ///数据源 var data : [Any]? ///占位文字 var placeText : String? ///列表是否显示 var isShowList: Bool?{ didSet{ if isShowList! { self.superview?.bringSubview(toFront: self) //设置下拉动画 UIView.beginAnimations("ResizeForKeyBorard", context: nil ) UIView.setAnimationCurve(UIViewAnimationCurve.easeIn) self.frame.size.height = textFieldH! + tableViewH! tableView?.frame.size.height = tableViewH! UIView.commitAnimations() }else{ //设置上拉动画 UIView.beginAnimations("ResizeForKeyBorard", context: nil ) UIView.setAnimationCurve(UIViewAnimationCurve.easeIn) self.frame.size.height = textFieldH! tableView?.frame.size.height = 0 UIView.commitAnimations() } } } /** frame : frame dataArr : 数据源 placeHolde: 占位文字 */ init(frame: CGRect, dataArr:[Any], placeHolder: String) { super.init(frame: frame); data = dataArr placeText = placeHolder textFieldH = frame.size.height self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ //创建并设置textfield和tableView textField = UITextField.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: textFieldH!)) textField?.delegate = self textField?.placeholder = placeText textField?.layer.borderWidth = 1 textField?.layer.masksToBounds = true textField?.layer.cornerRadius = 5 textField?.layer.borderColor = UIColor.gray.cgColor textField?.placeholder = placeText tableView = UITableView.init(frame: CGRect.init(x: 0, y: self.frame.size.height, width: self.frame.size.width, height: 0)) tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId) tableView?.delegate = self tableView?.rowHeight = rowH! tableView?.dataSource = self tableView?.layer.cornerRadius = 5 tableView?.layer.masksToBounds = true tableView?.layer.borderWidth = 1 tableView?.layer.borderColor = UIColor.gray.cgColor self.addSubview(textField!) self.addSubview(tableView!) //初始化不显示列表 isShowList = false } //MARK: - UITextFieldDelegate func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{ //控制列表显示状态 if self.isShowList! { self.isShowList = false }else{ self.isShowList = true } //不允许TextField编辑 return false } //MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return (self.data?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: cellId) cell?.textLabel?.text = self.data?[indexPath.row] as? String cell?.selectionStyle = .none return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.isShowList = false textField?.text = self.data?[indexPath.row] as? String } //重写hitTest方法,来处理在View点击外区域收回下拉列表 override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if self.isUserInteractionEnabled == false && self.alpha <= 0.01 && self.isHidden == true { return nil } if self.point(inside: point, with: event) == false { self.isShowList = false return nil }else{ for subView in self.subviews.reversed() { let convertPoint = subView.convert(point, from: self) let hitTestView = subView.hitTest(convertPoint, with: event) if (hitTestView != nil) { return hitTestView } } return self } } }
apache-2.0
d7a5df3970beb30c4d68774d34586a42
28.849398
130
0.568113
4.910803
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadDataKit/Network/Models/Response/HDWalletResponse.swift
1
2934
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import WalletPayloadKit struct HDWalletResponse: Equatable, Codable { let seedHex: String let passphrase: String let mnemonicVerified: Bool let defaultAccountIndex: Int let accounts: [AccountResponse] enum CodingKeys: String, CodingKey { case seedHex = "seed_hex" case passphrase case mnemonicVerified = "mnemonic_verified" case defaultAccountIndex = "default_account_idx" case accounts } init( seedHex: String, passphrase: String, mnemonicVerified: Bool, defaultAccountIndex: Int, accounts: [AccountResponse] ) { self.seedHex = seedHex self.passphrase = passphrase self.mnemonicVerified = mnemonicVerified self.defaultAccountIndex = defaultAccountIndex self.accounts = accounts } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) seedHex = try container.decode(String.self, forKey: .seedHex) passphrase = try container.decode(String.self, forKey: .passphrase) mnemonicVerified = try container.decodeIfPresent(Bool.self, forKey: .mnemonicVerified) ?? false defaultAccountIndex = try container.decode(Int.self, forKey: .defaultAccountIndex) // attempt to decode version4 first and then version3, if both fail then an error will be thrown do { let accountsVersion4 = try container.decode([AccountWrapper.Version4].self, forKey: .accounts) accounts = try decodeAccounts( using: accountWrapperDecodingStrategy(version4:), value: accountsVersion4 ) .get() } catch is DecodingError { let accountsVersion3 = try container.decode([AccountWrapper.Version3].self, forKey: .accounts) accounts = try decodeAccounts( using: accountWrapperDecodingStrategy(version3:), value: accountsVersion3 ) .get() } } } extension WalletPayloadKit.HDWallet { static func from(model: HDWalletResponse) -> HDWallet { HDWallet( seedHex: model.seedHex, passphrase: model.passphrase, mnemonicVerified: model.mnemonicVerified, defaultAccountIndex: model.defaultAccountIndex, accounts: model.accounts.enumerated().map { index, model in WalletPayloadKit.Account.from(model: model, index: index) } ) } var toHDWalletResponse: HDWalletResponse { HDWalletResponse( seedHex: seedHex, passphrase: passphrase, mnemonicVerified: mnemonicVerified, defaultAccountIndex: defaultAccountIndex, accounts: accounts.map(\.toAccountResponse) ) } }
lgpl-3.0
519e56843ca953d75f7d5c7af0da9681
33.916667
106
0.640641
4.971186
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Public/Primitives/Color.swift
1
735
// // Color.swift // lottie-swift // // Created by Brandon Withrow on 2/4/19. // import Foundation public enum ColorFormatDenominator { case One case OneHundred case TwoFiftyFive var value: Double { switch self { case .One: return 1.0 case .OneHundred: return 100.0 case .TwoFiftyFive: return 255.0 } } } public struct Color { public var r: Double public var g: Double public var b: Double public var a: Double public init(r: Double, g: Double, b: Double, a: Double, denominator: ColorFormatDenominator = .One) { self.r = r / denominator.value self.g = g / denominator.value self.b = b / denominator.value self.a = a / denominator.value } }
mit
6488bfb173ba8a531806a0550c8cb911
16.926829
103
0.635374
3.466981
false
false
false
false
tache/SwifterSwift
Sources/Extensions/UIKit/UINavigationControllerExtensions.swift
1
1692
// // UINavigationControllerExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/6/16. // Copyright © 2016 SwifterSwift // #if os(iOS) || os(tvOS) import UIKit // MARK: - Methods public extension UINavigationController { /// SwifterSwift: Pop ViewController with completion handler. /// /// - Parameter completion: optional completion handler (default is nil). public func popViewController(_ completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) popViewController(animated: true) CATransaction.commit() } /// SwifterSwift: Push ViewController with completion handler. /// /// - Parameters: /// - viewController: viewController to push. /// - completion: optional completion handler (default is nil). public func pushViewController(_ viewController: UIViewController, completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) pushViewController(viewController, animated: true) CATransaction.commit() } /// SwifterSwift: Make navigation controller's navigation bar transparent. /// /// - Parameter tint: tint color (default is .white). public func makeTransparent(withTint tint: UIColor = .white) { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true navigationBar.tintColor = tint navigationBar.titleTextAttributes = [.foregroundColor: tint] } } #endif
mit
947957f05f5666c0802b64ea832d53e3
32.156863
102
0.746304
4.2275
false
false
false
false
mirego/taylor-ios
TaylorTests/UIViewSafeAreaTests.swift
1
4886
// // UIViewSafeAreaTests.swift // TaylorTests // // Created by Antoine Lamy on 2017-12-28. // Copyright © 2017 Mirego. All rights reserved. // import XCTest import Taylor class UIViewSafeAreaTests: XCTestCase { private var viewController: TestViewController! private var navigationController: UINavigationController! private var window: UIWindow! override class func setUp() { super.setUp() UIViewController.enableCompatibilitySafeAreaInsets() } override func setUp() { super.setUp() viewController = TestViewController() navigationController = UINavigationController(rootViewController: viewController) } override func tearDown() { super.tearDown() viewController = nil navigationController = nil window = nil } private func setupWindow(with viewController: UIViewController) { window = UIWindow() window.rootViewController = viewController window.addSubview(viewController.view) // Testing UIViewController's layout methods is kind of bad // but needed in our case so we need to wait some time RunLoop.current.run(until: Date().addingTimeInterval(1)) } func testOpaqueNavigationBar() { navigationController.navigationBar.barStyle = .blackOpaque navigationController.navigationBar.isTranslucent = false setupWindow(with: navigationController) let expectedSafeAreaInsets = UIEdgeInsets.zero let expectedOffsetViewSafeAreaInsets = UIEdgeInsets.zero if #available(iOS 11.0, *) { XCTAssertEqual(viewController.view.safeAreaInsets, expectedSafeAreaInsets) XCTAssertEqual(viewController.mainView.offsetView.safeAreaInsets, expectedOffsetViewSafeAreaInsets) XCTAssertFalse(viewController.mainView.safeAreaInsetsDidChangeCalled) } XCTAssertEqual(viewController.mainView.compatibilitySafeAreaInsets, expectedSafeAreaInsets) XCTAssertEqual(viewController.mainView.offsetView.compatibilitySafeAreaInsets, expectedOffsetViewSafeAreaInsets) XCTAssertFalse(viewController.mainView.compatibilitySafeAreaInsetsDidChangeCalled) } func testTranslucentNavigationBar() { let expectedSafeAreaInsets: UIEdgeInsets let expectedOffsetViewSafeAreaInsets: UIEdgeInsets if #available(iOS 11.0, *) { viewController.additionalSafeAreaInsets = UIEdgeInsets(top: 10, left: 10, bottom: 30, right: 0) expectedSafeAreaInsets = UIEdgeInsets(top: 54, left: 10, bottom: 30, right: 0) expectedOffsetViewSafeAreaInsets = UIEdgeInsets(top: 44, left: 10, bottom: 0, right: 0) } else { expectedSafeAreaInsets = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0) expectedOffsetViewSafeAreaInsets = UIEdgeInsets(top: 34, left: 0, bottom: 0, right: 0) } navigationController.navigationBar.barStyle = .blackTranslucent setupWindow(with: navigationController) if #available(iOS 11.0, *) { XCTAssertEqual(viewController.view.safeAreaInsets, expectedSafeAreaInsets) XCTAssertEqual(viewController.mainView.offsetView.safeAreaInsets, expectedOffsetViewSafeAreaInsets) XCTAssertTrue(viewController.mainView.safeAreaInsetsDidChangeCalled) } XCTAssertEqual(viewController.mainView.compatibilitySafeAreaInsets, expectedSafeAreaInsets) XCTAssertEqual(viewController.mainView.offsetView.compatibilitySafeAreaInsets, expectedOffsetViewSafeAreaInsets) XCTAssertTrue(viewController.mainView.compatibilitySafeAreaInsetsDidChangeCalled) } } fileprivate class TestViewController: UIViewController, IgnoreNewerSafeAreaInsets { var mainView: TestView { return self.view as! TestView } override func loadView() { self.view = TestView() } } fileprivate class TestView: UIView, CompatibilitySafeAreaInsetsUpdate, IgnoreNewerSafeAreaInsets { let offsetView = UIView() var safeAreaInsetsDidChangeCalled: Bool = false var compatibilitySafeAreaInsetsDidChangeCalled: Bool = false init() { super.init(frame: CGRect.zero) backgroundColor = UIColor.red offsetView.backgroundColor = UIColor.green addSubview(offsetView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() offsetView.frame = CGRect(x: 0, y: 10, width: bounds.width, height: 100) } func compatibilitySafeAreaInsetsDidChange() { compatibilitySafeAreaInsetsDidChangeCalled = true } @available(iOS 11.0, *) override func safeAreaInsetsDidChange() { super.safeAreaInsetsDidChange() safeAreaInsetsDidChangeCalled = true } }
bsd-3-clause
27b59b5bba0cd0b553d2aaaf92bde99b
37.769841
120
0.718321
5.538549
false
true
false
false
stripe/stripe-ios
StripeFinancialConnections/StripeFinancialConnections/Source/Web/AuthenticationSessionManager.swift
1
5544
// // AuthenticationSessionManager.swift // StripeFinancialConnections // // Created by Vardges Avetisyan on 12/3/21. // import UIKit import AuthenticationServices @_spi(STP) import StripeCore final class AuthenticationSessionManager: NSObject { // MARK: - Types enum Result { case success case webCancelled case nativeCancelled case redirect(url: URL) } // MARK: - Properties private var authSession: ASWebAuthenticationSession? private let manifest: FinancialConnectionsSessionManifest private var window: UIWindow? // MARK: - Init init(manifest: FinancialConnectionsSessionManifest, window: UIWindow?) { self.manifest = manifest self.window = window } // MARK: - Public func start(additionalQueryParameters: String? = nil) -> Promise<AuthenticationSessionManager.Result> { let promise = Promise<AuthenticationSessionManager.Result>() let urlString = manifest.hostedAuthUrl + (additionalQueryParameters ?? "") guard let url = URL(string: urlString) else { promise.reject(with: FinancialConnectionsSheetError.unknown(debugDescription: "Malformed hosted auth URL")) return promise } let authSession = ASWebAuthenticationSession( url: url, callbackURLScheme: URL(string: manifest.successUrl)?.scheme, completionHandler: { [weak self] returnUrl, error in guard let self = self else { return } if let error = error { if let authenticationSessionError = error as? ASWebAuthenticationSessionError { switch authenticationSessionError.code { case .canceledLogin: promise.resolve(with: .nativeCancelled) default: promise.reject(with: authenticationSessionError) } } else { promise.reject(with: error) } return } guard let returnUrlString = returnUrl?.absoluteString else { promise.reject(with: FinancialConnectionsSheetError.unknown(debugDescription: "Missing return URL")) return } if returnUrlString == self.manifest.successUrl { promise.resolve(with: .success) } else if returnUrlString == self.manifest.cancelUrl { promise.resolve(with: .webCancelled) } else if returnUrlString.starts(with: Constants.nativeRedirectPrefix), let targetURL = URL(string: returnUrlString.dropPrefix(Constants.nativeRedirectPrefix)) { promise.resolve(with: .redirect(url: targetURL)) } else { promise.reject(with: FinancialConnectionsSheetError.unknown(debugDescription: "Nil return URL")) } }) if #available(iOS 13.0, *) { authSession.presentationContextProvider = self authSession.prefersEphemeralWebBrowserSession = true } self.authSession = authSession if #available(iOS 13.4, *) { if !authSession.canStart { promise.reject(with: FinancialConnectionsSheetError.unknown(debugDescription: "Failed to start session")) return promise } } /** This terribly hacky animation disabling is needed to control the presentation of ASWebAuthenticationSession underlying view controller. Since we present a modal already that itself presents ASWebAuthenticationSession, the double modal animation is jarring and a bad UX. We disable animations for a second. Sometimes there is a delay in creating the ASWebAuthenticationSession underlying view controller to be safe, I made the delay a full second. I didn't find a good way to make this approach less clowny. PresentedViewController is not KVO compliant and the notifications sent by presentation view controller that could help with knowing when ASWebAuthenticationSession underlying view controller finished presenting are considered private API. */ let animationsEnabledOriginalValue = UIView.areAnimationsEnabled if #available(iOS 13, *) { UIView.setAnimationsEnabled(false) } if !authSession.start() { if #available(iOS 13, *) { UIView.setAnimationsEnabled(animationsEnabledOriginalValue) } promise.reject(with: FinancialConnectionsSheetError.unknown(debugDescription: "Failed to start session")) return promise } if #available(iOS 13, *) { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { UIView.setAnimationsEnabled(animationsEnabledOriginalValue) } } return promise } } // MARK: - ASWebAuthenticationPresentationContextProviding /// :nodoc: extension AuthenticationSessionManager: ASWebAuthenticationPresentationContextProviding { func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { return self.window ?? ASPresentationAnchor() } } // MARK: - Constants /// :nodoc: extension AuthenticationSessionManager { private enum Constants { static let nativeRedirectPrefix = "stripe-auth://native-redirect/" } }
mit
cb114387480b82d40ac780d50be2a29a
38.042254
177
0.636544
5.691992
false
false
false
false
stripe/stripe-ios
Example/CardImageVerification Example/CardImageVerification Example/View Controllers/ViewController.swift
1
1405
// // ViewController.swift // CardImageVerification Example // // Created by Jaime Park on 11/17/21. // import UIKit import StripeCardScan class ViewController: UIViewController { func displayAlert(title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: { _ in DispatchQueue.main.async { self.navigationController?.popViewController(animated: true) } }) alertController.addAction(OKAction) present(alertController, animated: true, completion: nil) } @IBAction func cardScanSheetExample() { let cardScanSheet = CardScanSheet() cardScanSheet.present(from: self) { [weak self] result in var title = "" var message = "" switch result { case .completed(let card): title = "Scan Completed" message = card.pan case .canceled: title = "Scan Canceled" message = "Canceled the scan" case .failed(let error): title = "Scan Failed" message = "Failed with error: \(error.localizedDescription)" } self?.displayAlert(title: title, message: message) } } }
mit
0f6b816b22e39a4a2b8aa036b5cd13dd
29.543478
103
0.584342
4.89547
false
false
false
false
ello/ello-ios
Sources/Utilities/KeyboardWindowExtension.swift
1
1233
//// /// KeyboardWindowExtension.swift // extension Keyboard { @objc func willShow(_ notification: Foundation.Notification) { isActive = true isAdjusting = bottomInset > 0 setFromNotification(notification) endFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue) .cgRectValue let window = UIWindow.mainWindow bottomInset = window.frame.size.height - endFrame.origin.y isExternal = endFrame.size.height > bottomInset postNotification(Notifications.KeyboardWillShow, value: self) } @objc func willHide(_ notification: Foundation.Notification) { setFromNotification(notification) endFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue) .cgRectValue bottomInset = 0 isAdjusting = false let windowBottom = UIWindow.mainWindow.frame.size.height if endFrame.origin.y >= windowBottom { isActive = false isExternal = false } else { isExternal = true } postNotification(Notifications.KeyboardWillHide, value: self) } }
mit
414dc22b2b1913040932a563d0b5f912
28.357143
89
0.63747
5.431718
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/04848-swift-sourcemanager-getmessage.swift
11
416
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { func b<e) -> c { struct A { let start = compose(e = [[] Void{ class d let f = [Void{ class B<T>: b { e) -> Void{ "\([] protocol c { func b<e) -> c { func a<T>: e) -> Void{ " let f = [Void{ let f = B<T where T: c : c { class case c, let f = [Voi
mit
e4446f0fb591d801d746bc91f372f31e
19.8
87
0.620192
2.810811
false
true
false
false
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/Common/Nodes/Effects/Delay/Variable Delay/AKVariableDelay.swift
1
4917
// // AKVariableDelay.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// A delay line with cubic interpolation. /// /// - parameter input: Input node to process /// - parameter time: Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. /// - parameter feedback: Feedback amount. Should be a value between 0-1. /// - parameter maximumDelayTime: The maximum delay time, in seconds. /// public class AKVariableDelay: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKVariableDelayAudioUnit? internal var token: AUParameterObserverToken? private var timeParameter: AUParameter? private var feedbackParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet(newValue) { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. public var time: Double = 1 { willSet(newValue) { if time != newValue { if internalAU!.isSetUp() { timeParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.time = Float(newValue) } } } } /// Feedback amount. Should be a value between 0-1. public var feedback: Double = 0 { willSet(newValue) { if feedback != newValue { if internalAU!.isSetUp() { feedbackParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.feedback = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this delay node /// /// - parameter input: Input node to process /// - parameter time: Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. /// - parameter feedback: Feedback amount. Should be a value between 0-1. /// - parameter maximumDelayTime: The maximum delay time, in seconds. /// public init( _ input: AKNode, time: Double = 1, feedback: Double = 0, maximumDelayTime: Double = 5) { self.time = time self.feedback = feedback var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x76646c61 /*'vdla'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKVariableDelayAudioUnit.self, asComponentDescription: description, name: "Local AKVariableDelay", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKVariableDelayAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } timeParameter = tree.valueForKey("time") as? AUParameter feedbackParameter = tree.valueForKey("feedback") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.timeParameter!.address { self.time = Double(value) } else if address == self.feedbackParameter!.address { self.feedback = Double(value) } } } internalAU?.time = Float(time) internalAU?.feedback = Float(feedback) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
apache-2.0
01fe1f35114c7e2bc9da88fa7bfa3486
33.384615
140
0.607077
5.219745
false
false
false
false
manavgabhawala/swift
test/ClangImporter/cf.swift
2
5868
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -import-cf-types -I %S/Inputs/custom-modules %s -verify-ignore-unknown // REQUIRES: objc_interop import CoreCooling import CFAndObjC func assertUnmanaged<T: AnyObject>(_ t: Unmanaged<T>) {} func assertManaged<T: AnyObject>(_ t: T) {} func test0(_ fridge: CCRefrigerator) { assertManaged(fridge) } func test1(_ power: Unmanaged<CCPowerSupply>) { assertUnmanaged(power) let fridge = CCRefrigeratorCreate(power) // expected-error {{cannot convert value of type 'Unmanaged<CCPowerSupply>' to expected argument type 'CCPowerSupply!'}} assertUnmanaged(fridge) } func test2() { let fridge = CCRefrigeratorCreate(kCCPowerStandard)! assertUnmanaged(fridge) } func test3(_ fridge: CCRefrigerator) { assertManaged(fridge) } func test4() { // FIXME: this should not require a type annotation let power: CCPowerSupply = kCCPowerStandard assertManaged(power) let fridge = CCRefrigeratorCreate(power)! assertUnmanaged(fridge) } func test5() { let power: Unmanaged<CCPowerSupply> = .passUnretained(kCCPowerStandard) assertUnmanaged(power) _ = CCRefrigeratorCreate(power.takeUnretainedValue()) } func test6() { let fridge = CCRefrigeratorCreate(nil) fridge?.release() } func test7() { let value = CFBottom()! assertUnmanaged(value) } func test8(_ f: CCRefrigerator) { _ = f as CFTypeRef _ = f as AnyObject } func test9() { let fridge = CCRefrigeratorCreateMutable(kCCPowerStandard).takeRetainedValue() let constFridge: CCRefrigerator = fridge CCRefrigeratorOpen(fridge) let item = CCRefrigeratorGet(fridge, 0).takeUnretainedValue() CCRefrigeratorInsert(item, fridge) // expected-error {{cannot convert value of type 'CCItem' to expected argument type 'CCMutableRefrigerator!'}} CCRefrigeratorInsert(constFridge, item) // expected-error {{cannot convert value of type 'CCRefrigerator' to expected argument type 'CCMutableRefrigerator!'}} CCRefrigeratorInsert(fridge, item) CCRefrigeratorClose(fridge) } func testProperty(_ k: Kitchen) { k.fridge = CCRefrigeratorCreate(kCCPowerStandard).takeRetainedValue() CCRefrigeratorOpen(k.fridge) CCRefrigeratorClose(k.fridge) } func testTollFree0(_ mduct: MutableDuct) { _ = mduct as CCMutableDuct let duct = mduct as Duct _ = duct as CCDuct } func testTollFree1(_ ccmduct: CCMutableDuct) { _ = ccmduct as MutableDuct let ccduct: CCDuct = ccmduct _ = ccduct as Duct } func testChainedAliases(_ fridge: CCRefrigerator) { _ = fridge as CCRefrigerator _ = fridge as CCFridge _ = fridge as CCFridgeRef // expected-error{{'CCFridgeRef' has been renamed to 'CCFridge'}} {{17-28=CCFridge}} } func testBannedImported(_ object: CCOpaqueTypeRef) { CCRetain(object) // expected-error {{'CCRetain' is unavailable: Core Foundation objects are automatically memory managed}} expected-warning {{result of call to 'CCRetain' is unused}} CCRelease(object) // expected-error {{'CCRelease' is unavailable: Core Foundation objects are automatically memory managed}} } func testOutParametersGood() { var fridge: CCRefrigerator? CCRefrigeratorCreateIndirect(&fridge) var power: CCPowerSupply? CCRefrigeratorGetPowerSupplyIndirect(fridge!, &power) var item: Unmanaged<CCItem>? CCRefrigeratorGetItemUnaudited(fridge!, 0, &item) } func testOutParametersBad() { let fridge: CCRefrigerator? CCRefrigeratorCreateIndirect(fridge) // expected-error {{cannot convert value of type 'CCRefrigerator?' to expected argument type 'UnsafeMutablePointer<CCRefrigerator?>?'}} let power: CCPowerSupply? CCRefrigeratorGetPowerSupplyIndirect(0, power) // expected-error {{cannot convert value of type 'Int' to expected argument type 'CCRefrigerator!'}} let item: CCItem? CCRefrigeratorGetItemUnaudited(0, 0, item) // expected-error {{cannot convert value of type 'Int' to expected argument type 'CCRefrigerator!'}} } func nameCollisions() { var objc: MyProblematicObject? var cf: MyProblematicObjectRef? cf = objc // expected-error {{cannot assign value of type 'MyProblematicObject?' to type 'MyProblematicObjectRef?'}} objc = cf // expected-error {{cannot assign value of type 'MyProblematicObjectRef?' to type 'MyProblematicObject?'}} var cfAlias: MyProblematicAliasRef? cfAlias = cf // okay cf = cfAlias // okay var otherAlias: MyProblematicAlias? otherAlias = cfAlias // expected-error {{cannot assign value of type 'MyProblematicAliasRef?' to type 'MyProblematicAlias?'}} cfAlias = otherAlias // expected-error {{cannot assign value of type 'MyProblematicAlias?' to type 'MyProblematicAliasRef?'}} func isOptionalFloat(_: inout Optional<Float>) {} isOptionalFloat(&otherAlias) // okay var np: NotAProblem? var np2: NotAProblemRef? // expected-error{{'NotAProblemRef' has been renamed to 'NotAProblem'}} {{12-26=NotAProblem}} np = np2 np2 = np } func testNonConstVoid() { let value: Unmanaged<CFNonConstVoidRef> = CFNonConstBottom()! assertUnmanaged(value) } class NuclearFridge: CCRefrigerator {} // expected-error {{cannot inherit from Core Foundation type 'CCRefrigerator'}} extension CCRefrigerator { @objc func foo() {} // expected-error {{method cannot be marked @objc because Core Foundation types are not classes in Objective-C}} func bar() {} // okay, implicitly non-objc } protocol SwiftProto {} @objc protocol ObjCProto {} extension CCRefrigerator: ObjCProto {} // expected-error {{Core Foundation class 'CCRefrigerator' cannot conform to @objc protocol 'ObjCProto' because Core Foundation types are not classes in Objective-C}} extension CCRefrigerator: SwiftProto {} // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: 'CCFridgeRef' was obsoleted in Swift 3 // <unknown>:0: error: unexpected note produced: 'NotAProblemRef' was obsoleted in Swift 3
apache-2.0
97688b608522435507b48bd28fac49d5
34.349398
205
0.753238
4.021933
false
true
false
false
koher/Argo
Argo/Types/StandardTypes.swift
1
2863
import Foundation extension String: Decodable { public static func decode(j: JSON) -> Decoded<String> { switch j { case let .String(s): return pure(s) default: return .typeMismatch("String", actual: j) } } } extension Int: Decodable { public static func decode(j: JSON) -> Decoded<Int> { switch j { case let .Number(n): return pure(n.integerValue) default: return .typeMismatch("Int", actual: j) } } } extension Int64: Decodable { public static func decode(j: JSON) -> Decoded<Int64> { switch j { case let .Number(n): return pure(n.longLongValue) case let .String(s): guard let i = Int64(s) else { fallthrough } return pure(i) default: return .typeMismatch("Int64", actual: j) } } } extension Double: Decodable { public static func decode(j: JSON) -> Decoded<Double> { switch j { case let .Number(n): return pure(n.doubleValue) default: return .typeMismatch("Double", actual: j) } } } extension Bool: Decodable { public static func decode(j: JSON) -> Decoded<Bool> { switch j { case let .Number(n): return pure(n.boolValue) default: return .typeMismatch("Bool", actual: j) } } } extension Float: Decodable { public static func decode(j: JSON) -> Decoded<Float> { switch j { case let .Number(n): return pure(n.floatValue) default: return .typeMismatch("Float", actual: j) } } } public extension Optional where Wrapped: Decodable, Wrapped == Wrapped.DecodedType { static func decode(j: JSON) -> Decoded<Wrapped?> { return .optional(Wrapped.decode(j)) } } public extension CollectionType where Generator.Element: Decodable, Generator.Element == Generator.Element.DecodedType { static func decode(j: JSON) -> Decoded<[Generator.Element]> { switch j { case let .Array(a): return sequence(a.map(Generator.Element.decode)) default: return .typeMismatch("Array", actual: j) } } } public func decodeArray<T: Decodable where T.DecodedType == T>(j: JSON) -> Decoded<[T]> { return [T].decode(j) } public extension DictionaryLiteralConvertible where Value: Decodable, Value == Value.DecodedType { static func decode(j: JSON) -> Decoded<[String: Value]> { switch j { case let .Object(o): return sequence(Value.decode <^> o) default: return .typeMismatch("Object", actual: j) } } } public func decodeObject<T: Decodable where T.DecodedType == T>(j: JSON) -> Decoded<[String: T]> { return [String: T].decode(j) } public func decodedJSON(json: JSON, forKey key: String) -> Decoded<JSON> { switch json { case let .Object(o): return guardNull(key, j: o[key] ?? .Null) default: return .typeMismatch("Object", actual: json) } } private func guardNull(key: String, j: JSON) -> Decoded<JSON> { switch j { case .Null: return .missingKey(key) default: return pure(j) } }
mit
642ac7368c217fc3296ac99b281bc0f5
26.528846
120
0.66364
3.61034
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Cells/HLHotelDetailsErrorTableCell.swift
1
1440
class HLHotelDetailsErrorTableCell: UITableViewCell { var buttonHandler: (() -> Void)! var hideTitle: Bool = false { didSet { self.centerButtonConstraint.constant = self.hideTitle ? 0.0 : -10.0 self.titleLabel.isHidden = self.hideTitle self.icon.isHidden = self.hideTitle } } var hideButton: Bool = false { didSet { self.button.isHidden = self.hideButton } } var titleText: String? { didSet { self.titleLabel.text = self.titleText } } var buttonText: String? { didSet { self.button.setTitle(self.buttonText, for: UIControl.State()) } } @IBOutlet fileprivate weak var button: UIButton! @IBOutlet fileprivate weak var titleLabel: UILabel! @IBOutlet fileprivate weak var icon: UIImageView! @IBOutlet fileprivate weak var centerButtonConstraint: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() self.initialize() } // MARK: - Private methods fileprivate func initialize() { button.isHidden = hideButton button.setTitle(buttonText, for: .normal) button.backgroundColor = JRColorScheme.actionColor() titleLabel.text = titleText } // MARK: - IBAction methods @IBAction private func onButton(_ sender: AnyObject?) { buttonHandler() } }
mit
ca93e8b02e59618b4c6dd8c7db080eba
24.263158
79
0.615972
4.864865
false
false
false
false
thehung111/ViSearchSwiftSDK
ViSearchSDK/ViSearchSDK/Classes/Helper/UidHelper.swift
3
1130
import Foundation public class UidHelper: NSObject { /// Internal key for storing search uid static let ViSearchUidKey = "visearch_uid" /// retrieve unique device uid and store into userDefaults /// this is needed for tracking API to identify various actions /// /// - returns: unique device uid public static func uniqueDeviceUid() -> String { let storeUid = SettingHelper.getStringSettingProp(propName: ViSearchUidKey) if storeUid == nil || storeUid?.characters.count == 0 { let deviceId = UIDevice.current.identifierForVendor?.uuidString ; // store in the setting SettingHelper.setSettingProp(propName: ViSearchUidKey, newValue: deviceId!) return deviceId! } return storeUid! } /// Force update the device uid and store in setting /// /// - parameter newUid: new device uid public static func updateStoreDeviceUid(newUid: String) -> Void { SettingHelper.setSettingProp(propName: ViSearchUidKey, newValue: newUid) } }
mit
85facd6cdeee2417243a585f739cfd40
31.285714
87
0.631858
5.067265
false
false
false
false
avaidyam/Parrot
Parrot/SortedArray.swift
1
12900
/// from @ole: https://github.com/ole/SortedArray/ /// An array that keeps its elements sorted at all times. public struct SortedArray<Element> { /// The backing store fileprivate var _elements: [Element] public typealias Comparator<A> = (A, A) -> Bool /// The predicate that determines the array's sort order. fileprivate let areInIncreasingOrder: Comparator<Element> /// Initializes an empty array. /// /// - Parameter areInIncreasingOrder: The comparison predicate the array should use to sort its elements. public init(areInIncreasingOrder: @escaping Comparator<Element>) { self._elements = [] self.areInIncreasingOrder = areInIncreasingOrder } /// Initializes the array with a sequence of unsorted elements and a comparison predicate. public init<S: Sequence>(unsorted: S, areInIncreasingOrder: @escaping Comparator<Element>) where S.Iterator.Element == Element { let sorted = unsorted.sorted(by: areInIncreasingOrder) self._elements = sorted self.areInIncreasingOrder = areInIncreasingOrder } /// Initializes the array with a sequence that is already sorted according to the given comparison predicate. /// /// This is faster than `init(unsorted:areInIncreasingOrder:)` because the elements don't have to sorted again. /// /// - Precondition: `sorted` is sorted according to the given comparison predicate. If you violate this condition, the behavior is undefined. public init<S: Sequence>(sorted: S, areInIncreasingOrder: @escaping Comparator<Element>) where S.Iterator.Element == Element { self._elements = Array(sorted) self.areInIncreasingOrder = areInIncreasingOrder } /// Inserts a new element into the array, preserving the sort order. /// /// - Returns: the index where the new element was inserted. /// - Complexity: O(_n_) where _n_ is the size of the array. O(_log n_) if the new /// element can be appended, i.e. if it is ordered last in the resulting array. @discardableResult public mutating func insert(_ newElement: Element) -> Index { let index = insertionIndex(for: newElement) // This should be O(1) if the element is to be inserted at the end, // O(_n) in the worst case (inserted at the front). _elements.insert(newElement, at: index) return index } /// Inserts all elements from `elements` into `self`, preserving the sort order. /// /// This can be faster than inserting the individual elements one after another because /// we only need to re-sort once. /// /// - Complexity: O(_n * log(n)_) where _n_ is the size of the resulting array. public mutating func insert<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == Element { _elements.append(contentsOf: newElements) _elements.sort(by: areInIncreasingOrder) } /// Re-sorts the array, preserving the sort order. public mutating func resort() { _elements.sort(by: areInIncreasingOrder) } } extension SortedArray where Element: Comparable { /// Initializes an empty sorted array. Uses `<` as the comparison predicate. public init() { self.init(areInIncreasingOrder: <) } /// Initializes the array with a sequence of unsorted elements. Uses `<` as the comparison predicate. public init<S: Sequence>(unsorted: S) where S.Iterator.Element == Element { self.init(unsorted: unsorted, areInIncreasingOrder: <) } /// Initializes the array with a sequence that is already sorted according to the `<` comparison predicate. Uses `<` as the comparison predicate. /// /// This is faster than `init(unsorted:)` because the elements don't have to sorted again. /// /// - Precondition: `sorted` is sorted according to the `<` predicate. If you violate this condition, the behavior is undefined. public init<S: Sequence>(sorted: S) where S.Iterator.Element == Element { self.init(sorted: sorted, areInIncreasingOrder: <) } } extension SortedArray: RandomAccessCollection { public typealias Index = Int public var startIndex: Index { return _elements.startIndex } public var endIndex: Index { return _elements.endIndex } public func index(after i: Index) -> Index { return _elements.index(after: i) } public func index(before i: Index) -> Index { return _elements.index(before: i) } public subscript(position: Index) -> Element { return _elements[position] } } extension SortedArray: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "\(String(describing: _elements)) (sorted)" } public var debugDescription: String { return "<SortedArray> \(String(reflecting: _elements))" } /// Like `Sequence.filter(_:)`, but returns a `SortedArray` instead of an `Array`. /// We can do this efficiently because filtering doesn't change the sort order. public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> SortedArray<Element> { let newElements = try _elements.filter(isIncluded) return SortedArray(sorted: newElements, areInIncreasingOrder: areInIncreasingOrder) } } // MARK: - Removing elements. This is mostly a reimplementation of part `RangeReplaceableCollection`'s interface. `SortedArray` can't conform to `RangeReplaceableCollection` because some of that protocol's semantics (e.g. `append(_:)` don't fit `SortedArray`'s semantics. extension SortedArray { /// Removes and returns the element at the specified position. /// /// - Parameter index: The position of the element to remove. `index` must be a valid index of the array. /// - Returns: The element at the specified index. /// - Complexity: O(_n_), where _n_ is the length of the array. @discardableResult public mutating func remove(at index: Int) -> Element { return _elements.remove(at: index) } /// Removes the elements in the specified subrange from the array. /// /// - Parameter bounds: The range of the array to be removed. The /// bounds of the range must be valid indices of the array. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeSubrange(_ bounds: Range<Int>) { _elements.removeSubrange(bounds) } /// Removes the elements in the specified subrange from the array. /// /// - Parameter bounds: The range of the array to be removed. The /// bounds of the range must be valid indices of the array. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeSubrange(_ bounds: ClosedRange<Int>) { _elements.removeSubrange(bounds) } /// Removes the specified number of elements from the beginning of the /// array. /// /// - Parameter n: The number of elements to remove from the array. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the array. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeFirst(_ n: Int) { _elements.removeFirst(n) } /// Removes and returns the first element of the array. /// /// - Precondition: The array must not be empty. /// - Returns: The removed element. /// - Complexity: O(_n_), where _n_ is the length of the collection. @discardableResult public mutating func removeFirst() -> Element { return _elements.removeFirst() } /// Removes and returns the last element of the array. /// /// - Precondition: The collection must not be empty. /// - Returns: The last element of the collection. /// - Complexity: O(1) @discardableResult public mutating func removeLast() -> Element { return _elements.removeLast() } /// Removes the given number of elements from the end of the array. /// /// - Parameter n: The number of elements to remove. `n` must be greater /// than or equal to zero, and must be less than or equal to the number of /// elements in the array. /// - Complexity: O(1). public mutating func removeLast(_ n: Int) { _elements.removeLast(n) } /// Removes all elements from the array. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of the array after removing its elements. The default value is `false`. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeAll(keepingCapacity keepCapacity: Bool = true) { _elements.removeAll(keepingCapacity: keepCapacity) } /// Removes an element from the array. If the array contains multiple instances of `element`, this method only removes the first one. /// /// - Complexity: O(_n_), where _n_ is the size of the array. public mutating func remove(_ element: Element) { guard let index = index(of: element) else { return } _elements.remove(at: index) } } // MARK: - More efficient variants of default implementations or implementations that need fewer constraints than the default implementations. extension SortedArray { /// Returns the first index where the specified value appears in the collection. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func index(of element: Element) -> Index? { switch search(for: element) { case let .found(at: index): return index case .notFound(insertAt: _): return nil } } /// Returns a Boolean value indicating whether the sequence contains the given element. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func contains(_ element: Element) -> Bool { return index(of: element) != nil } /// Returns the minimum element in the sequence. /// /// - Complexity: O(1). @warn_unqualified_access public func min() -> Element? { return first } /// Returns the maximum element in the sequence. /// /// - Complexity: O(1). @warn_unqualified_access public func max() -> Element? { return last } } // MARK: - Binary search extension SortedArray { /// The index where `newElement` should be inserted to preserve the array's sort order. fileprivate func insertionIndex(for newElement: Element) -> Index { switch search(for: newElement) { case let .found(at: index): return index case let .notFound(insertAt: index): return index } } } fileprivate enum Match<Index: Comparable> { case found(at: Index) case notFound(insertAt: Index) } extension SortedArray { /// Searches the array for `newElement` using binary search. /// /// - Returns: If `newElement` is in the array, returns `.found(at: index)` /// where `index` is the index of the element in the array. /// If `newElement` is not in the array, returns `.notFound(insertAt: index)` /// where `index` is the index where the element should be inserted to /// preserve the sort order. /// If the array contains multiple elements that are equal to `newElement`, /// there is no guarantee which of these is found. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. fileprivate func search(for newElement: Element) -> Match<Index> { guard !isEmpty else { return .notFound(insertAt: endIndex) } var left = startIndex var right = index(before: endIndex) while left <= right { let dist = distance(from: left, to: right) let mid = index(left, offsetBy: dist/2) let candidate = self[mid] if areInIncreasingOrder(candidate, newElement) { left = index(after: mid) } else if areInIncreasingOrder(newElement, candidate) { right = index(before: mid) } else { // If neither element comes before the other, they _must_ be // equal, per the strict ordering requirement of `areInIncreasingOrder`. return .found(at: mid) } } // Not found. left is the index where this element should be placed if it were inserted. return .notFound(insertAt: left) } } public func ==<Element: Equatable> (lhs: SortedArray<Element>, rhs: SortedArray<Element>) -> Bool { return lhs._elements == rhs._elements } public func !=<Element: Equatable> (lhs: SortedArray<Element>, rhs: SortedArray<Element>) -> Bool { return lhs._elements != rhs._elements }
mpl-2.0
3d2316ea57b7858054c1ac94539daa9e
40.082803
271
0.649302
4.607143
false
false
false
false
Aprobado/Automatic.Writer
AutomaticWriter/Views/OutlineView/DragNDropScrollView.swift
1
2709
// // DragNDropScrollView.swift // AutomaticWriter // // Created by Raphael on 26.01.15. // Copyright (c) 2015 HEAD Geneva. All rights reserved. // import Cocoa protocol DragNDropScrollViewDelegate { func onFilesDrop(files:[String]); } class DragNDropScrollView: NSScrollView { var delegate:DragNDropScrollViewDelegate? override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) // Drawing code here. } func registerForDragAndDrop(theDelegate:DragNDropScrollViewDelegate) { registerForDraggedTypes([NSColorPboardType, NSFilenamesPboardType]) delegate = theDelegate } // the value returned changes the mouse icon override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { println("drag entered") let pboard:NSPasteboard = sender.draggingPasteboard() let sourceDragMask:NSDragOperation = sender.draggingSourceOperationMask() // cast the types array from [AnyObject]? to [String] var types:[String]? = pboard.types as? [String] if let actualTypes = types { if contains(actualTypes, NSFilenamesPboardType) { if (sourceDragMask & NSDragOperation.Link) == NSDragOperation.Link { // we get a link, but we're going to copy files // so we show a "copy" icon return NSDragOperation.Copy } else if (sourceDragMask & NSDragOperation.Copy) == NSDragOperation.Copy { return NSDragOperation.Copy } } } return NSDragOperation.None } override func performDragOperation(sender: NSDraggingInfo) -> Bool { println("perform drag operation") let pboard = sender.draggingPasteboard() let sourceDragMask = sender.draggingSourceOperationMask() // cast the types array from [AnyObject]? to [String] var types:[String]? = pboard.types as? [String] if let actualTypes = types { if contains(actualTypes, NSFilenamesPboardType) { let files: AnyObject? = pboard.propertyListForType(NSFilenamesPboardType) var paths = files as? [String] if (sourceDragMask & NSDragOperation.Link) == NSDragOperation.Link { if let actualPaths = paths { println("files dropped: \(actualPaths)") delegate?.onFilesDrop(actualPaths) } } } } return true } }
mit
9c5b8480e7cb3661b2bc65a6432f953c
32.036585
89
0.587302
5.364356
false
false
false
false
AleManni/LightOperations
LightOperations/OperationsCoupler.swift
1
4769
// // OperationsCoupler.swift // GeoApp // // Created by Alessandro Manni on 06/08/2017. // Copyright © 2017 Alessandro Manni. All rights reserved. // import Foundation /** Transforming function - seealso: `public init(finishedOperation: LightOperation, startingOperation: LightOperation, transformer: OperationTransformer?`, for a description of the errors that can be thrown */ public typealias OperationTransformer = (Any) -> Any? /** This class provides an interface between two instances of LightOperations, allowing to pass the finalResult of the finishedOperaton into the initialData of the startingOperation. This same class will also automatically take care of setting the correct dependencies between the finished operation and the starting operation. A transformation block can be injected through initialization, in order to transform the oputut of the finishedOperation before passing it to the input of the startingOperation. */ public class CouplerOperation: Operation { private var finishedOperation: LightOperation private var startingOperation: LightOperation private var operationTransformer: OperationTransformer override open var isAsynchronous: Bool { return true } var state = OperationState.ready { willSet { willChangeValue(forKey: state.keyPath) willChangeValue(forKey: newValue.keyPath) } didSet { didChangeValue(forKey: state.keyPath) didChangeValue(forKey: oldValue.keyPath) } } override open var isExecuting: Bool { return state == .executing } override open var isFinished: Bool { return state == .finished } override open var isCancelled: Bool { return state == .cancelled } /** Initialize the coupler operation - Parameter finishedOperation: the input operation. This operation must be a sublcass of LightOperation - Parameter startingOperation: the output operation. This operation must be a sublcass of LightOperation - Parameter transformer: an optional transformer block. If this parameter is `nil`, the output of the finished operation will be passed directly to the input of the startingOperation */ public init(finishedOperation: LightOperation, startingOperation: LightOperation, transformer: OperationTransformer? = { input in return input}) { self.finishedOperation = finishedOperation self.startingOperation = startingOperation self.operationTransformer = transformer! super.init() self.name = String(describing: self) self.addDependency(finishedOperation) startingOperation.addDependency(self) } override open func start() { addObserver(self, forKeyPath: OperationState.executing.keyPath, options: .new, context: nil) addObserver(self, forKeyPath: OperationState.finished.keyPath, options: .new, context: nil) addObserver(self, forKeyPath: OperationState.cancelled.keyPath, options: .new, context: nil) if self.isCancelled { state = .finished } else { state = .ready main() } } override open func main() { if self.isCancelled { state = .finished return } else { state = .executing } guard let result = self.finishedOperation.operationFinalResult else { state = .cancelled self.cancel() return } switch result { case .success(let data): if let inputData = self.operationTransformer(data) { self.startingOperation.initialData = inputData self.state = .finished } default: state = .cancelled self.cancel() return } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } switch keyPath { case OperationState.executing.keyPath: print("\(self.name ?? "un-named operation") is executing") case OperationState.finished.keyPath: print("\(self.name ?? "un-named operation") finished") case OperationState.cancelled.keyPath: print("\(self.name ?? "un-named operation") CANCELLED") default: return } } deinit { removeObserver(self, forKeyPath: OperationState.executing.keyPath) removeObserver(self, forKeyPath: OperationState.finished.keyPath) removeObserver(self, forKeyPath: OperationState.cancelled.keyPath) } }
mit
fe5ceebe8302a19ad450cea28c895cdc
36.25
188
0.667366
5.176982
false
false
false
false
viviancrs/fanboy
FanBoy/Source/Model/Item/Item.swift
1
1313
// // Item.swift // FanBoy // // Created by Vivian Cristhine da Rosa Soares on 16/07/17. // Copyright © 2017 CI&T. All rights reserved. // import Foundation struct Item { //MARK: - Constants private let kName = "name" private let kTitle = "title" private let kIgnoreProperties = ["name", "title", "created", "edited", "url"] //MARK: - Properties var name: String var details: [Detail] //MARK: - Initializers init(itemDictionary:[String:AnyObject]) throws { var name = "" if itemDictionary.keys.contains(kName) { guard let propertie = itemDictionary[kName] as? String else { throw BusinessError.parse(kName) } name = propertie } else { guard let propertie = itemDictionary[kTitle] as? String else { throw BusinessError.parse(kTitle) } name = propertie } self.name = name.normalize() var details: [Detail] = [] for key in itemDictionary.keys { if !kIgnoreProperties.contains(key) { guard let properties = itemDictionary[key] else { throw BusinessError.parse(key) } details.append(Detail.init(name: key, value: properties)) } } self.details = details } }
gpl-3.0
d73d79329449ff9c0f01f602813adf8b
28.155556
110
0.583841
4.049383
false
false
false
false
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Services/APIConstants.swift
1
4032
// // APIConstants.swift // ScoreReporterCore // // Created by Bradley Smith on 11/23/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation struct APIConstants { struct Path { static let baseURL = "https://play.usaultimate.org/" struct Keys { static let function = "f" } struct Values { static let login = "MemberLogin" static let events = "GETALLEVENTS" static let eventDetails = "GETGAMESBYEVENT" static let teams = "GetTeams" static let teamDetails = "GetGamesByTeam" static let updateGame = "UpdateGameStatus" } } struct Request { struct Keys { static let username = "username" static let password = "password" static let eventID = "EventId" static let teamID = "TeamId" static let gameID = "GameId" static let homeScore = "HomeScore" static let awayScore = "AwayScore" static let gameStatus = "GameStatus" static let userToken = "UserToken" } } struct Response { struct Keys { static let success = "success" static let message = "message" static let error = "error" static let userToken = "UserToken" static let events = "Events" static let groups = "EventGroups" static let teams = "Teams" static let eventID = "EventId" static let eventName = "EventName" static let eventType = "EventType" static let eventTypeName = "EventTypeName" static let city = "City" static let state = "State" static let startDate = "StartDate" static let endDate = "EndDate" static let eventLogo = "EventLogo" static let competitionGroup = "CompetitionGroup" static let groupID = "EventGroupId" static let divisionName = "DivisionName" static let teamCount = "TeamCount" static let groupName = "GroupName" static let eventGroupName = "EventGroupName" static let eventRounds = "EventRounds" static let roundID = "RoundId" static let brackets = "Brackets" static let clusters = "Clusters" static let pools = "Pools" static let bracketID = "BracketId" static let bracketName = "BracketName" static let stage = "Stage" static let stageID = "StageId" static let stageName = "StageName" static let games = "Games" static let clusterID = "ClusterId" static let name = "Name" static let poolID = "PoolId" static let standings = "Standings" static let gameID = "EventGameId" static let homeTeamName = "HomeTeamName" static let homeTeamScore = "HomeTeamScore" static let awayTeamName = "AwayTeamName" static let awayTeamScore = "AwayTeamScore" static let fieldName = "FieldName" static let gameStatus = "GameStatus" static let startTime = "StartTime" static let wins = "Wins" static let losses = "Losses" static let sortOrder = "SortOrder" static let teamName = "TeamName" static let teamID = "TeamId" static let teamLogo = "TeamLogo" static let schoolName = "SchoolName" static let competitionLevel = "CompetitionLevel" static let teamDesignation = "TeamDesignation" static let memberID = "MemberId" static let accountID = "AccountId" static let updatedGameRecord = "Updated GameRecord" } struct Values { static let tournament = "Tournament" static let inProgress = "In Progress" } } }
mit
e810deb54e0133304bb9450a6484855c
32.31405
63
0.56264
4.964286
false
false
false
false
WeltN24/Carlos
Sources/Carlos/CacheLevels/BatchAllCache.swift
1
1632
import Combine /// A reified batchGetAll public final class BatchAllCache<KeySeq: Sequence, Cache: CacheLevel>: CacheLevel where KeySeq.Iterator.Element == Cache.KeyType { /// A sequence of keys for the wrapped cache public typealias KeyType = KeySeq /// An array of output elements public typealias OutputType = [Cache.OutputType] private let cache: Cache public init(cache: Cache) { self.cache = cache } /** Dispatch each key in the sequence in parallel Merge the results -- if any key fails, it all fails */ public func get(_ key: KeyType) -> AnyPublisher<OutputType, Error> { let all = key.map(cache.get) return all.publisher .setFailureType(to: Error.self) .flatMap { $0 } .collect(all.count) .eraseToAnyPublisher() } /** Zip the keys with the values and set them all */ public func set(_ value: OutputType, forKey key: KeyType) -> AnyPublisher<Void, Error> { let initial = Just(()) .setFailureType(to: Error.self) .eraseToAnyPublisher() return zip(value, key) .map(cache.set) .reduce(initial) { previous, current in previous.flatMap { current } .eraseToAnyPublisher() } } public func clear() { cache.clear() } public func onMemoryWarning() { cache.onMemoryWarning() } } extension CacheLevel { /** Wrap a <K, V> cache into a <Sequence<K>, [V]> cache where each k in Sequence<K> is dispatched in parallel and if any K fails, it all fails */ public func allBatch<KeySeq: Sequence>() -> BatchAllCache<KeySeq, Self> { BatchAllCache(cache: self) } }
mit
22725c12b8eebb17f64dcbe2252907ff
24.904762
130
0.655637
4.039604
false
false
false
false
appsandwich/ppt2rk
ppt2rk/Polar.swift
1
3759
// // Polar.swift // ppt2rk // // Created by Vinny Coyne on 11/05/2017. // Copyright © 2017 App Sandwich Limited. All rights reserved. // import Foundation class Polar { class func stringForDate(_ date: Date) -> String { let df = DateFormatter() df.locale = Locale(identifier: "en_US_POSIX") df.timeZone = TimeZone(identifier: "UTC") df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" return df.string(from: date) } class func loginWithEmail(_ email: String, password: String, handler: @escaping (Bool) -> Void) { print("Logging in to Polar as \(email)...") _ = Network.sendPOSTRequest(.polar, path: "/index.ftl", bodyParams: [ "email" : email, "password" : password, ".action" : "login" ], contentType: .form, handler: { (d, e) in var loggedIn = false if let htmlString = d?.utf8String() { loggedIn = (htmlString.range(of: "<a href=\"/user/logout.ftl\">Log out</a>") != nil) } handler(loggedIn) }) } class func loadWorkoutsSince(_ startDate: Date, handler: @escaping ([PolarWorkout]?) -> Void) { self.loadWorkoutsFrom(startDate, to: Date(), handler: handler) } class func loadWorkoutsFrom(_ startDate: Date, to endDate: Date, handler: @escaping ([PolarWorkout]?) -> Void) { let start = self.stringForDate(startDate) let end = self.stringForDate(endDate) print("Getting Polar workouts from \(start) to \(end). This may take some time...") let xmlString = "<request><object name=\"root\"><prop name=\"startDate\" type=\"Timestamp\"><![CDATA[\(start)]]></prop><prop name=\"endDate\" type=\"Timestamp\"><![CDATA[\(end)]]></prop></object></request>" _ = Network.sendPOSTRequest(.polar, path: "/user/calendar/index.xml?.action=items&rmzer=1494499701372", bodyParams: [ "xml" : xmlString ] , contentType: .xml, handler: { (d, e) in guard let data = d else { handler(nil) return } let parser = PolarWorkoutsParser(data: data) parser.parseWithHandler({ (workouts) in handler(workouts) }) }) } class func loadWorkoutsWithHandler(_ handler: @escaping ([PolarWorkout]?) -> Void) { /* curl -b pptcookies.txt --compressed -X POST 'https://www.polarpersonaltrainer.com/user/calendar/index.xml?.action=items&rmzer=1494499701372' --data '<request><object name="root"><prop name="startDate" type="Timestamp"><![CDATA[2010-05-01T00:00:00.000]]></prop><prop name="endDate" type="Timestamp"><![CDATA[2017-05-08T00:00:00.000]]></prop></object></request>' -H 'Accept: application/xml' -H 'Content-Type: application/xml' */ let date = Date(timeIntervalSince1970: 0) self.loadWorkoutsSince(date, handler: handler) } class func exportGPXForWorkoutID(_ workoutID: String, handler: @escaping (Data?) -> Void) { print("Exporting GPX for workout \(workoutID)...") // curl -b pptcookies.txt -d 'items.0.item=777850771&items.0.itemType=OptimizedExercise&.filename=filename&.action=gpx' https://www.polarpersonaltrainer.com/user/calendar/index.gpx _ = Network.sendPOSTRequest(.polar, path: "/user/calendar/index.gpx", bodyParams: [ "items.0.item" : workoutID, "items.0.itemType" : "OptimizedExercise", ".filename" : workoutID + ".gpx", ".action" : "gpx" ], contentType: .form, handler: { (d, e) in handler(d) }) } }
mit
5456160bd798ddca6ea1e77baf5d3e09
41.224719
433
0.578499
4.006397
false
false
false
false
arsonik/AKYamahaAV
Source/YamahaAVSlider.swift
1
1117
// // YamahaAVSlider.swift // Pods // // Created by Florian Morello on 21/11/15. // // import UIKit public class YamahaAVSlider : UISlider { public weak var yamaha:YamahaAV? public func resumePolling() { yamaha?.startListening(self, selector: #selector(YamahaAVSlider.updated(notification:))) } public func pausePolling() { yamaha?.stopListening(observer: self) } public override func awakeFromNib() { super.awakeFromNib() isEnabled = false isContinuous = false minimumValue = -800 maximumValue = 165 addTarget(self, action: #selector(YamahaAVSlider.valueChanged), for: UIControlEvents.valueChanged) } internal func updated(notification: NSNotification) { if let o = yamaha?.mainZonePower { isEnabled = o } if let v = yamaha?.mainZoneVolume , !isHighlighted { setValue(Float(v), animated: true) } } @IBAction func valueChanged() { value = ceilf(value) yamaha?.setMainZoneVolume(value: Int(value)) } deinit { yamaha?.stopListening(observer: self) } }
mit
1712b70204d9a9c811d3ccda929c944f
21.34
106
0.646374
3.946996
false
false
false
false
agrippa1994/iOS-PLC
Pods/Charts/Charts/Classes/Renderers/BarChartRenderer.swift
1
24270
// // BarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit @objc public protocol BarChartRendererDelegate { func barChartRendererData(renderer: BarChartRenderer) -> BarChartData! func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter! func barChartRendererChartYMax(renderer: BarChartRenderer) -> Double func barChartRendererChartYMin(renderer: BarChartRenderer) -> Double func barChartRendererChartXMax(renderer: BarChartRenderer) -> Double func barChartRendererChartXMin(renderer: BarChartRenderer) -> Double func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool } public class BarChartRenderer: ChartDataRendererBase { public weak var delegate: BarChartRendererDelegate? public init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.delegate = delegate } public override func drawData(context context: CGContext?) { let barData = delegate!.barChartRendererData(self) if (barData === nil) { return } for (var i = 0; i < barData.dataSetCount; i++) { let set = barData.getDataSetByIndex(i) if (set !== nil && set!.isVisible) { drawDataSet(context: context, dataSet: set as! BarChartDataSet, index: i) } } } internal func drawDataSet(context context: CGContext?, dataSet: BarChartDataSet, index: Int) { CGContextSaveGState(context) let barData = delegate!.barChartRendererData(self) let trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) let drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self) let dataSetOffset = (barData.dataSetCount - 1) let groupSpace = barData.groupSpace let groupSpaceHalf = groupSpace / 2.0 let barSpace = dataSet.barSpace let barSpaceHalf = barSpace / 2.0 let containsStacks = dataSet.isStacked let isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] let barWidth: CGFloat = 0.5 let phaseY = _animator.phaseY var barRect = CGRect() var barShadow = CGRect() var y: Double // do the drawing for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++) { let e = entries[j] // calculate the x-position, depending on datasetcount let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(e.xIndex) + groupSpaceHalf var vals = e.values if (!containsStacks || vals == nil) { y = e.value let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (top > 0) { top *= phaseY } else { bottom *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = barRect.origin.x barShadow.origin.y = viewPortHandler.contentTop barShadow.size.width = barRect.size.width barShadow.size.height = viewPortHandler.contentHeight CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextFillRect(context, barRect) } else { var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (top > 0) { top *= phaseY } else { bottom *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) barShadow.origin.x = barRect.origin.x barShadow.origin.y = viewPortHandler.contentTop barShadow.size.width = barRect.size.width barShadow.size.height = viewPortHandler.contentHeight CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // fill the stack for (var k = 0; k < vals!.count; k++) { let value = vals![k] if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top: CGFloat, bottom: CGFloat if isInverted { bottom = y >= yStart ? CGFloat(y) : CGFloat(yStart) top = y <= yStart ? CGFloat(y) : CGFloat(yStart) } else { top = y >= yStart ? CGFloat(y) : CGFloat(yStart) bottom = y <= yStart ? CGFloat(y) : CGFloat(yStart) } // multiply the height of the rect with the phase top *= phaseY bottom *= phaseY barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { // Skip to next bar break } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor) CGContextFillRect(context, barRect) } } } CGContextRestoreGState(context) } /// Prepares a bar for being highlighted. internal func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5 let left = x - barWidth + barspacehalf let right = x + barWidth - barspacehalf let top = CGFloat(y1) let bottom = CGFloat(y2) rect.origin.x = left rect.origin.y = top rect.size.width = right - left rect.size.height = bottom - top trans.rectValueToPixel(&rect, phaseY: _animator.phaseY) } public override func drawValues(context context: CGContext?) { // if values are drawn if (passesCheck()) { let barData = delegate!.barChartRendererData(self) let defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self) var dataSets = barData.dataSets let drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self) var posOffset: CGFloat var negOffset: CGFloat for (var i = 0, count = barData.dataSetCount; i < count; i++) { let dataSet = dataSets[i] as! BarChartDataSet if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) // calculate the correct offset depending on the draw position of the value let valueOffsetPlus: CGFloat = 4.5 let valueFont = dataSet.valueFont let valueTextHeight = valueFont.lineHeight posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus) negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus)) if (isInverted) { posOffset = -posOffset - valueTextHeight negOffset = -negOffset - valueTextHeight } let valueTextColor = dataSet.valueTextColor var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } let trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i) // if only single values are drawn (sum) if (!dataSet.isStacked) { for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsRight(valuePoints[j].x)) { break } if (!viewPortHandler.isInBoundsY(valuePoints[j].y) || !viewPortHandler.isInBoundsLeft(valuePoints[j].x)) { continue } let val = entries[j].value drawValue(context: context, value: formatter!.stringFromNumber(val)!, xPos: valuePoints[j].x, yPos: valuePoints[j].y + (val >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: valueTextColor) } } else { // if we have stacks for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { let e = entries[j] let values = e.values // we still draw stacked bars, but there is one non-stacked in between if (values == nil) { if (!viewPortHandler.isInBoundsRight(valuePoints[j].x)) { break } if (!viewPortHandler.isInBoundsY(valuePoints[j].y) || !viewPortHandler.isInBoundsLeft(valuePoints[j].x)) { continue } drawValue(context: context, value: formatter!.stringFromNumber(e.value)!, xPos: valuePoints[j].x, yPos: valuePoints[j].y + (e.value >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: valueTextColor) } else { // draw stack values let vals = values! var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for (var k = 0; k < vals.count; k++) { let value = vals[k] var y: Double if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: 0.0, y: CGFloat(y) * _animator.phaseY)) } trans.pointValuesToPixel(&transformed) for (var k = 0; k < transformed.count; k++) { let x = valuePoints[j].x let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset) if (!viewPortHandler.isInBoundsRight(x)) { break } if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)) { continue } drawValue(context: context, value: formatter!.stringFromNumber(vals[k])!, xPos: x, yPos: y, font: valueFont, align: .Center, color: valueTextColor) } } } } } } } /// Draws a value at the specified x and y position. internal func drawValue(context context: CGContext?, value: String, xPos: CGFloat, yPos: CGFloat, font: UIFont, align: NSTextAlignment, color: UIColor) { ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color]) } public override func drawExtras(context context: CGContext?) { } private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint()) public override func drawHighlighted(context context: CGContext?, indices: [ChartHighlight]) { let barData = delegate!.barChartRendererData(self) if (barData === nil) { return } CGContextSaveGState(context) let setCount = barData.dataSetCount let drawHighlightArrowEnabled = delegate!.barChartIsDrawHighlightArrowEnabled(self) var barRect = CGRect() for (var i = 0; i < indices.count; i++) { let h = indices[i] let index = h.xIndex let dataSetIndex = h.dataSetIndex let set = barData.getDataSetByIndex(dataSetIndex) as! BarChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } let barspaceHalf = set.barSpace / 2.0 let trans = delegate!.barChartRenderer(self, transformerForAxis: set.axisDependency) CGContextSetFillColorWithColor(context, set.highlightColor.CGColor) CGContextSetAlpha(context, set.highLightAlpha) // check outofbounds if (CGFloat(index) < (CGFloat(delegate!.barChartRendererChartXMax(self)) * _animator.phaseX) / CGFloat(setCount)) { let e = set.entryForXIndex(index) as! BarChartDataEntry! if (e === nil || e.xIndex != index) { continue } let groupspace = barData.groupSpace let isStack = h.stackIndex < 0 ? false : true // calculate the correct x-position let x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index) let y1: Double let y2: Double if (isStack) { y1 = h.range?.from ?? 0.0 y2 = (h.range?.to ?? 0.0) * Double(_animator.phaseY) } else { y1 = e.value y2 = 0.0 } prepareBarHighlight(x: x, y1: y1, y2: y2, barspacehalf: barspaceHalf, trans: trans, rect: &barRect) CGContextFillRect(context, barRect) if (drawHighlightArrowEnabled) { CGContextSetAlpha(context, 1.0) // distance between highlight arrow and bar let offsetY = _animator.phaseY * 0.07 CGContextSaveGState(context) let pixelToValueMatrix = trans.pixelToValueMatrix let xToYRel = abs(sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d) / sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c)) let arrowWidth = set.barSpace / 2.0 let arrowHeight = arrowWidth * xToYRel let yArrow = y1 > -y2 ? y1 : y1; _highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4 _highlightArrowPtsBuffer[0].y = CGFloat(yArrow) + offsetY _highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth _highlightArrowPtsBuffer[1].y = CGFloat(yArrow) + offsetY - arrowHeight _highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth _highlightArrowPtsBuffer[2].y = CGFloat(yArrow) + offsetY + arrowHeight trans.pointValuesToPixel(&_highlightArrowPtsBuffer) CGContextBeginPath(context) CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y) CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y) CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y) CGContextClosePath(context) CGContextFillPath(context) CGContextRestoreGState(context) } } } CGContextRestoreGState(context) } public func getTransformedValues(trans trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint] { return trans.generateTransformedValuesBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY) } internal func passesCheck() -> Bool { let barData = delegate!.barChartRendererData(self) if (barData === nil) { return false } return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX } }
mit
4cf00a46762433523c3b993a1e264da8
40.207131
232
0.460569
6.441083
false
false
false
false
infinum/iOS-Loggie
Loggie/Classes/Utility/URLRequest+Data.swift
1
737
// // URLRequest+HTTPBody.swift // Pods // // Created by Filip Bec on 16/03/2017. // // import UIKit extension URLRequest { var data: Data? { if let body = httpBody { return body } else if let stream = httpBodyStream { let body = NSMutableData() var buffer = [UInt8](repeating: 0, count: 4096) stream.open() while stream.hasBytesAvailable { let length = stream.read(&buffer, maxLength: 4096) if length == 0 { break } else { body.append(&buffer, length: length) } } return body as Data } return nil } }
mit
dc78388961ccc14a76233b94bdfc2822
21.333333
66
0.476255
4.60625
false
false
false
false
HsiaoShan/SwiftGirl20170807
SwiftGirl20170807/FaceDetectViewController.swift
1
4755
// // FaceDetectViewController.swift // SwiftGirl20170807 // // Created by HsiaoShan on 2017/8/1. // Copyright © 2017年 ESoZuo. All rights reserved. // import UIKit import CoreImage class FaceDetectViewController: UIViewController { var myImage: UIImage? @IBOutlet weak var myImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() if let img = myImage { myImageView.image = img } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //臉部辨識 @IBAction func detect(_ sender: Any) { guard let ciimage = CIImage(image: myImageView.image!) else { return } let ciImageSize = ciimage.extent.size //用於轉換座標 var transform = CGAffineTransform(scaleX: 1, y: -1) transform = transform.translatedBy(x: 0, y: -ciImageSize.height) let viewSize = myImageView.bounds.size let scale = min(viewSize.width / ciImageSize.width, viewSize.height / ciImageSize.height) //開始臉部辨識 let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh] let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy) let faces = faceDetector?.features(in: ciimage) print("Face: \(faces?.count ?? 0)") var i = 1 for face in faces as! [CIFaceFeature] { //將CoreImage用的座標轉乘UIView用的座標 var faceViewBounds = face.bounds.applying(transform) print("faceBounds..\(faceViewBounds)...") // Calculate the actual position and size of the rectangle in the image view faceViewBounds = faceViewBounds.applying(CGAffineTransform(scaleX: scale, y: scale)) print("faceBounds scale..\(faceViewBounds)...") let offsetX = (viewSize.width - ciImageSize.width * scale) / 2 let offsetY = (viewSize.height - ciImageSize.height * scale) / 2 print("offsetX..\(offsetX)...offsetY...\(offsetY)") faceViewBounds.origin.x += offsetX faceViewBounds.origin.y += offsetY print("\(i) bounds: \(face.bounds)...\(faceViewBounds)") let faceBox = UIView(frame: faceViewBounds) faceBox.layer.borderWidth = 3 faceBox.layer.borderColor = UIColor.red.cgColor faceBox.backgroundColor = UIColor.clear myImageView.addSubview(faceBox) if face.hasLeftEyePosition { print("\(i) Left eye bounds are \(face.leftEyePosition)") } if face.hasRightEyePosition { print("\(i) Right eye bounds are \(face.rightEyePosition)") } if face.hasMouthPosition { print("\(i) Mouth bounds are \(face.mouthPosition)") var mouthPosition = face.mouthPosition.applying(transform) mouthPosition = mouthPosition.applying(CGAffineTransform(scaleX: scale, y: scale)) let lipSize: CGFloat = faceViewBounds.width / 2 let x = mouthPosition.x + offsetX - (lipSize / 2) let y = mouthPosition.y + offsetY - (lipSize / 2) let frame = CGRect(x: x, y: y, width: lipSize, height: lipSize) let mouth = UIImageView(frame: frame) mouth.image = #imageLiteral(resourceName: "lips") myImageView.addSubview(mouth) } i += 1 } } @IBAction func save(_ sender: Any) { UIGraphicsBeginImageContextWithOptions(myImageView.frame.size, false, 0) myImageView.image?.draw(in: CGRect(x: 0, y: 0, width: myImageView.frame.size.width, height: myImageView.frame.size.height), blendMode: CGBlendMode.normal, alpha: 1.0) myImageView.subviews.forEach { view in if let imageView = view as? UIImageView { imageView.image?.draw(in: CGRect(x: imageView.frame.origin.x, y: imageView.frame.origin.y, width: imageView.frame.size.width, height: imageView.frame.size.height)) } else { view.drawHierarchy(in: view.frame, afterScreenUpdates: true) } } let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() UIImageWriteToSavedPhotosAlbum(newImage!, nil, nil, nil) self.dismiss(animated: true, completion: nil) } @IBAction func goBack(_ sender: Any) { self.dismiss(animated: true, completion: nil) } }
mit
798889ab577a36210dbbf6bcf5a9d9fb
39.852174
179
0.600255
4.624016
false
false
false
false
Urinx/SomeCodes
Swift/swiftDemo/video/video/ViewController.swift
1
2058
// // ViewController.swift // video // // Created by Eular on 15/4/21. // Copyright (c) 2015年 Eular. All rights reserved. // import UIKit import MediaPlayer import MobileCoreServices class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var mpPlayer: MPMoviePlayerViewController! var piker: UIImagePickerController! var fileURL: NSURL? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func play(sender: AnyObject) { mpPlayer = MPMoviePlayerViewController(contentURL: NSBundle.mainBundle().URLForResource("0", withExtension: "mp4")) self.presentMoviePlayerViewControllerAnimated(mpPlayer) } @IBAction func startRec(sender: AnyObject) { piker = UIImagePickerController() piker.mediaTypes = [kUTTypeMovie!] piker.sourceType = UIImagePickerControllerSourceType.Camera piker.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video piker.delegate = self self.presentViewController(piker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { fileURL = info[UIImagePickerControllerMediaURL] as? NSURL piker.dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { println("canceled") piker.dismissViewControllerAnimated(true, completion: nil) } @IBAction func playRec(sender: AnyObject) { if let video = fileURL { mpPlayer = MPMoviePlayerViewController(contentURL: video) self.presentMoviePlayerViewControllerAnimated(mpPlayer) } } }
gpl-2.0
48b2810732b3114e5f9f36f867da6c0e
32.16129
125
0.708658
5.368146
false
false
false
false
AlexRamey/mbird-iOS
Pods/CVCalendar/CVCalendar/CVCalendarMonthView.swift
1
7120
// // CVCalendarMonthView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public final class CVCalendarMonthView: UIView { // MARK: - Non public properties fileprivate var interactiveView: UIView! public override var frame: CGRect { didSet { if let calendarView = calendarView { if calendarView.calendarMode == CalendarMode.monthView { updateInteractiveView() } } } } fileprivate var touchController: CVCalendarTouchController { return calendarView.touchController } var allowScrollToPreviousMonth = true var allowScrollToNextMonth = true // MARK: - Public properties public weak var calendarView: CVCalendarView! public var date: Foundation.Date! public var numberOfWeeks: Int! public var weekViews: [CVCalendarWeekView]! public var weeksIn: [[Int : [Int]]]? public var weeksOut: [[Int : [Int]]]? public var currentDay: Int? public var potentialSize: CGSize { return CGSize(width: bounds.width, height: CGFloat(weekViews.count) * weekViews[0].bounds.height + calendarView.appearance.spaceBetweenWeekViews! * CGFloat(weekViews.count)) } // MARK: - Initialization public init(calendarView: CVCalendarView, date: Foundation.Date) { super.init(frame: CGRect.zero) self.calendarView = calendarView self.date = date commonInit() } public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func mapDayViews(_ body: (DayView) -> Void) { for weekView in self.weekViews { for dayView in weekView.dayViews { body(dayView) } } } } // MARK: - Creation and destruction extension CVCalendarMonthView { public func commonInit() { let calendarManager = calendarView.manager safeExecuteBlock({ let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current self.numberOfWeeks = calendarManager?.monthDateRange(self.date).countOfWeeks self.weeksIn = calendarManager?.weeksWithWeekdaysForMonthDate(self.date).weeksIn self.weeksOut = calendarManager?.weeksWithWeekdaysForMonthDate(self.date).weeksOut self.currentDay = Manager.dateRange(Foundation.Date(), calendar: calendar).day }, collapsingOnNil: true, withObjects: date as AnyObject?) } } // MARK: Content reload extension CVCalendarMonthView { public func reloadViewsWithRect(_ frame: CGRect) { self.frame = frame safeExecuteBlock({ for (index, weekView) in self.weekViews.enumerated() { if let size = self.calendarView.weekViewSize { weekView.frame = CGRect(x: 0, y: size.height * CGFloat(index), width: size.width, height: size.height) weekView.reloadDayViews() } } }, collapsingOnNil: true, withObjects: weekViews as AnyObject?) } } // MARK: - Content fill & update extension CVCalendarMonthView { public func updateAppearance(_ frame: CGRect) { self.frame = frame createWeekViews() } public func createWeekViews() { weekViews = [CVCalendarWeekView]() safeExecuteBlock({ for i in 0..<self.numberOfWeeks! { let weekView = CVCalendarWeekView(monthView: self, index: i) self.safeExecuteBlock({ self.weekViews!.append(weekView) }, collapsingOnNil: true, withObjects: self.weekViews as AnyObject?) self.addSubview(weekView) } }, collapsingOnNil: true, withObjects: numberOfWeeks as AnyObject?) } } // MARK: - Interactive view management & update extension CVCalendarMonthView { public func updateInteractiveView() { safeExecuteBlock({ let mode = self.calendarView!.calendarMode! if mode == .monthView { if let interactiveView = self.interactiveView { interactiveView.frame = self.bounds interactiveView.removeFromSuperview() self.addSubview(interactiveView) } else { self.interactiveView = UIView(frame: self.bounds) self.interactiveView.backgroundColor = .clear let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(CVCalendarMonthView.didTouchInteractiveView(_:))) let pressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(CVCalendarMonthView.didPressInteractiveView(_:))) pressRecognizer.minimumPressDuration = 0.3 self.interactiveView.addGestureRecognizer(pressRecognizer) self.interactiveView.addGestureRecognizer(tapRecognizer) self.addSubview(self.interactiveView) } } }, collapsingOnNil: false, withObjects: calendarView) } @objc public func didPressInteractiveView(_ recognizer: UILongPressGestureRecognizer) { let location = recognizer.location(in: self.interactiveView) let state: UIGestureRecognizerState = recognizer.state switch state { case .began: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .range(.started)) case .changed: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .range(.changed)) case .ended: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .range(.ended)) default: break } } @objc public func didTouchInteractiveView(_ recognizer: UITapGestureRecognizer) { let location = recognizer.location(in: self.interactiveView) touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .single) } } // MARK: - Safe execution extension CVCalendarMonthView { public func safeExecuteBlock(_ block: () -> Void, collapsingOnNil collapsing: Bool, withObjects objects: AnyObject?...) { for object in objects { if object == nil { if collapsing { fatalError("Object { \(String(describing: object)) } must not be nil!") } else { return } } } block() } }
mit
c2c4d4dd7d4e249df12d27002d5f552f
33.235577
94
0.597472
5.760518
false
false
false
false
megha14/Lets-Code-Them-Up
Learning-Swift/Learning Swift - Functions [Return Values].playground/Contents.swift
1
909
/* Copyright (C) {2016} {Megha Rastogi} You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* func functionName (paramName: paramType ) -> returnType{ //block of code return object } */ //Example //Factorial of a Number func factorial (number : Int) { var factorial = 1 var temp = number while(temp>1){ factorial = factorial * temp temp = temp - 1 } print("Factorial is \(factorial)") } //functionName(paramName: paramValue) factorial(number: 7) //divide function with two return values quotient and remainder func divide(numA: Int, numB: Int) -> (quotient: Int, remainder: Int){ return (numA/numB, numA%numB) } let result = divide(numA: 9, numB: 2) print("Quotient is \(result.quotient) and Remainder is \(result.remainder)")
gpl-3.0
117db3af809aeaeba7ee60e8b8fba18a
11.283784
133
0.645765
3.650602
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/DatabaseSnapshotTests.swift
1
17299
import XCTest @testable import GRDB class DatabaseSnapshotTests: GRDBTestCase { /// A helper class private class Counter { let dbPool: DatabasePool init(dbPool: DatabasePool) throws { self.dbPool = dbPool try dbPool.write { db in try db.execute(sql: "CREATE TABLE counter(id INTEGER PRIMARY KEY)") } } func increment(_ db: Database) throws { try db.execute(sql: "INSERT INTO counter DEFAULT VALUES") } func value(_ db: Database) throws -> Int { try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")! } } // MARK: - Creation func testSnapshotCanReadBeforeDatabaseModification() throws { let dbPool = try makeDatabasePool() let snapshot = try dbPool.makeSnapshot() try XCTAssertEqual(snapshot.read { try $0.tableExists("foo") }, false) } func testSnapshotCreatedFromMainQueueCanRead() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) let snapshot = try dbPool.makeSnapshot() try XCTAssertEqual(snapshot.read(counter.value), 0) } func testSnapshotCreatedFromWriterOutsideOfTransactionCanRead() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in XCTAssertFalse(db.isInsideTransaction) let snapshot = try dbPool.makeSnapshot() try counter.increment(db) return snapshot } try XCTAssertEqual(snapshot.read(counter.value), 0) } func testSnapshotCreatedFromReaderTransactionCanRead() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) let snapshot = try dbPool.read { db -> DatabaseSnapshot in XCTAssertTrue(db.isInsideTransaction) return try dbPool.makeSnapshot() } try XCTAssertEqual(snapshot.read(counter.value), 0) } func testSnapshotCreatedFromReaderOutsideOfTransactionCanRead() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) let snapshot = try dbPool.unsafeRead { db -> DatabaseSnapshot in XCTAssertFalse(db.isInsideTransaction) return try dbPool.makeSnapshot() } try XCTAssertEqual(snapshot.read(counter.value), 0) } func testSnapshotCreatedFromTransactionObserver() throws { // Creating a snapshot from a didCommit callback is an important use // case. But we know SQLite snapshots created with // sqlite3_snapshot_get() requires a transaction. This means that // creating a snapshot will open a transaction. We must make sure this // transaction does not create any deadlock of reentrancy issue with // transaction observers. class Observer: TransactionObserver { let dbPool: DatabasePool var snapshot: DatabaseSnapshot init(dbPool: DatabasePool, snapshot: DatabaseSnapshot) { self.dbPool = dbPool self.snapshot = snapshot } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidCommit(_ db: Database) { snapshot = try! dbPool.makeSnapshot() } func databaseDidRollback(_ db: Database) { } } let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) let observer = try Observer(dbPool: dbPool, snapshot: dbPool.makeSnapshot()) dbPool.add(transactionObserver: observer) try XCTAssertEqual(observer.snapshot.read(counter.value), 0) try dbPool.write(counter.increment) try XCTAssertEqual(observer.snapshot.read(counter.value), 1) } // MARK: - Behavior func testSnapshotIsReadOnly() throws { let dbPool = try makeDatabasePool() let snapshot = try dbPool.makeSnapshot() do { try snapshot.read { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY") } XCTFail("Expected error") } catch is DatabaseError { } } func testSnapshotIsImmutable() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.writeWithoutTransaction { db in try counter.increment(db) let snapshot = try dbPool.makeSnapshot() try counter.increment(db) try XCTAssertEqual(counter.value(db), 2) try XCTAssertEqual(snapshot.read(counter.value), 1) try XCTAssertEqual(dbPool.read(counter.value), 2) try XCTAssertEqual(snapshot.read(counter.value), 1) try XCTAssertEqual(counter.value(db), 2) try XCTAssertEqual(dbPool.read(counter.value), 2) } } // MARK: - Functions func testSnapshotInheritPoolFunctions() throws { dbConfiguration.prepareDatabase { db in let function = DatabaseFunction("foo", argumentCount: 0, pure: true) { _ in return "foo" } db.add(function: function) } let dbPool = try makeDatabasePool() let snapshot = try dbPool.makeSnapshot() try snapshot.read { db in try XCTAssertEqual(String.fetchOne(db, sql: "SELECT foo()")!, "foo") } } // MARK: - Collations func testSnapshotInheritPoolCollations() throws { dbConfiguration.prepareDatabase { db in let collation = DatabaseCollation("reverse") { (string1, string2) in return (string1 == string2) ? .orderedSame : ((string1 < string2) ? .orderedDescending : .orderedAscending) } db.add(collation: collation) } let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute(sql: "CREATE TABLE items (text TEXT)") try db.execute(sql: "INSERT INTO items (text) VALUES ('a')") try db.execute(sql: "INSERT INTO items (text) VALUES ('b')") try db.execute(sql: "INSERT INTO items (text) VALUES ('c')") } let snapshot = try dbPool.makeSnapshot() try snapshot.read { db in XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE reverse"), ["c", "b", "a"]) } } // MARK: - Concurrency func testReadBlockIsolationStartingWithRead() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") } // Block 1 Block 2 // dbSnapshot.read { // > let s1 = DispatchSemaphore(value: 0) // INSERT INTO items (id) VALUES (NULL) // < let s2 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 0 // > let s3 = DispatchSemaphore(value: 0) // INSERT INTO items (id) VALUES (NULL) // < let s4 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 0 // } let block1 = { () in let snapshot = try! dbPool.makeSnapshot() try! snapshot.read { db in s1.signal() _ = s2.wait(timeout: .distantFuture) // We read 0 due to snaphot isolation which was acquired before // `s1` could let the writer insert an item. XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) s3.signal() _ = s4.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) } } let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) try dbPool.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") s2.signal() _ = s3.wait(timeout: .distantFuture) try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") s4.signal() } } catch { XCTFail("error: \(error)") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testDefaultLabel() throws { let dbPool = try makeDatabasePool() let snapshot1 = try dbPool.makeSnapshot() snapshot1.unsafeRead { db in XCTAssertEqual(db.configuration.label, nil) XCTAssertEqual(db.description, "GRDB.DatabasePool.snapshot.1") // This test CAN break in future releases: the dispatch queue labels // are documented to be a debug-only tool. let label = String(utf8String: __dispatch_queue_get_label(nil)) XCTAssertEqual(label, "GRDB.DatabasePool.snapshot.1") } let snapshot2 = try dbPool.makeSnapshot() snapshot2.unsafeRead { db in XCTAssertEqual(db.configuration.label, nil) XCTAssertEqual(db.description, "GRDB.DatabasePool.snapshot.2") // This test CAN break in future releases: the dispatch queue labels // are documented to be a debug-only tool. let label = String(utf8String: __dispatch_queue_get_label(nil)) XCTAssertEqual(label, "GRDB.DatabasePool.snapshot.2") } } func testCustomLabel() throws { dbConfiguration.label = "Toreador" let dbPool = try makeDatabasePool() let snapshot1 = try dbPool.makeSnapshot() snapshot1.unsafeRead { db in XCTAssertEqual(db.configuration.label, "Toreador") XCTAssertEqual(db.description, "Toreador.snapshot.1") // This test CAN break in future releases: the dispatch queue labels // are documented to be a debug-only tool. let label = String(utf8String: __dispatch_queue_get_label(nil)) XCTAssertEqual(label, "Toreador.snapshot.1") } let snapshot2 = try dbPool.makeSnapshot() snapshot2.unsafeRead { db in XCTAssertEqual(db.configuration.label, "Toreador") XCTAssertEqual(db.description, "Toreador.snapshot.2") // This test CAN break in future releases: the dispatch queue labels // are documented to be a debug-only tool. let label = String(utf8String: __dispatch_queue_get_label(nil)) XCTAssertEqual(label, "Toreador.snapshot.2") } } // MARK: - Checkpoints func testAutomaticCheckpointDoesNotInvalidateSnapshot() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.writeWithoutTransaction { db in // 1000 is enough to trigger automatic snapshot for _ in 0..<1000 { try counter.increment(db) } } try XCTAssertEqual(snapshot.read(counter.value), 1) } func testPassiveCheckpointDoesNotInvalidateSnapshot() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) } func testFullCheckpointDoesNotInvalidateSnapshot() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) } func testRestartCheckpointDoesNotInvalidateSnapshot() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) } func testTruncateCheckpointDoesNotInvalidateSnapshot() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) } // MARK: - Schema Cache func testSnapshotSchemaCache() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY)") } let snapshot = try dbPool.makeSnapshot() try snapshot.read { db in // Schema cache is updated XCTAssertNil(db.schemaCache[.main].primaryKey("t")) _ = try db.primaryKey("t") XCTAssertNotNil(db.schemaCache[.main].primaryKey("t")) } snapshot.read { db in // Schema cache is not cleared between reads XCTAssertNotNil(db.schemaCache[.main].primaryKey("t")) } } // MARK: - Closing func testClose() throws { let snapshot = try makeDatabasePool().makeSnapshot() try snapshot.close() // After close, access throws SQLITE_MISUSE do { try snapshot.read { db in try db.execute(sql: "SELECT * FROM sqlite_master") } XCTFail("Expected Error") } catch DatabaseError.SQLITE_MISUSE { } // After close, closing is a noop try snapshot.close() } func testCloseAfterUse() throws { let snapshot = try makeDatabasePool().makeSnapshot() try snapshot.read { db in try db.execute(sql: "SELECT * FROM sqlite_master") } try snapshot.close() // After close, access throws SQLITE_MISUSE do { try snapshot.read { db in try db.execute(sql: "SELECT * FROM sqlite_master") } XCTFail("Expected Error") } catch DatabaseError.SQLITE_MISUSE { } // After close, closing is a noop try snapshot.close() } func testCloseWithCachedStatement() throws { let snapshot = try makeDatabasePool().makeSnapshot() try snapshot.read { db in _ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master") } try snapshot.close() // After close, access throws SQLITE_MISUSE do { try snapshot.read { db in try db.execute(sql: "SELECT * FROM sqlite_master") } XCTFail("Expected Error") } catch DatabaseError.SQLITE_MISUSE { } // After close, closing is a noop try snapshot.close() } func testFailedClose() throws { let snapshot = try makeDatabasePool().makeSnapshot() let statement = try snapshot.read { db in try db.makeStatement(sql: "SELECT * FROM sqlite_master") } try withExtendedLifetime(statement) { do { try snapshot.close() XCTFail("Expected Error") } catch DatabaseError.SQLITE_BUSY { } } XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) // Database is not closed: no error try snapshot.read { db in try db.execute(sql: "SELECT * FROM sqlite_master") } } }
mit
0a444e1afb97514eaf33a23f4511a457
38.585812
129
0.587722
4.92008
false
true
false
false
midjuly/cordova-plugin-iosrtc
src/PluginRTCDataChannel.swift
2
6308
import Foundation class PluginRTCDataChannel : NSObject, RTCDataChannelDelegate { var rtcDataChannel: RTCDataChannel? var eventListener: ((data: NSDictionary) -> Void)? var eventListenerForBinaryMessage: ((data: NSData) -> Void)? var lostStates = Array<String>() var lostMessages = Array<RTCDataBuffer>() /** * Constructor for pc.createDataChannel(). */ init( rtcPeerConnection: RTCPeerConnection, label: String, options: NSDictionary?, eventListener: (data: NSDictionary) -> Void, eventListenerForBinaryMessage: (data: NSData) -> Void ) { NSLog("PluginRTCDataChannel#init()") self.eventListener = eventListener self.eventListenerForBinaryMessage = eventListenerForBinaryMessage let rtcDataChannelInit = RTCDataChannelInit() if options?.objectForKey("ordered") != nil { rtcDataChannelInit.isOrdered = options!.objectForKey("ordered") as! Bool } if options?.objectForKey("maxPacketLifeTime") != nil { // TODO: rtcDataChannel.maxRetransmitTime always reports 0. rtcDataChannelInit.maxRetransmitTimeMs = options!.objectForKey("maxPacketLifeTime") as! Int } if options?.objectForKey("maxRetransmits") != nil { rtcDataChannelInit.maxRetransmits = options!.objectForKey("maxRetransmits") as! Int } // TODO: error: expected member name following '.' // https://code.google.com/p/webrtc/issues/detail?id=4614 // if options?.objectForKey("protocol") != nil { // rtcDataChannelInit.protocol = options!.objectForKey("protocol") as! String // } if options?.objectForKey("protocol") != nil { rtcDataChannelInit.`protocol` = options!.objectForKey("protocol") as! String } if options?.objectForKey("negotiated") != nil { rtcDataChannelInit.isNegotiated = options!.objectForKey("negotiated") as! Bool } if options?.objectForKey("id") != nil { rtcDataChannelInit.streamId = options!.objectForKey("id") as! Int } self.rtcDataChannel = rtcPeerConnection.createDataChannelWithLabel(label, config: rtcDataChannelInit ) if self.rtcDataChannel == nil { NSLog("PluginRTCDataChannel#init() | rtcPeerConnection.createDataChannelWithLabel() failed !!!") return } // Report definitive data to update the JS instance. self.eventListener!(data: [ "type": "new", "channel": [ "ordered": self.rtcDataChannel!.isOrdered, "maxPacketLifeTime": self.rtcDataChannel!.maxRetransmitTime, "maxRetransmits": self.rtcDataChannel!.maxRetransmits, "protocol": self.rtcDataChannel!.`protocol`, "negotiated": self.rtcDataChannel!.isNegotiated, "id": self.rtcDataChannel!.streamId, "readyState": PluginRTCTypes.dataChannelStates[self.rtcDataChannel!.state.rawValue] as String!, "bufferedAmount": self.rtcDataChannel!.bufferedAmount ] ]) } deinit { NSLog("PluginRTCDataChannel#deinit()") } /** * Constructor for pc.ondatachannel event. */ init(rtcDataChannel: RTCDataChannel) { NSLog("PluginRTCDataChannel#init()") self.rtcDataChannel = rtcDataChannel } func run() { NSLog("PluginRTCDataChannel#run()") self.rtcDataChannel!.delegate = self } func setListener( eventListener: (data: NSDictionary) -> Void, eventListenerForBinaryMessage: (data: NSData) -> Void ) { NSLog("PluginRTCDataChannel#setListener()") self.eventListener = eventListener self.eventListenerForBinaryMessage = eventListenerForBinaryMessage for readyState in self.lostStates { self.eventListener!(data: [ "type": "statechange", "readyState": readyState ]) } self.lostStates.removeAll() for buffer in self.lostMessages { self.emitReceivedMessage(buffer) } self.lostMessages.removeAll() } func sendString( data: String, callback: (data: NSDictionary) -> Void ) { NSLog("PluginRTCDataChannel#sendString()") let buffer = RTCDataBuffer( data: (data.dataUsingEncoding(NSUTF8StringEncoding))!, isBinary: false ) let result = self.rtcDataChannel!.sendData(buffer) if result == true { callback(data: [ "bufferedAmount": self.rtcDataChannel!.bufferedAmount ]) } else { NSLog("PluginRTCDataChannel#sendString() | RTCDataChannel#sendData() failed") } } func sendBinary( data: NSData, callback: (data: NSDictionary) -> Void ) { NSLog("PluginRTCDataChannel#sendBinary()") let buffer = RTCDataBuffer( data: data, isBinary: true ) let result = self.rtcDataChannel!.sendData(buffer) if result == true { callback(data: [ "bufferedAmount": self.rtcDataChannel!.bufferedAmount ]) } else { NSLog("PluginRTCDataChannel#sendBinary() | RTCDataChannel#sendData() failed") } } func close() { NSLog("PluginRTCDataChannel#close()") self.rtcDataChannel!.close() } /** * Methods inherited from RTCDataChannelDelegate. */ func channelDidChangeState(channel: RTCDataChannel!) { let state_str = PluginRTCTypes.dataChannelStates[self.rtcDataChannel!.state.rawValue] as String! NSLog("PluginRTCDataChannel | state changed [state:\(state_str)]") if self.eventListener != nil { self.eventListener!(data: [ "type": "statechange", "readyState": state_str ]) } else { // It may happen that the eventListener is not yet set, so store the lost states. self.lostStates.append(state_str) } } func channel(channel: RTCDataChannel!, didReceiveMessageWithBuffer buffer: RTCDataBuffer!) { if buffer.isBinary == false { NSLog("PluginRTCDataChannel | utf8 message received") if self.eventListener != nil { self.emitReceivedMessage(buffer!) } else { // It may happen that the eventListener is not yet set, so store the lost messages. self.lostMessages.append(buffer!) } } else { NSLog("PluginRTCDataChannel | binary message received") if self.eventListenerForBinaryMessage != nil { self.emitReceivedMessage(buffer!) } else { // It may happen that the eventListener is not yet set, so store the lost messages. self.lostMessages.append(buffer!) } } } func emitReceivedMessage(buffer: RTCDataBuffer) { if buffer.isBinary == false { let string = NSString( data: buffer.data, encoding: NSUTF8StringEncoding ) self.eventListener!(data: [ "type": "message", "message": string as! String ]) } else { self.eventListenerForBinaryMessage!(data: buffer.data) } } }
mit
0c56b51a38da6f9b0e19187bbaa2571c
25.066116
99
0.711477
3.706228
false
false
false
false
fcanas/ios-charts
Charts/Classes/Charts/CombinedChartView.swift
10
6651
// // CombinedChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics /// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area. public class CombinedChartView: BarLineChartViewBase { /// the fill-formatter used for determining the position of the fill-line internal var _fillFormatter: ChartFillFormatter! /// enum that allows to specify the order in which the different data objects for the combined-chart are drawn @objc public enum CombinedChartDrawOrder: Int { case Bar case Bubble case Line case Candle case Scatter } public override func initialize() { super.initialize() _fillFormatter = BarLineChartFillFormatter(chart: self) renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } override func calcMinMax() { super.calcMinMax() if (self.barData !== nil || self.candleData !== nil || self.bubbleData !== nil) { _chartXMin = -0.5 _chartXMax = Double(_data.xVals.count) - 0.5 if (self.bubbleData !== nil) { for set in self.bubbleData.dataSets as! [BubbleChartDataSet] { let xmin = set.xMin let xmax = set.xMax if (xmin < chartXMin) { _chartXMin = xmin } if (xmax > chartXMax) { _chartXMax = xmax } } } _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) } } public override var data: ChartData? { get { return super.data } set { super.data = newValue (renderer as! CombinedChartRenderer?)!.createRenderers() } } public var fillFormatter: ChartFillFormatter { get { return _fillFormatter } set { _fillFormatter = newValue if (_fillFormatter === nil) { _fillFormatter = BarLineChartFillFormatter(chart: self) } } } public var lineData: LineChartData! { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).lineData } } public var barData: BarChartData! { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).barData } } public var scatterData: ScatterChartData! { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).scatterData } } public var candleData: CandleChartData! { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).candleData } } public var bubbleData: BubbleChartData! { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).bubbleData } } // MARK: Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled; } set { (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled = newValue; } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled; } set { (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled = newValue; } } /// if set to true, all values of a stack are drawn individually, and not just their sum public var drawValuesForWholeStackEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawValuesForWholeStackEnabled; } set { (renderer as! CombinedChartRenderer!).drawValuesForWholeStackEnabled = newValue; } } /// if set to true, a grey area is darawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled; } set { (renderer as! CombinedChartRenderer!).drawBarShadowEnabled = newValue; } } /// returns true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled; } /// returns true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled; } /// returns true if all values of a stack are drawn, and not just their sum public var isDrawValuesForWholeStackEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawValuesForWholeStackEnabled; } /// returns true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled; } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. public var drawOrder: [Int] { get { return (renderer as! CombinedChartRenderer!).drawOrder.map { $0.rawValue } } set { (renderer as! CombinedChartRenderer!).drawOrder = newValue.map { CombinedChartDrawOrder(rawValue: $0)! } } } }
apache-2.0
474d1d9dd679463c5db745e4b41c01bf
29.236364
134
0.569087
5.442717
false
false
false
false
xingerdayu/dayu
dayu/ImageLoader.swift
2
1812
// // ImageLoader.swift // extension // // Created by Nate Lyman on 7/5/14. // Copyright (c) 2014 NateLyman.com. All rights reserved. // import UIKit import Foundation class ImageLoader { var cache = NSCache() class var sharedLoader : ImageLoader { struct Static { static let instance : ImageLoader = ImageLoader() } return Static.instance } func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in let data: NSData? = self.cache.objectForKey(urlString) as? NSData if let goodData = data { let image = UIImage(data: goodData) dispatch_async(dispatch_get_main_queue(), {() in completionHandler(image: image, url: urlString) }) return } let downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in if (error != nil) { completionHandler(image: nil, url: urlString) return } if data != nil { let image = UIImage(data: data!) self.cache.setObject(data!, forKey: urlString) dispatch_async(dispatch_get_main_queue(), {() in completionHandler(image: image, url: urlString) }) return } }) downloadTask.resume() }) } }
bsd-3-clause
7a8993018e4dea6addc05fc759a3e08a
31.963636
214
0.521523
5.267442
false
false
false
false
netprotections/atonecon-ios
AtoneConDemo/View/Controller/ViewController.swift
1
7405
// // ViewController.swift // AtoneConDemo // // Created by Pham Ngoc Hanh on 6/28/17. // Copyright © 2017 AsianTech Inc. All rights reserved. // import UIKit import AtoneCon import Toast_Swift final class ViewController: UIViewController { @IBOutlet fileprivate weak var payButton: UIButton! @IBOutlet fileprivate weak var authenTokenTitleLabel: UILabel! @IBOutlet fileprivate weak var authenTokenValueLabel: UILabel! @IBOutlet fileprivate weak var authenTokenView: UIView! @IBOutlet fileprivate weak var resetTokenButton: UIButton! @IBOutlet fileprivate weak var transactionTextField: UITextField! var viewModel = PaymentViewModel() override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) authenTokenValueLabel.text = viewModel.getAuthenToken() transactionTextField.text = "" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) view.endEditing(true) } // MARK: - Setup UI private func setupUI() { title = Define.String.homeTitle setupPayButton() setupAuthenTokenView() setupAuthenTokenLabel() setupResetTokenButton() setupNavigationController() setupTextField() } // MARK: - Action @IBAction func payButtonTapped(_ sender: Any) { var options = AtoneCon.Options(publicKey: "bB2uNvcOP2o8fJzHpWUumA") options.environment = .development options.terminalId = "" let atoneCon = AtoneCon.shared atoneCon.delegate = self atoneCon.config(options) let payment = viewModel.payment(withTransaction: transactionTextField.text) atoneCon.performPayment(payment) } @IBAction func resetTokenButtonTapped(_ sender: Any) { viewModel.resetAuthenToken() updateView() } } // MARK: - AtoneConDelegate extension ViewController: AtoneConDelegate { func atoneCon(atoneCon: AtoneCon, didReceivePaymentEvent event: AtoneCon.PaymentEvent) { switch event { case .authenticated(let authenToken, let userNo): viewModel.saveAuthenToken(token: authenToken) guard let authenToken = authenToken?.description else { return } let message = "Authentication: \(authenToken) \n user_no: \(userNo?.description ?? "empty")" let view = UIApplication.shared.keyWindow view?.makeToast(message, duration: 2, position: .bottom) case .cancelled: atoneCon.dismiss { [weak self] in guard let this = self else { return } this.view.makeToast(Define.String.cancel, duration: 2, position: .bottom) } case .failed(let response): let message = response?.toJSONString() showAlert(title: Define.String.failed, message: message) { _ in atoneCon.dismiss() } case .finished(let response): let message = response?.description atoneCon.dismiss { [weak self] in guard let this = self else { return } this.showAlert(title: Define.String.finished, message: message) } case .error(let name, let message, let errors): showAlert(title: Define.String.failed, message: message) { _ in atoneCon.dismiss() } } } } // MARK: - UITextFieldDelegate extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.endEditing(true) return true } } // MARK: - setup UI extension ViewController { fileprivate func showAlert(title: String?, message: String?, handler: ((UIAlertAction) -> Void)? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let ok = UIAlertAction(title: Define.String.okay, style: .cancel, handler: handler) alert.addAction(ok) let root = AppDelegate.shared.window?.topViewController root?.present(alert, animated: true, completion: nil) } fileprivate func setupPayButton() { payButton.layer.cornerRadius = 5 payButton.backgroundColor = Define.Color.lightBlue payButton.setTitle(Define.String.atoneButtonTitle, for: .normal) } fileprivate func setupNavigationController() { if let navigationBar = navigationController?.navigationBar { navigationBar.barTintColor = Define.Color.lightBlue navigationBar.tintColor = UIColor.white navigationBar.isTranslucent = false navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] navigationBar.tintColor = UIColor.white } } fileprivate func setupAuthenTokenView() { authenTokenView.layer.borderWidth = 2 authenTokenView.layer.borderColor = Define.Color.lightBlue.cgColor authenTokenView.layer.cornerRadius = 5 } fileprivate func setupAuthenTokenLabel() { authenTokenTitleLabel.backgroundColor = .white authenTokenTitleLabel.text = Define.String.authenTokenTitle authenTokenTitleLabel.textColor = Define.Color.lightBlue } fileprivate func setupResetTokenButton() { let attributes: [NSAttributedStringKey:Any] = [ NSAttributedString.Key(rawValue: NSAttributedStringKey.font.rawValue): UIFont.systemFont(ofSize: 17), NSAttributedString.Key(rawValue: NSAttributedStringKey.foregroundColor.rawValue): UIColor.black, NSAttributedString.Key(rawValue: NSAttributedStringKey.underlineStyle.rawValue): NSUnderlineStyle.styleSingle.rawValue] let attributedString: NSAttributedString = NSAttributedString(string: Define.String.resetAuthen, attributes: attributes) resetTokenButton.setAttributedTitle(attributedString, for: .normal) } fileprivate func setupTextField() { transactionTextField.placeholder = Define.String.textFieldPlaceHolder transactionTextField.delegate = self } fileprivate func updateView() { if isViewLoaded { authenTokenValueLabel.text = viewModel.getAuthenToken() } } } // MARK: extension extension UIWindow { var topViewController: UIViewController? { return rootViewController?.visibleController } } extension UIViewController { var visibleController: UIViewController? { switch self { case let navi as UINavigationController: return navi.visibleViewController?.visibleController case let tabBar as UITabBarController: return tabBar.selectedViewController?.visibleController case let controller where self.presentedViewController != nil: return controller.presentedViewController?.visibleController default: return self } } } extension Dictionary where Key == String, Value == Any { func toJSONString(options: JSONSerialization.WritingOptions = []) -> String? { do { let data = try JSONSerialization.data(withJSONObject: self, options: options) return String(data: data, encoding: .utf8) } catch { return nil } } }
mit
3fe5649e78031c1fdc4f42f60ce459b5
35.835821
131
0.671664
4.906561
false
false
false
false
rallahaseh/RALocalization
RALocalization/Classes/RALanguage.swift
1
1767
// // RALanguage.swift // RALocalization // // Created by Rashed Al Lahaseh on 10/17/17. // import Foundation import UIKit let APPLE_LANGUAGE_KEY = "AppleLanguages" let FONT_TYPE = "Lato-LightItalic" public enum RALanguages: String { case english = "en" case french = "fr" case spanish = "es" case german = "de" case arabic = "ar" case hebrew = "he" case japanese = "ja" case chineseSimplified = "zh-Hans" case chineseTraditional = "zh-Hant" } open class RALanguage { // Get Current App language open class func currentLanguage(withLocale: Bool = true) -> String{ let userDefault = UserDefaults.standard let languageArray = userDefault.object(forKey: APPLE_LANGUAGE_KEY) as! NSArray let current = languageArray.firstObject as! String let index = current.index(current.startIndex, offsetBy: 2) let currentWithoutLocale = String(current[..<index]) return withLocale ? currentWithoutLocale : current } /// set @lang to be the first in App Languages List open class func setLanguage(language: RALanguages) { let userDefault = UserDefaults.standard userDefault.set([language.rawValue, currentLanguage()], forKey: APPLE_LANGUAGE_KEY) userDefault.synchronize() } open class var isRTL: Bool { if RALanguage.currentLanguage() == RALanguages.arabic.rawValue { return true } else if RALanguage.currentLanguage() == RALanguages.hebrew.rawValue { return true } else { return false } } }
mit
efe89d4205746adb4ad4d67a495bb9f2
31.722222
96
0.591964
4.352217
false
false
false
false
PiXeL16/BudgetShare
BudgetShare/UI/SignUp/SignUpViewController.swift
1
2276
// // SignUpViewController.swift // BudgetShare // // Created by Chris Jimenez on 3/5/17. // Copyright © 2017 Chris Jimenez. All rights reserved. // import UIKit class SignUpViewController: UIViewController { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var fieldContainerView: UIView! @IBOutlet weak var signUpButton: UIButton! var presenter: SignUpModule! deinit { presenter = nil } override func viewDidLoad() { super.viewDidLoad() self.setupView() } @IBAction func signUpTapped(_ sender: Any) { self.didTapSignUp() } @IBAction func cancelTapped(_ sender: Any) { self.didTapCancel() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupView() { self.fieldContainerView.layer.cornerRadius = Constants.cornerRadius self.signUpButton.layer.cornerRadius = Constants.cornerRadius let backgroundGradient = Gradients(self.view.bounds).orangeBackgroundGradient self.view.layer.insertSublayer(backgroundGradient, at: 0) } override var prefersStatusBarHidden: Bool { return true } } extension SignUpViewController: SignUpView { var controller: UIViewController? { return self } func didTapSignUp() { guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text, !email.isEmpty, !password.isEmpty, !name.isEmpty else { self.fieldContainerView.shake() return } //TODO: Validate fields presenter.singUp(email: email, password: password, name: name) } func didTapCancel() { presenter.presentLogin() } func receiveError(message: String) { presenter.presentError(message: message) } func signUpSuccessful() { } }
mit
2c19e6412c65c8d7a4cd2a22edb41836
21.75
85
0.607033
5.266204
false
false
false
false
sambatech/player_sdk_ios
SambaPlayer/AESAssetLoaderDelegate.swift
1
3458
// // AESAssetLoaderDelegate.swift // SambaPlayer // // Created by Kesley Vaz on 06/12/18. // Copyright © 2018 Samba Tech. All rights reserved. // import Foundation class AESAssetLoaderDelegate: NSObject { /// The AVURLAsset associated with the asset. fileprivate let asset: AVURLAsset /// The name associated with the asset. fileprivate let assetName: String /// The document URL to use for saving persistent content key. fileprivate let documentURL: URL fileprivate var previousScheme: String init(asset: AVURLAsset, assetName: String, previousScheme: String) { // Determine the library URL. guard let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { fatalError("Unable to determine library URL") } documentURL = URL(fileURLWithPath: documentPath) self.asset = asset self.assetName = assetName self.previousScheme = previousScheme super.init() self.asset.resourceLoader.setDelegate(self, queue: DispatchQueue(label: "\(assetName)-delegateQueue")) self.asset.resourceLoader.preloadsEligibleContentKeys = true } } extension AESAssetLoaderDelegate: AVAssetResourceLoaderDelegate { public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { var component = URLComponents(url: loadingRequest.request.url!, resolvingAgainstBaseURL: true) component?.scheme = previousScheme loadingRequest.redirect = URLRequest(url: (component?.url)!) if let data = UserDefaults.standard.data(forKey: "teste") { loadingRequest.contentInformationRequest?.contentType = AVStreamingKeyDeliveryPersistentContentKeyType loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true loadingRequest.contentInformationRequest?.contentLength = Int64(data.count) loadingRequest.dataRequest?.respond(with: data) UserDefaults.standard.set(data, forKey: "teste") loadingRequest.finishLoading() } else { let request = URLRequest(url: URL(string: "https://fast.player.liquidplatform.com/v3/v1/key/\(assetName)")!) let task = URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data, error == nil else { loadingRequest.finishLoading() return } loadingRequest.contentInformationRequest?.contentType = AVStreamingKeyDeliveryPersistentContentKeyType loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true loadingRequest.contentInformationRequest?.contentLength = Int64(data.count) loadingRequest.dataRequest?.respond(with: data) UserDefaults.standard.set(data, forKey: "teste") loadingRequest.finishLoading() } task.resume() } return true } public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForRenewalOfRequestedResource renewalRequest: AVAssetResourceRenewalRequest) -> Bool { return true } }
mit
2931c69793c1e8bd7f31e2b3c03f92b8
37.842697
172
0.668209
5.557878
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0168.xcplaygroundpage/Contents.swift
1
6040
/*: # Multi-Line String Literals * Proposal: [SE-0168](0168-multi-line-string-literals.md) * Authors: [John Holdsworth](https://github.com/johnno1962), [Brent Royal-Gordon](https://github.com/brentdax), [Tyler Cloutier](https://github.com/TheArtOfEngineering) * Review Manager: [Joe Groff](https://github.com/jckarter) * Status: **Implemented (Swift 4)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170417/035923.html) * Bug: [SR-170](https://bugs.swift.org/browse/SR-170) ## Introduction This proposal introduces multi-line string literals to Swift source code. This has been discussed a few times on swift-evolution most recently putting forward a number of different syntaxes that could achieve this goal each of which has their own use case and constituency for discussion. [Swift-evolution thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001565.html) ## Motivation Multi-line String literals are a common programming-language feature that is, to date, still missing in Swift. Whether generating XML/JSON messages or building usage messages in Swift scripts, providing string literals that extend over multiple lines offers a simple way to represent text without having to manually break lines using string concatenation. Concatenation is ungainly and may result in slow compilation. ## Proposed solution After consideration this proposal puts forward a single simple syntax for inclusion: `"""long strings"""`. This has the advantage that it is well supported by the syntax highlighters on GitHub and existing editors and is a relatively minor change to the Swift Lexer. Interpolation would work as before. ### Long strings Long strings are strings delimited by `"""triple quotes"""` that can contain newlines and individual `"` characters without the need to escape them. assert( xml == """ <?xml version="1.0"?> <catalog> <book id="bk101" empty=""> <author>\(author)</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> </catalog> """ ) To allow free formatting of the literal an indentation stripping operation is applied whereby any whitespace characters in front of the closing delimiter are removed from each of the lines in the literal. As part of this process any initial linefeed is also removed. This allows the developer to paste literal content directly into the string without modification. Some concern has been expressed about could introduce confusion if the prefixing indentation of each line does not contain the same whitespace characters, though this can be checked for by a compiler warning. ## Detailed design These changes are envisaged to be mostly confined to the Swift tokeniser: lib/Parse/Lexer.cpp. The new string literals would be presented to the grammar as simply being string literals. This has been explored in a PR for a [prototype toolchain](https://github.com/apple/swift/pull/2275) and seems to be a robust approach. Other details are explored in the prototype such as escaping the newline in literals resulting in it not being included in the final literal. ## Impact on existing code As this proposal is additive it does not affect existing code. ## Alternatives considered Two other alternative syntaxes were discussed in the swift-evolution thread. It became apparent that each syntax had its own, at times, non-overlapping constituency of supporters. ### Continuation quotes The basic idea of continuation quotes is straightforward. If a quoted string literal is not closed by " before the end of the line and the first non-whitespace character on the next line is " it is taken to be a continuation of the previous literal. let xml = "<?xml version=\"1.0\"?> "<catalog> " <book id=\"bk101\" empty=\"\"> " <author>\(author)</author> " <title>XML Developer's Guide</title> " <genre>Computer</genre> " <price>44.95</price> " <publish_date>2000-10-01</publish_date> " <description>An in-depth look at creating applications with XML.</description> " </book> "</catalog> "" The advantage of this format is it gives precise control of exactly what is included in the literal. It also allows code to be formatted in an aesthetically pleasing manner. Its main disadvantage is that some external editors will not be familiar with the format and will be unable to correctly syntax highlight literals. ### Heredoc Taking a precedent from other languages, a syntax such as the following could be used to introduce literals into a codebase. assert( xml == <<"XML" ) <?xml version="1.0"?> <catalog> <book id="bk101" empty=""> <author>\(author)</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> </catalog> XML The same indentation stripping rules would be applied as for long strings. This syntax has the advantage of being able to paste content in directly and the additional advantage that the literal is separated from the line of code using it, increasing clarity. Its main disadvantage is a more practical one: it is a more major departure for the compiler in that tokens in the AST are no longer in source file order. Testing has, however, shown the toolchain to be surprisingly robust in dealing with this change once a few assertions were removed. ---------- [Previous](@previous) | [Next](@next) */
mit
97662cd57155232064ff7f6c3310de7f
45.10687
168
0.715728
4.326648
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/ViewControllers/Transitions/ImageDetailPresentAnimator.swift
2
2080
// // ImageDetailPresentAnimator.swift // SwiftNetworkImages // // Created by Arseniy on 5/10/16. // Copyright © 2016 Arseniy Kuznetsov. All rights reserved. // import UIKit class ImageDetailPresentAnimator: NSObject, UIViewControllerAnimatedTransitioning { var sourceFrame = CGRect.zero func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return ImageDetailTransitionsOptions.PresentAnimationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return } let finalFrame = transitionContext.finalFrame(for: toViewController) let xScaleFactor = sourceFrame.width / finalFrame.width let yScaleFactor = sourceFrame.height / finalFrame.height let scaleTransform = CGAffineTransform(scaleX: xScaleFactor, y: yScaleFactor) toView.alpha = 0.0 toView.frame = finalFrame toView.transform = scaleTransform toView.center = CGPoint( x: sourceFrame.midX, y: sourceFrame.midY ) toView.clipsToBounds = true containerView.addSubview(toView) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: [], animations: { toView.alpha = 1.0 toView.transform = CGAffineTransform.identity toView.center = CGPoint( x: finalFrame.midX, y: finalFrame.midY ) }, completion: {_ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } }
mit
3cb37da70ca610ccb88101038fb1556c
38.980769
119
0.666667
5.95702
false
false
false
false
vmalakhovskiy/Gemini
Gemini/Gemini/Extensions/NSBezierPathExtensions.swift
1
1564
// // NSBezierPathExtensions.swift // Gemini // // Created by Vitaliy Malakhovskiy on 7/25/16. // Copyright © 2016 Vitalii Malakhovskyi. All rights reserved. // import Foundation import Cocoa extension NSBezierPath { var CGPath: CGPathRef { get { return transformToCGPath() } } private func transformToCGPath() -> CGPathRef { let path = CGPathCreateMutable() let points = UnsafeMutablePointer<NSPoint>.alloc(3) let numElements = elementCount if numElements > 0 { var didClosePath = true for index in 0..<numElements { let pathType = elementAtIndex(index, associatedPoints: points) switch pathType { case .MoveToBezierPathElement: CGPathMoveToPoint(path, nil, points[0].x, points[0].y) case .LineToBezierPathElement: CGPathAddLineToPoint(path, nil, points[0].x, points[0].y) didClosePath = false case .CurveToBezierPathElement: CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y) didClosePath = false case .ClosePathBezierPathElement: CGPathCloseSubpath(path) didClosePath = true } } if !didClosePath { CGPathCloseSubpath(path) } } points.dealloc(3) return path } }
mit
d7c54a5fe46bbde38e329ebb681612e9
28.509434
130
0.552783
4.961905
false
false
false
false
swiftsanyue/TestKitchen
TestKitchen/TestKitchen/classes/ingredient(食材)/recommend(推荐)/main(主要模块)/view/IngreTopicCell.swift
1
2601
// // IngreTopicCell.swift // TestKitchen // // Created by ZL on 16/11/1. // Copyright © 2016年 zl. All rights reserved. // import UIKit class IngreTopicCell: UITableViewCell { @IBOutlet weak var topicImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descLabel: UILabel! //点击事件 var jumpClosure:IngreJumpClosure? //显示数据 var cellArray:Array<IngreRecommendWidgetData>?{ didSet{ showData() } } func showData(){ //图片 if cellArray?.count > 0 { let imageData = cellArray![0] if imageData.type == "image" { let url = NSURL(string: imageData.content!) topicImageView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } //标题 if cellArray?.count > 1 { let titleData = cellArray![1] if titleData.type == "text" { nameLabel.text = titleData.content } } //描述文字 if cellArray?.count > 2{ let descData = cellArray![2] if descData.type == "text" { descLabel.text = descData.content } } } //创建cell的方法 class func createTopicCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,cellArray:Array<IngreRecommendWidgetData>?)->IngreTopicCell { let cellId = "ingreTopicCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? IngreTopicCell if nil == cell { cell = NSBundle.mainBundle().loadNibNamed("IngreTopicCell", owner: nil, options: nil).last as? IngreTopicCell } //显示数据 cell?.cellArray = cellArray return cell! } func tapAction(){ if cellArray?.count > 0 { let imageData = cellArray![0] if imageData.link != nil && jumpClosure != nil { jumpClosure!(imageData.link!) } } } override func awakeFromNib() { super.awakeFromNib() //点击事件 let g = UITapGestureRecognizer(target: self, action: #selector(tapAction)) addGestureRecognizer(g) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
662e0a6032a301a7f20f1d93fd60f581
26.608696
168
0.570079
4.951267
false
false
false
false
yarshure/Surf
Surf/StatViewController.swift
1
3208
// // StatViewController.swift // Surf // // Created by yarshure on 16/2/14. // Copyright © 2016年 yarshure. All rights reserved. // import UIKit class StatViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
bsd-3-clause
8448163987d38ff8c7f01933678a5e87
32.041237
157
0.678939
5.525862
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Services/AccountService+MergeDuplicates.swift
1
1519
import Foundation extension AccountService { func mergeDuplicatesIfNecessary() { guard numberOfAccounts() > 1 else { return } let accounts = allAccounts() let accountGroups = Dictionary(grouping: accounts) { $0.userID } for group in accountGroups.values where group.count > 1 { mergeDuplicateAccounts(accounts: group) } if managedObjectContext.hasChanges { ContextManager.sharedInstance().save(managedObjectContext) } } private func mergeDuplicateAccounts(accounts: [WPAccount]) { // For paranoia guard accounts.count > 1 else { return } // If one of the accounts is the default account, merge the rest into it. // Otherwise just use the first account. var destination = accounts.first! if let defaultAccount = defaultWordPressComAccount(), accounts.contains(defaultAccount) { destination = defaultAccount } for account in accounts where account != destination { mergeAccount(account: account, into: destination) } let service = BlogService(managedObjectContext: managedObjectContext) service.deduplicateBlogs(for: destination) } private func mergeAccount(account: WPAccount, into destination: WPAccount) { // Move all blogs to the destination account destination.addBlogs(account.blogs) managedObjectContext.delete(account) } }
gpl-2.0
7a8c173f8d9283240c7267f3ca705581
30.645833
97
0.647136
5.329825
false
false
false
false
apple/swift
lib/ASTGen/Sources/ASTGen/Macros.swift
1
9357
import SwiftParser import SwiftSyntax @_spi(Testing) import _SwiftSyntaxMacros extension SyntaxProtocol { func token(at position: AbsolutePosition) -> TokenSyntax? { // If the position isn't within this node at all, return early. guard position >= self.position && position < self.endPosition else { return nil } // If we are a token syntax, that's it! if let token = Syntax(self).as(TokenSyntax.self) { return token } // Otherwise, it must be one of our children. return children(viewMode: .sourceAccurate).lazy.compactMap { child in child.token(at: position) }.first } } /// Describes a macro that has been "exported" to the C++ part of the /// compiler, with enough information to interface with the C++ layer. struct ExportedMacro { var macro: Macro.Type } /// Look up a macro with the given name. /// /// Returns an unmanaged pointer to an ExportedMacro instance that describes /// the specified macro. If there is no macro with the given name, produces /// nil. @_cdecl("swift_ASTGen_lookupMacro") public func lookupMacro( macroNamePtr: UnsafePointer<UInt8> ) -> UnsafeRawPointer? { let macroSystem = MacroSystem.exampleSystem // Look for a macro with this name. let macroName = String(cString: macroNamePtr) guard let macro = macroSystem.lookup(macroName) else { return nil } // Allocate and initialize the exported macro. let exportedPtr = UnsafeMutablePointer<ExportedMacro>.allocate(capacity: 1) exportedPtr.initialize(to: .init(macro: macro)) return UnsafeRawPointer(exportedPtr) } /// Destroys the given macro. @_cdecl("swift_ASTGen_destroyMacro") public func destroyMacro( macroPtr: UnsafeMutablePointer<UInt8> ) { macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in macro.deinitialize(count: 1) macro.deallocate() } } /// Allocate a copy of the given string as a UTF-8 string. private func allocateUTF8String( _ string: String, nullTerminated: Bool = false ) -> (UnsafePointer<UInt8>, Int) { var string = string return string.withUTF8 { utf8 in let capacity = utf8.count + (nullTerminated ? 1 : 0) let ptr = UnsafeMutablePointer<UInt8>.allocate( capacity: capacity ) if let baseAddress = utf8.baseAddress { ptr.initialize(from: baseAddress, count: utf8.count) } if nullTerminated { ptr[utf8.count] = 0 } return (UnsafePointer<UInt8>(ptr), utf8.count) } } @_cdecl("swift_ASTGen_getMacroGenericSignature") public func getMacroGenericSignature( macroPtr: UnsafeMutablePointer<UInt8>, genericSignaturePtr: UnsafeMutablePointer<UnsafePointer<UInt8>?>, genericSignatureLengthPtr: UnsafeMutablePointer<Int> ) { macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in guard let genericSig = macro.pointee.macro.genericSignature else { (genericSignaturePtr.pointee, genericSignatureLengthPtr.pointee) = (nil, 0) return } (genericSignaturePtr.pointee, genericSignatureLengthPtr.pointee) = allocateUTF8String(genericSig.description) } } /// Query the type signature of the given macro. @_cdecl("swift_ASTGen_getMacroTypeSignature") public func getMacroTypeSignature( macroPtr: UnsafeMutablePointer<UInt8>, signaturePtr: UnsafeMutablePointer<UnsafePointer<UInt8>?>, signatureLengthPtr: UnsafeMutablePointer<Int> ) { macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in (signaturePtr.pointee, signatureLengthPtr.pointee) = allocateUTF8String(macro.pointee.macro.signature.description) } } /// Query the documentation of the given macro. @_cdecl("swift_ASTGen_getMacroDocumentation") public func getMacroDocumentation( macroPtr: UnsafeMutablePointer<UInt8>, documentationPtr: UnsafeMutablePointer<UnsafePointer<UInt8>?>, documentationLengthPtr: UnsafeMutablePointer<Int> ) { macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in (documentationPtr.pointee, documentationLengthPtr.pointee) = allocateUTF8String(macro.pointee.macro.documentation) } } /// Query the owning module of the given macro. @_cdecl("swift_ASTGen_getMacroOwningModule") public func getMacroOwningModule( macroPtr: UnsafeMutablePointer<UInt8>, owningModulePtr: UnsafeMutablePointer<UnsafePointer<UInt8>?>, owningModuleLengthPtr: UnsafeMutablePointer<Int> ) { macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in (owningModulePtr.pointee, owningModuleLengthPtr.pointee) = allocateUTF8String(macro.pointee.macro.owningModule) } } /// Query the supplemental signature modules of the given macro, /// as a semicolon-separated string @_cdecl("swift_ASTGen_getMacroSupplementalSignatureModules") public func getMacroSupplementableSignatureModules( macroPtr: UnsafeMutablePointer<UInt8>, modulesPtr: UnsafeMutablePointer<UnsafePointer<UInt8>?>, modulesLengthPtr: UnsafeMutablePointer<Int> ) { macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in let modules = macro.pointee.macro.supplementalSignatureModules .joined(separator: ";") (modulesPtr.pointee, modulesLengthPtr.pointee) = allocateUTF8String(modules) } } /// Query the macro evaluation context given the evaluation /// context sources. @_cdecl("swift_ASTGen_getMacroEvaluationContext") public func getMacroEvaluationContext( sourceFilePtr: UnsafePointer<UInt8>, declContext: UnsafeMutableRawPointer, context: UnsafeMutableRawPointer, evaluatedSourceBuffer: UnsafePointer<UInt8>, evaluatedSourceBufferLength: Int ) -> UnsafeMutableRawPointer? { let evaluatedSource = UnsafeBufferPointer( start: evaluatedSourceBuffer, count: evaluatedSourceBufferLength ) let sourceFile = Parser.parse(source: evaluatedSource) // Dig out the top-level typealias declaration. That's all we'll // parse. guard let typealiasDecl = sourceFile.statements.first( where: { item in item.item.is(TypealiasDeclSyntax.self) })?.item.as(TypealiasDeclSyntax.self) else { return nil } // Parse and ASTGen that top-level declaration. // FIXME: we need to emit diagnostics from this. return ASTGenVisitor( ctx: context, base: sourceFilePtr, declContext: declContext ).visit(typealiasDecl).rawValue } @_cdecl("swift_ASTGen_evaluateMacro") @usableFromInline func evaluateMacro( sourceFilePtr: UnsafePointer<UInt8>, sourceLocationPtr: UnsafePointer<UInt8>?, expandedSourcePointer: UnsafeMutablePointer<UnsafePointer<UInt8>?>, expandedSourceLength: UnsafeMutablePointer<Int> ) -> Int { // We didn't expand anything so far. expandedSourcePointer.pointee = nil expandedSourceLength.pointee = 0 guard let sourceLocationPtr = sourceLocationPtr else { print("NULL source location") return -1 } return sourceFilePtr.withMemoryRebound( to: ExportedSourceFile.self, capacity: 1 ) { (sourceFile: UnsafePointer<ExportedSourceFile>) -> Int in // Find the offset. let buffer = sourceFile.pointee.buffer let offset = sourceLocationPtr - buffer.baseAddress! if offset < 0 || offset >= buffer.count { print("source location isn't inside this buffer") return -1 } let sf = sourceFile.pointee.syntax guard let token = sf.token(at: AbsolutePosition(utf8Offset: offset)) else { print("couldn't find token at offset \(offset)") return -1 } guard let parentSyntax = token.parent, parentSyntax.is(MacroExpansionExprSyntax.self) else { print("not on a macro expansion node: \(token.recursiveDescription)") return -1 } let macroSystem = MacroSystem.exampleSystem let converter = SourceLocationConverter( file: sourceFile.pointee.fileName, tree: sf ) let context = MacroEvaluationContext( moduleName: sourceFile.pointee.moduleName, sourceLocationConverter: converter ) let evaluatedSyntax = parentSyntax.evaluateMacro( with: macroSystem, context: context ) { error in /* TODO: Report errors */ } var evaluatedSyntaxStr = evaluatedSyntax.withoutTrivia().description evaluatedSyntaxStr.withUTF8 { utf8 in let evaluatedResultPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: utf8.count + 1) if let baseAddress = utf8.baseAddress { evaluatedResultPtr.initialize(from: baseAddress, count: utf8.count) } evaluatedResultPtr[utf8.count] = 0 expandedSourcePointer.pointee = UnsafePointer(evaluatedResultPtr) expandedSourceLength.pointee = utf8.count } return 0 } } /// Calls the given `allMacros: [Any.Type]` function pointer and produces a /// newly allocated buffer containing metadata pointers. @_cdecl("swift_ASTGen_getMacroTypes") @usableFromInline func getMacroTypes( getterAddress: UnsafeRawPointer, resultAddress: UnsafeMutablePointer<UnsafePointer<UnsafeRawPointer>?>, count: UnsafeMutablePointer<Int> ) { let getter = unsafeBitCast( getterAddress, to: (@convention(thin) () -> [Any.Type]).self) let metatypes = getter() let address = UnsafeMutableBufferPointer<Any.Type>.allocate( capacity: metatypes.count ) _ = address.initialize(from: metatypes) address.withMemoryRebound(to: UnsafeRawPointer.self) { resultAddress.initialize(to: UnsafePointer($0.baseAddress)) } count.initialize(to: address.count) }
apache-2.0
d752209c243e53be7394101fb4e9f529
32.417857
93
0.739981
4.362238
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios
Example/SuperAwesomeExampleTests/Common/Repositories/EventRepositoryTests.swift
1
2963
// // EventRepositoryTests.swift // SuperAwesome-Unit-Moya-Tests // // Created by Gunhan Sancar on 30/04/2020. // import XCTest import Nimble @testable import SuperAwesome class EventRepositoryTests: XCTestCase { private var result: Result<Void, Error>? private let mockAdQueryMaker = AdQueryMakerMock() private let mockDataSource = AdDataSourceMock() private var repository: EventRepository! override func setUp() { super.setUp() result = nil repository = EventRepository(dataSource: mockDataSource, adQueryMaker: mockAdQueryMaker, logger: LoggerMock()) } func test_givenSuccess_impressionCalled_returnsSuccess() throws { // Given let expectedResult = Result<(), Error>.success(()) mockDataSource.mockEventResult = expectedResult // When let expectation = self.expectation(description: "request") repository.impression(MockFactory.makeAdResponse()) { result in self.result = result expectation.fulfill() } waitForExpectations(timeout: 2.0, handler: nil) // Then expect(self.result?.isSuccess).to(equal(expectedResult.isSuccess)) } func test_givenSuccess_clickCalled_returnsSuccess() throws { // Given let expectedResult = Result<(), Error>.success(()) mockDataSource.mockEventResult = expectedResult // When let expectation = self.expectation(description: "request") repository.impression(MockFactory.makeAdResponse()) { result in self.result = result expectation.fulfill() } waitForExpectations(timeout: 2.0, handler: nil) // Then expect(self.result?.isSuccess).to(equal(expectedResult.isSuccess)) } func test_givenSuccess_videoClickCalled_returnsSuccess() throws { // Given let expectedResult = Result<(), Error>.success(()) mockDataSource.mockEventResult = expectedResult // When let expectation = self.expectation(description: "request") repository.impression(MockFactory.makeAdResponse()) { result in self.result = result expectation.fulfill() } waitForExpectations(timeout: 2.0, handler: nil) // Then expect(self.result?.isSuccess).to(equal(expectedResult.isSuccess)) } func test_givenSuccess_eventCalled_returnsSuccess() throws { // Given let expectedResult = Result<(), Error>.success(()) mockDataSource.mockEventResult = expectedResult // When let expectation = self.expectation(description: "request") repository.impression(MockFactory.makeAdResponse()) { result in self.result = result expectation.fulfill() } waitForExpectations(timeout: 2.0, handler: nil) // Then expect(self.result?.isSuccess).to(equal(expectedResult.isSuccess)) } }
lgpl-3.0
41dcb410266d67205b81a44850106888
31.56044
118
0.651029
4.825733
false
true
false
false
sonsongithub/reddift
application/MoviePlayerController.swift
1
2609
// // MoviePlayerController.swift // reddift // // Created by sonson on 2016/10/22. // Copyright © 2016年 sonson. All rights reserved. // import Foundation import AVKit import AVFoundation class MoviePlayerController: ImageViewController { let movieView: MoviePlayView let movieURL: URL @objc func didChangeStatus(notification: Notification) { var f = movieView.frame f.size = movieView.presentationSize movieView.frame = f updateImageCenter() let boundsSize = self.view.bounds var frameToCenter = movieView.frame let ratio = movieView.presentationSize.width / movieView.presentationSize.height var contentSize = CGSize.zero if ratio > 1 { contentSize = CGSize(width: boundsSize.width, height: boundsSize.height / ratio) } else { contentSize = CGSize(width: boundsSize.height * ratio, height: boundsSize.height) } frameToCenter.size = contentSize var f2 = mainImageView.bounds f2.origin = CGPoint.zero movieView.frame = f2 if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2 } else { frameToCenter.origin.x = 0 } if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2 } else { frameToCenter.origin.y = 0 } movieView.playerLayer.player?.play() } override func viewDidLoad() { print("MovieViewController - viewDidLoad") super.viewDidLoad() mainImageView.addSubview(movieView) NotificationCenter.default.addObserver(self, selector: #selector(MoviePlayerController.didChangeStatus(notification:)), name: MoviePlayViewDidChangeStatus, object: nil) } required init?(coder aDecoder: NSCoder) { movieURL = URL(string: "")! movieView = MoviePlayView(url: movieURL) super.init(coder: aDecoder) } override init(index: Int, thumbnails: [Thumbnail], isOpenedBy3DTouch: Bool = false) { let thumbnail = thumbnails[index] switch thumbnail { case .Image: movieURL = URL(string: "")! case .Movie(let movieURL, _, _): self.movieURL = movieURL } movieView = MoviePlayView(url: movieURL) super.init(index: index, thumbnails: thumbnails, isOpenedBy3DTouch: isOpenedBy3DTouch) } }
mit
04c00fe25b572e2eddd93045f051b59c
32.410256
176
0.629701
4.68705
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/IDCard/Model/IDCardClient.swift
1
1039
// // IDCardClient.swift // byuSuite // // Created by Alex Boswell on 12/5/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let BASE_URL = "https://api.byu.edu/domains/legacy/identity/person/PRO/personidcard/v1" class IDCardClient: ByuClient2 { static func getIDCard(callback: @escaping (IDCard?, ByuError?) -> Void) { ByuCredentialManager.getPersonSummary { (personSummary, error) in if let personSummary = personSummary { let request = ByuRequest2(url: super.url(base: BASE_URL, pathParams: [personSummary.personId]), authMethod: .OAUTH, acceptType: .JSON) makeRequest(request, callback: { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any], let response = data["ID Card Service"] as? [String: Any], let dict = response["response"] as? [String: Any] { callback(IDCard(dict: dict), nil) } else { callback(nil, response.error) } }) } else { callback(nil, PERSON_SUMMARY_ERROR) } } } }
apache-2.0
607ab5c1204f5b63eeeea4b3976eb518
32.483871
138
0.674374
3.326923
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/Room/NotificationSettings/Coordinator/RoomNotificationSettingsBridgePresenter.swift
1
4153
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation @objc protocol RoomNotificationSettingsCoordinatorBridgePresenterDelegate { func roomNotificationSettingsCoordinatorBridgePresenterDelegateDidComplete(_ coordinatorBridgePresenter: RoomNotificationSettingsCoordinatorBridgePresenter) } /// RoomNotificationSettingsCoordinatorBridgePresenter enables to start RoomNotificationSettingsCoordinator from a view controller. /// This bridge is used while waiting for global usage of coordinator pattern. /// It breaks the Coordinator abstraction and it has been introduced for Objective-C compatibility (mainly for integration in legacy view controllers). /// Each bridge should be removed once the underlying Coordinator has been integrated by another Coordinator. @objcMembers final class RoomNotificationSettingsCoordinatorBridgePresenter: NSObject { // MARK: - Properties // MARK: Private private let room: MXRoom private var coordinator: RoomNotificationSettingsCoordinator? // MARK: Public weak var delegate: RoomNotificationSettingsCoordinatorBridgePresenterDelegate? // MARK: - Setup init(room: MXRoom) { self.room = room super.init() } // MARK: - Public // NOTE: Default value feature is not compatible with Objective-C. // func present(from viewController: UIViewController, animated: Bool) { // self.present(from: viewController, animated: animated) // } func present(from viewController: UIViewController, animated: Bool) { let roomNotificationSettingsCoordinator = RoomNotificationSettingsCoordinator(room: room) roomNotificationSettingsCoordinator.delegate = self let presentable = roomNotificationSettingsCoordinator.toPresentable() let navigationController = RiotNavigationController(rootViewController: presentable) navigationController.modalPresentationStyle = .formSheet presentable.presentationController?.delegate = self viewController.present(navigationController, animated: animated, completion: nil) roomNotificationSettingsCoordinator.start() self.coordinator = roomNotificationSettingsCoordinator } func dismiss(animated: Bool, completion: (() -> Void)?) { guard let coordinator = self.coordinator else { return } coordinator.toPresentable().dismiss(animated: animated) { self.coordinator = nil if let completion = completion { completion() } } } } // MARK: - RoomNotificationSettingsCoordinatorDelegate extension RoomNotificationSettingsCoordinatorBridgePresenter: RoomNotificationSettingsCoordinatorDelegate { func roomNotificationSettingsCoordinatorDidCancel(_ coordinator: RoomNotificationSettingsCoordinatorType) { self.delegate?.roomNotificationSettingsCoordinatorBridgePresenterDelegateDidComplete(self) } func roomNotificationSettingsCoordinatorDidComplete(_ coordinator: RoomNotificationSettingsCoordinatorType) { self.delegate?.roomNotificationSettingsCoordinatorBridgePresenterDelegateDidComplete(self) } } // MARK: - UIAdaptivePresentationControllerDelegate extension RoomNotificationSettingsCoordinatorBridgePresenter: UIAdaptivePresentationControllerDelegate { func roomNotificationSettingsCoordinatorDidComplete(_ presentationController: UIPresentationController) { self.delegate?.roomNotificationSettingsCoordinatorBridgePresenterDelegateDidComplete(self) } }
apache-2.0
0a3cda3d8544b166246094cc4c954cb8
40.53
160
0.756562
6.152593
false
false
false
false
powerytg/Accented
Accented/UI/Common/Components/Drawer/DrawerOpenAnimator.swift
1
2222
// // DrawerOpenAnimator.swift // Accented // // Created by You, Tiangong on 6/16/16. // Copyright © 2016 Tiangong You. All rights reserved. // import UIKit class DrawerOpenAnimator: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning { private var animationContext : DrawerAnimationContext init(animationContext : DrawerAnimationContext) { self.animationContext = animationContext super.init() } // MARK: UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.2 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) let fromView = fromViewController?.view let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let duration = self.transitionDuration(using: transitionContext) let animationOptions : UIViewAnimationOptions = (animationContext.interactive ? .curveLinear : .curveEaseOut) UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { if fromView != nil { let scale = CGAffineTransform(scaleX: 0.94, y: 0.94) var translation : CGAffineTransform switch(self.animationContext.anchor) { case .bottom: translation = CGAffineTransform(translationX: 0, y: -25) case .left: translation = CGAffineTransform(translationX: 25, y: 0) case .right: translation = CGAffineTransform(translationX: -25, y: 0) } fromView!.transform = scale.concatenating(translation) } toView.transform = CGAffineTransform.identity }) { (finished) in let transitionCompleted = !transitionContext.transitionWasCancelled transitionContext.completeTransition(transitionCompleted) } } }
mit
542d929e81de534e516c42f6b50e51cf
39.381818
117
0.656461
6.203911
false
false
false
false
liuche/FirefoxAccounts-ios
Shared/Functions.swift
5
6049
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import SwiftyJSON // Pipelining. precedencegroup PipelinePrecedence { associativity: left } infix operator |> : PipelinePrecedence public func |> <T, U>(x: T, f: (T) -> U) -> U { return f(x) } // Basic currying. public func curry<A, B>(_ f: @escaping (A) -> B) -> (A) -> B { return { a in return f(a) } } public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C { return { a in return { b in return f(a, b) } } } public func curry<A, B, C, D>(_ f: @escaping (A, B, C) -> D) -> (A) -> (B) -> (C) -> D { return { a in return { b in return { c in return f(a, b, c) } } } } public func curry<A, B, C, D, E>(_ f: @escaping (A, B, C, D) -> E) -> (A, B, C) -> (D) -> E { return { (a, b, c) in return { d in return f(a, b, c, d) } } } // Function composition. infix operator • public func •<T, U, V>(f: @escaping (T) -> U, g: @escaping (U) -> V) -> (T) -> V { return { t in return g(f(t)) } } public func •<T, V>(f: @escaping (T) -> Void, g: @escaping () -> V) -> (T) -> V { return { t in f(t) return g() } } public func •<V>(f: @escaping () -> Void, g: @escaping () -> V) -> () -> V { return { f() return g() } } // Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse. // This is enough to catch arrays, which Swift will delegate to element-==. public func optArrayEqual<T: Equatable>(_ lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.none, _): return false case (_, .none): return false default: // This delegates to Swift's own array '==', which calls T's == on each element. return lhs! == rhs! } } /** * Given an array, return an array of slices of size `by` (possibly excepting the last slice). * * If `by` is longer than the input, returns a single chunk. * If `by` is less than 1, acts as if `by` is 1. * If the length of the array isn't a multiple of `by`, the final slice will * be smaller than `by`, but never empty. * * If the input array is empty, returns an empty array. */ public func chunk<T>(_ arr: [T], by: Int) -> [ArraySlice<T>] { var result = [ArraySlice<T>]() var chunk = -1 let size = max(1, by) for (index, elem) in arr.enumerated() { if index % size == 0 { result.append(ArraySlice<T>()) chunk += 1 } result[chunk].append(elem) } return result } public extension Sequence { // [T] -> (T -> K) -> [K: [T]] // As opposed to `groupWith` (to follow Haskell's naming), which would be // [T] -> (T -> K) -> [[T]] func groupBy<Key, Value>(_ selector: (Self.Iterator.Element) -> Key, transformer: (Self.Iterator.Element) -> Value) -> [Key: [Value]] { var acc: [Key: [Value]] = [:] for x in self { let k = selector(x) var a = acc[k] ?? [] a.append(transformer(x)) acc[k] = a } return acc } func zip<S: Sequence>(_ elems: S) -> [(Self.Iterator.Element, S.Iterator.Element)] { var rights = elems.makeIterator() return self.flatMap { lhs in guard let rhs = rights.next() else { return nil } return (lhs, rhs) } } } public func optDictionaryEqual<K: Equatable, V: Equatable>(_ lhs: [K: V]?, rhs: [K: V]?) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.none, _): return false case (_, .none): return false default: return lhs! == rhs! } } /** * Return members of `a` that aren't nil, changing the type of the sequence accordingly. */ public func optFilter<T>(_ a: [T?]) -> [T] { return a.flatMap { $0 } } /** * Return a new map with only key-value pairs that have a non-nil value. */ public func optFilter<K, V>(_ source: [K: V?]) -> [K: V] { var m = [K: V]() for (k, v) in source { if let v = v { m[k] = v } } return m } /** * Map a function over the values of a map. */ public func mapValues<K, T, U>(_ source: [K: T], f: ((T) -> U)) -> [K: U] { var m = [K: U]() for (k, v) in source { m[k] = f(v) } return m } public func findOneValue<K, V>(_ map: [K: V], f: (V) -> Bool) -> V? { for v in map.values { if f(v) { return v } } return nil } /** * Take a JSON array, returning the String elements as an array. * It's usually convenient for this to accept an optional. */ public func jsonsToStrings(_ arr: [JSON]?) -> [String]? { return arr?.flatMap { $0.stringValue } } // Encapsulate a callback in a way that we can use it with NSTimer. private class Callback { private let handler:() -> Void init(handler:@escaping () -> Void) { self.handler = handler } @objc func go() { handler() } } /** * Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call * Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires. **/ public func debounce(_ delay: TimeInterval, action:@escaping () -> Void) -> () -> Void { let callback = Callback(handler: action) var timer: Timer? return { // If calling again, invalidate the last timer. if let timer = timer { timer.invalidate() } timer = Timer(timeInterval: delay, target: callback, selector: #selector(Callback.go), userInfo: nil, repeats: false) RunLoop.current.add(timer!, forMode: RunLoopMode.defaultRunLoopMode) } }
mpl-2.0
31a85bfbbca39efca082522a77958d34
25.495614
139
0.536501
3.372976
false
false
false
false
xedin/swift
test/SourceKit/ExpressionType/basic.swift
20
718
func foo() -> Int { return 1 } func bar(f: Float) -> Float { return bar(f: 1) } protocol P {} func fooP(_ p: P) { fooP(p) } class C {} func ArrayC(_ a: [C]) { _ = a.count _ = a.description.count.advanced(by: 1).description } struct S { let val = 4 } func DictS(_ a: [Int: S]) { _ = a[2]?.val.advanced(by: 1).byteSwapped } // RUN: %sourcekitd-test -req=collect-type %s -- %s | %FileCheck %s // CHECK: (183, 202): Int // CHECK: (183, 196): String // CHECK: (183, 184): [C] // CHECK: (203, 211): (Int) -> (Int) -> Int // CHECK: (211, 218): (by: Int) // CHECK: (216, 217): Int // CHECK: (257, 258): Int // CHECK: (291, 332): () // CHECK: (291, 292): Int? // CHECK: (295, 332): Int? // CHECK: (295, 320): Int
apache-2.0
af73f542799f5e9a23042fe6ba4d75b7
20.117647
67
0.544568
2.475862
false
false
false
false
silt-lang/silt
Sources/Moho/ScopeDiagnostics.swift
1
4932
/// ScopeDiagnostics.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Lithosphere // MARK: Scope Check extension Diagnostic.Message { static func undeclaredIdentifier(_ n: QualifiedName) -> Diagnostic.Message { return Diagnostic.Message(.error, "use of undeclared identifier '\(n)'") } static func undeclaredIdentifier(_ n: Name) -> Diagnostic.Message { return Diagnostic.Message(.error, "use of undeclared identifier '\(n)'") } static func ambiguousName(_ n: Name) -> Diagnostic.Message { return Diagnostic.Message(.error, "ambiguous use of name '\(n)'") } static func ambiguousCandidate( _ n: FullyQualifiedName) -> Diagnostic.Message { return Diagnostic.Message(.note, "candidate has name '\(n)") } static func nameReserved(_ n: Name) -> Diagnostic.Message { return Diagnostic.Message(.error, "cannot use reserved name '\(n)'") } static func nameShadows(_ n: Name) -> Diagnostic.Message { return Diagnostic.Message(.error, "cannot shadow name '\(n)'") } static func shadowsOriginal(_ n: Name) -> Diagnostic.Message { return Diagnostic.Message(.note, "first declaration of '\(n)' occurs here") } static func nameShadows( _ local: Name, _ n: FullyQualifiedName) -> Diagnostic.Message { return Diagnostic.Message(.error, "name '\(local)' shadows qualified '\(n)'") } static func duplicateImport(_ qn: QualifiedName) -> Diagnostic.Message { return Diagnostic.Message(.warning, "duplicate import of \(qn)") } static func bodyBeforeSignature(_ n: Name) -> Diagnostic.Message { return Diagnostic.Message(.error, "function body for '\(n)' must appear after function type signature") } static func recordMissingConstructor( _ n: FullyQualifiedName) -> Diagnostic.Message { return Diagnostic.Message(.error, "record '\(n)' must have constructor declared") } static func precedenceNotIntegral(_ p: TokenSyntax) -> Diagnostic.Message { return Diagnostic.Message(.warning, """ operator precedence '\(p.triviaFreeSourceText)' \ is invalid; precedence must be a positive integer """) } static var assumingDefaultPrecedence: Diagnostic.Message { return Diagnostic.Message(.note, "assuming default precedence of 20") } static func tooManyPatternsInLHS( _ expectedArgCount: Int, _ haveArgs: Int, _ implArgs: Int ) -> Diagnostic.Message { let argsPlural = self.pluralize( singular: "argument", plural: "arguments", expectedArgCount) let patternPlural = self.pluralize( singular: "pattern", plural: "patterns", haveArgs) let implPatternPlural = self.pluralize( singular: "pattern", plural: "patterns", implArgs) return Diagnostic.Message(.error, """ function expects \(expectedArgCount) \(argsPlural) but has \ \(haveArgs) declared \(patternPlural) and \(implArgs) implicit \ \(implPatternPlural); extra patterns will be ignored """) } static var ignoringExcessPattern: Diagnostic.Message { return Diagnostic.Message(.note, "extra pattern will be ignored") } static func incorrectModuleStructure( _ name: QualifiedName ) -> Diagnostic.Message { return Diagnostic.Message(.error, """ module name '\(name)' does not match expected module structure """) } static func expectedModulePath( _ name: QualifiedName, _ fileName: String, _ expectedDir: String, _ actualDir: String ) -> Diagnostic.Message { return Diagnostic.Message(.note, """ module name '\(name)' implies '\(fileName)' should be at path '\(expectedDir)'; it is currently at path '\(actualDir)' """) } static func unexpectedDirectory(_ fileName: String) -> Diagnostic.Message { return Diagnostic.Message(.note, """ '\(fileName)' references a directory; it must reference a file """) } static func incorrectModuleName(_ name: QualifiedName) -> Diagnostic.Message { return Diagnostic.Message(.error, "no such module \(name)") } } // MARK: Reparsing extension Diagnostic.Message { static var reparseLHSFailed: Diagnostic.Message = Diagnostic.Message(.error, "unable to parse function parameter clause") static var reparseRHSFailed: Diagnostic.Message = Diagnostic.Message(.error, "unable to parse expression") static func reparseAbleToParse(_ s: Syntax) -> Diagnostic.Message { return Diagnostic.Message(.note, "partial parse recovered expression '\(s.diagnosticSourceText)'") } static func reparseUsedNotation(_ n: NewNotation) -> Diagnostic.Message { return Diagnostic.Message(.note, "while using notation \(n.description)") } }
mit
3edc3d96a7c849abebfd5e595abdfdc7
33.25
80
0.669911
4.626642
false
false
false
false
joemcbride/outlander-osx
src/Outlander/AutoMapperWindowController.swift
1
13338
// // AutoMapperWindowController.swift // Outlander // // Created by Joseph McBride on 4/2/15. // Copyright (c) 2015 Joe McBride. All rights reserved. // import Cocoa func loadMap <R> ( backgroundClosure: () -> R, mainClosure: (R) -> ()) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { let res = backgroundClosure() dispatch_async(dispatch_get_main_queue(), { mainClosure(res) }) } } func mainThread(mainClosure: () -> ()) { dispatch_async(dispatch_get_main_queue(), { mainClosure() }) } class MapsDataSource : NSObject, NSComboBoxDataSource { private var maps:[MapInfo] = [] func loadMaps(mapsFolder:String, mapLoader:MapLoader, loaded: (()->Void)?) { { () -> [MapMetaResult] in return mapLoader.loadFolder(mapsFolder) } ~> { (results) ->() in var success:[MapInfo] = [] for res in results { switch res { case let .Success(mapInfo): success.append(mapInfo) case let .Error(error): print("\(error)") } } self.maps = success.sort { $0.id.compare($1.id, options: NSStringCompareOptions.NumericSearch, range: $0.id.startIndex..<$0.id.endIndex, locale:nil) == NSComparisonResult.OrderedAscending } loaded?() } } func mapForZoneId(id:String) -> MapInfo? { return self.maps.filter { $0.id == id }.first } func mapForFile(file:String) -> MapInfo? { return self.maps.filter { $0.file == file }.first } func mapAtIndex(index:Int) -> MapInfo { return self.maps[index]; } func indexOfMap(id:String) -> Int? { if let info = mapForZoneId(id) { return self.maps.indexOf(info) } return nil } func initializeMaps(context:GameContext, loader: MapLoader) { guard let mapsFolder = context.pathProvider.mapsFolder() else { return } let start = NSDate() let maps = self.maps.filter { $0.zone == nil } context.events.echoText("[Automapper]: loading all maps...", preset: "automapper") loadMap({ () -> [MapLoadResult] in var results: [MapLoadResult] = [] maps.forEach { m in let result = loader.load(mapsFolder.stringByAppendingPathComponent(m.file)) switch result { case let .Success(zone): zone.file = m.file m.zone = zone case let .Error(error): print(error) } results.append(result) } return results }, mainClosure: { result -> () in let diff = NSDate().timeIntervalSinceDate(start) self.maps.forEach { map in context.maps[map.id] = map.zone! } context.events.echoText("[Automapper]: all \(self.maps.count) maps loaded in \(diff.format("0.2")) seconds", preset: "automapper") context.resetMap() }) } // MARK - NSComboBoxDataSource func numberOfItemsInComboBox(aComboBox: NSComboBox) -> Int { return self.maps.count } func comboBox(aComboBox: NSComboBox, objectValueForItemAtIndex index: Int) -> AnyObject? { guard index > -1 else { return "" } let map = self.maps[index] return "\(map.id). \(map.name)" } } class AutoMapperWindowController: NSWindowController, NSComboBoxDataSource, ISubscriber { @IBOutlet weak var mapsComboBox: NSComboBox! @IBOutlet weak var nodesLabel: NSTextField! @IBOutlet weak var scrollView: NSScrollView! @IBOutlet weak var mapView: MapView! @IBOutlet weak var mapLevelLabel: NSTextField! @IBOutlet weak var nodeNameLabel: NSTextField! private var mapsDataSource: MapsDataSource = MapsDataSource() private var context:GameContext? private let mapLoader:MapLoader = MapLoader() var mapLevel:Int = 0 { didSet { self.mapView.mapLevel = self.mapLevel self.mapLevelLabel.stringValue = "Level: \(self.mapLevel)" } } var mapZoom:CGFloat = 1.0 { didSet { if self.mapZoom == 0 { self.mapZoom = 0.5 } } } override func windowDidLoad() { super.windowDidLoad() self.nodeNameLabel.stringValue = "" self.mapsComboBox.dataSource = self.mapsDataSource self.mapView.nodeHover = { node in if let room = node { var notes = "" if room.notes != nil { notes = "(\(room.notes!))" } self.nodeNameLabel.stringValue = "#\(room.id) - \(room.name) \(notes)" } else { self.nodeNameLabel.stringValue = "" } } self.mapView.nodeClicked = { node in if node.isTransfer() { self.context?.globalVars.set(node.id, forKey: "roomid") } } self.mapView.nodeTravelTo = { node in self.context?.events.sendCommandText("#goto \(node.id)") } } func setSelectedZone() { if let zone = self.context?.mapZone { if let idx = self.mapsDataSource.indexOfMap(zone.id) { self.mapsComboBox.selectItemAtIndex(idx) self.renderMap(zone) } } if let charname = self.context?.globalVars["charactername"], let game = self.context?.globalVars["game"] { self.window?.title = "AutoMapper - \(game): \(charname)" } } internal func handle(token:String, data:[String:AnyObject]) { guard token == "variable:changed" else { return } guard let changed = data as? [String:String] else { return } let key = changed.keys.first ?? "" if key == "zoneid" { if let zoneId = changed["zoneid"], let mapInfo = self.mapsDataSource.mapForZoneId(zoneId) { self.setZoneFromMap(mapInfo) } } if key == "roomid" { if let id = changed["roomid"], let room = self.context!.mapZone?.roomWithId(id) { if room.isTransfer() { guard let mapfile = room.transferMap else { return } if let mapInfo = self.mapsDataSource.mapForFile(mapfile) { self.setZoneFromMap(mapInfo) } } else { mainThread { if self.mapView != nil { self.mapView.mapLevel = room.position.z self.mapView.currentRoomId = id } } } } } } func setContext(context:GameContext) { self.context = context self.context?.events.subscribe(self, token: "variable:changed") } func setZoneFromMap(mapInfo:MapInfo) { if let idx = self.mapsDataSource.indexOfMap(mapInfo.id) { mainThread { if self.mapsComboBox != nil && self.mapsComboBox.indexOfSelectedItem != idx { self.mapsComboBox.selectItemAtIndex(idx) } else { if mapInfo.zone != nil { self.renderMap(mapInfo.zone!) self.context?.mapZone = mapInfo.zone! } else { self.loadMapFromInfo(mapInfo) } } } } } func findCurrentRoom(zone:MapZone) -> MapNode? { if let ctx = self.context { let roomId = ctx.globalVars["roomid"] ?? "" return zone.roomWithId(roomId) } return nil } func loadMaps() { if let mapsFolder = self.context?.pathProvider.mapsFolder() { if self.nodesLabel != nil { self.nodesLabel.stringValue = "Loading Maps ..." } self.mapsDataSource.loadMaps(mapsFolder, mapLoader: self.mapLoader, loaded: { ()->Void in if self.nodesLabel != nil { self.nodesLabel.stringValue = "" } if let zoneId = self.context!.globalVars["zoneid"] { if let idx = self.mapsDataSource.indexOfMap(zoneId) { if self.mapsComboBox != nil { self.mapsComboBox.selectItemAtIndex(idx) } else { self.loadMapFromInfo(self.mapsDataSource.mapAtIndex(idx)) } } } self.mapsDataSource.initializeMaps(self.context!, loader: self.mapLoader) }) } } func renderMap(zone:MapZone) { if self.mapView == nil { return } let room = self.findCurrentRoom(zone) let rect = zone.mapSize(0, padding: 100.0) self.mapLevel = room?.position.z ?? 0 self.mapView?.setFrameSize(rect.size) self.mapView?.currentRoomId = room != nil ? room!.id : "" self.mapView?.setZone(zone, rect: rect) let roomCount = zone.rooms.count self.nodesLabel.stringValue = "Map \(zone.id). \(zone.name), Rooms: \(roomCount)" if let rect = self.mapView?.rectForRoom(self.mapView?.currentRoomId) { self.scrollView.scrollRectToVisible(rect) } } func loadMapFromInfo(info:MapInfo) { if let loaded = info.zone { self.context?.mapZone = loaded info.zone = loaded if self.mapView != nil { self.renderMap(loaded) } return } if let mapsFolder = context?.pathProvider.mapsFolder() { let file = mapsFolder.stringByAppendingPathComponent(info.file) if self.nodesLabel != nil { self.nodesLabel.stringValue = "Loading ..." } self.context?.events.echoText("[Automapper]: loading selected map \(info.file)", preset: "automapper") let start = NSDate() loadMap({ () -> MapLoadResult in return self.mapLoader.load(file) }, mainClosure: { (result) -> () in let diff = NSDate().timeIntervalSinceDate(start) switch result { case let .Success(zone): self.context?.events.echoText("[Automapper]: \(zone.name) loaded in \(diff.format(".2")) seconds", preset: "automapper") self.context?.mapZone = zone info.zone = zone if self.mapView != nil { self.renderMap(zone) } case let .Error(error): self.context?.events.echoText("[Automapper]: map loaded with error in \(diff.format(".2")) seconds", preset: "automapper") self.context?.events.echoText("\(error)") if self.nodesLabel != nil { self.nodesLabel.stringValue = "Error loading map: \(error)" } } }) } } @IBAction func mapLevelAction(sender: NSSegmentedControl) { if sender.selectedSegment == 0 { self.mapLevel += 1 } else { self.mapLevel -= 1 } } @IBAction func mapZoomAction(sender: NSSegmentedControl) { if sender.selectedSegment == 0 { self.mapZoom += 0.5 } else { self.mapZoom -= 0.5 } let clipView = self.scrollView.contentView var clipViewBounds = clipView.bounds let clipViewSize = clipView.frame.size clipViewBounds.size.width = clipViewSize.width / self.mapZoom clipViewBounds.size.height = clipViewSize.height / self.mapZoom clipView.setBoundsSize(clipViewBounds.size) } func comboBoxSelectionDidChange(notification: NSNotification) { let idx = self.mapsComboBox.indexOfSelectedItem let selectedMap = self.mapsDataSource.mapAtIndex(idx) if self.context?.mapZone != selectedMap.zone { self.loadMapFromInfo(selectedMap) } else if selectedMap.zone != nil { self.renderMap(selectedMap.zone!) } } }
mit
63fdf3a6933f90c0462d8809dd7872ea
30.457547
201
0.50135
4.799568
false
false
false
false
JohnSansoucie/MyProject2
BlueCap/Peripheral/PeripheralManagerServiceCharacteristicViewController.swift
1
6054
// // PeripheralManagerServiceCharacteristicViewController.swift // BlueCap // // Created by Troy Stribling on 8/19/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import UIkit import CoreBluetooth import BlueCapKit class PeripheralManagerServiceCharacteristicViewController : UITableViewController { var characteristic : MutableCharacteristic? var peripheralManagerViewController : PeripheralManagerViewController? @IBOutlet var uuidLabel : UILabel! @IBOutlet var permissionReadableLabel : UILabel! @IBOutlet var permissionWriteableLabel : UILabel! @IBOutlet var permissionReadEncryptionLabel : UILabel! @IBOutlet var permissionWriteEncryptionLabel : UILabel! @IBOutlet var propertyBroadcastLabel : UILabel! @IBOutlet var propertyReadLabel : UILabel! @IBOutlet var propertyWriteWithoutResponseLabel : UILabel! @IBOutlet var propertyWriteLabel : UILabel! @IBOutlet var propertyNotifyLabel : UILabel! @IBOutlet var propertyIndicateLabel : UILabel! @IBOutlet var propertyAuthenticatedSignedWritesLabel : UILabel! @IBOutlet var propertyExtendedPropertiesLabel : UILabel! @IBOutlet var propertyNotifyEncryptionRequiredLabel : UILabel! @IBOutlet var propertyIndicateEncryptionRequiredLabel : UILabel! struct MainStoryboard { static let peripheralManagerServiceCharacteristicValuesSegue = "PeripheralManagerServiceCharacteristicValues" } required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let characteristic = self.characteristic { self.uuidLabel.text = characteristic.uuid.UUIDString self.permissionReadableLabel.text = self.booleanStringValue(characteristic.permissionEnabled(CBAttributePermissions.Readable)) self.permissionWriteableLabel.text = self.booleanStringValue(characteristic.permissionEnabled(CBAttributePermissions.Writeable)) self.permissionReadEncryptionLabel.text = self.booleanStringValue(characteristic.permissionEnabled(CBAttributePermissions.ReadEncryptionRequired)) self.permissionWriteEncryptionLabel.text = self.booleanStringValue(characteristic.permissionEnabled(CBAttributePermissions.WriteEncryptionRequired)) self.propertyBroadcastLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.Broadcast)) self.propertyReadLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.Read)) self.propertyWriteWithoutResponseLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.WriteWithoutResponse)) self.propertyWriteLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.Write)) self.propertyNotifyLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.Notify)) self.propertyIndicateLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.Indicate)) self.propertyAuthenticatedSignedWritesLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.AuthenticatedSignedWrites)) self.propertyExtendedPropertiesLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.ExtendedProperties)) self.propertyNotifyEncryptionRequiredLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.NotifyEncryptionRequired)) self.propertyIndicateEncryptionRequiredLabel.text = self.booleanStringValue(characteristic.propertyEnabled(CBCharacteristicProperties.IndicateEncryptionRequired)) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let characteristic = self.characteristic { self.navigationItem.title = characteristic.name } NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationItem.title = "" NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) { if segue.identifier == MainStoryboard.peripheralManagerServiceCharacteristicValuesSegue { let viewController = segue.destinationViewController as PeripheralManagerServicesCharacteristicValuesViewController viewController.characteristic = self.characteristic if let peripheralManagerViewController = self.peripheralManagerViewController { viewController.peripheralManagerViewController = peripheralManagerViewController } } } func didResignActive() { Logger.debug("PeripheralManagerServiceCharacteristicViewController#didResignActive") if let peripheralManagerViewController = self.peripheralManagerViewController { self.navigationController?.popToViewController(peripheralManagerViewController, animated:false) } } func didBecomeActive() { Logger.debug("PeripheralManagerServiceCharacteristicViewController#didBecomeActive") } func booleanStringValue(value:Bool) -> String { return value ? "YES" : "NO" } }
mit
268b7f85eea6e30bef252c5e82a36e1d
55.055556
174
0.736373
6.241237
false
false
false
false
iOSDevLog/iOSDevLog
Instagram/Pods/LeanCloud/Sources/Storage/Logger.swift
1
941
// // Logger.swift // LeanCloud // // Created by Tang Tianyong on 10/19/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation class Logger { static let defaultLogger = Logger() static let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = NSLocale.current dateFormatter.dateFormat = "yyyy'-'MM'-'dd'.'HH':'mm':'ss'.'SSS" return dateFormatter }() public func log<T>( _ value: @autoclosure () -> T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { guard globalOptions.logLevel.isDebugEnabled else { return } let date = Logger.dateFormatter.string(from: Date()) let file = NSURL(string: file)?.lastPathComponent ?? "Unknown" print("[LeanCloud \(date) \(file) #\(line) \(function)]:", value()) } }
mit
91570bb2d5e90dacf9b3fb17a914b718
23.736842
75
0.588298
4.253394
false
false
false
false
soapyigu/LeetCode_Swift
Array/StrobogrammaticNumber.swift
1
980
/** * Question Link: https://leetcode.com/problems/strobogrammatic-number/ * Primary idea: Two pointers, compare two characters until they are all valid * * Time Complexity: O(n), Space Complexity: O(1) * */ class StrobogrammaticNumber { func isStrobogrammatic(_ num: String) -> Bool { let numChars = Array(num) var i = 0, j = num.count - 1 while i <= j { if isValid(numChars[i], numChars[j]) { i += 1 j -= 1 } else { return false } } return true } fileprivate func isValid(_ charA: Character, _ charB: Character) -> Bool { if charA == charB { return ["0", "1", "8"].contains(charA) } else { if (charA == "6" && charB == "9") || (charA == "9" && charB == "6") { return true } else { return false } } } }
mit
ffb11015d0f7c5328df9f5d39a3f6ded
24.789474
81
0.461224
3.951613
false
false
false
false
yunuserenguzel/road-game
Road/Views/CellView.swift
1
10628
// // CellView.swift // Road // // Created by Yunus Eren Guzel on 28/08/15. // Copyright (c) 2015 yeg. All rights reserved. // import UIKit enum CellType { case passive, active } enum CellState { case hightlighted, normal } enum Direction { case north,south,west,east } class CellView: UIView { struct Connection { var north:CellView? var south:CellView? var west:CellView? var east:CellView? } struct ConnectionView { var north = UIView() var south = UIView() var west = UIView() var east = UIView() } var point:Map.Point! var state:CellState! = CellState.normal { didSet { configureViews() } } var connection:Connection = Connection() fileprivate var connectionView:ConnectionView = ConnectionView() var cellType:CellType! { didSet { configureViews() } } var label = UILabel() init() { super.init(frame: CGRect.zero) initViews() } override init(frame: CGRect) { super.init(frame: frame) initViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initViews() } func redirectedCellFrom(_ cell:CellView?) -> CellView? { if(connection.north != cell && connection.north != nil) { return connection.north } else if (connection.south != cell && connection.south != nil) { return connection.south } else if (connection.west != cell && connection.west != nil) { return connection.west } else if (connection.east != cell && connection.east != nil) { return connection.east } else { return nil; } } func clearConnections(){ // clear any connection for any direction. make the connection nil before calling disconnectFrom if let cell = connection.north { connection.north = nil cell.disconnectFrom(self) } if let cell = connection.south { connection.south = nil cell.disconnectFrom(cell) } if let cell = connection.east { connection.east = nil cell.disconnectFrom(self) } if let cell = connection.west { connection.west = nil cell.disconnectFrom(self) } configureViews() } func disconnectFrom(_ cell:CellView) { // check for all directions and then call configure views if any connection is set to nil if connection.east == cell { connection.east = nil configureViews() if cell.connection.west == self { cell.disconnectFrom(self) } } else if connection.north == cell { connection.north = nil configureViews() if cell.connection.south == self { cell.disconnectFrom(self) } } else if connection.south == cell { connection.south = nil configureViews() if cell.connection.north == self { cell.disconnectFrom(self) } } else if connection.west == cell { connection.west = nil configureViews() if cell.connection.east == self { cell.disconnectFrom(self) } } } func connectionCount() -> Int { return (connection.west != nil ? 1 : 0) + (connection.east != nil ? 1 : 0) + (connection.north != nil ? 1 : 0) + (connection.south != nil ? 1 : 0) } func connectOrDisconnect(_ cell:CellView) -> Bool { if let direction = findDirection(cell) as Direction! { var isConnected = false switch direction { case .north: isConnected = self.connection.north == cell case .south: isConnected = self.connection.south == cell case .west: isConnected = self.connection.west == cell case .east: isConnected = self.connection.east == cell } if isConnected { disconnectFrom(cell) return true } else { return connectWith(cell) } } return false } func connectWith(_ cell:CellView) -> Bool { if connectionCount() > 1 { return false } if let direction = findDirection(cell) as Direction! { switch direction { case .north: connection.north = cell if cell.connection.south == nil { cell.connectWith(self) } case .south: connection.south = cell if cell.connection.north == nil { cell.connectWith(self) } case .west: connection.west = cell if cell.connection.east == nil { cell.connectWith(self) } case .east: connection.east = cell if cell.connection.west == nil { cell.connectWith(self) } } configureViews() return true } return false } func findDirection(_ cell:CellView) -> Direction? { if cell == self { return nil } if cell.cellType == CellType.passive { return nil } if point.x == cell.point.x { if point.y == cell.point.y + 1 { // north if cell.connectionCount() > 1 && cell.connection.south == nil { return nil } return Direction.north } else if point.y + 1 == cell.point.y { // south if cell.connectionCount() > 1 && cell.connection.north == nil { return nil } return Direction.south } } else if point.y == cell.point.y { if point.x == cell.point.x + 1 { // west if cell.connectionCount() > 1 && cell.connection.east == nil { return nil } return Direction.west } else if point.x + 1 == cell.point.x { // east if cell.connectionCount() > 1 && cell.connection.west == nil { return nil } return Direction.east } } return nil } fileprivate func initViews() { label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = NSTextAlignment.center addSubview(label) connectionView.west.translatesAutoresizingMaskIntoConstraints = false connectionView.west.backgroundColor = UIColor.black connectionView.west.isHidden = true addSubview(connectionView.west) connectionView.east.translatesAutoresizingMaskIntoConstraints = false connectionView.east.backgroundColor = UIColor.black connectionView.east.isHidden = true addSubview(connectionView.east) connectionView.north.translatesAutoresizingMaskIntoConstraints = false connectionView.north.backgroundColor = UIColor.black connectionView.north.isHidden = true addSubview(connectionView.north) connectionView.south.translatesAutoresizingMaskIntoConstraints = false connectionView.south.backgroundColor = UIColor.black connectionView.south.isHidden = true addSubview(connectionView.south) let views = [ "label":label, "west":connectionView.west, "east":connectionView.east, "north":connectionView.north, "south":connectionView.south ] let metrics = [ "stroke":5 ] addConstraints(NSLayoutConstraint .constraints(withVisualFormat: "H:|[label]|", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint .constraints(withVisualFormat: "V:|[label]|", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint .constraints(withVisualFormat: "V:|-0-[north]-0-[south(north)]-0-|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: metrics, views: views)) addConstraint(NSLayoutConstraint(item: connectionView.north, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0)) addConstraints(NSLayoutConstraint .constraints(withVisualFormat: "H:[north(stroke)]", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint .constraints(withVisualFormat: "H:[south(stroke)]", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint .constraints(withVisualFormat: "H:|-0-[west]-0-[east(west)]-0-|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: metrics, views: views)) addConstraint(NSLayoutConstraint(item: connectionView.west, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0)) addConstraints(NSLayoutConstraint .constraints(withVisualFormat: "V:[west(stroke)]", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint .constraints(withVisualFormat: "V:[east(stroke)]", options: [], metrics: metrics, views: views)) } func configureViews() { if cellType == CellType.active { if state == CellState.hightlighted { backgroundColor = UIColor.lightGray } else { backgroundColor = UIColor.white } } else { backgroundColor = UIColor.gray } connectionView.north.isHidden = connection.north == nil connectionView.east.isHidden = connection.east == nil connectionView.south.isHidden = connection.south == nil connectionView.west.isHidden = connection.west == nil } }
mit
1d7f8cb9d8a058b536b228c87fa4f676
32.632911
224
0.549962
5.174294
false
false
false
false
MattFoley/IQKeyboardManager
IQKeybordManagerSwift/IQToolbar/IQUIView+IQKeyboardToolbar.swift
1
21579
// // IQUIView+IQKeyboardToolbar.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-14 Iftekhar Qurashi. // // 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 ///* @const kIQRightButtonToolbarTag Default tag for toolbar with Right button -1001. */ //let kIQRightButtonToolbarTag : NSInteger = -1001 ///* @const kIQRightLeftButtonToolbarTag Default tag for toolbar with Right/Left buttons -1003. */ //let kIQRightLeftButtonToolbarTag : NSInteger = -1003 ///* @const kIQCancelDoneButtonToolbarTag Default tag for toolbar with Cancel/Done buttons -1004. */ //let kIQCancelDoneButtonToolbarTag : NSInteger = -1004 /*! @abstract UIView category methods to add IQToolbar on UIKeyboard. */ extension UIView { /*! @abstract if shouldHideTitle is YES, then title will not be added to the toolbar. Default to NO. */ var shouldHideTitle: Bool? { get { let aValue: AnyObject? = objc_getAssociatedObject(self, "shouldHideTitle")? if aValue == nil { return false } else { return aValue as? Bool } } set(newValue) { objc_setAssociatedObject(self, "shouldHideTitle", newValue, UInt(OBJC_ASSOCIATION_ASSIGN)) } } /*! @method addDoneOnKeyboardWithTarget:action: @abstract Helper functions to add Done button on keyboard. @param target: Target object for selector. Usually 'self'. @param action: Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder: A boolean to indicate whether to show textField placeholder on IQToolbar'. @param titleText: text to show as title in IQToolbar'. */ func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 50 done button frame. 24 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-50.0-24, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(title: text, style: UIBarButtonItemStyle.Done, target: target, action: action) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: title) } func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector) { addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: nil) } func addDoneOnKeyboardWithTarget (target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 50 done button frame. 24 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-64.0-12.0, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: action) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } func addDoneOnKeyboardWithTarget (target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addDoneOnKeyboardWithTarget(target, action: action, titleText: title) } func addDoneOnKeyboardWithTarget(target : AnyObject?, action : Selector) { addDoneOnKeyboardWithTarget(target, action: action, titleText: nil) } /*! @method addCancelDoneOnKeyboardWithTarget:cancelAction:doneAction: @abstract Helper function to add Cancel and Done button on keyboard. @param target: Target object for selector. Usually 'self'. @param cancelAction: Crevious button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param doneAction: Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder: A boolean to indicate whether to show textField placeholder on IQToolbar'. @param titleText: text to show as title in IQToolbar'. */ func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] // Create a cancel button to show on keyboard to resign it. Adding a selector to resign it. let cancelButton = IQBarButtonItem(title: leftButtonTitle, style: UIBarButtonItemStyle.Bordered, target: target, action: leftButtonAction) items.append(cancelButton) if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 66 Cancel button maximum x. 50 done button frame. 8+8 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-66-50.0-16, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItemStyle.Bordered, target: target, action: rightButtonAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: title) } func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector) { addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: nil) } func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] // Create a cancel button to show on keyboard to resign it. Adding a selector to resign it. let cancelButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: target, action: cancelAction) items.append(cancelButton) if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 66 Cancel button maximum x. 50 done button frame. 8+8 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-66-50.0-16, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: title) } func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector) { addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: nil) } /*! @method addPreviousNextDoneOnKeyboardWithTarget:previousAction:nextAction:doneAction @abstract Helper function to add SegmentedNextPrevious and Done button on keyboard. @param target: Target object for selector. Usually 'self'. @param previousAction: Previous button action name. Usually 'previousAction:(IQSegmentedNextPrevious*)segmentedControl'. @param nextAction: Next button action name. Usually 'nextAction:(IQSegmentedNextPrevious*)segmentedControl'. @param doneAction: Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder: A boolean to indicate whether to show textField placeholder on IQToolbar'. @param titleText: text to show as title in IQToolbar'. */ func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction) let prev = IQBarButtonItem(image: UIImage(named: "IQKeyboardManager.bundle/IQButtonBarArrowLeft"), style: UIBarButtonItemStyle.Plain, target: target, action: previousAction) let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) fixed.width = 23 let next = IQBarButtonItem(image: UIImage(named: "IQKeyboardManager.bundle/IQButtonBarArrowRight"), style: UIBarButtonItemStyle.Plain, target: target, action: nextAction) items.append(prev) items.append(fixed) items.append(next) if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 72.5 next/previous maximum x. 50 done button frame. 8+8 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-72.5-50.0-16, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } public func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: title) } func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector) { addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: nil) } /*! @method setEnablePrevious:next: @abstract Helper function to enable and disable previous next buttons. @param isPreviousEnabled: BOOL to enable/disable previous button on keyboard. @param isNextEnabled: BOOL to enable/disable next button on keyboard.. */ func setEnablePrevious ( isPreviousEnabled : Bool, isNextEnabled : Bool) { // Getting inputAccessoryView. if let inputAccessoryView = self.inputAccessoryView as? IQToolbar { // If it is IQToolbar and it's items are greater than zero. if inputAccessoryView.items?.count > 3 { if let items = inputAccessoryView.items { if let prevButton = items[0] as? IQBarButtonItem { if let nextButton = items[2] as? IQBarButtonItem { if prevButton.enabled != isPreviousEnabled { prevButton.enabled = isPreviousEnabled } if nextButton.enabled != isNextEnabled { nextButton.enabled = isNextEnabled } } } } } } } }
mit
2553e54c552f2d60cd365d83b54de8f6
44.815287
210
0.611659
5.871837
false
false
false
false
wuyezhiguhun/DDMusicFM
DDMusicFM/DDFound/View/DDHeaderIconView.swift
1
2675
// // DDHeaderIconView.swift // DDMusicFM // // Created by yutongmac on 2017/9/14. // Copyright © 2017年 王允顶. All rights reserved. // import UIKit class DDHeaderIconView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.iconImageView) self.addSubview(self.titleLabel) self.addViewConstrains() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addViewConstrains() -> Void { self.iconImageView.snp.makeConstraints { (make) in // make.center.equalTo(self) make.centerX.equalTo(self.snp.centerX).offset(0) make.centerY.equalTo(self.snp.centerY).offset(-10) make.width.equalTo(43) make.height.equalTo(43) } self.titleLabel.snp.makeConstraints { (make) in make.top.equalTo(self.iconImageView.snp.bottom).offset(10) make.left.equalTo(self).offset(0) make.right.equalTo(self).offset(0) make.height.equalTo(20) } } var _iconImageView: UIImageView? var iconImageView: UIImageView { get { if _iconImageView == nil { _iconImageView = UIImageView() } return _iconImageView! } set { _iconImageView = newValue } } var _titleLabel: UILabel? var titleLabel: UILabel { get { if _titleLabel == nil { _titleLabel = UILabel() _titleLabel?.font = UIFont.systemFont(ofSize: 13) _titleLabel?.backgroundColor = UIColor.clear _titleLabel?.textColor = UIColor.black _titleLabel?.textAlignment = NSTextAlignment.center } return _titleLabel! } set { _titleLabel = newValue } } var _detailModel: DDFindDiscoverDetailModel? var detailModel: DDFindDiscoverDetailModel { get { if _detailModel == nil { _detailModel = DDFindDiscoverDetailModel() } return _detailModel! } set { _detailModel = newValue self.titleLabel.text = _detailModel?.title self.iconImageView.sd_setImage(with: URL(string: (_detailModel?.coverPath!)!), completed: nil) } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
apache-2.0
fd0579be6b5f86a2ff8225a48391ce0f
28.296703
106
0.565266
4.652705
false
false
false
false
NikitaAsabin/pdpDecember
Pods/FSHelpers+Swift/Swift/Helpers/FSHelpers.swift
1
5702
// // FSHelpers.swift // DayPhoto // // Created by Kruperfone on 08.12.14. // Copyright (c) 2014 Flatstack. All rights reserved. // import UIKit //MARK: - Application Directory public func FSApplicationDirectoryPath (directoryToSearch:NSSearchPathDirectory) -> String { return NSSearchPathForDirectoriesInDomains(directoryToSearch, NSSearchPathDomainMask.UserDomainMask, true).first! } public func FSApplicationDirectoryURL (directoryToSearch:NSSearchPathDirectory) -> NSURL { return NSURL(string: FSApplicationDirectoryPath(directoryToSearch))! } //MARK: - Interface public let FSScreenBounds: CGRect = UIScreen.mainScreen().bounds public func FSIsIPad () -> Bool { return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad } public func FSIsIPhone () -> Bool { return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone } public func FSScaleFactor () -> CGFloat { return UIScreen.mainScreen().scale } public func FSIsRetina () -> Bool { return FSScaleFactor() == 2 } public func FSDeviceOrientation () -> UIDeviceOrientation { return UIDevice.currentDevice().orientation } //MARK: - System Version public func FSSystemVersionEqualTo(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedSame } public func FSSystemVersionGreatherThan(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending } public func FSSystemVersionGreatherThanOrEqualTo(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending } public func FSSystemVersionLessThan(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending } public func FSSystemVersionLessThanOrEqualTo(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedDescending } //MARK: - Images and colors public func FSRGBA (r:CGFloat, _ g:CGFloat, _ b:CGFloat, _ a:CGFloat) -> UIColor { return UIColor(red: r/255, green: g/255, blue: b/255, alpha: a) } public func FSImageFromColor (color:UIColor) -> UIImage { let rect:CGRect = CGRectMake(0, 0, 1, 1) UIGraphicsBeginImageContext(rect.size) let context:CGContextRef = UIGraphicsGetCurrentContext()! CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image:UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public func FSRandomColor () -> UIColor { let red = CGFloat(arc4random_uniform(255))/255.0 let green = CGFloat(arc4random_uniform(255))/255.0 let blue = CGFloat(arc4random_uniform(255))/255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1) } //MARK: - GCD public func FSDispatch_after_short (delay:Double, block:dispatch_block_t) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), block); } //MARK: - Other public func FSDLog(message: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) { #if DEBUG print("Message \"\(message)\" (File: \(file), Function: \(function), Line: \(line))") #endif } //MARK: - Enumerations public enum FSScreenTypeInch { case _3_5 case _4 case _4_7 case _5_5 public var size:CGSize { switch self { case ._3_5: return CGSizeMake(320, 480) case ._4: return CGSizeMake(320, 568) case ._4_7: return CGSizeMake(375, 667) case ._5_5: return CGSizeMake(414, 736) } } public init () { self = FSScreenTypeInch.typeForSize(UIScreen.mainScreen().bounds.size) } public init (size: CGSize) { self = FSScreenTypeInch.typeForSize(size) } static private func typeForSize (size: CGSize) -> FSScreenTypeInch { let width = min(size.width, size.height) let height = max(size.width, size.height) switch CGSizeMake(width, height) { case FSScreenTypeInch._3_5.size: return FSScreenTypeInch._3_5 case FSScreenTypeInch._4.size: return FSScreenTypeInch._4 case FSScreenTypeInch._4_7.size: return FSScreenTypeInch._4_7 case FSScreenTypeInch._5_5.size: return FSScreenTypeInch._5_5 default: return FSScreenTypeInch._4 } } public func getScreenValue (value3_5 value3_5:Any, value4:Any, value4_7:Any, value5_5:Any) -> Any { switch self { case ._3_5: return value3_5 case ._4: return value4 case ._4_7: return value4_7 case ._5_5: return value5_5 } } public func getScreenCGFloat (value3_5 value3_5:CGFloat, value4:CGFloat, value4_7:CGFloat, value5_5:CGFloat) -> CGFloat { return self.getScreenValue(value3_5:value3_5, value4: value4, value4_7: value4_7, value5_5: value5_5) as! CGFloat } public func getScreenCGFloat (value4 value4:CGFloat, value4_7:CGFloat, value5_5:CGFloat) -> CGFloat { return self.getScreenCGFloat(value3_5:value4, value4: value4, value4_7: value4_7, value5_5: value5_5) } }
mit
4750ae69c24740849479267f9fd68d3a
32.541176
125
0.693616
4.015493
false
false
false
false
alessiobrozzi/firefox-ios
Storage/ThirdParty/SwiftData.swift
2
41737
/* 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/. */ /* * This is a heavily modified version of SwiftData.swift by Ryan Fowler * This has been enhanced to support custom files, correct binding, versioning, * and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and * to force callers to request a connection before executing commands. Database creation helpers, savepoint * helpers, image support, and other features have been removed. */ // SwiftData.swift // // Copyright (c) 2014 Ryan Fowler // // 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 Shared import XCGLogger private let DatabaseBusyTimeout: Int32 = 3 * 1000 private let log = Logger.syncLogger /** * Handle to a SQLite database. * Each instance holds a single connection that is shared across all queries. */ open class SwiftData { let filename: String static var EnableWAL = true static var EnableForeignKeys = true /// Used to keep track of the corrupted databases we've logged. static var corruptionLogsWritten = Set<String>() /// Used for testing. static var ReuseConnections = true /// For thread-safe access to the shared connection. fileprivate let sharedConnectionQueue: DispatchQueue /// Shared connection to this database. fileprivate var sharedConnection: ConcreteSQLiteDBConnection? fileprivate var key: String? fileprivate var prevKey: String? /// A simple state flag to track whether we should accept new connection requests. /// If a connection request is made while the database is closed, a /// FailedSQLiteDBConnection will be returned. fileprivate(set) var closed = false init(filename: String, key: String? = nil, prevKey: String? = nil) { self.filename = filename self.sharedConnectionQueue = DispatchQueue(label: "SwiftData queue: \(filename)", attributes: []) // Ensure that multi-thread mode is enabled by default. // See https://www.sqlite.org/threadsafe.html assert(sqlite3_threadsafe() == 2) self.key = key self.prevKey = prevKey } fileprivate func getSharedConnection() -> ConcreteSQLiteDBConnection? { var connection: ConcreteSQLiteDBConnection? sharedConnectionQueue.sync { if self.closed { log.warning(">>> Database is closed for \(self.filename)") return } if self.sharedConnection == nil { log.debug(">>> Creating shared SQLiteDBConnection for \(self.filename) on thread \(Thread.current).") self.sharedConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.readWriteCreate.toSQL(), key: self.key, prevKey: self.prevKey) } connection = self.sharedConnection } return connection } /** * The real meat of all the execute methods. This is used internally to open and * close a database connection and run a block of code inside it. */ func withConnection(_ flags: SwiftData.Flags, synchronous: Bool=true, cb: @escaping (_ db: SQLiteDBConnection) -> NSError?) -> NSError? { /** * We use a weak reference here instead of strongly retaining the connection because we don't want * any control over when the connection deallocs. If the only owner of the connection (SwiftData) * decides to dealloc it, we should respect that since the deinit method of the connection is tied * to the app lifecycle. This is to prevent background disk access causing springboard crashes. */ weak var conn = getSharedConnection() let queue = self.sharedConnectionQueue if synchronous { var error: NSError? = nil queue.sync { /** * By the time this dispatch block runs, it is possible the user has backgrounded the app * and the connection has been dealloc'ed since we last grabbed the reference */ guard let connection = SwiftData.ReuseConnections ? conn : ConcreteSQLiteDBConnection(filename: filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) else { error = cb(FailedSQLiteDBConnection()) ?? NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"]) return } error = cb(connection) } return error } queue.async { guard let connection = SwiftData.ReuseConnections ? conn : ConcreteSQLiteDBConnection(filename: self.filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) else { let _ = cb(FailedSQLiteDBConnection()) return } let _ = cb(connection) } return nil } func transaction(_ transactionClosure: @escaping (_ db: SQLiteDBConnection) -> Bool) -> NSError? { return self.transaction(synchronous: true, transactionClosure: transactionClosure) } /** * Helper for opening a connection, starting a transaction, and then running a block of code inside it. * The code block can return true if the transaction should be committed. False if we should roll back. */ func transaction(synchronous: Bool=true, transactionClosure: @escaping (_ db: SQLiteDBConnection) -> Bool) -> NSError? { return withConnection(SwiftData.Flags.readWriteCreate, synchronous: synchronous) { db in if let err = db.executeChange("BEGIN EXCLUSIVE") { log.warning("BEGIN EXCLUSIVE failed.") return err } if transactionClosure(db) { log.verbose("Op in transaction succeeded. Committing.") if let err = db.executeChange("COMMIT") { log.error("COMMIT failed. Rolling back.") let _ = db.executeChange("ROLLBACK") return err } } else { log.debug("Op in transaction failed. Rolling back.") if let err = db.executeChange("ROLLBACK") { return err } } return nil } } /// Don't use this unless you know what you're doing. The deinitializer /// should be used to achieve refcounting semantics. func forceClose() { sharedConnectionQueue.sync { self.closed = true self.sharedConnection = nil } } /// Reopens a database that had previously been force-closed. /// Does nothing if this database is already open. func reopenIfClosed() { sharedConnectionQueue.sync { self.closed = false } } public enum Flags { case readOnly case readWrite case readWriteCreate fileprivate func toSQL() -> Int32 { switch self { case .readOnly: return SQLITE_OPEN_READONLY case .readWrite: return SQLITE_OPEN_READWRITE case .readWriteCreate: return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE } } } } /** * Wrapper class for a SQLite statement. * This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure * the connection is never deinitialized while the statement is active. This class is responsible for * finalizing the SQL statement once it goes out of scope. */ private class SQLiteDBStatement { var pointer: OpaquePointer? fileprivate let connection: ConcreteSQLiteDBConnection init(connection: ConcreteSQLiteDBConnection, query: String, args: [Any?]?) throws { self.connection = connection let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil) if status != SQLITE_OK { throw connection.createErr("During: SQL Prepare \(query)", status: Int(status)) } if let args = args, let bindError = bind(args) { throw bindError } } /// Binds arguments to the statement. fileprivate func bind(_ objects: [Any?]) -> NSError? { let count = Int(sqlite3_bind_parameter_count(pointer)) if count < objects.count { return connection.createErr("During: Bind", status: 202) } if count > objects.count { return connection.createErr("During: Bind", status: 201) } for (index, obj) in objects.enumerated() { var status: Int32 = SQLITE_OK // Doubles also pass obj as Int, so order is important here. if obj is Double { status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double) } else if obj is Int { status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int)) } else if obj is Bool { status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0) } else if obj is String { typealias CFunction = @convention(c) (UnsafeMutableRawPointer?) -> Void let transient = unsafeBitCast(-1, to: CFunction.self) status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cString(using: String.Encoding.utf8)!, -1, transient) } else if obj is Data { status = sqlite3_bind_blob(pointer, Int32(index+1), ((obj as! Data) as NSData).bytes, -1, nil) } else if obj is Date { let timestamp = (obj as! Date).timeIntervalSince1970 status = sqlite3_bind_double(pointer, Int32(index+1), timestamp) } else if obj is UInt64 { status = sqlite3_bind_double(pointer, Int32(index+1), Double(obj as! UInt64)) } else if obj == nil { status = sqlite3_bind_null(pointer, Int32(index+1)) } if status != SQLITE_OK { return connection.createErr("During: Bind", status: Int(status)) } } return nil } func close() { if nil != self.pointer { sqlite3_finalize(self.pointer) self.pointer = nil } } deinit { if nil != self.pointer { sqlite3_finalize(self.pointer) } } } protocol SQLiteDBConnection { var lastInsertedRowID: Int { get } var numberOfRowsModified: Int { get } func executeChange(_ sqlStr: String) -> NSError? func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func interrupt() func checkpoint() func checkpoint(_ mode: Int32) func vacuum() -> NSError? } // Represents a failure to open. class FailedSQLiteDBConnection: SQLiteDBConnection { func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? { return self.fail("Non-open connection; can't execute change.") } fileprivate func fail(_ str: String) -> NSError { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: str]) } var lastInsertedRowID: Int { return 0 } var numberOfRowsModified: Int { return 0 } func executeChange(_ sqlStr: String) -> NSError? { return self.fail("Non-open connection; can't execute change.") } func executeQuery<T>(_ sqlStr: String) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func interrupt() {} func checkpoint() {} func checkpoint(_ mode: Int32) {} func vacuum() -> NSError? { return self.fail("Non-open connection; can't vacuum.") } } open class ConcreteSQLiteDBConnection: SQLiteDBConnection { fileprivate var sqliteDB: OpaquePointer? fileprivate let filename: String fileprivate let debug_enabled = false fileprivate let queue: DispatchQueue open var version: Int { get { return pragma("user_version", factory: IntFactory) ?? 0 } set { let _ = executeChange("PRAGMA user_version = \(newValue)") } } fileprivate func setKey(_ key: String?) -> NSError? { sqlite3_key(sqliteDB, key ?? "", Int32((key ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?) if cursor.status != .success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid key"]) } return nil } fileprivate func reKey(_ oldKey: String?, newKey: String?) -> NSError? { sqlite3_key(sqliteDB, oldKey ?? "", Int32((oldKey ?? "").characters.count)) sqlite3_rekey(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) // Check that the new key actually works sqlite3_key(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?) if cursor.status != .success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Rekey failed"]) } return nil } func interrupt() { log.debug("Interrupt") sqlite3_interrupt(sqliteDB) } fileprivate func pragma<T: Equatable>(_ pragma: String, expected: T?, factory: @escaping (SDRow) -> T, message: String) throws { let cursorResult = self.pragma(pragma, factory: factory) if cursorResult != expected { log.error("\(message): \(cursorResult), \(expected)") throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "PRAGMA didn't return expected output: \(message)."]) } } fileprivate func pragma<T>(_ pragma: String, factory: @escaping (SDRow) -> T) -> T? { let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory, withArgs: [] as Args) defer { cursor.close() } return cursor[0] } fileprivate func prepareShared() { if SwiftData.EnableForeignKeys { let _ = pragma("foreign_keys=ON", factory: IntFactory) } // Retry queries before returning locked errors. sqlite3_busy_timeout(self.sqliteDB, DatabaseBusyTimeout) } fileprivate func prepareEncrypted(_ flags: Int32, key: String?, prevKey: String? = nil) throws { // Setting the key needs to be the first thing done with the database. if let _ = setKey(key) { if let err = closeCustomConnection(immediately: true) { log.error("Couldn't close connection: \(err). Failing to open.") throw err } if let err = openWithFlags(flags) { throw err } if let err = reKey(prevKey, newKey: key) { log.error("Unable to encrypt database") throw err } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") try pragma("journal_mode=WAL", expected: "wal", factory: StringFactory, message: "WAL journal mode set") } self.prepareShared() } fileprivate func prepareCleartext() throws { // If we just created the DB -- i.e., no tables have been created yet -- then // we can set the page size right now and save a vacuum. // // For where these values come from, see Bug 1213623. // // Note that sqlcipher uses cipher_page_size instead, but we don't set that // because it needs to be set from day one. let desiredPageSize = 32 * 1024 let _ = pragma("page_size=\(desiredPageSize)", factory: IntFactory) let currentPageSize = pragma("page_size", factory: IntFactory) // This has to be done without WAL, so we always hop into rollback/delete journal mode. if currentPageSize != desiredPageSize { try pragma("journal_mode=DELETE", expected: "delete", factory: StringFactory, message: "delete journal mode set") try pragma("page_size=\(desiredPageSize)", expected: nil, factory: IntFactory, message: "Page size set") log.info("Vacuuming to alter database page size from \(currentPageSize) to \(desiredPageSize).") if let err = self.vacuum() { log.error("Vacuuming failed: \(err).") } else { log.debug("Vacuuming succeeded.") } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") let desiredPagesPerJournal = 16 let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize let desiredJournalSizeLimit = 3 * desiredCheckpointSize /* * With whole-module-optimization enabled in Xcode 7.2 and 7.2.1, the * compiler seems to eagerly discard these queries if they're simply * inlined, causing a crash in `pragma`. * * Hackily hold on to them. */ let journalModeQuery = "journal_mode=WAL" let autoCheckpointQuery = "wal_autocheckpoint=\(desiredPagesPerJournal)" let journalSizeQuery = "journal_size_limit=\(desiredJournalSizeLimit)" try withExtendedLifetime(journalModeQuery, { try pragma(journalModeQuery, expected: "wal", factory: StringFactory, message: "WAL journal mode set") }) try withExtendedLifetime(autoCheckpointQuery, { try pragma(autoCheckpointQuery, expected: desiredPagesPerJournal, factory: IntFactory, message: "WAL autocheckpoint set") }) try withExtendedLifetime(journalSizeQuery, { try pragma(journalSizeQuery, expected: desiredJournalSizeLimit, factory: IntFactory, message: "WAL journal size limit set") }) } self.prepareShared() } init?(filename: String, flags: Int32, key: String? = nil, prevKey: String? = nil) { log.debug("Opening connection to \(filename).") self.filename = filename self.queue = DispatchQueue(label: "SQLite connection: \(filename)", attributes: []) if let failure = openWithFlags(flags) { log.warning("Opening connection to \(filename) failed: \(failure).") return nil } if key == nil && prevKey == nil { do { try self.prepareCleartext() } catch { return nil } } else { do { try self.prepareEncrypted(flags, key: key, prevKey: prevKey) } catch { return nil } } } deinit { log.debug("deinit: closing connection on thread \(Thread.current).") let _ = self.queue.sync { self.closeCustomConnection() } } open var lastInsertedRowID: Int { return Int(sqlite3_last_insert_rowid(sqliteDB)) } open var numberOfRowsModified: Int { return Int(sqlite3_changes(sqliteDB)) } func checkpoint() { self.checkpoint(SQLITE_CHECKPOINT_FULL) } /** * Blindly attempts a WAL checkpoint on all attached databases. */ func checkpoint(_ mode: Int32) { guard sqliteDB != nil else { log.warning("Trying to checkpoint a nil DB!") return } log.debug("Running WAL checkpoint on \(self.filename) on thread \(Thread.current).") sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil) log.debug("WAL checkpoint done on \(self.filename).") } func vacuum() -> NSError? { return self.executeChange("VACUUM") } /// Creates an error from a sqlite status. Will print to the console if debug_enabled is set. /// Do not call this unless you're going to return this error. fileprivate func createErr(_ description: String, status: Int) -> NSError { var msg = SDError.errorMessageFromCode(status) if debug_enabled { log.debug("SwiftData Error -> \(description)") log.debug(" -> Code: \(status) - \(msg)") } if let errMsg = String(validatingUTF8: sqlite3_errmsg(sqliteDB)) { msg += " " + errMsg if debug_enabled { log.debug(" -> Details: \(errMsg)") } } return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg]) } /// Open the connection. This is called when the db is created. You should not call it yourself. fileprivate func openWithFlags(_ flags: Int32) -> NSError? { let status = sqlite3_open_v2(filename.cString(using: String.Encoding.utf8)!, &sqliteDB, flags, nil) if status != SQLITE_OK { return createErr("During: Opening Database with Flags", status: Int(status)) } return nil } /// Closes a connection. This is called via deinit. Do not call this yourself. fileprivate func closeCustomConnection(immediately: Bool=false) -> NSError? { log.debug("Closing custom connection for \(self.filename) on \(Thread.current).") // TODO: add a lock here? let db = self.sqliteDB self.sqliteDB = nil // Don't bother trying to call sqlite3_close multiple times. guard db != nil else { log.warning("Connection was nil.") return nil } let status = immediately ? sqlite3_close(db) : sqlite3_close_v2(db) // Note that if we use sqlite3_close_v2, this will still return SQLITE_OK even if // there are outstanding prepared statements if status != SQLITE_OK { log.error("Got status \(status) while attempting to close.") return createErr("During: closing database with flags", status: Int(status)) } log.debug("Closed \(self.filename).") return nil } open func executeChange(_ sqlStr: String) -> NSError? { return self.executeChange(sqlStr, withArgs: nil) } /// Executes a change on the database. open func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil log.error("SQL error: \(error1.localizedDescription) for SQL \(sqlStr).") } // Close, not reset -- this isn't going to be reused. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) } log.error("SQL error: \(error.localizedDescription) for SQL \(sqlStr).") return error } let status = sqlite3_step(statement!.pointer) if status != SQLITE_DONE && status != SQLITE_OK { error = createErr("During: SQL Step \(sqlStr)", status: Int(status)) } return error } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> { return self.executeQuery(sqlStr, factory: factory, withArgs: nil) } /// Queries the database. /// Returns a cursor pre-filled with the complete result set. func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused, and the FilledSQLiteCursor // consumes everything. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) } log.error("SQL error: \(error.localizedDescription).") return Cursor<T>(err: error) } return FilledSQLiteCursor<T>(statement: statement!, factory: factory) } func writeCorruptionInfoForDBNamed(_ dbFilename: String, toLogger logger: XCGLogger) { DispatchQueue.global(qos: DispatchQoS.default.qosClass).sync { guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return } logger.error("Corrupt DB detected! DB filename: \(dbFilename)") let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0 logger.error("DB file size: \(dbFileSize) bytes") logger.error("Integrity check:") let args: [Any?]? = nil let messages = self.executeQueryUnsafe("PRAGMA integrity_check", factory: StringFactory, withArgs: args) defer { messages.close() } if messages.status == CursorStatus.success { for message in messages { logger.error(message) } logger.error("----") } else { logger.error("Couldn't run integrity check: \(messages.statusMessage).") } // Write call stack. logger.error("Call stack: ") for message in Thread.callStackSymbols { logger.error(" >> \(message)") } logger.error("----") // Write open file handles. let openDescriptors = FSUtils.openFileDescriptors() logger.error("Open file descriptors: ") for (k, v) in openDescriptors { logger.error(" \(k): \(v)") } logger.error("----") SwiftData.corruptionLogsWritten.insert(dbFilename) } } // func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { // return self.executeQueryUnsafe(sqlStr, factory: factory, withArgs: args) // } /** * Queries the database. * Returns a live cursor that holds the query statement and database connection. * Instances of this class *must not* leak outside of the connection queue! */ func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { return Cursor(err: error) } return LiveSQLiteCursor(statement: statement!, factory: factory) } } /// Helper for queries that return a single integer result. func IntFactory(_ row: SDRow) -> Int { return row[0] as! Int } /// Helper for queries that return a single String result. func StringFactory(_ row: SDRow) -> String { return row[0] as! String } /// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing /// and a generator for iterating over columns. class SDRow: Sequence { // The sqlite statement this row came from. fileprivate let statement: SQLiteDBStatement // The columns of this database. The indices of these are assumed to match the indices // of the statement. fileprivate let columnNames: [String] fileprivate init(statement: SQLiteDBStatement, columns: [String]) { self.statement = statement self.columnNames = columns } // Return the value at this index in the row fileprivate func getValue(_ index: Int) -> Any? { let i = Int32(index) let type = sqlite3_column_type(statement.pointer, i) var ret: Any? = nil switch type { case SQLITE_NULL, SQLITE_INTEGER: //Everyone expects this to be an Int. On Ints larger than 2^31 this will lose information. ret = Int(truncatingBitPattern: sqlite3_column_int64(statement.pointer, i)) case SQLITE_TEXT: if let text = sqlite3_column_text(statement.pointer, i) { return String(cString: text) } case SQLITE_BLOB: if let blob = sqlite3_column_blob(statement.pointer, i) { let size = sqlite3_column_bytes(statement.pointer, i) ret = Data(bytes: blob, count: Int(size)) } case SQLITE_FLOAT: ret = Double(sqlite3_column_double(statement.pointer, i)) default: log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil") } return ret } // Accessor getting column 'key' in the row subscript(key: Int) -> Any? { return getValue(key) } // Accessor getting a named column in the row. This (currently) depends on // the columns array passed into this Row to find the correct index. subscript(key: String) -> Any? { get { if let index = columnNames.index(of: key) { return getValue(index) } return nil } } // Allow iterating through the row. This is currently broken. func makeIterator() -> AnyIterator<Any> { let nextIndex = 0 return AnyIterator() { // This crashes the compiler. Yay! if nextIndex < self.columnNames.count { return nil // self.getValue(nextIndex) } return nil } } } /// Helper for pretty printing SQL (and other custom) error codes. private struct SDError { fileprivate static func errorMessageFromCode(_ errorCode: Int) -> String { switch errorCode { case -1: return "No error" // SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html case 0: return "Successful result" case 1: return "SQL error or missing database" case 2: return "Internal logic error in SQLite" case 3: return "Access permission denied" case 4: return "Callback routine requested an abort" case 5: return "The database file is busy" case 6: return "A table in the database is locked" case 7: return "A malloc() failed" case 8: return "Attempt to write a readonly database" case 9: return "Operation terminated by sqlite3_interrupt()" case 10: return "Some kind of disk I/O error occurred" case 11: return "The database disk image is malformed" case 12: return "Unknown opcode in sqlite3_file_control()" case 13: return "Insertion failed because database is full" case 14: return "Unable to open the database file" case 15: return "Database lock protocol error" case 16: return "Database is empty" case 17: return "The database schema changed" case 18: return "String or BLOB exceeds size limit" case 19: return "Abort due to constraint violation" case 20: return "Data type mismatch" case 21: return "Library used incorrectly" case 22: return "Uses OS features not supported on host" case 23: return "Authorization denied" case 24: return "Auxiliary database format error" case 25: return "2nd parameter to sqlite3_bind out of range" case 26: return "File opened that is not a database file" case 27: return "Notifications from sqlite3_log()" case 28: return "Warnings from sqlite3_log()" case 100: return "sqlite3_step() has another row ready" case 101: return "sqlite3_step() has finished executing" // Custom SwiftData errors // Binding errors case 201: return "Not enough objects to bind provided" case 202: return "Too many objects to bind provided" // Custom connection errors case 301: return "A custom connection is already open" case 302: return "Cannot open a custom connection inside a transaction" case 303: return "Cannot open a custom connection inside a savepoint" case 304: return "A custom connection is not currently open" case 305: return "Cannot close a custom connection inside a transaction" case 306: return "Cannot close a custom connection inside a savepoint" // Index and table errors case 401: return "At least one column name must be provided" case 402: return "Error extracting index names from sqlite_master" case 403: return "Error extracting table names from sqlite_master" // Transaction and savepoint errors case 501: return "Cannot begin a transaction within a savepoint" case 502: return "Cannot begin a transaction within another transaction" // Unknown error default: return "Unknown error" } } } /// Provides access to the result set returned by a database query. /// The entire result set is cached, so this does not retain a reference /// to the statement or the database connection. private class FilledSQLiteCursor<T>: ArrayCursor<T> { fileprivate init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { var status = CursorStatus.success var statusMessage = "" let data = FilledSQLiteCursor.getValues(statement, factory: factory, status: &status, statusMessage: &statusMessage) super.init(data: data, status: status, statusMessage: statusMessage) } /// Return an array with the set of results and release the statement. fileprivate class func getValues(_ statement: SQLiteDBStatement, factory: (SDRow) -> T, status: inout CursorStatus, statusMessage: inout String) -> [T] { var rows = [T]() var count = 0 status = CursorStatus.success statusMessage = "Success" var columns = [String]() let columnCount = sqlite3_column_count(statement.pointer) for i in 0..<columnCount { let columnName = String(cString: sqlite3_column_name(statement.pointer, i)) columns.append(columnName) } while true { let sqlStatus = sqlite3_step(statement.pointer) if sqlStatus != SQLITE_ROW { if sqlStatus != SQLITE_DONE { // NOTE: By setting our status to failure here, we'll report our count as zero, // regardless of how far we've read at this point. status = CursorStatus.failure statusMessage = SDError.errorMessageFromCode(Int(sqlStatus)) } break } count += 1 let row = SDRow(statement: statement, columns: columns) let result = factory(row) rows.append(result) } return rows } } /// Wrapper around a statement to help with iterating through the results. private class LiveSQLiteCursor<T>: Cursor<T> { fileprivate var statement: SQLiteDBStatement! // Function for generating objects of type T from a row. fileprivate let factory: (SDRow) -> T // Status of the previous fetch request. fileprivate var sqlStatus: Int32 = 0 // Number of rows in the database // XXX - When Cursor becomes an interface, this should be a normal property, but right now // we can't override the Cursor getter for count with a stored property. fileprivate var _count: Int = 0 override var count: Int { get { if status != .success { return 0 } return _count } } fileprivate var position: Int = -1 { didSet { // If we're already there, shortcut out. if oldValue == position { return } var stepStart = oldValue // If we're currently somewhere in the list after this position // we'll have to jump back to the start. if position < oldValue { sqlite3_reset(self.statement.pointer) stepStart = -1 } // Now step up through the list to the requested position for _ in stepStart..<position { sqlStatus = sqlite3_step(self.statement.pointer) } } } init(statement: SQLiteDBStatement, factory: @escaping (SDRow) -> T) { self.factory = factory self.statement = statement // The only way I know to get a count. Walk through the entire statement to see how many rows there are. var count = 0 self.sqlStatus = sqlite3_step(statement.pointer) while self.sqlStatus != SQLITE_DONE { count += 1 self.sqlStatus = sqlite3_step(statement.pointer) } sqlite3_reset(statement.pointer) self._count = count super.init(status: .success, msg: "success") } // Helper for finding all the column names in this statement. fileprivate lazy var columns: [String] = { // This untangles all of the columns and values for this row when its created let columnCount = sqlite3_column_count(self.statement.pointer) var columns = [String]() for i: Int32 in 0 ..< columnCount { let columnName = String(cString: sqlite3_column_name(self.statement.pointer, i)) columns.append(columnName) } return columns }() override subscript(index: Int) -> T? { get { if status != .success { return nil } self.position = index if self.sqlStatus != SQLITE_ROW { return nil } let row = SDRow(statement: statement, columns: self.columns) return self.factory(row) } } override func close() { statement = nil super.close() } }
mpl-2.0
24bfb66ec45bb5594a0e8e6beb4a2a82
36.771041
177
0.597959
4.801772
false
false
false
false
alessiobrozzi/firefox-ios
Client/Frontend/Browser/WindowCloseHelper.swift
9
1510
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit protocol WindowCloseHelperDelegate: class { func windowCloseHelper(_ windowCloseHelper: WindowCloseHelper, didRequestToCloseTab tab: Tab) } class WindowCloseHelper: TabHelper { weak var delegate: WindowCloseHelperDelegate? fileprivate weak var tab: Tab? required init(tab: Tab) { self.tab = tab if let path = Bundle.main.path(forResource: "WindowCloseHelper", ofType: "js") { if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } } func scriptMessageHandlerName() -> String? { return "windowCloseHelper" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let tab = tab { DispatchQueue.main.async { self.delegate?.windowCloseHelper(self, didRequestToCloseTab: tab) } } } class func name() -> String { return "WindowCloseHelper" } }
mpl-2.0
4b1cc1f87f02f824da651836985a571c
35.829268
141
0.684106
5.016611
false
false
false
false
eugenepavlyuk/swift-algorithm-club
Count Occurrences/CountOccurrences.playground/Contents.swift
4
1343
//: Playground - noun: a place where people can play func countOccurrencesOfKey(_ key: Int, inArray a: [Int]) -> Int { func leftBoundary() -> Int { var low = 0 var high = a.count while low < high { let midIndex = low + (high - low)/2 if a[midIndex] < key { low = midIndex + 1 } else { high = midIndex } } return low } func rightBoundary() -> Int { var low = 0 var high = a.count while low < high { let midIndex = low + (high - low)/2 if a[midIndex] > key { high = midIndex } else { low = midIndex + 1 } } return low } return rightBoundary() - leftBoundary() } // Simple test let a = [ 0, 1, 1, 3, 3, 3, 3, 6, 8, 10, 11, 11 ] countOccurrencesOfKey(3, inArray: a) // Test with arrays of random size and contents (see debug output) import Foundation func createArray() -> [Int] { var a = [Int]() for i in 0...5 { if i != 2 { // don't include the number 2 let count = Int(arc4random_uniform(UInt32(6))) + 1 for _ in 0..<count { a.append(i) } } } return a.sorted() } for _ in 0..<10 { let a = createArray() print(a) // Note: we also test -1 and 6 to check the edge cases. for k in -1...6 { print("\t\(k): \(countOccurrencesOfKey(k, inArray: a))") } }
mit
fbf7f1362713e21fba6ace7d2e9a3407
19.661538
66
0.541325
3.299754
false
false
false
false
mojio/mojio-ios-sdk
MojioSDK/Models/MeasurementStatistics.swift
1
1314
// // MeasurementStatistics.swift // MojioSDK // // Created by Ashish Agarwal on 2016-02-11. // Copyright © 2016 Mojio. All rights reserved. // import UIKit import ObjectMapper public class MeasurementStatistics: Mappable { public dynamic var NumOfSamples : Float = 0 public dynamic var Average : Float = 0 public dynamic var Variance : Float = 0 public dynamic var StdDev : Float = 0 public dynamic var IndexOfDispersion : Float = 0 public dynamic var CoeffOfVariation : Float = 0 public dynamic var M2 : Float = 0 public dynamic var Min : Float = 0 public dynamic var Max : Float = 0 public var StandardScore : Score? = nil public var MinMaxScore : Score? = nil public required convenience init?(_ map: Map) { self.init() } public required init() { } public func mapping(map: Map) { NumOfSamples <- map["NumOfSamples"] Average <- map["Average"] Variance <- map["Variance"] StdDev <- map["StdDev"] IndexOfDispersion <- map["IndexOfDispersion"] CoeffOfVariation <- map["CoeffOfVariation"] M2 <- map["M2"] Min <- map["Min"] Max <- map["Max"] StandardScore <- map["StandardScore"] MinMaxScore <- map["MinMaxScore"] } }
mit
5cd660e91d10e97fd2c2ee2eddd96a3d
26.354167
53
0.619193
4.128931
false
false
false
false
felix-dumit/EasySpotlight
Example/EasySpotlight/ViewController.swift
1
3425
// // ViewController.swift // EasySpotlight // // Created by Felix Dumit on 09/10/2015. // Copyright (c) 2015 Felix Dumit. All rights reserved. // import UIKit import RealmSwift import EasySpotlight class ViewController: UIViewController { var items: Results<SimpleRealmClass>? @IBOutlet weak var tableView: UITableView! func reloadItems() { items = try? Realm().objects(SimpleRealmClass.self) tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() reloadItems() } // MARK: Outlets @IBAction func addNewElement(_ sender: UIBarButtonItem) { let alert = UIAlertController(title: "New Element", message: "enter title", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default) { _ in if let txt = alert.textFields?[0].text { let item = SimpleRealmClass(name: txt, longDescription: "item with name \(txt)") //swiftlint:disable force_try let realm = try! Realm() try! realm.write { realm.add(item) } //swiftlint:enable force_try EasySpotlight.index(item) { error in print("error indexing: \(error as Any)") } self.reloadItems() } } alert.addAction(action) alert.addTextField(configurationHandler: nil) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } @IBAction func removeAllElements(_ sender: UIBarButtonItem) { EasySpotlight.deIndexAll(of: SimpleRealmClass.self) } @IBAction func addAllElements(_ sender: UIBarButtonItem) { if let items = items { EasySpotlight.index(Array(items)) } } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (items?.count ?? 0) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: "cellOk") cell.textLabel?.text = items?[(indexPath as NSIndexPath).row].name return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete else { return } guard let item = items?[(indexPath as NSIndexPath).row] else { return } EasySpotlight.deIndex(item) { error in print("got error: \(error as Any)") } //swiftlint:disable force_try let realm = try! Realm() try! realm.write { realm.delete(item) } //swiftlint:enable force_try tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: .automatic) tableView.endUpdates() } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .delete } }
mit
33fc3bada54efd3a5538cb7a0e4b426d
28.025424
121
0.616058
4.885877
false
false
false
false
kelvin13/maxpng
examples/decode-online/main.swift
1
6521
import PNG struct Stream { private(set) var data:[UInt8], position:Int, available:Int } extension Stream:PNG.Bytestream.Source { init(_ data:[UInt8]) { self.data = data self.position = data.startIndex self.available = data.startIndex } mutating func read(count:Int) -> [UInt8]? { guard self.position + count <= data.endIndex else { return nil } guard self.position + count < self.available else { self.available += 4096 return nil } defer { self.position += count } return .init(self.data[self.position ..< self.position + count]) } mutating func reset(position:Int) { precondition(self.data.indices ~= position) self.position = position } } extension Stream { init(path:String) { guard let data:[UInt8] = (System.File.Source.open(path: path) { (source:inout System.File.Source) -> [UInt8]? in guard let count:Int = source.count else { return nil } return source.read(count: count) } ?? nil) else { fatalError("failed to open or read file '\(path)'") } self.init(data) } } func waitSignature(stream:inout Stream) throws { let position:Int = stream.position while true { do { return try stream.signature() } catch PNG.LexingError.truncatedSignature { stream.reset(position: position) continue } } } func waitChunk(stream:inout Stream) throws -> (type:PNG.Chunk, data:[UInt8]) { let position:Int = stream.position while true { do { return try stream.chunk() } catch PNG.LexingError.truncatedChunkHeader, PNG.LexingError.truncatedChunkBody { stream.reset(position: position) continue } } } func decodeOnline(stream:inout Stream, overdraw:Bool, capture:(PNG.Data.Rectangular) throws -> ()) throws -> PNG.Data.Rectangular { // lex PNG signature bytes try waitSignature(stream: &stream) // lex header chunk, and preceeding cgbi chunk, if present let (standard, header):(PNG.Standard, PNG.Header) = try { var chunk:(type:PNG.Chunk, data:[UInt8]) = try waitChunk(stream: &stream) let standard:PNG.Standard switch chunk.type { case .CgBI: standard = .ios chunk = try waitChunk(stream: &stream) default: standard = .common } switch chunk.type { case .IHDR: return (standard, try .init(parsing: chunk.data, standard: standard)) default: fatalError("missing image header") } }() var chunk:(type:PNG.Chunk, data:[UInt8]) = try waitChunk(stream: &stream) var context:PNG.Context = try { var palette:PNG.Palette? var background:PNG.Background?, transparency:PNG.Transparency? var metadata:PNG.Metadata = .init() while true { switch chunk.type { case .PLTE: guard palette == nil, background == nil, transparency == nil else { fatalError("invalid chunk ordering") } palette = try .init(parsing: chunk.data, pixel: header.pixel) case .IDAT: guard let context:PNG.Context = PNG.Context.init( standard: standard, header: header, palette: palette, background: background, transparency: transparency, metadata: metadata, uninitialized: false) else { fatalError("missing palette") } return context case .IHDR, .IEND: fatalError("unexpected chunk") default: try metadata.push(ancillary: chunk, pixel: header.pixel, palette: palette, background: &background, transparency: &transparency) } chunk = try waitChunk(stream: &stream) } }() while chunk.type == .IDAT { try context.push(data: chunk.data, overdraw: overdraw) try capture(context.image) chunk = try waitChunk(stream: &stream) } while true { try context.push(ancillary: chunk) guard chunk.type != .IEND else { return context.image } chunk = try stream.chunk() } } let path:String = "examples/decode-online/example" var stream:Stream = .init(path: "\(path).png") var counter:Int = 0 let image:PNG.Data.Rectangular = try decodeOnline(stream: &stream, overdraw: false) { (snapshot:PNG.Data.Rectangular) in let _:[PNG.RGBA<UInt8>] = snapshot.unpack(as: PNG.RGBA<UInt8>.self) try snapshot.compress(path: "\(path)-\(counter).png") counter += 1 } let layout:PNG.Layout = .init(format: image.layout.format, interlaced: true) let progressive:PNG.Data.Rectangular = image.bindStorage(to: layout) try progressive.compress(path: "\(path)-progressive.png", hint: 1 << 12) stream = .init(path: "\(path)-progressive.png") counter = 0 let _:PNG.Data.Rectangular = try decodeOnline(stream: &stream, overdraw: false) { (snapshot:PNG.Data.Rectangular) in try snapshot.compress(path: "\(path)-progressive-\(counter).png") counter += 1 } stream.reset(position: 0) counter = 0 let _:PNG.Data.Rectangular = try decodeOnline(stream: &stream, overdraw: true) { (snapshot:PNG.Data.Rectangular) in try snapshot.compress(path: "\(path)-progressive-overdrawn-\(counter).png") counter += 1 }
gpl-3.0
aa525506c19a26005bb5644eeb7fbd76
25.50813
87
0.509738
4.484869
false
false
false
false
lakesoft/LKUserDefaultOption
Pod/Classes/LKUserDefaultOptionMultipleSelectionGeneric.swift
1
2133
// // LKUserDefaultOptionMultipleSelectionGeneric.swift // Pods // // Created by Hiroshi Hashiguchi on 2015/10/11. // // public class LKUserDefaultOptionMultipleSelectionGeneric: LKUserDefaultOption, LKUserDefaultOptionMultipleSelection { // MARK: - Local public var items:[LKUserDefaultOptionModelItem] = [] func setupSelectedItems(ids:[String]) { selectedIndexPathSet = [] for id in ids { for (index, item) in items.enumerate() { if id == item.itemId { selectedIndexPathSet.insert(NSIndexPath(forRow: index, inSection: 0)) break } } } } // MARK: - LKUserDefaultOptionModel override public func valueLabel() -> String { return selectedIndexPathSet.map { return label($0) }.sort().joinWithSeparator(labelSeparator()) } override public func setDefaultValue(value: AnyObject) { if let ids = value as? [String] { setupSelectedItems(ids) } } override public func save() { saveUserDefaults(selectedItems.map {return $0.itemId}) } override public func restore() { if let ids = restoreUserDefaults() as? [String] { setupSelectedItems(ids) } } // MARK: - LKUserDefaultOptionSelection public func label(indexPath:NSIndexPath) -> String { let item = items[indexPath.row] return item.itemLabel } public func numberOfRows(section:Int) -> Int { return items.count } // MARK: - LKUserDefaultOptionMultipleSelection public var selectedIndexPathSet: Set<NSIndexPath> = [] public func closeWhenSelected() -> Bool { return false } // MARK: - Helper var selectedItems: [LKUserDefaultOptionModelItem] { get { var selectedItems = [LKUserDefaultOptionModelItem]() for indexPath in selectedIndexPathSet { selectedItems.append(items[indexPath.row]) } return selectedItems } } }
mit
bc050f354b903441fba38708e249bec8
27.065789
117
0.595874
5.152174
false
false
false
false
BareFeetWare/BFWControls
BFWControls/Modules/Shadable/View/Shadable.swift
2
4578
// // Shadable.swift // BFWControls // // Created by Tom Brodhurst-Hill on 24/6/17. // Copyright © 2017 BareFeetWare. All rights reserved. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit public protocol Shadable { func setNeedsUpdateView() // Declare these variables as stored @IBInspectable to set per instance: var isLight: Bool { get } // Can override: var isLightAuto: Bool { get } var isLightUse: Bool { get } var parentShadable: Shadable? { get } var shadeLevel: Int { get } var lightColors: [UIColor] { get } var darkColors: [UIColor] { get } // func applyShade() } public extension Shadable { var isLight: Bool { return false } var isLightAuto: Bool { return true } var isLightUse: Bool { return isLightAuto ? parentShadable?.isLightUse ?? isLight : isLight } var parentShadable: Shadable? { return nil } var shadeLevel: Int { get { return 0 } set { fatalError("Shadable priority set not implemented") } } var lightColors: [UIColor] { get { return [.white, .lightGray, .gray, .darkGray, .black] } set { fatalError("Shadable lightColors set not implemented") } } var darkColors: [UIColor] { get { return lightColors.reversed() } set { fatalError("Shadable darkColors set not implemented") } } var shadeColor: UIColor { let colors = isLightUse ? lightColors : darkColors let index = min(shadeLevel, colors.count - 1) let color = colors[index] return color } } public extension Shadable where Self: UIView { var parentShadable: Shadable? { return superview as? Shadable } var isLightUse: Bool { return isLightAuto ? (superview as? Shadable)?.isLightUse ?? superview?.isBackgroundLight.map { !$0 } ?? isLight : isLight } } public extension UIView { func shadeSubviews() { subviews.forEach { subview in if let shadable = subview as? Shadable { shadable.setNeedsUpdateView() } else { subview.shadeSubviews() } } } } //extension Shadable where Self: UILabel { // // func applyShade() { // textColor = shadeColor // } // //} fileprivate extension UIView { struct Threshold { static let alpha: CGFloat = 0.5 static let light: CGFloat = 0.8 static let dark: CGFloat = 0.6 } /// Color that shows through background of the view. Recursively checks superview if view background is clear. var visibleBackgroundColor: UIColor? { get { var color: UIColor? var superview: UIView? = self while superview != nil { if superview is UIImageView { // TODO: Determine average color of image. color = .darkGray break } if let backgroundColor: UIColor = superview?.backgroundColor ?? (superview as? UINavigationBar)?.barTintColor { var white: CGFloat = 0.0 var alpha: CGFloat = 0.0 backgroundColor.getWhite(&white, alpha: &alpha) if alpha > Threshold.alpha { color = backgroundColor break } } superview = superview!.superview } return color } } /// True if background color is closer to white than black. Recursively checks superview if view background is clear. var isBackgroundLight: Bool? { var isBackgroundLight: Bool? var white: CGFloat = 0.0 var alpha: CGFloat = 0.0 if let visibleBackgroundColor = visibleBackgroundColor { visibleBackgroundColor.getWhite(&white, alpha: &alpha) isBackgroundLight = white < Threshold.dark ? false : white > Threshold.light ? true : nil } return isBackgroundLight } }
mit
bb15a8af3b4be88fde16128b229cab40
23.875
121
0.52305
4.964208
false
false
false
false
kgn/KGNAutoLayout
Example/SpringView.swift
1
3138
// // SpringView.swift // KGNAutoLayout // // Created by David Keegan on 10/24/15. // Copyright © 2015 David Keegan. All rights reserved. // import UIKit enum SpringViewDirection { case horizontal case vertical } class SpringView: UIView { var showEnds: Bool = true var direction: SpringViewDirection = .horizontal override var intrinsicContentSize: CGSize { if direction == .horizontal { return CGSize(width: UIView.noIntrinsicMetric, height: 20) } else { return CGSize(width: 20, height: UIView.noIntrinsicMetric) } } override init(frame: CGRect) { super.init(frame: frame) self.isOpaque = false } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.isOpaque = false } override func draw(_ rect: CGRect) { super.draw(rect) let lineSize: CGFloat = 1 let lineOffset: CGFloat = 0.5 let context = UIGraphicsGetCurrentContext() let lineColor = UIColor(red: 1, green: 0.2902, blue: 0.2902, alpha: 1) context?.setLineWidth(lineSize) context?.setLineCap(.round) context?.setStrokeColor(lineColor.cgColor) if direction == .horizontal { context?.saveGState() context?.setLineDash(phase: 0, lengths: [2, 2]) context?.move(to: CGPoint(x: rect.minX, y: rect.midY+lineOffset)) context?.addLine(to: CGPoint(x: rect.maxX, y: rect.midY+lineOffset)) context?.strokePath() context?.restoreGState() if self.showEnds { context?.saveGState() context?.move(to: CGPoint(x: lineOffset, y: rect.minY)) context?.addLine(to: CGPoint(x: lineOffset, y: rect.maxY)) context?.strokePath() context?.restoreGState() context?.saveGState() context?.move(to: CGPoint(x: rect.maxX-lineOffset, y: rect.minY)) context?.addLine(to: CGPoint(x: rect.maxX-lineOffset, y: rect.maxY)) context?.strokePath() context?.restoreGState() } } else { context?.saveGState() context?.setLineDash(phase: 0, lengths: [2, 2]) context?.move(to: CGPoint(x: rect.midX+lineOffset, y: rect.minY)) context?.addLine(to: CGPoint(x: rect.midX+lineOffset, y: rect.maxY)) context?.strokePath() context?.restoreGState() if self.showEnds { context?.saveGState() context?.move(to: CGPoint(x: rect.minX, y: lineOffset)) context?.addLine(to: CGPoint(x: rect.maxX, y: lineOffset)) context?.strokePath() context?.restoreGState() context?.saveGState() context?.move(to: CGPoint(x: rect.minX, y: rect.maxY-lineOffset)) context?.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY-lineOffset)) context?.strokePath() context?.restoreGState() } } } }
mit
aa5727791d1f24eb989b357563ca2ea1
31.677083
84
0.568059
4.387413
false
false
false
false
ociata/SwiftSpinner
SwiftSpinner/SwiftSpinner.swift
1
15898
// // Copyright (c) 2015 Marin Todorov, Underplot ltd. // This code is distributed under the terms and conditions of the MIT license. // // 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 public class SwiftSpinner: UIView { // MARK: - Singleton // // Access the singleton instance // public class var sharedInstance: SwiftSpinner { struct Singleton { static let instance = SwiftSpinner(frame: CGRect.zero) } return Singleton.instance } // MARK: - Init // // Custom init to build the spinner UI // public override init(frame: CGRect) { super.init(frame: frame) blurEffect = UIBlurEffect(style: blurEffectStyle) blurView = UIVisualEffectView(effect: blurEffect) addSubview(blurView) vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect)) addSubview(vibrancyView) let titleScale: CGFloat = 0.85 titleLabel.frame.size = CGSize(width: frameSize.width * titleScale, height: frameSize.height * titleScale) titleLabel.font = defaultTitleFont titleLabel.numberOfLines = 0 titleLabel.textAlignment = .Center titleLabel.lineBreakMode = .ByWordWrapping titleLabel.adjustsFontSizeToFitWidth = true vibrancyView.contentView.addSubview(titleLabel) blurView.contentView.addSubview(vibrancyView) outerCircleView.frame.size = frameSize outerCircle.path = UIBezierPath(ovalInRect: CGRect(x: 0.0, y: 0.0, width: frameSize.width, height: frameSize.height)).CGPath outerCircle.lineWidth = 8.0 outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 0.45 outerCircle.lineCap = kCALineCapRound outerCircle.fillColor = UIColor.clearColor().CGColor outerCircle.strokeColor = UIColor.whiteColor().CGColor outerCircleView.layer.addSublayer(outerCircle) outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 1.0 vibrancyView.contentView.addSubview(outerCircleView) innerCircleView.frame.size = frameSize let innerCirclePadding: CGFloat = 12 innerCircle.path = UIBezierPath(ovalInRect: CGRect(x: innerCirclePadding, y: innerCirclePadding, width: frameSize.width - 2*innerCirclePadding, height: frameSize.height - 2*innerCirclePadding)).CGPath innerCircle.lineWidth = 4.0 innerCircle.strokeStart = 0.5 innerCircle.strokeEnd = 0.9 innerCircle.lineCap = kCALineCapRound innerCircle.fillColor = UIColor.clearColor().CGColor innerCircle.strokeColor = UIColor.grayColor().CGColor innerCircleView.layer.addSublayer(innerCircle) innerCircle.strokeStart = 0.0 innerCircle.strokeEnd = 1.0 vibrancyView.contentView.addSubview(innerCircleView) userInteractionEnabled = true } public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { return self } private static let DEFAULT_LEVEL = SpinnerLevel.Normal private var lastLevel = DEFAULT_LEVEL // MARK: - Public interface public lazy var titleLabel = UILabel() public var subtitleLabel: UILabel? public enum SpinnerLevel: Int, Comparable { case Low = 1 case Normal = 2 case High = 3 } // // Show the spinner activity on screen, if visible only update the title // public class func show(title: String, animated: Bool = true, level: SpinnerLevel = .Normal) -> SwiftSpinner { let window = UIApplication.sharedApplication().windows.first! let spinner = SwiftSpinner.sharedInstance if spinner.lastLevel <= level { //new level should override spinner.lastLevel = level spinner.showWithDelayBlock = nil spinner.clearTapHandler() spinner.updateFrame() if spinner.superview == nil { //show the spinner spinner.alpha = 0.0 window.addSubview(spinner) UIView.animateWithDuration(0.33, delay: 0.0, options: .CurveEaseOut, animations: { spinner.alpha = 1.0 }, completion: nil) // Orientation change observer NSNotificationCenter.defaultCenter().addObserver( spinner, selector: "updateFrame", name: UIApplicationDidChangeStatusBarOrientationNotification, object: nil) } spinner.title = title spinner.animating = animated } return spinner } // // Show the spinner activity on screen, after delay. If new call to show, // showWithDelay or hide is maked before execution this call is discarded // public class func showWithDelay(delay: Double, title: String, animated: Bool = true, level: SpinnerLevel = .Normal) -> SwiftSpinner { let spinner = SwiftSpinner.sharedInstance if spinner.lastLevel <= level { spinner.lastLevel = level spinner.showWithDelayBlock = { SwiftSpinner.show(title, animated: animated) } spinner.delay(seconds: delay) { [weak spinner] in if let spinner = spinner { spinner.showWithDelayBlock?() } } } return spinner } // // Hide the spinner(keeping old interface) // public class func hide(completion: (() -> Void)? = nil) { SwiftSpinner.hide(DEFAULT_LEVEL, completion: completion) } // // Hide the spinner // public class func hide(level: SpinnerLevel, completion: (() -> Void)? = nil) { let spinner = SwiftSpinner.sharedInstance if spinner.lastLevel <= level { spinner.lastLevel = DEFAULT_LEVEL NSNotificationCenter.defaultCenter().removeObserver(spinner) dispatch_async(dispatch_get_main_queue(), { spinner.showWithDelayBlock = nil spinner.clearTapHandler() if spinner.superview == nil { return } UIView.animateWithDuration(0.33, delay: 0.0, options: .CurveEaseOut, animations: { spinner.alpha = 0.0 }, completion: {_ in spinner.alpha = 1.0 spinner.removeFromSuperview() spinner.titleLabel.font = spinner.defaultTitleFont spinner.titleLabel.text = nil completion?() }) spinner.animating = false }) } } // // Set the default title font // public class func setTitleFont(font: UIFont?) { let spinner = SwiftSpinner.sharedInstance if let font = font { spinner.titleLabel.font = font } else { spinner.titleLabel.font = spinner.defaultTitleFont } } // // The spinner title // public var title: String = "" { didSet { let spinner = SwiftSpinner.sharedInstance UIView.animateWithDuration(0.15, delay: 0.0, options: .CurveEaseOut, animations: { spinner.titleLabel.transform = CGAffineTransformMakeScale(0.75, 0.75) spinner.titleLabel.alpha = 0.2 }, completion: {_ in spinner.titleLabel.text = self.title UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 0.0, options: [], animations: { spinner.titleLabel.transform = CGAffineTransformIdentity spinner.titleLabel.alpha = 1.0 }, completion: nil) }) } } // // observe the view frame and update the subviews layout // public override var frame: CGRect { didSet { if frame == CGRect.zero { return } blurView.frame = bounds vibrancyView.frame = blurView.bounds titleLabel.center = vibrancyView.center outerCircleView.center = vibrancyView.center innerCircleView.center = vibrancyView.center if let subtitle = subtitleLabel { subtitle.bounds.size = subtitle.sizeThatFits(CGRectInset(bounds, 20.0, 0.0).size) subtitle.center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMaxY(bounds) - CGRectGetMidY(subtitle.bounds) - subtitle.font.pointSize) } } } // // Start the spinning animation // public var animating: Bool = false { willSet (shouldAnimate) { if shouldAnimate && !animating { spinInner() spinOuter() } } didSet { // update UI if animating { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 0.45 self.innerCircle.strokeStart = 0.5 self.innerCircle.strokeEnd = 0.9 } else { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 1.0 self.innerCircle.strokeStart = 0.0 self.innerCircle.strokeEnd = 1.0 } } } // // Tap handler // public func addTapHandler(tap: (()->()), subtitle subtitleText: String? = nil) { clearTapHandler() //vibrancyView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTapSpinner"))) tapHandler = tap if subtitleText != nil { subtitleLabel = UILabel() if let subtitle = subtitleLabel { subtitle.text = subtitleText subtitle.font = UIFont(name: defaultTitleFont.familyName, size: defaultTitleFont.pointSize * 0.8) subtitle.textColor = UIColor.whiteColor() subtitle.numberOfLines = 0 subtitle.textAlignment = .Center subtitle.lineBreakMode = .ByWordWrapping subtitle.bounds.size = subtitle.sizeThatFits(CGRectInset(bounds, 20.0, 0.0).size) subtitle.center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMaxY(bounds) - CGRectGetMidY(subtitle.bounds) - subtitle.font.pointSize) vibrancyView.contentView.addSubview(subtitle) } } } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) if tapHandler != nil { tapHandler?() tapHandler = nil } } public func clearTapHandler() { userInteractionEnabled = false subtitleLabel?.removeFromSuperview() tapHandler = nil } // MARK: - Private interface // // layout elements // private var blurEffectStyle: UIBlurEffectStyle = .Dark private var blurEffect: UIBlurEffect! private var blurView: UIVisualEffectView! private var vibrancyView: UIVisualEffectView! var defaultTitleFont = UIFont(name: "HelveticaNeue", size: 22.0)! let frameSize = CGSize(width: 200.0, height: 200.0) private lazy var outerCircleView = UIView() private lazy var innerCircleView = UIView() private let outerCircle = CAShapeLayer() private let innerCircle = CAShapeLayer() private var showWithDelayBlock: (()->())? required public init?(coder aDecoder: NSCoder) { fatalError("Not coder compliant") } private var currentOuterRotation: CGFloat = 0.0 private var currentInnerRotation: CGFloat = 0.1 private func spinOuter() { if superview == nil { return } let duration = Double(Float(arc4random()) / Float(UInt32.max)) * 2.0 + 1.5 let randomRotation = Double(Float(arc4random()) / Float(UInt32.max)) * M_PI_4 + M_PI_4 //outer circle UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: { self.currentOuterRotation -= CGFloat(randomRotation) self.outerCircleView.transform = CGAffineTransformMakeRotation(self.currentOuterRotation) }, completion: {_ in let waitDuration = Double(Float(arc4random()) / Float(UInt32.max)) * 1.0 + 1.0 self.delay(seconds: waitDuration, completion: { if self.animating { self.spinOuter() } }) }) } private func spinInner() { if superview == nil { return } //inner circle UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: [], animations: { self.currentInnerRotation += CGFloat(M_PI_4) self.innerCircleView.transform = CGAffineTransformMakeRotation(self.currentInnerRotation) }, completion: {_ in self.delay(seconds: 0.5, completion: { if self.animating { self.spinInner() } }) }) } public func updateFrame() { let window = UIApplication.sharedApplication().windows.first! SwiftSpinner.sharedInstance.frame = window.frame } // MARK: - Util methods func delay(seconds seconds: Double, completion:()->()) { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds )) dispatch_after(popTime, dispatch_get_main_queue()) { completion() } } override public func layoutSubviews() { super.layoutSubviews() updateFrame() } // MARK: - Tap handler private var tapHandler: (()->())? func didTapSpinner() { tapHandler?() } } public func <<T: RawRepresentable where T.RawValue: Comparable>(a: T, b: T) -> Bool { return a.rawValue < b.rawValue }
mit
69724b8b463a0049e9a4148e714805bf
35.052154
463
0.582526
5.429645
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift
13
1284
// // CTR.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 08/03/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // // Counter (CTR) // struct CTRModeWorker: RandomAccessBlockModeWorker { typealias Element = Array<UInt8> let cipherOperation: CipherOperationOnBlock private let iv: Element var counter: UInt = 0 init(iv: Array<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) { self.iv = iv self.cipherOperation = cipherOperation } mutating func encrypt(_ plaintext: ArraySlice<UInt8>) -> Array<UInt8> { let nonce = buildNonce(iv, counter: UInt64(counter)) counter = counter + 1 guard let ciphertext = cipherOperation(nonce) else { return Array(plaintext) } return xor(plaintext, ciphertext) } mutating func decrypt(_ ciphertext: ArraySlice<UInt8>) -> Array<UInt8> { return encrypt(ciphertext) } } private func buildNonce(_ iv: Array<UInt8>, counter: UInt64) -> Array<UInt8> { let noncePartLen = AES.blockSize / 2 let noncePrefix = Array(iv[0 ..< noncePartLen]) let nonceSuffix = Array(iv[noncePartLen ..< iv.count]) let c = UInt64(bytes: nonceSuffix) + counter return noncePrefix + c.bytes() }
mit
2ac7e96ae2d9f3ae98b208815d527da4
27.511111
79
0.66251
4.085987
false
false
false
false
nathanlea/CS4153MobileAppDev
WIA/WIA2_lea_nathan/WIA2_lea_nathan/ViewController.swift
1
1516
// // ViewController.swift // WIA2_lea_nathan // // Created by Nathan on 8/31/15. // Copyright © 2015 Nathan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var numerator: UITextField! @IBOutlet weak var denominator: UITextField! @IBOutlet weak var result: UILabel! @IBAction func calcDecimal(sender: UIButton) { if let x = Int(numerator.text!), y = Int(denominator.text!) { calculateDecimal(Double(x), second: Double(y)) } else { result.text = "Undefined" } } @IBAction func calcInverse(sender: UIButton) { if let x = Int(numerator.text!), y = Int(denominator.text!) { numerator.text = String(y) denominator.text = String(x) calculateDecimal(Double(y), second: Double(x)) } else { result.text = "Undefined" } } func calculateDecimal(first: Double, second: Double) { if second == 0 { result.text = "Undefined" } else { let num = first / second result.text = String(num) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
98690b597cd974aebfedbc51827b4396
23.435484
80
0.567657
4.495549
false
false
false
false
wftllc/hahastream
Haha Stream/Extensions/Game+LocalImage.swift
1
3846
import Foundation import UIKit import Kingfisher extension Game: LocalImage { public typealias Completion = ((_ homeImage: Image?, _ awayImage: Image?, _ error: NSError?) -> ()) fileprivate func fetchImages(_ completion: Completion?) { completion?(nil, nil, nil) DispatchQueue.global().async { var __FIXME_REIMPLEMENT_THIS: Any /* let semaphore = DispatchSemaphore(value: 0); let res1 = ImageResource(downloadURL: self.awayTeamLogoURL!); let res2 = ImageResource(downloadURL: self.homeTeamLogoURL!); var image1: Image? var image2: Image? var outerError: NSError? KingfisherManager.shared.retrieveImage(with: res1, options: nil, progressBlock: nil) { (image, error, cacheType, url) in if let error = error { outerError = error; } image1 = image semaphore.signal() } KingfisherManager.shared.retrieveImage(with: res2, options: nil, progressBlock: nil) { (image, error, cacheType, url) in if let error = error { outerError = error; } image2 = image semaphore.signal() } semaphore.wait() semaphore.wait() completion?(image1, image2, outerError) */ } } public func saveLocalImage(_ completion: @escaping ((_ url: URL?, _ error: Error?) -> ())) { fetchImages { (image1, image2, error) in if let error = error { completion(nil, error) } else { DispatchQueue.global().async { do { let data = self.combine(image1: image1!, image2: image2!); try data.write(to: self.singleImageLocalURL) completion(self.singleImageLocalURL, nil) } catch { completion(nil, error) } } } } } public var localImageExists: Bool { return FileManager.default.fileExists(atPath: singleImageLocalURL.path); } public var singleImageLocalURL: URL { let name = self.uuid let fileURL = self.getCacheDirectory().appendingPathComponent(name).appendingPathExtension("png") return fileURL; } fileprivate func combine(image1: UIImage, image2: UIImage) -> Data { let topPadding: CGFloat = 40.0; let middlePadding: CGFloat = 40.0; let bottomPadding: CGFloat = 40.0; let str:NSString = NSString(string: self.startTimeString) let style = NSMutableParagraphStyle(); style.alignment = .center var attr: [NSAttributedStringKey: Any] = [ .paragraphStyle: style, .foregroundColor: UIColor.darkGray, ] if let font = UIFont(name: UIFont.preferredFont(forTextStyle: .title1).fontName, size: 90) { attr[.font] = font } let textSize = str.size(withAttributes: attr) let width = max(image1.size.width, image2.size.width) let height: CGFloat = topPadding + image1.size.height + middlePadding + image2.size.height + middlePadding + textSize.height + bottomPadding; let finalWidth = height * 2/3 let contextSize = CGSize(width: finalWidth, height: height) let renderer = UIGraphicsImageRenderer(size: contextSize) let x = (finalWidth - width)/2; let textRect = CGRect(origin: CGPoint(x: finalWidth/2 - textSize.width/2, y: height-textSize.height-bottomPadding), size: textSize); let data = renderer.pngData { (context) in context.cgContext.setFillColor(UIColor.white.cgColor) context.cgContext.fill(CGRect(origin: CGPoint(x:0, y:0), size: contextSize)) image1.draw(at: CGPoint(x: x, y: topPadding)) image2.draw(at: CGPoint(x: x, y: topPadding+image1.size.height+middlePadding)) context.cgContext.setShouldSmoothFonts(true) context.cgContext.setFillColor(UIColor.lightGray.cgColor) str.draw(in: textRect, withAttributes: attr) } return data; } fileprivate func getCacheDirectory() -> URL { let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) let path = paths[0] return path; // return path.appendingPathComponent("games", isDirectory: true) } }
mit
f37de5697386bf89496d9f49f3c4f40c
29.283465
143
0.692148
3.577674
false
false
false
false
soffes/HotKey
Sources/HotKey/Key.swift
1
19365
import Carbon public enum Key { // MARK: - Letters case a case b case c case d case e case f case g case h case i case j case k case l case m case n case o case p case q case r case s case t case u case v case w case x case y case z // MARK: - Numbers case zero case one case two case three case four case five case six case seven case eight case nine // MARK: - Symbols case period case quote case rightBracket case semicolon case slash case backslash case comma case equal case grave // Backtick case leftBracket case minus // MARK: - Whitespace case space case tab case `return` // MARK: - Modifiers case command case rightCommand case option case rightOption case control case rightControl case shift case rightShift case function case capsLock // MARK: - Navigation case pageUp case pageDown case home case end case upArrow case rightArrow case downArrow case leftArrow // MARK: - Functions case f1 case f2 case f3 case f4 case f5 case f6 case f7 case f8 case f9 case f10 case f11 case f12 case f13 case f14 case f15 case f16 case f17 case f18 case f19 case f20 // MARK: - Keypad case keypad0 case keypad1 case keypad2 case keypad3 case keypad4 case keypad5 case keypad6 case keypad7 case keypad8 case keypad9 case keypadClear case keypadDecimal case keypadDivide case keypadEnter case keypadEquals case keypadMinus case keypadMultiply case keypadPlus // MARK: - Misc case escape case delete case forwardDelete case help case volumeUp case volumeDown case mute // MARK: - Initializers public init?(string: String) { switch string.lowercased() { case "a": self = .a case "s": self = .s case "d": self = .d case "f": self = .f case "h": self = .h case "g": self = .g case "z": self = .z case "x": self = .x case "c": self = .c case "v": self = .v case "b": self = .b case "q": self = .q case "w": self = .w case "e": self = .e case "r": self = .r case "y": self = .y case "t": self = .t case "one", "1": self = .one case "two", "2": self = .two case "three", "3": self = .three case "four", "4": self = .four case "six", "6": self = .six case "five", "5": self = .five case "equal", "=": self = .equal case "nine", "9": self = .nine case "seven", "7": self = .seven case "minus", "-": self = .minus case "eight", "8": self = .eight case "zero", "0": self = .zero case "rightBracket", "]": self = .rightBracket case "o": self = .o case "u": self = .u case "leftBracket", "[": self = .leftBracket case "i": self = .i case "p": self = .p case "l": self = .l case "j": self = .j case "quote", "\"": self = .quote case "k": self = .k case "semicolon", ";": self = .semicolon case "backslash", "\\": self = .backslash case "comma", ",": self = .comma case "slash", "/": self = .slash case "n": self = .n case "m": self = .m case "period", ".": self = .period case "grave", "`", "ˋ", "`": self = .grave case "keypaddecimal": self = .keypadDecimal case "keypadmultiply": self = .keypadMultiply case "keypadplus": self = .keypadPlus case "keypadclear", "⌧": self = .keypadClear case "keypaddivide": self = .keypadDivide case "keypadenter": self = .keypadEnter case "keypadminus": self = .keypadMinus case "keypadequals": self = .keypadEquals case "keypad0": self = .keypad0 case "keypad1": self = .keypad1 case "keypad2": self = .keypad2 case "keypad3": self = .keypad3 case "keypad4": self = .keypad4 case "keypad5": self = .keypad5 case "keypad6": self = .keypad6 case "keypad7": self = .keypad7 case "keypad8": self = .keypad8 case "keypad9": self = .keypad9 case "return", "\r", "↩︎", "⏎", "⮐": self = .return case "tab", "\t", "⇥": self = .tab case "space", " ", "␣": self = .space case "delete", "⌫": self = .delete case "escape", "⎋": self = .escape case "command", "⌘", "": self = .command case "shift", "⇧": self = .shift case "capslock", "⇪": self = .capsLock case "option", "⌥": self = .option case "control", "⌃": self = .control case "rightcommand": self = .rightCommand case "rightshift": self = .rightShift case "rightoption": self = .rightOption case "rightcontrol": self = .rightControl case "function", "fn": self = .function case "f17", "F17": self = .f17 case "volumeup", "🔊": self = .volumeUp case "volumedown", "🔉": self = .volumeDown case "mute", "🔇": self = .mute case "f18", "F18": self = .f18 case "f19", "F19": self = .f19 case "f20", "F20": self = .f20 case "f5", "F5": self = .f5 case "f6", "F6": self = .f6 case "f7", "F7": self = .f7 case "f3", "F3": self = .f3 case "f8", "F8": self = .f8 case "f9", "F9": self = .f9 case "f11", "F11": self = .f11 case "f13", "F13": self = .f13 case "f16", "F16": self = .f16 case "f14", "F14": self = .f14 case "f10", "F10": self = .f10 case "f12", "F12": self = .f12 case "f15", "F15": self = .f15 case "help", "?⃝": self = .help case "home", "↖": self = .home case "pageup", "⇞": self = .pageUp case "forwarddelete", "⌦": self = .forwardDelete case "f4", "F4": self = .f4 case "end", "↘": self = .end case "f2", "F2": self = .f2 case "pagedown", "⇟": self = .pageDown case "f1", "F1": self = .f1 case "leftarrow", "←": self = .leftArrow case "rightarrow", "→": self = .rightArrow case "downarrow", "↓": self = .downArrow case "uparrow", "↑": self = .upArrow default: return nil } } public init?(carbonKeyCode: UInt32) { switch carbonKeyCode { case UInt32(kVK_ANSI_A): self = .a case UInt32(kVK_ANSI_S): self = .s case UInt32(kVK_ANSI_D): self = .d case UInt32(kVK_ANSI_F): self = .f case UInt32(kVK_ANSI_H): self = .h case UInt32(kVK_ANSI_G): self = .g case UInt32(kVK_ANSI_Z): self = .z case UInt32(kVK_ANSI_X): self = .x case UInt32(kVK_ANSI_C): self = .c case UInt32(kVK_ANSI_V): self = .v case UInt32(kVK_ANSI_B): self = .b case UInt32(kVK_ANSI_Q): self = .q case UInt32(kVK_ANSI_W): self = .w case UInt32(kVK_ANSI_E): self = .e case UInt32(kVK_ANSI_R): self = .r case UInt32(kVK_ANSI_Y): self = .y case UInt32(kVK_ANSI_T): self = .t case UInt32(kVK_ANSI_1): self = .one case UInt32(kVK_ANSI_2): self = .two case UInt32(kVK_ANSI_3): self = .three case UInt32(kVK_ANSI_4): self = .four case UInt32(kVK_ANSI_6): self = .six case UInt32(kVK_ANSI_5): self = .five case UInt32(kVK_ANSI_Equal): self = .equal case UInt32(kVK_ANSI_9): self = .nine case UInt32(kVK_ANSI_7): self = .seven case UInt32(kVK_ANSI_Minus): self = .minus case UInt32(kVK_ANSI_8): self = .eight case UInt32(kVK_ANSI_0): self = .zero case UInt32(kVK_ANSI_RightBracket): self = .rightBracket case UInt32(kVK_ANSI_O): self = .o case UInt32(kVK_ANSI_U): self = .u case UInt32(kVK_ANSI_LeftBracket): self = .leftBracket case UInt32(kVK_ANSI_I): self = .i case UInt32(kVK_ANSI_P): self = .p case UInt32(kVK_ANSI_L): self = .l case UInt32(kVK_ANSI_J): self = .j case UInt32(kVK_ANSI_Quote): self = .quote case UInt32(kVK_ANSI_K): self = .k case UInt32(kVK_ANSI_Semicolon): self = .semicolon case UInt32(kVK_ANSI_Backslash): self = .backslash case UInt32(kVK_ANSI_Comma): self = .comma case UInt32(kVK_ANSI_Slash): self = .slash case UInt32(kVK_ANSI_N): self = .n case UInt32(kVK_ANSI_M): self = .m case UInt32(kVK_ANSI_Period): self = .period case UInt32(kVK_ANSI_Grave): self = .grave case UInt32(kVK_ANSI_KeypadDecimal): self = .keypadDecimal case UInt32(kVK_ANSI_KeypadMultiply): self = .keypadMultiply case UInt32(kVK_ANSI_KeypadPlus): self = .keypadPlus case UInt32(kVK_ANSI_KeypadClear): self = .keypadClear case UInt32(kVK_ANSI_KeypadDivide): self = .keypadDivide case UInt32(kVK_ANSI_KeypadEnter): self = .keypadEnter case UInt32(kVK_ANSI_KeypadMinus): self = .keypadMinus case UInt32(kVK_ANSI_KeypadEquals): self = .keypadEquals case UInt32(kVK_ANSI_Keypad0): self = .keypad0 case UInt32(kVK_ANSI_Keypad1): self = .keypad1 case UInt32(kVK_ANSI_Keypad2): self = .keypad2 case UInt32(kVK_ANSI_Keypad3): self = .keypad3 case UInt32(kVK_ANSI_Keypad4): self = .keypad4 case UInt32(kVK_ANSI_Keypad5): self = .keypad5 case UInt32(kVK_ANSI_Keypad6): self = .keypad6 case UInt32(kVK_ANSI_Keypad7): self = .keypad7 case UInt32(kVK_ANSI_Keypad8): self = .keypad8 case UInt32(kVK_ANSI_Keypad9): self = .keypad9 case UInt32(kVK_Return): self = .`return` case UInt32(kVK_Tab): self = .tab case UInt32(kVK_Space): self = .space case UInt32(kVK_Delete): self = .delete case UInt32(kVK_Escape): self = .escape case UInt32(kVK_Command): self = .command case UInt32(kVK_Shift): self = .shift case UInt32(kVK_CapsLock): self = .capsLock case UInt32(kVK_Option): self = .option case UInt32(kVK_Control): self = .control case UInt32(kVK_RightCommand): self = .rightCommand case UInt32(kVK_RightShift): self = .rightShift case UInt32(kVK_RightOption): self = .rightOption case UInt32(kVK_RightControl): self = .rightControl case UInt32(kVK_Function): self = .function case UInt32(kVK_F17): self = .f17 case UInt32(kVK_VolumeUp): self = .volumeUp case UInt32(kVK_VolumeDown): self = .volumeDown case UInt32(kVK_Mute): self = .mute case UInt32(kVK_F18): self = .f18 case UInt32(kVK_F19): self = .f19 case UInt32(kVK_F20): self = .f20 case UInt32(kVK_F5): self = .f5 case UInt32(kVK_F6): self = .f6 case UInt32(kVK_F7): self = .f7 case UInt32(kVK_F3): self = .f3 case UInt32(kVK_F8): self = .f8 case UInt32(kVK_F9): self = .f9 case UInt32(kVK_F11): self = .f11 case UInt32(kVK_F13): self = .f13 case UInt32(kVK_F16): self = .f16 case UInt32(kVK_F14): self = .f14 case UInt32(kVK_F10): self = .f10 case UInt32(kVK_F12): self = .f12 case UInt32(kVK_F15): self = .f15 case UInt32(kVK_Help): self = .help case UInt32(kVK_Home): self = .home case UInt32(kVK_PageUp): self = .pageUp case UInt32(kVK_ForwardDelete): self = .forwardDelete case UInt32(kVK_F4): self = .f4 case UInt32(kVK_End): self = .end case UInt32(kVK_F2): self = .f2 case UInt32(kVK_PageDown): self = .pageDown case UInt32(kVK_F1): self = .f1 case UInt32(kVK_LeftArrow): self = .leftArrow case UInt32(kVK_RightArrow): self = .rightArrow case UInt32(kVK_DownArrow): self = .downArrow case UInt32(kVK_UpArrow): self = .upArrow default: return nil } } public var carbonKeyCode: UInt32 { switch self { case .a: return UInt32(kVK_ANSI_A) case .s: return UInt32(kVK_ANSI_S) case .d: return UInt32(kVK_ANSI_D) case .f: return UInt32(kVK_ANSI_F) case .h: return UInt32(kVK_ANSI_H) case .g: return UInt32(kVK_ANSI_G) case .z: return UInt32(kVK_ANSI_Z) case .x: return UInt32(kVK_ANSI_X) case .c: return UInt32(kVK_ANSI_C) case .v: return UInt32(kVK_ANSI_V) case .b: return UInt32(kVK_ANSI_B) case .q: return UInt32(kVK_ANSI_Q) case .w: return UInt32(kVK_ANSI_W) case .e: return UInt32(kVK_ANSI_E) case .r: return UInt32(kVK_ANSI_R) case .y: return UInt32(kVK_ANSI_Y) case .t: return UInt32(kVK_ANSI_T) case .one: return UInt32(kVK_ANSI_1) case .two: return UInt32(kVK_ANSI_2) case .three: return UInt32(kVK_ANSI_3) case .four: return UInt32(kVK_ANSI_4) case .six: return UInt32(kVK_ANSI_6) case .five: return UInt32(kVK_ANSI_5) case .equal: return UInt32(kVK_ANSI_Equal) case .nine: return UInt32(kVK_ANSI_9) case .seven: return UInt32(kVK_ANSI_7) case .minus: return UInt32(kVK_ANSI_Minus) case .eight: return UInt32(kVK_ANSI_8) case .zero: return UInt32(kVK_ANSI_0) case .rightBracket: return UInt32(kVK_ANSI_RightBracket) case .o: return UInt32(kVK_ANSI_O) case .u: return UInt32(kVK_ANSI_U) case .leftBracket: return UInt32(kVK_ANSI_LeftBracket) case .i: return UInt32(kVK_ANSI_I) case .p: return UInt32(kVK_ANSI_P) case .l: return UInt32(kVK_ANSI_L) case .j: return UInt32(kVK_ANSI_J) case .quote: return UInt32(kVK_ANSI_Quote) case .k: return UInt32(kVK_ANSI_K) case .semicolon: return UInt32(kVK_ANSI_Semicolon) case .backslash: return UInt32(kVK_ANSI_Backslash) case .comma: return UInt32(kVK_ANSI_Comma) case .slash: return UInt32(kVK_ANSI_Slash) case .n: return UInt32(kVK_ANSI_N) case .m: return UInt32(kVK_ANSI_M) case .period: return UInt32(kVK_ANSI_Period) case .grave: return UInt32(kVK_ANSI_Grave) case .keypadDecimal: return UInt32(kVK_ANSI_KeypadDecimal) case .keypadMultiply: return UInt32(kVK_ANSI_KeypadMultiply) case .keypadPlus: return UInt32(kVK_ANSI_KeypadPlus) case .keypadClear: return UInt32(kVK_ANSI_KeypadClear) case .keypadDivide: return UInt32(kVK_ANSI_KeypadDivide) case .keypadEnter: return UInt32(kVK_ANSI_KeypadEnter) case .keypadMinus: return UInt32(kVK_ANSI_KeypadMinus) case .keypadEquals: return UInt32(kVK_ANSI_KeypadEquals) case .keypad0: return UInt32(kVK_ANSI_Keypad0) case .keypad1: return UInt32(kVK_ANSI_Keypad1) case .keypad2: return UInt32(kVK_ANSI_Keypad2) case .keypad3: return UInt32(kVK_ANSI_Keypad3) case .keypad4: return UInt32(kVK_ANSI_Keypad4) case .keypad5: return UInt32(kVK_ANSI_Keypad5) case .keypad6: return UInt32(kVK_ANSI_Keypad6) case .keypad7: return UInt32(kVK_ANSI_Keypad7) case .keypad8: return UInt32(kVK_ANSI_Keypad8) case .keypad9: return UInt32(kVK_ANSI_Keypad9) case .`return`: return UInt32(kVK_Return) case .tab: return UInt32(kVK_Tab) case .space: return UInt32(kVK_Space) case .delete: return UInt32(kVK_Delete) case .escape: return UInt32(kVK_Escape) case .command: return UInt32(kVK_Command) case .shift: return UInt32(kVK_Shift) case .capsLock: return UInt32(kVK_CapsLock) case .option: return UInt32(kVK_Option) case .control: return UInt32(kVK_Control) case .rightCommand: return UInt32(kVK_RightCommand) case .rightShift: return UInt32(kVK_RightShift) case .rightOption: return UInt32(kVK_RightOption) case .rightControl: return UInt32(kVK_RightControl) case .function: return UInt32(kVK_Function) case .f17: return UInt32(kVK_F17) case .volumeUp: return UInt32(kVK_VolumeUp) case .volumeDown: return UInt32(kVK_VolumeDown) case .mute: return UInt32(kVK_Mute) case .f18: return UInt32(kVK_F18) case .f19: return UInt32(kVK_F19) case .f20: return UInt32(kVK_F20) case .f5: return UInt32(kVK_F5) case .f6: return UInt32(kVK_F6) case .f7: return UInt32(kVK_F7) case .f3: return UInt32(kVK_F3) case .f8: return UInt32(kVK_F8) case .f9: return UInt32(kVK_F9) case .f11: return UInt32(kVK_F11) case .f13: return UInt32(kVK_F13) case .f16: return UInt32(kVK_F16) case .f14: return UInt32(kVK_F14) case .f10: return UInt32(kVK_F10) case .f12: return UInt32(kVK_F12) case .f15: return UInt32(kVK_F15) case .help: return UInt32(kVK_Help) case .home: return UInt32(kVK_Home) case .pageUp: return UInt32(kVK_PageUp) case .forwardDelete: return UInt32(kVK_ForwardDelete) case .f4: return UInt32(kVK_F4) case .end: return UInt32(kVK_End) case .f2: return UInt32(kVK_F2) case .pageDown: return UInt32(kVK_PageDown) case .f1: return UInt32(kVK_F1) case .leftArrow: return UInt32(kVK_LeftArrow) case .rightArrow: return UInt32(kVK_RightArrow) case .downArrow: return UInt32(kVK_DownArrow) case .upArrow: return UInt32(kVK_UpArrow) } } } extension Key: CustomStringConvertible { public var description: String { switch self { case .a: return "A" case .s: return "S" case .d: return "D" case .f: return "F" case .h: return "H" case .g: return "G" case .z: return "Z" case .x: return "X" case .c: return "C" case .v: return "V" case .b: return "B" case .q: return "Q" case .w: return "W" case .e: return "E" case .r: return "R" case .y: return "Y" case .t: return "T" case .one, .keypad1: return "1" case .two, .keypad2: return "2" case .three, .keypad3: return "3" case .four, .keypad4: return "4" case .six, .keypad6: return "6" case .five, .keypad5: return "5" case .equal: return "=" case .nine, .keypad9: return "9" case .seven, .keypad7: return "7" case .minus: return "-" case .eight, .keypad8: return "8" case .zero, .keypad0: return "0" case .rightBracket: return "]" case .o: return "O" case .u: return "U" case .leftBracket: return "[" case .i: return "I" case .p: return "P" case .l: return "L" case .j: return "J" case .quote: return "\"" case .k: return "K" case .semicolon: return ";" case .backslash: return "\\" case .comma: return "," case .slash: return "/" case .n: return "N" case .m: return "M" case .period: return "." case .grave: return "`" case .keypadDecimal: return "." case .keypadMultiply: return "𝗑" case .keypadPlus: return "+" case .keypadClear: return "⌧" case .keypadDivide: return "/" case .keypadEnter: return "↩︎" case .keypadMinus: return "-" case .keypadEquals: return "=" case .`return`: return "↩︎" case .tab: return "⇥" case .space: return "␣" case .delete: return "⌫" case .escape: return "⎋" case .command, .rightCommand: return "⌘" case .shift, .rightShift: return "⇧" case .capsLock: return "⇪" case .option, .rightOption: return "⌥" case .control, .rightControl: return "⌃" case .function: return "fn" case .f17: return "F17" case .volumeUp: return "🔊" case .volumeDown: return "🔉" case .mute: return "🔇" case .f18: return "F18" case .f19: return "F19" case .f20: return "F20" case .f5: return "F5" case .f6: return "F6" case .f7: return "F7" case .f3: return "F3" case .f8: return "F8" case .f9: return "F9" case .f11: return "F11" case .f13: return "F13" case .f16: return "F16" case .f14: return "F14" case .f10: return "F10" case .f12: return "F12" case .f15: return "F15" case .help: return "?⃝" case .home: return "↖" case .pageUp: return "⇞" case .forwardDelete: return "⌦" case .f4: return "F4" case .end: return "↘" case .f2: return "F2" case .pageDown: return "⇟" case .f1: return "F1" case .leftArrow: return "←" case .rightArrow: return "→" case .downArrow: return "↓" case .upArrow: return "↑" } } }
mit
6322c25476db266854a0075228148347
30.518092
62
0.622919
2.816432
false
false
false
false
teacurran/alwaysawake-ios
Pods/p2.OAuth2/Sources/Base/OAuth2CodeGrant.swift
2
5093
// // OAuth2CodeGrant.swift // OAuth2 // // Created by Pascal Pfiffner on 6/16/14. // Copyright 2014 Pascal Pfiffner // // 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 /** A class to handle authorization for confidential clients via the authorization code grant method. This auth flow is designed for clients that are capable of protecting their client secret but can be used from installed apps. During code exchange and token refresh flows, **if** the client has a secret, a "Basic key:secret" Authorization header will be used. If not the client key will be embedded into the request body. */ public class OAuth2CodeGrant: OAuth2 { public override class var grantType: String { return "authorization_code" } override public class var responseType: String? { return "code" } // MARK: - Token Request /** Generate the request to be used for the token request from known instance variables and supplied parameters. This will set "grant_type" to "authorization_code", add the "code" provided and fill the remaining parameters. The "client_id" is only added if there is no secret (public client) or if the request body is used for id and secret. - parameter code: The code you want to exchange for an access token - parameter params: Optional additional params to add as URL parameters - returns: A request you can use to create a URL request to exchange the code for an access token */ func tokenRequestWithCode(code: String, params: OAuth2StringDict? = nil) throws -> OAuth2AuthRequest { guard let clientId = clientConfig.clientId where !clientId.isEmpty else { throw OAuth2Error.NoClientId } guard let redirect = context.redirectURL else { throw OAuth2Error.NoRedirectURL } let req = OAuth2AuthRequest(url: (clientConfig.tokenURL ?? clientConfig.authorizeURL)) req.params["code"] = code req.params["grant_type"] = self.dynamicType.grantType req.params["redirect_uri"] = redirect req.params["client_id"] = clientId return req } /** Extracts the code from the redirect URL and exchanges it for a token. */ override public func handleRedirectURL(redirect: NSURL) { logger?.debug("OAuth2", msg: "Handling redirect URL \(redirect.description)") do { let code = try validateRedirectURL(redirect) exchangeCodeForToken(code) } catch let error { didFail(error) } } /** Takes the received code and exchanges it for a token. */ public func exchangeCodeForToken(code: String) { do { guard !code.isEmpty else { throw OAuth2Error.PrerequisiteFailed("I don't have a code to exchange, let the user authorize first") } let post = try tokenRequestWithCode(code).asURLRequestFor(self) logger?.debug("OAuth2", msg: "Exchanging code \(code) for access token at \(post.URL!)") performRequest(post) { data, status, error in do { guard let data = data else { throw error ?? OAuth2Error.NoDataInResponse } let params = try self.parseAccessTokenResponseData(data) if status < 400 { self.logger?.debug("OAuth2", msg: "Did exchange code for access [\(nil != self.clientConfig.accessToken)] and refresh [\(nil != self.clientConfig.refreshToken)] tokens") self.didAuthorize(params) } else { throw OAuth2Error.Generic("\(status)") } } catch let error { self.didFail(error) } } } catch let error { didFail(error) } } // MARK: - Utilities /** Validates the redirect URI: returns a tuple with the code and nil on success, nil and an error on failure. */ func validateRedirectURL(redirect: NSURL) throws -> String { guard let expectRedirect = context.redirectURL else { throw OAuth2Error.NoRedirectURL } let comp = NSURLComponents(URL: redirect, resolvingAgainstBaseURL: true) if !redirect.absoluteString.hasPrefix(expectRedirect) && (!redirect.absoluteString.hasPrefix("urn:ietf:wg:oauth:2.0:oob") && "localhost" != comp?.host) { throw OAuth2Error.InvalidRedirectURL("Expecting «\(expectRedirect)» but received «\(redirect)»") } if let compQuery = comp?.query where compQuery.characters.count > 0 { let query = OAuth2CodeGrant.paramsFromQuery(comp!.percentEncodedQuery!) try assureNoErrorInResponse(query) if let cd = query["code"] { // we got a code, use it if state is correct (and reset state) try assureMatchesState(query) return cd } throw OAuth2Error.ResponseError("No “code” received") } throw OAuth2Error.PrerequisiteFailed("The redirect URL contains no query fragment") } }
apache-2.0
cffa190c9a5cd65885a1df4ce53329bb
32.9
175
0.717994
3.846445
false
false
false
false
JeremyJacquemont/SchoolProjects
IUT/iOS-Projects/Locations/Locations/GooglePlacesHelper.swift
1
6794
// // GooglePlacesHelper.swift // Locations // // Created by iem on 12/05/2015. // Copyright (c) 2015 JeremyJacquemont. All rights reserved. // import Foundation import Alamofire import SwiftyJSON //MARK: - GooglePlacesType enum GooglePlacesType { case SEARCH, DETAIL, IMAGE } //MARK: - Extension Alamofire (Request) extension Alamofire.Request { //MARK: - Serializer Part class func responseImage() -> Serializer { return { request, response, data in if data == nil { return (nil, nil) } let image = UIImage(data: data!, scale: UIScreen.mainScreen().scale) return (image, nil) } } //MARK: - Function func responseImage(completionHandler: (NSURLRequest, NSHTTPURLResponse?, UIImage?, NSError?) -> Void) -> Self { return response(serializer: Request.responseImage(), completionHandler: { (request, response, image, error) in completionHandler(request, response, image as? UIImage, error) }) } } //MARK: - GooglePlacesHelper class GooglePlacesHelper { //MARK: - Constants class var TYPES : [String] { return ["restaurant", "bar", "museum", "park"] } class var API_KEY : String { return "AIzaSyDKM0DTyGkocydBgbIatEpiAWwSFCawyTk" } class var MAX_WIDTH : String { return "250" } //MARK: - sharedManager class var sharedManager: GooglePlacesHelper { struct Singleton { static let instance = GooglePlacesHelper() } return Singleton.instance } //MARK: - Functions func getPlace(place: GooglePlace?, callback:(NSError?, GooglePlace?) -> Void) -> Void { //Create params var params = createParams(GooglePlacesType.DETAIL, params: place) //Execute request & return response Alamofire.request(.GET, GooglePlaceRessourceUrl.DETAIL, parameters: params) .responseJSON { (request, response, data, error) in if(error != nil) { println("Error getPlace: \(error)") callback(error, nil) } else { var json = JSON(data!) if json[GooglePlaceRessourceKeysJson.ERROR].string == nil { if let currentPlace = place { let result = json[GooglePlaceRessourceKeysJson.RESULT] currentPlace.setDescription(result) self.setImage(place, callback) } else { callback(error, place) } } else { callback(error, place) } } } } func setImage(place: GooglePlace?, callback:(NSError?, GooglePlace?) -> Void) -> Void { //Create params var params = createParams(GooglePlacesType.IMAGE, params: place) //Execute request & set image Alamofire.request(.GET, GooglePlaceRessourceUrl.PHOTO, parameters: params) .validate(contentType: ["image/*"]) .responseImage() { (request, _, image, error) in if error == nil && image != nil { place?.image = image callback(error, place) } else { println("Error setImage: \(error)") callback(error, nil) } } } func searchPlaces(location: Location, callback:(NSError?, [GooglePlace]?) -> Void) -> Void { //Create params var params = createParams(GooglePlacesType.SEARCH, params: location) //Execute request & return response Alamofire.request(.GET, GooglePlaceRessourceUrl.SEARCH, parameters: params) .responseJSON { (request, response, data, error) in if(error != nil) { println("Error searchPlaces: \(error)") callback(error, nil) } else { var json = JSON(data!) var places = [GooglePlace]() if json[GooglePlaceRessourceKeysJson.ERROR].string == nil { if let results = json[GooglePlaceRessourceKeysJson.RESULTS].array { for element in results { places.append(GooglePlace(json: element)) } } } callback(error, places) } } } private func createParams(type: GooglePlacesType, params: AnyObject?) -> [String: String]? { //Get All types var returnValue: [String: String]? var types = "|".join(GooglePlacesHelper.TYPES) //Create good parameters for type switch(type) { case .DETAIL : if let place = params as? GooglePlace { if let placeId = place.placeId { returnValue = [ GooglePlaceRessourceKeysApi.PLACE_ID: "\(placeId)", GooglePlaceRessourceKeysApi.KEY: "\(GooglePlacesHelper.API_KEY)" ] } } break case .SEARCH: if let location = params as? Location { returnValue = [ GooglePlaceRessourceKeysApi.LOCATION: "\(location.latitude),\(location.longitude)", GooglePlaceRessourceKeysApi.RADIUS: "\(location.radius)", GooglePlaceRessourceKeysApi.TYPES: "\(types)", GooglePlaceRessourceKeysApi.KEY: "\(GooglePlacesHelper.API_KEY)" ] } break case .IMAGE: if let place = params as? GooglePlace { if let photos = place.photos { if photos.count > 0 { let photo = photos[0] let photoReference = photo[GooglePlaceRessourceKeysJson.PHOTO_REFERENCE] returnValue = [ GooglePlaceRessourceKeysApi.PHOTO_REFERENCE: "\(photoReference)", GooglePlaceRessourceKeysApi.KEY: "\(GooglePlacesHelper.API_KEY)", GooglePlaceRessourceKeysApi.MAX_WIDTH: "\(GooglePlacesHelper.MAX_WIDTH)" ] } } } default: break } return returnValue } }
apache-2.0
dbc28421cf6c52d87db5dd4d74cf897e
35.532258
118
0.504563
5.226154
false
false
false
false
iprebeg/EnigmaKit
EnigmaKit/Enigma.swift
1
3014
// // Enigma.swift // EnigmaKit // // Created by Prebeg, Ivor on 02/12/2016. // Copyright © 2016 Prebeg, Ivor. All rights reserved. // import Foundation class Enigma : SignalHandler { var rotorArray:RotorArray var reflector:Reflector var plugboard:Plugboard init(rotorArray:RotorArray, reflector:Reflector, plugboard:Plugboard) { self.rotorArray = rotorArray self.reflector = reflector self.plugboard = plugboard } func signal(c: Character) -> (Character) { rotorArray.rotate() var r = Array<SignalHandler>(arrayLiteral: plugboard, rotorArray, reflector).reduce(c){ $1.signal(c: $0)} r = Array<ReversibleSignalHandler>(arrayLiteral: plugboard, rotorArray).reversed().reduce(r){ $1.signalReverse(c:$0)} return r } func encrypt(s:String) -> (String) { return String(s.characters.map{self.signal(c: $0)}) } func setOffsets(s:String) { rotorArray.setOffsets(s: Array(s.characters)) } func setSettings(s:String) { rotorArray.setSettings(s: Array(s.characters)) } func setPlugboard(plugboard:Plugboard) { self.plugboard = plugboard } static func M3() -> (Enigma) { return Enigma( rotorArray:RotorArray(rotorsInit: Array(arrayLiteral: Rotor.ROTOR_I(), Rotor.ROTOR_II(), Rotor.ROTOR_III() )), reflector:Reflector.REFLECTOR_B(), plugboard:Plugboard.NONE()) } static func M4() -> (Enigma) { return Enigma( rotorArray:RotorArray(rotorsInit: Array(arrayLiteral: Rotor.ROTOR_BETA(), Rotor.ROTOR_I(), Rotor.ROTOR_II(), Rotor.ROTOR_III() )), reflector:Reflector.REFLECTOR_B_THIN(), plugboard:Plugboard.NONE()) } } struct Constants { static let ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; static let ROTOR_I = "EKMFLGDQVZNTOWYHXUSPAIBRCJ"; static let ROTOR_II = "AJDKSIRUXBLHWTMCQGZNPYFVOE"; static let ROTOR_III = "BDFHJLCPRTXVZNYEIWGAKMUSQO"; static let ROTOR_IV = "ESOVPZJAYQUIRHXLNFTGKDCMWB"; static let ROTOR_V = "VZBRGITYUPSDNHLXAWMJQOFECK"; static let ROTOR_VI = "JPGVOUMFYQBENHZRDKASXLICTW"; static let ROTOR_VII = "NZJHGRCXMYSWBOUFAIVLPEKQDT"; static let ROTOR_VIII = "FKQHTLXOCBJSPDZRAMEWNIUYGV"; static let ROTOR_BETA = "LEYJVCNIXWPBQMDRTAKZGFUHOS"; static let ROTOR_GAMMA = "FSOKANUERHMBTIYCWLQPZXVGJD"; static let REFLECTOR_A = "EJMZALYXVBWFCRQUONTSPIKHGD"; static let REFLECTOR_B = "YRUHQSLDPXNGOKMIEBFZCWVJAT"; static let REFLECTOR_C = "FVPJIAOYEDRZXWGCTKUQSBNMHL"; static let REFLECTOR_B_THIN = "ENKQAUYWJICOPBLMDXZVFTHRGS"; static let REFLECTOR_C_THIN = "RDOBJNTKVEHMLFCWZAXGYIPSUQ"; static let EKW = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
gpl-3.0
db0e42e5a2b614a0cc5c704281eb8ed5
29.13
80
0.623631
3.212154
false
false
false
false
alpascual/DigitalWil
FrostedSidebar/ViewController.swift
1
2776
// // ViewController.swift // CustomStuff // // Created by Evan Dekhayser on 7/9/14. // Copyright (c) 2014 Evan Dekhayser. All rights reserved. // import UIKit class ViewController: MasterPage { private var idx: Int = 0 private let backGroundArray = [UIImage(named: "img1.jpg"),UIImage(named:"img2.jpg"), UIImage(named: "img3.jpg"), UIImage(named: "img4.jpg")] @IBOutlet var backGroundImage: UIImageView! @IBOutlet var setupButton: UIButton! override func viewDidLoad() { viewControllerIndex = 0 super.viewDidLoad() // Visual Effect View for background var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark)) as UIVisualEffectView visualEffectView.frame = self.view.frame visualEffectView.alpha = 0.5 backGroundImage.image = UIImage(named: "img1.jpg") backGroundImage.addSubview(visualEffectView) NSTimer.scheduledTimerWithTimeInterval(6, target: self, selector: "changeImage", userInfo: nil, repeats: true) // // On Board experience in case they never seen it before // let firstPage: OnboardingContentViewController = OnboardingContentViewController(title: "What A Beautiful Photo", body: "This city background image is so beautiful", image: UIImage(named: // "blue"), buttonText: "Enable Location Services") { // } // // 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: "Connect With Facebook") { // } // // let thirdPage: OnboardingContentViewController = OnboardingContentViewController(title: "Seriously Though", body: "Kudos to the photographer.", image: UIImage(named: // "yellow"), buttonText: "Let's Get Started") { // } // // let onboardingVC: OnboardingViewController = OnboardingViewController(backgroundImage: UIImage(named: "street"), contents: [firstPage, secondPage, thirdPage]) // // self.presentViewController(onboardingVC, animated: true, completion: nil) } func changeImage(){ if idx == backGroundArray.count-1{ idx = 0 } else{ idx++ } var toImage = backGroundArray[idx]; UIView.transitionWithView(self.backGroundImage, duration: 3, options: .TransitionCrossDissolve, animations: {self.backGroundImage.image = toImage}, completion: nil) } @IBAction func setupButtonPressed(sender: AnyObject) { self.performSegueWithIdentifier("SecondSegue", sender: self) } }
mit
032037cf721738a57ad5dfb85eb82f0a
38.657143
197
0.659942
4.634391
false
false
false
false
almachelouche/Alien-Adventure
Alien Adventure/ItemsFromPlanet.swift
1
847
// // ItemsFromPlanet.swift // Alien Adventure // // Created by Jarrod Parkes on 10/3/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func itemsFromPlanet(inventory: [UDItem], planet: String) -> [UDItem] { var planetGems = [UDItem]() for item in inventory { if let PlanetOfOrigin = item.historicalData["PlanetOfOrigin"] as? String { print(PlanetOfOrigin) if PlanetOfOrigin == planet { planetGems.append(item) } } } return planetGems } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 1"
mit
fa4388ca75741c73459ee31e3ea50e25
31.538462
235
0.617021
4.429319
false
false
false
false
shuuchen/SwiftTips
initialization_3.swift
1
4696
// failable initializers for classes // for value types, initialization faliure can be triggered at any point of the failable initializer // for classes, it can only be triggered after all stored properties are set & all initializer delegations are finished class Product { let name: String! init?(name: String) { self.name = name if name.isEmpty { return nil } } } if let bowTie = Product(name: "bow tie") { print("The product's name is \(bowTie.name)") } // propagation of initialization failure // failable initializer can delegate another failable (or non-failable) initializer across the same class or from superclass // if initialization failure is triggered at any point in the process, the initialization fails immediately class CartItem: Product { let quantity: Int! init?(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) if quantity < 1 { return nil } } } if let twoSocks = CartItem(name: "sock", quantity: 2) { print("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)") } if let zeroShirts = CartItem(name: "shirt", quantity: 0) { print("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)") } else { print("Unable to initialize zero shirts") } if let oneUnnamed = CartItem(name: "", quantity: 1) { print("Item: \(oneUnnamed.name), quantity: \(oneUnnamed.quantity)") } else { print("Unable to initialize one unnamed product") } // overriding a failable initializer // a superclass failable initializer can be overriden by a subclass non-failable initializer, but not the other way around // in this case, the only way to delegate up to the superclass initializer is to force-unwrap the result of the failable superclass initializer class Document { var name: String? // this initializer creates a document with a nil name value init() {} // this initializer creates a document with a non-empty name value init?(name: String) { self.name = name if name.isEmpty { return nil } } } class AutomaticallyNamedDocument: Document { override init() { super.init() self.name = "[Untitled]" } override init(name: String) { super.init() if name.isEmpty { self.name = "[Untitled]" } else { self.name = name } } } class UntitledDocument: Document { override init() { // force-unwrap // here, a runtime error will occur if nil is returned super.init(name: "[Untitled]")! } } // init! failable initializer // init? creates an optional instance of the appropriate type // init! creates an implicitly unwrapped optional instance of the appropriate type // init! & init? can be delegated, overriden through each other // delegate from init to init! is allowed, although doing so will trigger an assertion if init! causes initialization to fail // required initializers // every subclass is required to implement the initializer // use "required" instead of "override" when overriding a required designated initializer class SomeClass2 { required init() { // initializer implementation goes here } } class SomeSubclass: SomeClass2 { required init() { // subclass implementation of the required initializer goes here } } // setting a default property value with a closure or function // provide a customized default value for that property // since the instance has not been initialized yet, other properties, methods or self cannot be used in closure class SomeClass { let someProperty: SomeType = { // create a default value for someProperty inside this closure // someValue must be of the same type as SomeType return someValue }() // use "()" to run the closure immediately } struct Checkerboard { let boardColors: [Bool] = { var temporaryBoard = [Bool]() var isBlack = false for i in 1...10 { for j in 1...10 { temporaryBoard.append(isBlack) isBlack = !isBlack } isBlack = !isBlack } return temporaryBoard }() func squareIsBlackAtRow(row: Int, column: Int) -> Bool { return boardColors[(row * 10) + column] } } let board = Checkerboard() print(board.squareIsBlackAtRow(0, column: 1)) // prints "true" print(board.squareIsBlackAtRow(9, column: 9)) // prints "false"
mit
0e86cc3cb34153c20649e284d244ecc6
25.234637
143
0.637564
4.545983
false
false
false
false
CreazyShadow/SimpleDemo
SimpleApp/Pods/PromiseKit/Sources/Guarantee.swift
1
4693
import class Foundation.Thread import Dispatch /** A `Guarantee` is a functional abstraction around an asynchronous operation that cannot error. - See: `Thenable` */ public class Guarantee<T>: Thenable { let box: Box<T> fileprivate init(box: SealedBox<T>) { self.box = box } /// Returns a `Guarantee` sealed with the provided value. public static func value(_ value: T) -> Guarantee<T> { return .init(box: SealedBox(value: value)) } /// Returns a pending `Guarantee` that can be resolved with the provided closure’s parameter. public init(resolver body: (@escaping(T) -> Void) -> Void) { box = EmptyBox() body(box.seal) } /// - See: `Thenable.pipe` public func pipe(to: @escaping(Result<T>) -> Void) { pipe{ to(.fulfilled($0)) } } func pipe(to: @escaping(T) -> Void) { switch box.inspect() { case .pending: box.inspect { switch $0 { case .pending(let handlers): handlers.append(to) case .resolved(let value): to(value) } } case .resolved(let value): to(value) } } /// - See: `Thenable.result` public var result: Result<T>? { switch box.inspect() { case .pending: return nil case .resolved(let value): return .fulfilled(value) } } init(_: PMKUnambiguousInitializer) { box = EmptyBox() } /// Returns a tuple of a pending `Guarantee` and a function that resolves it. public class func pending() -> (guarantee: Guarantee<T>, resolve: (T) -> Void) { return { ($0, $0.box.seal) }(Guarantee<T>(.pending)) } } public extension Guarantee { @discardableResult func done(on: DispatchQueue? = conf.Q.return, _ body: @escaping(T) -> Void) -> Guarantee<Void> { let rg = Guarantee<Void>(.pending) pipe { (value: T) in on.async { body(value) rg.box.seal(()) } } return rg } func map<U>(on: DispatchQueue? = conf.Q.map, _ body: @escaping(T) -> U) -> Guarantee<U> { let rg = Guarantee<U>(.pending) pipe { value in on.async { rg.box.seal(body(value)) } } return rg } @discardableResult func then<U>(on: DispatchQueue? = conf.Q.map, _ body: @escaping(T) -> Guarantee<U>) -> Guarantee<U> { let rg = Guarantee<U>(.pending) pipe { value in on.async { body(value).pipe(to: rg.box.seal) } } return rg } public func asVoid() -> Guarantee<Void> { return map(on: nil) { _ in } } /** Blocks this thread, so you know, don’t call this on a serial thread that any part of your chain may use. Like the main thread for example. */ public func wait() -> T { if Thread.isMainThread { print("PromiseKit: warning: `wait()` called on main thread!") } var result = value if result == nil { let group = DispatchGroup() group.enter() pipe { (foo: T) in result = foo; group.leave() } group.wait() } return result! } } #if swift(>=3.1) public extension Guarantee where T == Void { convenience init() { self.init(box: SealedBox(value: Void())) } } #endif public extension DispatchQueue { /** Asynchronously executes the provided closure on a dispatch queue. DispatchQueue.global().async(.promise) { md5(input) }.done { md5 in //… } - Parameter body: The closure that resolves this promise. - Returns: A new `Guarantee` resolved by the result of the provided closure. - Note: There is no Promise/Thenable version of this due to Swift compiler ambiguity issues. */ @available(macOS 10.10, iOS 2.0, tvOS 10.0, watchOS 2.0, *) final func async<T>(_: PMKNamespacer, group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () -> T) -> Guarantee<T> { let rg = Guarantee<T>(.pending) async(group: group, qos: qos, flags: flags) { rg.box.seal(body()) } return rg } } #if os(Linux) import func CoreFoundation._CFIsMainThread extension Thread { // `isMainThread` is not implemented yet in swift-corelibs-foundation. static var isMainThread: Bool { return _CFIsMainThread() } } #endif
apache-2.0
cd2d0a07d65ac99fef95e47544f3997e
26.409357
185
0.548965
4.047496
false
false
false
false
eKasztany/4ania
ios/Queue/Pods/PopupDialog/PopupDialog/Classes/PopupDialogContainerView.swift
3
6477
// // PopupDialogContainerView.swift // Pods // // Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk) // Author - Martin Wildfeuer (http://www.mwfire.de) // // 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 /// The main view of the popup dialog final public class PopupDialogContainerView: UIView { // MARK: - Appearance /// The background color of the popup dialog override public dynamic var backgroundColor: UIColor? { get { return container.backgroundColor } set { container.backgroundColor = newValue } } /// The corner radius of the popup view public dynamic var cornerRadius: Float { get { return Float(shadowContainer.layer.cornerRadius) } set { let radius = CGFloat(newValue) shadowContainer.layer.cornerRadius = radius container.layer.cornerRadius = radius } } /// Enable / disable shadow rendering public dynamic var shadowEnabled: Bool { get { return shadowContainer.layer.shadowRadius > 0 } set { shadowContainer.layer.shadowRadius = newValue ? 5 : 0 } } /// The shadow color public dynamic var shadowColor: UIColor? { get { guard let color = shadowContainer.layer.shadowColor else { return nil } return UIColor(cgColor: color) } set { shadowContainer.layer.shadowColor = newValue?.cgColor } } // MARK: - Views /// The shadow container is the basic view of the PopupDialog /// As it does not clip subviews, a shadow can be applied to it internal lazy var shadowContainer: UIView = { let shadowContainer = UIView(frame: .zero) shadowContainer.translatesAutoresizingMaskIntoConstraints = false shadowContainer.backgroundColor = UIColor.clear shadowContainer.layer.shadowColor = UIColor.black.cgColor shadowContainer.layer.shadowRadius = 5 shadowContainer.layer.shadowOpacity = 0.4 shadowContainer.layer.shadowOffset = CGSize(width: 0, height: 0) shadowContainer.layer.cornerRadius = 4 return shadowContainer }() /// The container view is a child of shadowContainer and contains /// all other views. It clips to bounds so cornerRadius can be set internal lazy var container: UIView = { let container = UIView(frame: .zero) container.translatesAutoresizingMaskIntoConstraints = false container.backgroundColor = UIColor.white container.clipsToBounds = true container.layer.cornerRadius = 4 return container }() // The container stack view for buttons internal lazy var buttonStackView: UIStackView = { let buttonStackView = UIStackView() buttonStackView.translatesAutoresizingMaskIntoConstraints = false buttonStackView.distribution = .fillEqually buttonStackView.spacing = 0 return buttonStackView }() // The main stack view, containing all relevant views internal lazy var stackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [self.buttonStackView]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = 0 return stackView }() // MARK: - Constraints /// The center constraint of the shadow container internal var centerYConstraint: NSLayoutConstraint? = nil // MARK: - Initializers internal override init(frame: CGRect) { super.init(frame: frame) setupViews() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View setup internal func setupViews() { // Add views addSubview(shadowContainer) shadowContainer.addSubview(container) container.addSubview(stackView) // Layout views let views = ["shadowContainer": shadowContainer, "container": container, "stackView": stackView] var constraints = [NSLayoutConstraint]() // Shadow container constraints constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=10,==20@900)-[shadowContainer(<=340,>=300)]-(>=10,==20@900)-|", options: [], metrics: nil, views: views) constraints += [NSLayoutConstraint(item: shadowContainer, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)] centerYConstraint = NSLayoutConstraint(item: shadowContainer, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) constraints.append(centerYConstraint!) // Container constraints constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[container]|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[container]|", options: [], metrics: nil, views: views) // Main stack view constraints constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: [], metrics: nil, views: views) // Activate constraints NSLayoutConstraint.activate(constraints) } }
apache-2.0
8fec25f3aefeda6be6d27d3bac5b837e
39.735849
184
0.686583
5.072044
false
false
false
false
Allow2CEO/browser-ios
Client/Frontend/Browser/BrowserToolbar.swift
1
7533
/* 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 UIKit import SnapKit import Shared import XCGLogger private let log = Logger.browserLogger @objc protocol BrowserToolbarProtocol { weak var browserToolbarDelegate: BrowserToolbarDelegate? { get set } var shareButton: UIButton { get } var pwdMgrButton: UIButton { get } var forwardButton: UIButton { get } var backButton: UIButton { get } var addTabButton: UIButton { get } // While implementing protocol lazy var `self` is not usable to access instance variables, so this needs to be a function/calc var var actionButtons: [UIButton] { get } func updateBackStatus(_ canGoBack: Bool) func updateForwardStatus(_ canGoForward: Bool) func updateReloadStatus(_ isLoading: Bool) func updatePageStatus(_ isWebPage: Bool) } @objc protocol BrowserToolbarDelegate: class { func browserToolbarDidPressBack(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressForward(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressBookmark(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressShare(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressPwdMgr(browserToolbar: BrowserToolbarProtocol, button: UIButton) } @objc open class BrowserToolbarHelper: NSObject { let toolbar: BrowserToolbarProtocol var buttonTintColor = BraveUX.ActionButtonTintColor { // TODO see if setting it here can be avoided didSet { setTintColor(buttonTintColor, forButtons: toolbar.actionButtons) } } fileprivate func setTintColor(_ color: UIColor, forButtons buttons: [UIButton]) { buttons.forEach { $0.tintColor = color } } init(toolbar: BrowserToolbarProtocol) { self.toolbar = toolbar super.init() // TODO: All of this should be configured directly inside the browser toolbar toolbar.backButton.setImage(UIImage(named: "back"), for: .normal) toolbar.backButton.accessibilityLabel = Strings.Back toolbar.backButton.addTarget(self, action: #selector(BrowserToolbarHelper.SELdidClickBack), for: UIControlEvents.touchUpInside) toolbar.forwardButton.setImage(UIImage(named: "forward"), for: .normal) toolbar.forwardButton.accessibilityLabel = Strings.Forward toolbar.forwardButton.addTarget(self, action: #selector(BrowserToolbarHelper.SELdidClickForward), for: UIControlEvents.touchUpInside) toolbar.shareButton.setImage(UIImage(named: "send"), for: .normal) toolbar.shareButton.accessibilityLabel = Strings.Share toolbar.shareButton.addTarget(self, action: #selector(BrowserToolbarHelper.SELdidClickShare), for: UIControlEvents.touchUpInside) toolbar.addTabButton.setImage(UIImage(named: "add"), for: .normal) toolbar.addTabButton.accessibilityLabel = Strings.Add_Tab toolbar.addTabButton.addTarget(self, action: #selector(BrowserToolbarHelper.SELdidClickAddTab), for: UIControlEvents.touchUpInside) toolbar.pwdMgrButton.setImage(UIImage(named: "passhelper_1pwd")?.withRenderingMode(.alwaysTemplate), for: .normal) toolbar.pwdMgrButton.isHidden = true toolbar.pwdMgrButton.tintColor = UIColor.white toolbar.pwdMgrButton.accessibilityLabel = Strings.PasswordManager toolbar.pwdMgrButton.addTarget(self, action: #selector(BrowserToolbarHelper.SELdidClickPwdMgr), for: UIControlEvents.touchUpInside) setTintColor(buttonTintColor, forButtons: toolbar.actionButtons) } func SELdidClickBack() { toolbar.browserToolbarDelegate?.browserToolbarDidPressBack(toolbar, button: toolbar.backButton) } func SELdidClickShare() { toolbar.browserToolbarDelegate?.browserToolbarDidPressShare(toolbar, button: toolbar.shareButton) } func SELdidClickForward() { toolbar.browserToolbarDelegate?.browserToolbarDidPressForward(toolbar, button: toolbar.forwardButton) } func SELdidClickAddTab() { let app = UIApplication.shared.delegate as! AppDelegate app.tabManager.addTabAndSelect() app.browserViewController.urlBar.browserLocationViewDidTapLocation(app.browserViewController.urlBar.locationView) } func SELdidClickPwdMgr() { toolbar.browserToolbarDelegate?.browserToolbarDidPressPwdMgr(browserToolbar: toolbar, button: toolbar.pwdMgrButton) } } class BrowserToolbar: Toolbar, BrowserToolbarProtocol { weak var browserToolbarDelegate: BrowserToolbarDelegate? let shareButton = UIButton() // Just used to conform to protocol, never used on this class, see BraveURLBarView for the one that is used on iPad let pwdMgrButton = UIButton() let forwardButton = UIButton() let backButton = UIButton() let addTabButton = UIButton() var actionButtons: [UIButton] { return [self.shareButton, self.forwardButton, self.backButton, self.addTabButton] } var stopReloadButton: UIButton { get { return getApp().browserViewController.urlBar.locationView.stopReloadButton } } var helper: BrowserToolbarHelper? static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.buttonTintColor = BraveUX.ActionButtonPrivateTintColor themes[Theme.PrivateMode] = theme theme = Theme() theme.buttonTintColor = BraveUX.ActionButtonTintColor theme.backgroundColor = UIColor.clear themes[Theme.NormalMode] = theme return themes }() // This has to be here since init() calls it override init(frame: CGRect) { shareButton.accessibilityIdentifier = "BrowserToolbar.shareButton" super.init(frame: frame) self.helper = BrowserToolbarHelper(toolbar: self) self.backgroundColor = UIColor.clear addButtons(actionButtons) accessibilityNavigationStyle = .combined accessibilityLabel = Strings.Navigation_Toolbar } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateBackStatus(_ canGoBack: Bool) { backButton.isEnabled = canGoBack } func updateForwardStatus(_ canGoForward: Bool) { forwardButton.isEnabled = canGoForward } func updateReloadStatus(_ isLoading: Bool) { getApp().browserViewController.urlBar.locationView.stopReloadButtonIsLoading(isLoading) } func updatePageStatus(_ isWebPage: Bool) { stopReloadButton.isEnabled = isWebPage shareButton.isEnabled = isWebPage } } // MARK: UIAppearance extension BrowserToolbar { dynamic var actionButtonTintColor: UIColor? { get { return helper?.buttonTintColor } set { guard let value = newValue else { return } helper?.buttonTintColor = value } } } extension BrowserToolbar: Themeable { func applyTheme(_ themeName: String) { guard let theme = BrowserToolbar.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } actionButtonTintColor = theme.buttonTintColor! } }
mpl-2.0
883eb4a13810e46c81059f843f335777
35.567961
141
0.714722
5.312412
false
false
false
false
uacaps/PageMenu
Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/PageMenuOneViewController.swift
4
3024
// // PageMenuOneViewController.swift // PageMenuDemoTabbar // // Created by Niklas Fahl on 1/9/15. // Copyright (c) 2015 Niklas Fahl. All rights reserved. // import UIKit import PageMenu class PageMenuOneViewController: UIViewController { var pageMenu : CAPSPageMenu? @IBOutlet weak var userPhotoImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() userPhotoImageView.layer.cornerRadius = 8 // MARK: - Scroll menu setup // Initialize view controllers to display and place in array var controllerArray : [UIViewController] = [] let controller1 : TestTableViewController = TestTableViewController(nibName: "TestTableViewController", bundle: nil) controller1.title = "favorites" controllerArray.append(controller1) let controller2 : RecentsTableViewController = RecentsTableViewController(nibName: "RecentsTableViewController", bundle: nil) controller2.title = "recents" controllerArray.append(controller2) let controller3 : ContactsTableViewController = ContactsTableViewController(nibName: "ContactsTableViewController", bundle: nil) controller3.title = "contacts" controllerArray.append(controller3) for i in 0...10 { let controller3 : ContactsTableViewController = ContactsTableViewController(nibName: "ContactsTableViewController", bundle: nil) controller3.title = "contr\(i)" // controller3.view.backgroundColor = getRandomColor() controllerArray.append(controller3) } // Customize menu (Optional) let parameters: [CAPSPageMenuOption] = [ .scrollMenuBackgroundColor(UIColor.orange), .viewBackgroundColor(UIColor.white), .selectionIndicatorColor(UIColor.white), .unselectedMenuItemLabelColor(UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 0.4)), .menuItemFont(UIFont(name: "HelveticaNeue", size: 35.0)!), .menuHeight(44.0), .menuMargin(20.0), .selectionIndicatorHeight(0.0), .bottomMenuHairlineColor(UIColor.orange), .menuItemWidthBasedOnTitleTextWidth(true), .selectedMenuItemLabelColor(UIColor.white) ] // Initialize scroll menu pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0.0, y: 60.0, width: self.view.frame.width, height: self.view.frame.height - 60.0), pageMenuOptions: parameters) self.view.addSubview(pageMenu!.view) } func getRandomColor() -> UIColor{ let randomRed:CGFloat = CGFloat(drand48()) let randomGreen:CGFloat = CGFloat(drand48()) let randomBlue:CGFloat = CGFloat(drand48()) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) } }
bsd-3-clause
41a44899accda2891c1386419e2c2f20
38.272727
195
0.646825
5.048414
false
false
false
false
shorlander/firefox-ios
Client/Frontend/Browser/OpenSearch.swift
10
10763
/* 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 UIKit import Shared import Fuzi private let TypeSearch = "text/html" private let TypeSuggest = "application/x-suggestions+json" class OpenSearchEngine: NSObject, NSCoding { static let PreferredIconSize = 30 let shortName: String let engineID: String? let image: UIImage let isCustomEngine: Bool let searchTemplate: String fileprivate let suggestTemplate: String? fileprivate let SearchTermComponent = "{searchTerms}" fileprivate let LocaleTermComponent = "{moz:locale}" fileprivate lazy var searchQueryComponentKey: String? = self.getQueryArgFromTemplate() init(engineID: String?, shortName: String, image: UIImage, searchTemplate: String, suggestTemplate: String?, isCustomEngine: Bool) { self.shortName = shortName self.image = image self.searchTemplate = searchTemplate self.suggestTemplate = suggestTemplate self.isCustomEngine = isCustomEngine self.engineID = engineID } required init?(coder aDecoder: NSCoder) { // this catches the cases where bool encoded in Swift 2 needs to be decoded with decodeObject, but a Bool encoded in swift 3 needs // to be decoded using decodeBool. This catches the upgrade case to ensure that we are always able to fetch a keyed valye for isCustomEngine // http://stackoverflow.com/a/40034694 let isCustomEngine = aDecoder.decodeAsBool(forKey: "isCustomEngine") guard let searchTemplate = aDecoder.decodeObject(forKey: "searchTemplate") as? String, let shortName = aDecoder.decodeObject(forKey: "shortName") as? String, let image = aDecoder.decodeObject(forKey: "image") as? UIImage else { assertionFailure() return nil } self.searchTemplate = searchTemplate self.shortName = shortName self.isCustomEngine = isCustomEngine self.image = image self.engineID = aDecoder.decodeObject(forKey: "engineID") as? String self.suggestTemplate = nil } func encode(with aCoder: NSCoder) { aCoder.encode(searchTemplate, forKey: "searchTemplate") aCoder.encode(shortName, forKey: "shortName") aCoder.encode(isCustomEngine, forKey: "isCustomEngine") aCoder.encode(image, forKey: "image") aCoder.encode(engineID, forKey: "engineID") } /** * Returns the search URL for the given query. */ func searchURLForQuery(_ query: String) -> URL? { return getURLFromTemplate(searchTemplate, query: query) } /** * Return the arg that we use for searching for this engine * Problem: the search terms may not be a query arg, they may be part of the URL - how to deal with this? **/ fileprivate func getQueryArgFromTemplate() -> String? { // we have the replace the templates SearchTermComponent in order to make the template // a valid URL, otherwise we cannot do the conversion to NSURLComponents // and have to do flaky pattern matching instead. let placeholder = "PLACEHOLDER" let template = searchTemplate.replacingOccurrences(of: SearchTermComponent, with: placeholder) let components = URLComponents(string: template) let searchTerm = components?.queryItems?.filter { item in return item.value == placeholder } guard let term = searchTerm, !term.isEmpty else { return nil } return term[0].name } /** * check that the URL host contains the name of the search engine somewhere inside it **/ fileprivate func isSearchURLForEngine(_ url: URL?) -> Bool { guard let urlHost = url?.hostSLD, let queryEndIndex = searchTemplate.range(of: "?")?.lowerBound, let templateURL = URL(string: searchTemplate.substring(to: queryEndIndex)) else { return false } return urlHost == templateURL.hostSLD } /** * Returns the query that was used to construct a given search URL **/ func queryForSearchURL(_ url: URL?) -> String? { if isSearchURLForEngine(url) { if let key = searchQueryComponentKey, let value = url?.getQuery()[key] { return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding } } return nil } /** * Returns the search suggestion URL for the given query. */ func suggestURLForQuery(_ query: String) -> URL? { if let suggestTemplate = suggestTemplate { return getURLFromTemplate(suggestTemplate, query: query) } return nil } fileprivate func getURLFromTemplate(_ searchTemplate: String, query: String) -> URL? { if let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: CharacterSet.SearchTermsAllowedCharacterSet()) { // Escape the search template as well in case it contains not-safe characters like symbols let templateAllowedSet = NSMutableCharacterSet() templateAllowedSet.formUnion(with: CharacterSet.URLAllowedCharacterSet()) // Allow brackets since we use them in our template as our insertion point templateAllowedSet.formUnion(with: CharacterSet(charactersIn: "{}")) if let encodedSearchTemplate = searchTemplate.addingPercentEncoding(withAllowedCharacters: templateAllowedSet as CharacterSet) { let localeString = Locale.current.identifier let urlString = encodedSearchTemplate .replacingOccurrences(of: SearchTermComponent, with: escapedQuery, options: String.CompareOptions.literal, range: nil) .replacingOccurrences(of: LocaleTermComponent, with: localeString, options: String.CompareOptions.literal, range: nil) return URL(string: urlString) } } return nil } } /** * OpenSearch XML parser. * * This parser accepts standards-compliant OpenSearch 1.1 XML documents in addition to * the Firefox-specific search plugin format. * * OpenSearch spec: http://www.opensearch.org/Specifications/OpenSearch/1.1 */ class OpenSearchParser { fileprivate let pluginMode: Bool init(pluginMode: Bool) { self.pluginMode = pluginMode } func parse(_ file: String, engineID: String) -> OpenSearchEngine? { guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)) else { print("Invalid search file") return nil } guard let indexer = try? XMLDocument(data: data), let docIndexer = indexer.root else { print("Invalid XML document") return nil } let shortNameIndexer = docIndexer.children(tag: "ShortName") if shortNameIndexer.count != 1 { print("ShortName must appear exactly once") return nil } let shortName = shortNameIndexer[0].stringValue if shortName == "" { print("ShortName must contain text") return nil } let urlIndexers = docIndexer.children(tag: "Url") if urlIndexers.isEmpty { print("Url must appear at least once") return nil } var searchTemplate: String! var suggestTemplate: String? for urlIndexer in urlIndexers { let type = urlIndexer.attributes["type"] if type == nil { print("Url element requires a type attribute", terminator: "\n") return nil } if type != TypeSearch && type != TypeSuggest { // Not a supported search type. continue } var template = urlIndexer.attributes["template"] if template == nil { print("Url element requires a template attribute", terminator: "\n") return nil } if pluginMode { let paramIndexers = urlIndexer.children(tag: "Param") if !paramIndexers.isEmpty { template! += "?" var firstAdded = false for paramIndexer in paramIndexers { if firstAdded { template! += "&" } else { firstAdded = true } let name = paramIndexer.attributes["name"] let value = paramIndexer.attributes["value"] if name == nil || value == nil { print("Param element must have name and value attributes", terminator: "\n") return nil } template! += name! + "=" + value! } } } if type == TypeSearch { searchTemplate = template } else { suggestTemplate = template } } if searchTemplate == nil { print("Search engine must have a text/html type") return nil } let imageIndexers = docIndexer.children(tag: "Image") var largestImage = 0 var largestImageElement: XMLElement? // TODO: For now, just use the largest icon. for imageIndexer in imageIndexers { let imageWidth = Int(imageIndexer.attributes["width"] ?? "") let imageHeight = Int(imageIndexer.attributes["height"] ?? "") // Only accept square images. if imageWidth != imageHeight { continue } if let imageWidth = imageWidth { if imageWidth > largestImage { largestImage = imageWidth largestImageElement = imageIndexer } } } let uiImage: UIImage if let imageElement = largestImageElement, let imageURL = URL(string: imageElement.stringValue), let imageData = try? Data(contentsOf: imageURL), let image = UIImage.imageFromDataThreadSafe(imageData) { uiImage = image } else { print("Error: Invalid search image data") return nil } return OpenSearchEngine(engineID: engineID, shortName: shortName, image: uiImage, searchTemplate: searchTemplate, suggestTemplate: suggestTemplate, isCustomEngine: false) } }
mpl-2.0
9e2e44b167f30617710fb00ff635d57e
37.302491
178
0.606058
5.389584
false
false
false
false
RamonGilabert/Prodam
Prodam/Prodam/TextSplitter.swift
1
2530
import Cocoa class TextSplitter: NSObject { class func checkNewStringForTextField(stringValue: String, fontSize: CGFloat) -> NSAttributedString { let arrayOfWords = split(stringValue, maxSplit: 1, allowEmptySlices: true, isSeparator: {$0 == " "}) let firstString = arrayOfWords[0] let finalMutableString = NSMutableAttributedString() var secondString = "" var mutableStringFirstPart = NSMutableAttributedString() var mutableStringSecondPart = NSMutableAttributedString() if arrayOfWords.count > 1 { secondString = arrayOfWords[1] mutableStringFirstPart = handleFirstPartOfSentence(firstString + " ", fontSize: fontSize) mutableStringSecondPart = NSMutableAttributedString(string: secondString) mutableStringSecondPart.addAttribute(NSFontAttributeName, value: NSFont(name: "HelveticaNeue-Medium", size: fontSize)!, range: NSMakeRange(0, secondString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))) mutableStringSecondPart.addAttribute(NSForegroundColorAttributeName, value: NSColor(calibratedHue:0, saturation:0, brightness:0.2, alpha:1), range: NSMakeRange(0, secondString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))) } else { mutableStringFirstPart = handleFirstPartOfSentence(firstString, fontSize: fontSize) } finalMutableString.appendAttributedString(mutableStringFirstPart) finalMutableString.appendAttributedString(mutableStringSecondPart) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.CenterTextAlignment finalMutableString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, finalMutableString.length)) return finalMutableString } // MARK: Helper methods class func handleFirstPartOfSentence(firstString: String, fontSize: CGFloat) -> NSMutableAttributedString { let mutableString = NSMutableAttributedString(string: firstString) mutableString.addAttribute(NSFontAttributeName, value: NSFont(name: "HelveticaNeue-Light", size: fontSize)!, range: NSMakeRange(0, firstString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))) mutableString.addAttribute(NSForegroundColorAttributeName, value: NSColor(calibratedHue:0, saturation:0, brightness:0.2, alpha:1), range: NSMakeRange(0, firstString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))) return mutableString } }
mit
d7ea63638ad27c3086ff5182ab6b5316
56.5
238
0.755731
5.87007
false
false
false
false
ylovesy/CodeFun
wuzhentao/averageOfLevels.swift
1
1862
//Input: //3 /// \ //9 20 /// \ //15 7 //Output: [3, 14.5, 11] //Explanation: //The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. //Note: //The range of node's value is in the range of 32-bit signed integer. //Seen this question in a real interview before? Yes No //Difficulty:Easy //Total Accepted:8.5K //Total Submissions:14.7K //Contributor: yangshun //Subscribe to see which companies asked this question. // //Related Topics //Tree //S public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } class Solution { func averageOfLevels(_ root: TreeNode?) -> [Double] { guard root != nil else { return [] } var container:[TreeNode] = [] container.append(root!) var result:[Double] = [] while !container.isEmpty { var nodeSum:Double = 0.0 let nodeCount = container.count var index = 0 while index < nodeCount { let node = container.first! nodeSum += Double(node.val) container.removeFirst() if let left = node.left { container.append(left) } if let right = node.right { container.append(right) } index += 1 } result.append(nodeSum/Double(nodeCount)) } return result } } let root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.right?.left = TreeNode(15) root.right?.right = TreeNode(7) let s = Solution() s.averageOfLevels(root)
apache-2.0
4298a93c365d863f5aead89ab430f13b
23.181818
116
0.540816
3.92
false
false
false
false