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
JV17/MyCal-iWatch
MyCal-Calculator/JVTouchEventsWindow.swift
1
3838
// // JVTouchEventsWindow.swift // MyCal-Calculator // // Created by Jorge Valbuena on 2015-04-19. // Copyright (c) 2015 Jorge Valbuena. All rights reserved. // import UIKit class JVTouchEventsImageView: NSObject { var imageViewArray = Array<UIImageView>() init(count: Int) { super.init() for(var x = 0; x < count; x++) { let imgView = UIImageView(image: UIImage(named: "JVTouchImage")) self.imageViewArray.append(imgView) } } func popTouchImageView() -> UIImageView { let touchImageView: UIImageView = self.imageViewArray.first! self.imageViewArray.removeAtIndex(0) return touchImageView } func pushTouchImageView(touchImageView: UIImageView) { self.imageViewArray.append(touchImageView) } } class JVTouchEventsWindow: UIWindow { var touchImageViewQueue = JVTouchEventsImageView(count: 8) var touchImageViewDic = NSMutableDictionary() override func sendEvent(event: UIEvent) { let touches: Set<UITouch> = event.allTouches()! for touch: UITouch in touches { switch touch.phase { case UITouchPhase.Began: self.touchBegan(touch) break case UITouchPhase.Moved: self.touchMoved(touch) break case UITouchPhase.Ended: self.touchEnded(touch) break case UITouchPhase.Cancelled: self.touchEnded(touch) break default: break } } super.sendEvent(event) } func touchBegan(touch: UITouch) { let touchImageView = self.touchImageViewQueue.popTouchImageView() touchImageView.center = touch.locationInView(self) self.addSubview(touchImageView) touchImageView.alpha = 0.0 touchImageView.transform = CGAffineTransformMakeScale(1.13, 1.13) self.setTouchImageView(touchImageView, touch: touch) UIView.animateWithDuration(0.1, animations: { () -> Void in touchImageView.alpha = 1.0 touchImageView.transform = CGAffineTransformMakeScale(1, 1) }) } func touchMoved(touch: UITouch) { let touchImageView = self.touchImageViewForTouch(touch) touchImageView.center = touch.locationInView(self) } func touchEnded(touch: UITouch) { let touchImageView = self.touchImageViewForTouch(touch) UIView.animateWithDuration(0.1, animations: { () -> Void in touchImageView.alpha = 0.0 touchImageView.transform = CGAffineTransformMakeScale(1.13, 1.13) }) { (value: Bool) -> Void in touchImageView.removeFromSuperview() touchImageView.alpha = 1.0 self.touchImageViewQueue.pushTouchImageView(touchImageView) self.removeTouchImageViewForTouch(touch) } } func touchImageViewForTouch(touch: UITouch) -> UIImageView { let touchStringHash = NSString(format: "%d", touch.hash) return self.touchImageViewDic[touchStringHash] as! UIImageView } func setTouchImageView(imageView: UIImageView, touch: UITouch) { let touchStringHash = NSString(format: "%d", touch.hash) self.touchImageViewDic.setObject(imageView, forKey: touchStringHash) } func removeTouchImageViewForTouch(touch: UITouch) { let touchStringHash = NSString(format: "%d", touch.hash) self.touchImageViewDic.removeObjectForKey(touchStringHash) } }
mit
13957b6389cf8151f5353c90157571df
29.228346
81
0.593278
4.907928
false
false
false
false
phr85/Shopy
Shopy/QueuedAlertPresenter.swift
1
7103
// // QueuedAlertPresenter.swift // RandomReminders // // Created by Antonio Nunes on 29/02/16. // Copyright © 2016 SintraWorks. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public typealias AlertActionHandler = () -> () /** An AlertAction instance encapsulates all the required information to create an alert action. */ public struct AlertAction { var title: String var style: UIAlertActionStyle var handler: AlertActionHandler? var enabled: Bool var isPreferredAction: Bool /** Initializes an AlertAction instance with the passed in values. All parameteres have default values, so pass only those you need. - title: Optional title for the action. Defaults to an empty string. - style: Alert style (UIAlertActionStyle). Defaults to .Default - isPreferredAction: Whether the action is the preferred action of the alert. Defaults to false. - handler: Optional closure containing code to execute when the action is clicked. */ public init(title: String = "", style: UIAlertActionStyle = .default, enabled: Bool = true, isPreferredAction: Bool = false, handler: AlertActionHandler? = nil) { self.title = title self.style = style self.enabled = enabled self.isPreferredAction = isPreferredAction self.handler = handler } } /** An AlertInfo instance encapsulates all the required information to create an Alert, including its actions. */ public struct AlertInfo { var title: String? var message: String? var style: UIAlertControllerStyle var actions: [AlertAction]? /** Initializes an AlertInfo instance with the passed in values. All parameteres have default values, so pass only those you need. - title: Optional title for the alert. Defaults to an empty string. - message: Optional message body for the alert. Defaults to an empty string - style: Alert style (UIAlertControllerStyle). Defaults to .Alert - actions: Optional array of AlertActions. Defaults to nil. */ public init(title: String? = "", message: String? = "", style: UIAlertControllerStyle = .alert, actions: [AlertAction]? = nil) { self.title = title self.message = message self.style = style self.actions = actions } } /** A QueuedAlertPresenter serializes the presentation of alerts. Use it when your code needs to present alerts in rapid succession, where the user may not be able to keep up with the alerts. Using QueuedAlertPresenter instead of UIAlertController directly, ensures your user gets to see all the alerts your code creates. To present an alert create an instance of AlertInfo then add it to the sharedAlertPresenter with addAlert(alertInfo). AlertInfo holds the information for an individual alert you want to present. */ open class QueuedAlertPresenter { open static let sharedAlertPresenter = QueuedAlertPresenter() fileprivate var queuedAlerts = [AlertInfo]() fileprivate var presentedAlert: AlertInfo? /** Adds an alert to the alert queue, and triggers presentation of the queued alerts. */ open func addAlert(_ alertInfo: AlertInfo) { objc_sync_enter(self) defer { objc_sync_exit(self) } self.queuedAlerts.append(alertInfo) self.presentAlerts() } /** Presents queued alerts in succession. - Returns: true if an alert was presented, false if no alert was presented. */ @discardableResult fileprivate func presentAlerts() -> Bool { if self.presentedAlert == nil { if let alertToPresent = self.queuedAlerts.first { self.presentedAlert = alertToPresent self.presentAlert(alertToPresent) return true } } return false } fileprivate func presentAlert(_ alertInfo :AlertInfo) { let alertController = UIAlertController(title: alertInfo.title, message:alertInfo.message, preferredStyle: alertInfo.style) if let actions = alertInfo.actions { for infoAction in actions { let alertAction = UIAlertAction(title: infoAction.title, style: infoAction.style) { action -> Void in infoAction.handler?() self.presentedAlert = nil self.queuedAlerts.removeFirst() self.presentAlerts() } alertAction.isEnabled = infoAction.enabled alertController.addAction(alertAction) if #available(iOS 9.0, *) { if infoAction.isPreferredAction { alertController.preferredAction = alertAction } } } } self.validViewControllerForPresentation.presentViewControllerOnMainThread(alertController, animated: true, completion: nil) } // Ensure we present on a view controller that is neither being dismissed, nor presenting another view controller. fileprivate var validViewControllerForPresentation: UIViewController { guard let rootViewController = UIApplication.shared.keyWindow?.rootViewController else { fatalError("There is no root view controller on the key window") } guard var presentedViewController = rootViewController.presentedViewController else { return rootViewController } while let candidate = presentedViewController.presentedViewController { presentedViewController = candidate } while presentedViewController.isBeingDismissed { guard let ancestor = presentedViewController.presentingViewController else { fatalError("Exhausted view controller hierarchy, while looking for a controller that is not being dismissed") } presentedViewController = ancestor } return presentedViewController } }
mit
9b86f3404cc5218da8b8610662921cc0
41.023669
200
0.681921
5.276374
false
false
false
false
maranas/crazycells
crazycells/MasterViewController.swift
1
3972
// // MasterViewController.swift // crazycells // // Created by Moises Anthony Aranas on 7/11/15. // Copyright © 2015 ganglion software. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() var cellAnimationType = GLSTableViewCellAnimationType.random() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MasterViewController.changeAnimationMode(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } self.tableView.separatorColor = UIColor.clear for number in 0...200 { objects.append("This is the number \(number)" as AnyObject) } } override func viewWillAppear(_ animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func changeAnimationMode(_ sender: AnyObject?) { self.cellAnimationType = GLSTableViewCellAnimationType.random() } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! String let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object as AnyObject controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let object = objects[indexPath.row] as! String cell.textLabel!.text = object return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { objects.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let customCell = cell as? GLSTableViewCell { customCell.animationType = self.cellAnimationType customCell.animateIn(0.8) } } }
mit
6953e78e4866fe3119bf010283f42b78
36.462264
145
0.677411
5.484807
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Library/Kingfisher/UIImage+Extension.swift
3
7052
// // UIImage+Decode.swift // Kingfisher // // Created by Wei Wang on 15/4/7. // // Copyright (c) 2015 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. import UIKit import ImageIO import MobileCoreServices private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8] private let jpgHeaderIF: [UInt8] = [0xFF] private let gifHeader: [UInt8] = [0x47, 0x49, 0x46] // MARK: - Image format enum ImageFormat { case Unknown, PNG, JPEG, GIF } extension NSData { var kf_imageFormat: ImageFormat { var buffer = [UInt8](count: 8, repeatedValue: 0) self.getBytes(&buffer, length: 8) if buffer == pngHeader { return .PNG } else if buffer[0] == jpgHeaderSOI[0] && buffer[1] == jpgHeaderSOI[1] && buffer[2] == jpgHeaderIF[0] { return .JPEG } else if buffer[0] == gifHeader[0] && buffer[1] == gifHeader[1] && buffer[2] == gifHeader[2] { return .GIF } return .Unknown } } // MARK: - Decode extension UIImage { func kf_decodedImage() -> UIImage? { return self.kf_decodedImage(scale: self.scale) } func kf_decodedImage(scale scale: CGFloat) -> UIImage? { let imageRef = self.CGImage let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue let contextHolder = UnsafeMutablePointer<Void>() let context = CGBitmapContextCreate(contextHolder, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo) if let context = context { let rect = CGRectMake(0, 0, CGFloat(CGImageGetWidth(imageRef)), CGFloat(CGImageGetHeight(imageRef))) CGContextDrawImage(context, rect, imageRef) let decompressedImageRef = CGBitmapContextCreateImage(context) return UIImage(CGImage: decompressedImageRef!, scale: scale, orientation: self.imageOrientation) } else { return nil } } } // MARK: - Normalization extension UIImage { public func kf_normalizedImage() -> UIImage { if imageOrientation == .Up { return self } UIGraphicsBeginImageContextWithOptions(size, false, scale) drawInRect(CGRect(origin: CGPointZero, size: size)) let normalizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return normalizedImage } } // MARK: - Create images from data extension UIImage { static func kf_imageWithData(data: NSData, scale: CGFloat) -> UIImage? { var image: UIImage? switch data.kf_imageFormat { case .JPEG: image = UIImage(data: data, scale: scale) case .PNG: image = UIImage(data: data, scale: scale) case .GIF: image = UIImage.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0) case .Unknown: image = nil } return image } } // MARK: - GIF func UIImageGIFRepresentation(image: UIImage) -> NSData? { return UIImageGIFRepresentation(image, duration: 0.0, repeatCount: 0) } func UIImageGIFRepresentation(image: UIImage, duration: NSTimeInterval, repeatCount: Int) -> NSData? { guard let images = image.images else { return nil } let frameCount = images.count let gifDuration = duration <= 0.0 ? image.duration / Double(frameCount) : duration / Double(frameCount) let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]] let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]] let data = NSMutableData() guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else { return nil } CGImageDestinationSetProperties(destination, imageProperties) for image in images { CGImageDestinationAddImage(destination, image.CGImage!, frameProperties) } return CGImageDestinationFinalize(destination) ? NSData(data: data) : nil } extension UIImage { static func kf_animatedImageWithGIFData(gifData data: NSData) -> UIImage? { return kf_animatedImageWithGIFData(gifData: data, scale: UIScreen.mainScreen().scale, duration: 0.0) } static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval) -> UIImage? { let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] guard let imageSource = CGImageSourceCreateWithData(data, options) else { return nil } let frameCount = CGImageSourceGetCount(imageSource) var images = [UIImage]() var gifDuration = 0.0 for i in 0 ..< frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { return nil } guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil), gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary, frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else { return nil } gifDuration += frameDuration.doubleValue images.append(UIImage(CGImage: imageRef, scale: scale, orientation: .Up)) } if frameCount == 1 { return images.first } else { return UIImage.animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration) } } }
apache-2.0
f0284504536745b19bd1b55f13778552
37.118919
151
0.661089
4.695073
false
false
false
false
robocopklaus/sportskanone
Sportskanone/Views/HealthDataSyncViewController.swift
1
3540
// // HealthDataSyncViewController.swift // Sportskanone // // Created by Fabian Pahl on 30.03.17. // Copyright © 2017 21st digital GmbH. All rights reserved. // import UIKit import ReactiveCocoa import ReactiveSwift final class HealthDataSyncViewController<Store: StoreType>: UIViewController { private let verticalStackView = UIStackView() private let logoImageView = UIImageView() private let titleLabel = HeadlineLabel() private let textLabel = TextLabel() private let activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray) private let (lifetime, token) = Lifetime.make() private let viewModel: HealthDataSyncViewModel<Store> // MARK: - Object Life Cycle init(viewModel: HealthDataSyncViewModel<Store>) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle override func loadView() { let view = UIView() view.addSubview(verticalStackView) verticalStackView.addArrangedSubview(logoImageView) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(titleLabel) verticalStackView.addArrangedSubview(textLabel) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(activityView) self.view = view setupConstraints() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white verticalStackView.axis = .vertical verticalStackView.alignment = .center verticalStackView.spacing = 10 logoImageView.contentMode = .scaleAspectFit logoImageView.image = UIImage(named: viewModel.logoName) titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .byWordWrapping textLabel.lineBreakMode = .byWordWrapping textLabel.numberOfLines = 0 viewModel.healthDataSyncAction.errors .take(during: lifetime) .observe(on: UIScheduler()) .observeValues { [weak self] error in self?.presentError(error: error, title: "Error.Default.Title".localized) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupBindings() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) viewModel.healthDataSyncAction.apply().start() } // MARK: - Styling func setupConstraints() { verticalStackView.translatesAutoresizingMaskIntoConstraints = false verticalStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true verticalStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true logoImageView.heightAnchor.constraint(equalTo: logoImageView.widthAnchor).isActive = true logoImageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5).isActive = true titleLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7).isActive = true textLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8).isActive = true } // MARK: - Reactive Bindings func setupBindings() { titleLabel.reactive.text <~ viewModel.title textLabel.reactive.text <~ viewModel.text activityView.reactive.isAnimating <~ viewModel.healthDataSyncAction.isExecuting } }
mit
f26660d229a8159d1587f4b3de4a7b28
28.991525
100
0.730997
5.062947
false
false
false
false
ingresse/ios-sdk
IngresseSDK/Services/AuthService.swift
1
19511
// // Copyright © 2017 Gondek. All rights reserved. // public class AuthService: BaseService { /// Login by company /// /// - Parameters: /// - email: user's email /// - pass: password /// - onSuccess: Success callback /// - onError: Fail callback @objc public func companyLogin(_ email: String, andPassword pass: String, onSuccess: @escaping (_ response: [CompanyData]) -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("company-login") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } let params = ["email": email, "password": pass] client.restClient.POST(request: request, parameters: params, onSuccess: { response in guard let logged = response["status"] as? Bool, logged else { let error = APIError.Builder() .setCode(-1) .setError(response["message"] as! String) .build() onError(error) return } guard let data = response["data"] as? [[String: Any]], let companyArray = JSONDecoder().decodeArray(of: [CompanyData].self, from: data) else { onError(APIError.getDefaultError()) return } onSuccess(companyArray) }, onError: onError) } /// Login with email and password /// /// - Parameters: /// - email: user's email /// - pass: password /// - onSuccess: Success callback /// - onError: Fail callback public func loginWithEmail(_ email: String, andPassword pass: String, onSuccess: @escaping (_ response: IngresseUser) -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("login/") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } let params = ["email": email, "password": pass] client.restClient.POST(request: request, parameters: params, onSuccess: { response in guard let logged = response["status"] as? Bool, logged else { let error = APIError.Builder() .setCode(-1) .setError(response["message"] as! String) .build() onError(error) return } guard let data = response["data"] as? [String: Any] else { onError(APIError.getDefaultError()) return } let user = IngresseUser.login(loginData: data) self.getUserData(userId: String(user.userId), userToken: user.token, onSuccess: { userData in userData.authToken = user.authToken onSuccess(userData) }, onError: onError) }, onError: onError) } /// Login with facebook /// /// - Parameters: /// - email: user's email /// - fbToken: facebook access token /// - fbUserId: facebook user id /// - onSuccess: Success callback /// - onError: Fail callback public func loginWithFacebook(email: String, fbToken: String, fbUserId: String, onSuccess: @escaping (_ response: IngresseUser) -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("login/facebook") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } let params = ["email": email, "fbToken": fbToken, "fbUserId": fbUserId] client.restClient.POST(request: request, parameters: params, onSuccess: { response in guard let logged = response["status"] as? Bool, logged else { let error = APIError.Builder() .setCode(-1) .setError(response["message"] as! String) .build() onError(error) return } guard let data = response["data"] as? [String: Any] else { onError(APIError.getDefaultError()) return } let user = IngresseUser.login(loginData: data) self.getUserData( userId: String(user.userId), userToken: user.token, onSuccess: { userData in userData.authToken = user.authToken onSuccess(userData) }, onError: onError) }, onError: onError) } /// Login with Apple /// /// - Parameters: /// - userIdentifier: Apple userIdentifier /// - identityToken: Apple identityToken /// - authorizationCode: Apple authorizationCode /// - onSuccess: Success callback /// - onError: Fail callback public func loginWithApple(userIdentifier: String, identityToken: String, authorizationCode: String, onSuccess: @escaping (_ response: IngresseUser) -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("login/apple") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } let params = ["userIdentifier": userIdentifier, "identityToken": identityToken, "authorizationCode": authorizationCode] client.restClient.POST(request: request, parameters: params, onSuccess: { response in guard let logged = response["status"] as? Bool, logged else { let error = APIError.Builder() .setCode(-1) .setError(response["message"] as! String) .build() onError(error) return } guard let data = response["data"] as? [String: Any] else { onError(APIError.getDefaultError()) return } let user = IngresseUser.login(loginData: data) self.getUserData( userId: String(user.userId), userToken: user.token, onSuccess: { userData in userData.authToken = user.authToken onSuccess(userData) }, onError: onError) }, onError: onError) } /// Complete user data /// /// - Parameters: /// - userId: Logged user's id /// - userToken: Logged user's token /// - fields: User attributes to get from API /// - onSuccess: Success callback /// - onError: Fail callback public func getUserData(userId: String, userToken: String, fields: String? = nil, onSuccess: @escaping (_ user: IngresseUser) -> Void, onError: @escaping ErrorHandler) { let fieldsArray = [ "id", "name", "lastname", "document", "email", "zip", "number", "complement", "city", "state", "street", "district", "ddi", "phone", "verified", "fbUserId", "type", "pictures", "picture", "birthdate"] let fieldsValue = fields ?? fieldsArray.joined(separator: ",") let builder = URLBuilder(client: client) .setPath("user/\(userId)") .addParameter(key: "usertoken", value: userToken) .addParameter(key: "fields", value: fieldsValue) guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } client.restClient.GET(request: request, onSuccess: { response in guard let userData = JSONDecoder().decodeDict(of: UserData.self, from: response) else { return onError(APIError.getDefaultError()) } let user = IngresseUser() user.data = userData user.userId = Int(userId) ?? -1 user.token = userToken IngresseUser.user = user onSuccess(user) }, onError: onError) } /// Recover user password /// /// - Parameters: /// - email: email of user to request password /// - onSuccess: Success callback /// - onError: Fail callback public func recoverPassword(email: String, onSuccess: @escaping () -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("recover-password") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } let params = ["email": email] client.restClient.POST(request: request, parameters: params, onSuccess: { _ in onSuccess() }, onError: onError) } /// Validate recovery hash /// /// - Parameters: /// - email: email of user to request password /// - token: hash received from email /// - onSuccess: Success callback /// - onError: Fail callback public func validateHash(_ token: String, email: String, onSuccess: @escaping () -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("recover-validate") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } var params = ["email": email] params["hash"] = token client.restClient.POST(request: request, parameters: params, onSuccess: { _ in onSuccess() }, onError: onError) } /// Validate Incomplete User Token /// /// - Parameters: /// - email: email of user to request activate account /// - token: token received from email /// - onSuccess: Success callback /// - onError: Fail callback public func validateIncompleteUserToken(_ token: String, email: String, onSuccess: @escaping (String) -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("activate-user-validate") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } var params = ["email": email] params["token"] = token client.restClient.POST(request: request, parameters: params, onSuccess: { response in guard let status = response["status"] as? String else { onError(APIError.getDefaultError()) return } onSuccess(status) }, onError: onError) } /// Activate User /// /// - Parameters: /// - email: email of user to request activate /// - password: password to update /// - token: token received from email /// - onSuccess: Success callback /// - onError: Fail callback public func activateUser(email: String, password: String, token: String, onSuccess: @escaping (_ user: IngresseUser) -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("activate-user") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } var params = ["email": email] params["password"] = password params["token"] = token client.restClient.POST(request: request, parameters: params, onSuccess: { response in guard let status = response["status"] as? Int else { onError(APIError.getDefaultError()) return } if status == 0 { guard let message = response["message"] as? [String] else { onError(APIError.getDefaultError()) return } let error = APIError.Builder() .setCode(0) .setTitle("Verifique suas informações") .setMessage(message.joined(separator: "\n")) .setResponse(response) .build() onError(error) return } let data = response["data"] as! [String: Any] _ = IngresseUser.login(loginData: data) IngresseUser.fillData(userData: data) onSuccess(IngresseUser.user!) }, onError: onError) } /// Update user password /// /// - Parameters: /// - email: email of user to request password /// - password: password to update /// - token: hash received from email /// - onSuccess: Success callback /// - onError: Fail callback public func updatePassword(email: String, password: String, token: String, onSuccess: @escaping () -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("recover-update-password") guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } var params = ["email": email] params["password"] = password params["hash"] = token client.restClient.POST(request: request, parameters: params, onSuccess: { _ in onSuccess() }, onError: onError) } /// Change profile password /// /// - Parameters: /// - currentPassword: current user password /// - newPassword: user new password /// - token: user logged token /// - userId: user logged id /// - onSuccess: success callback /// - onError: fail callback public func changeProfilePassword(currentPassword: String, newPassword: String, token: String, userId: String, onSuccess: @escaping () -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("user/\(userId)") .addParameter(key: "usertoken", value: token) var params = ["password": currentPassword] params["newPassword"] = newPassword guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } client.restClient.POST(request: request, parameters: params, onSuccess: { response in guard let status = response["status"] as? Int else { onError(APIError.getDefaultError()) return } if status == 0 { guard let message = response["message"] as? [String] else { onError(APIError.getDefaultError()) return } let error = APIError.Builder() .setCode(0) .setTitle("Verifique suas informações") .setMessage(message.joined(separator: "\n")) .setResponse(response) .build() onError(error) return } onSuccess() }, onError: onError) } /// Renew User Auth Token /// /// - Parameters: /// - userToken: Logged user's token /// - onSuccess: success callback /// - onError: fail callback public func renewAuthToken(userToken: String, onSuccess: @escaping (String) -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("/login/renew-token") .addParameter(key: "usertoken", value: userToken) guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } client.restClient.GET(request: request, onSuccess: { response in guard let authToken = response["authToken"] as? String else { onError(APIError.getDefaultError()) return } onSuccess(authToken) }, onError: onError) } /// Get Two Factor token for user /// /// - Parameters: /// - deviceId: unique id of user's device /// - otpCode: one time password, sent via sms /// - onSuccess: success callback /// - onError: fail callback public func createTwoFactorToken(userToken: String, deviceId: String, otpCode: String, onSuccess: @escaping (Response.Auth.TwoFactor) -> Void, onError: @escaping ErrorHandler) { let builder = URLBuilder(client: client) .setPath("two-factor") .addParameter(key: "usertoken", value: userToken) guard let request = try? builder.build() else { return onError(APIError.getDefaultError()) } let header = ["X-INGRESSE-OTP": otpCode, "X-INGRESSE-DEVICE": deviceId] client.restClient.POST(request: request, customHeader: header, onSuccess: { response in guard let twoFactorResponse = JSONDecoder().decodeDict(of: Response.Auth.TwoFactor.self, from: response) else { onError(APIError.getDefaultError()) return } onSuccess(twoFactorResponse) }, onError: onError) } }
mit
7417830b2f6e73d8708fc610314fff43
33.832143
165
0.490772
5.483835
false
false
false
false
yanif/circator
MetabolicCompass/View Controller/DailyProgressViewController.swift
1
11896
// // DailyProgressViewController.swift // MetabolicCompass // // Created by Artem Usachov on 5/16/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import Foundation import UIKit import MetabolicCompassKit import Async import SwiftDate import Crashlytics enum UIUserInterfaceIdiom : Int { case Unspecified case Phone case Pad } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width static let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_6 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6P = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0 static let IS_IPAD = UIDevice.currentDevice().userInterfaceIdiom == .Pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0 } class DailyProgressViewController : UIViewController, DailyChartModelProtocol { var dailyChartModel = DailyChartModel() @IBOutlet weak var daysTableView: UITableView! @IBOutlet weak var dailyProgressChartView: MetabolicDailyProgressChartView! @IBOutlet weak var dailyProgressChartScrollView: UIScrollView! @IBOutlet weak var dailyProgressChartDaysTable: UITableView! @IBOutlet weak var mainScrollView: UIScrollView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var fastingSquare: UIView! @IBOutlet weak var sleepSquare: UIView! @IBOutlet weak var eatingSquare: UIView! @IBOutlet weak var exerciseSquare: UIView! @IBOutlet weak var dailyEatingLabel: UILabel! @IBOutlet weak var maxDailyFastingLabel: UILabel! @IBOutlet weak var lastAteLabel: UILabel! @IBOutlet weak var chartLegendHeight: NSLayoutConstraint! @IBOutlet weak var dailyValuesTopMargin: NSLayoutConstraint! @IBOutlet weak var dailyEatingContainer: UIView! @IBOutlet weak var maxDailyFastingContainer: UIView! @IBOutlet weak var lastAteContainer: UIView! @IBOutlet weak var scrollRecentButton: UIButton! @IBOutlet weak var scrollOlderButton: UIButton! private var dailyEatingTip: TapTip! = nil private var maxDailyFastingTip: TapTip! = nil private var lastAteTip: TapTip! = nil private var updateContentWithAnimation = true private var loadStart: NSDate! = nil //MARK: View life circle override func viewDidLoad() { super.viewDidLoad() self.setupTooltips() self.fastingSquare.layer.borderColor = UIColor.colorWithHexString("#ffffff", alpha: 0.3)?.CGColor self.dailyChartModel.daysTableView = self.daysTableView self.dailyChartModel.delegate = self self.dailyChartModel.registerCells() self.dailyProgressChartDaysTable.dataSource = self.dailyChartModel self.dailyProgressChartView.changeColorCompletion = { _ in Async.main { self.updateContentWithAnimation = false self.dailyChartModel.toggleHighlightFasting() if self.dailyChartModel.highlightFasting { self.fastingSquare.backgroundColor = MetabolicDailyProgressChartView.highlightFastingColor self.sleepSquare.backgroundColor = MetabolicDailyProgressChartView.mutedSleepColor self.eatingSquare.backgroundColor = MetabolicDailyProgressChartView.mutedEatingColor self.exerciseSquare.backgroundColor = MetabolicDailyProgressChartView.mutedExerciseColor } else { self.fastingSquare.backgroundColor = MetabolicDailyProgressChartView.fastingColor self.sleepSquare.backgroundColor = MetabolicDailyProgressChartView.sleepColor self.eatingSquare.backgroundColor = MetabolicDailyProgressChartView.eatingColor self.exerciseSquare.backgroundColor = MetabolicDailyProgressChartView.exerciseColor } self.contentDidUpdate() } } self.dailyProgressChartView.prepareChart() self.scrollRecentButton.setImage(UIImage(named: "icon-daily-progress-scroll-recent"), forState: .Normal) self.scrollOlderButton.setImage(UIImage(named: "icon-daily-progress-scroll-older"), forState: .Normal) self.scrollRecentButton.addTarget(self, action: #selector(scrollRecent), forControlEvents: .TouchUpInside) self.scrollOlderButton.addTarget(self, action: #selector(scrollOlder), forControlEvents: .TouchUpInside) self.scrollRecentButton.enabled = false self.scrollOlderButton.enabled = true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let width = self.dailyProgressChartScrollView.contentSize.width let height = CGRectGetHeight(self.dailyProgressChartView.frame) self.dailyProgressChartScrollView.contentSize = CGSizeMake(width, height) self.dailyChartModel.updateRowHeight() let mainScrollViewContentWidth = CGRectGetWidth(self.mainScrollView.frame) let mainScrollViewContentHeight = self.mainScrollView.contentSize.height self.mainScrollView.contentSize = CGSizeMake(mainScrollViewContentWidth, mainScrollViewContentHeight) //updating chart data self.contentDidUpdate() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) logContentView() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) logContentView(false) } func logContentView(asAppear: Bool = true) { Answers.logContentViewWithName("Body Clock", contentType: asAppear ? "Appear" : "Disappear", contentId: NSDate().toString(DateFormat.Custom("YYYY-MM-dd:HH")), customAttributes: nil) } func setupTooltips() { let dailyEatingMsg = "Total time spent eating meals today (in hours and minutes)" dailyEatingTip = TapTip(forView: dailyEatingContainer, text: dailyEatingMsg, asTop: true) dailyEatingContainer.addGestureRecognizer(dailyEatingTip.tapRecognizer) dailyEatingContainer.userInteractionEnabled = true let maxDailyFastingMsg = "Maximum duration spent in a fasting state in the last 24 hours. You are fasting when not eating, that is, while you are awake, sleeping or exercising." maxDailyFastingTip = TapTip(forView: maxDailyFastingContainer, text: maxDailyFastingMsg, asTop: true) maxDailyFastingContainer.addGestureRecognizer(maxDailyFastingTip.tapRecognizer) maxDailyFastingContainer.userInteractionEnabled = true let lastAteMsg = "Time elapsed since your last meal (in hours and minutes)" lastAteTip = TapTip(forView: lastAteContainer, text: lastAteMsg, asTop: true) lastAteContainer.addGestureRecognizer(lastAteTip.tapRecognizer) lastAteContainer.userInteractionEnabled = true } func contentDidUpdate(withDailyProgress dailyProgress: Bool = true) { Async.main { if self.activityIndicator != nil { self.activityIndicator.startAnimating() self.loadStart = NSDate() } self.dailyChartModel.prepareChartData() if dailyProgress { self.dailyChartModel.getDailyProgress() } } } //MARK: DailyChartModelProtocol func dataCollectingFinished() { Async.main { self.activityIndicator.stopAnimating() if self.loadStart != nil { log.info("BODY CLOCK query time: \((NSDate().timeIntervalSinceReferenceDate - self.loadStart.timeIntervalSinceReferenceDate))") } self.dailyProgressChartView.updateChartData(self.updateContentWithAnimation, valuesArr: self.dailyChartModel.chartDataArray, chartColorsArray: self.dailyChartModel.chartColorsArray) self.updateContentWithAnimation = true self.dailyProgressChartView.setNeedsDisplay() } } func dailyProgressStatCollected() { self.dailyEatingLabel.attributedText = self.dailyChartModel.eatingText.formatTextWithRegex("[-+]?(\\d*[.,])?\\d+", format: [NSForegroundColorAttributeName: UIColor.whiteColor()], defaultFormat: [NSForegroundColorAttributeName: UIColor.colorWithHexString("#ffffff", alpha: 0.3)!]) self.maxDailyFastingLabel.attributedText = self.dailyChartModel.fastingText.formatTextWithRegex("[-+]?(\\d*[.,])?\\d+", format: [NSForegroundColorAttributeName: UIColor.whiteColor()], defaultFormat: [NSForegroundColorAttributeName: UIColor.colorWithHexString("#ffffff", alpha: 0.3)!]) self.lastAteLabel.attributedText = self.dailyChartModel.lastAteText.formatTextWithRegex("[-+]?(\\d*[.,])?\\d+", format: [NSForegroundColorAttributeName: UIColor.whiteColor()], defaultFormat: [NSForegroundColorAttributeName: UIColor.colorWithHexString("#ffffff", alpha: 0.3)!]) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if DeviceType.IS_IPHONE_4_OR_LESS { self.chartLegendHeight.constant -= 10 } else if DeviceType.IS_IPHONE_5 { self.chartLegendHeight.constant -= 5 } } func scrollRecent() { var newDate: NSDate? = nil if let date = self.dailyChartModel.getEndDate() { if !date.isInToday() { let today = NSDate() newDate = today < (date + 1.weeks) ? today : (date + 1.weeks) self.scrollRecentButton.enabled = !(newDate?.isInSameDayAsDate(today) ?? false) self.scrollOlderButton.enabled = true self.dailyChartModel.setEndDate(newDate) self.dailyProgressChartDaysTable.reloadData() self.contentDidUpdate(withDailyProgress: false) } } } func scrollOlder() { var newDate: NSDate? = nil if let date = self.dailyChartModel.getEndDate() { let oldest = 3.months.ago if !date.isInSameDayAsDate(oldest) { newDate = (date - 1.weeks) < oldest ? oldest : (date - 1.weeks) self.scrollOlderButton.enabled = !(newDate?.isInSameDayAsDate(oldest) ?? false) self.scrollRecentButton.enabled = true self.dailyChartModel.setEndDate(newDate) self.dailyProgressChartDaysTable.reloadData() self.contentDidUpdate(withDailyProgress: false) } } } }
apache-2.0
b3412b9a059e69671e4e53a63f773dd2
46.01581
200
0.649517
5.237781
false
false
false
false
jad6/CV
Swift/Jad's CV/Other/Subclasses/Controllers/TableViewController.swift
1
2986
// // TableViewController.swift // Jad's CV // // Created by Jad Osseiran on 22/07/2014. // Copyright (c) 2014 Jad. All rights reserved. // import UIKit //TODO: Make class Generic once Apple fixes the bug in Beta 4 class TableViewController : UITableViewController, List { //MARK:- Properties //TODO: re-enable that once Swift supports class variables // private class let defaultCellIdentifier = "Cell" private class func defaultCellIdentifier() -> String { return "Cell" } var listData: ListData<TimelineEvent> = ListData() { didSet { tableView.reloadData() } } //MARK:- Init required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init(style: UITableViewStyle, listData: ListData<TimelineEvent>) { super.init(style: style) self.listData = listData self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: TableViewController.defaultCellIdentifier()) } //MARK:- Abstract Methods func listView(listView: UIView, configureCell cell: UIView, withObject object: Any, atIndexPath indexPath: NSIndexPath) { // Override me! } func listView(listView: UIView, didSelectObject object: Any, atIndexPath indexPath: NSIndexPath) { // Override me! } func cellIdentifierForIndexPath(indexPath: NSIndexPath) -> String { return TableViewController.defaultCellIdentifier() } //MARK:- Table view override func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return listData.sections.count } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return listData[section].rowObjects.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { // Get identifiers from overrriden method. let identifier = cellIdentifierForIndexPath(indexPath) let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as UITableViewCell // Get object from overriden method. if let object = listData[indexPath] { // Let the subclasses configure the cell. listView(tableView, configureCell: cell, withObject: object, atIndexPath: indexPath) } return cell } override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { // Get object from overriden method. if let object = listData[indexPath] { // Call overridable method. listView(tableView, didSelectObject: object, atIndexPath: indexPath) } } }
bsd-3-clause
5e53fb026816b5cc1a20551fe087e745
31.456522
127
0.667113
5.389892
false
false
false
false
cfilipov/MuscleBook
MuscleBook/WorksetAdapter+Dropbox.swift
1
2534
/* Muscle Book Copyright (C) 2016 Cristian Filipov This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation extension Workset { // static func importFromDropbox(file: String, completion: (SuccessOrFail -> Void)?) { // let t = Profiler.trace(String(Workset), #function).start() // Dropbox.authorizedClient! // .files // .download(path: file, destination: self.dropboxDestination(NSURL.cacheUUID())) // .response { response, error in // t.end() // Profiler.trace("Dropbox import").start() // defer { // Profiler.trace("Dropbox import").end() // completion?(.Success) // } // guard let (_, url) = response else { return } // let sets = Workset.fromYAML(url.path!) // try! DB.sharedInstance.save(sets) // } // } // // static func downloadFromDropbox(file: String, completion: (NSURL? -> Void)?) { // let t = Profiler.trace(String(Workset), #function).start() // Dropbox.authorizedClient! // .files // .download(path: file, destination: self.dropboxDestination(NSURL.cacheUUID())) // .response { response, error in // t.end() // completion?(response?.1) // } // } // // static func dropboxDestination(destination: NSURL) -> (url: NSURL, response: NSHTTPURLResponse) -> NSURL { // return { _, _ in return destination } // } // static func uploadToDropbox(file: String, completion: (SuccessOrFail -> Void)?) { // guard let sets = try! all() else { completion?(.Fail); return } // Dropbox.authorizedClient! // .files // .upload(path: file, mode: .Overwrite, body: sets.toYAML) // .response { response, error in // completion?(SuccessOrFail(error: error)) // } // } }
gpl-3.0
cab3ad45d3c609fd0c1f550b08e2a3d0
38
112
0.601026
4.154098
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Extensions/UITextView+Extensions.swift
1
2639
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import UIKit extension UITextView { /// The maximum number of lines to use for rendering text. /// /// This property controls the maximum number of lines to use in order to fit /// the label’s text into its bounding rectangle. The default value for this /// property is `1`. To remove any maximum limit, and use as many lines as /// needed, set the value of this property to `0`. /// /// If you constrain your text using this property, any text that does not fit /// within the maximum number of lines and inside the bounding rectangle of the /// label is truncated using the appropriate line break mode, as specified by /// the `lineBreakMode` property. /// /// When the label is resized using the `sizeToFit()` method, resizing takes /// into account the value stored in this property. For example, if this /// property is set to `3`, the `sizeToFit()` method resizes the receiver so /// that it is big enough to display three lines of text. public var numberOfLines: Int { get { guard let font = font else { return 0 } return Int(contentSize.height / font.lineHeight) } set { textContainer.maximumNumberOfLines = newValue } } func textRange(from range: NSRange) -> UITextRange? { guard let start = position(from: beginningOfDocument, offset: range.location), let end = position(from: start, offset: range.length) else { return nil } return textRange(from: start, to: end) } /// Returns `UIAccessibilityElement` for all links inside current instance it /// was given when created. public var linkAccessibilityElements: [UIAccessibilityElement] { var linkElements: [UIAccessibilityElement] = [] attributedText.enumerateAttribute(.link, in: NSRange(0..<attributedText.length)) { value, range, _ in guard value != nil else { return } let element = UIAccessibilityElement(accessibilityContainer: self) element.accessibilityTraits = .link element.accessibilityValue = (value as? URL)?.absoluteString if let textRange = textRange(from: range) { element.accessibilityFrameInContainerSpace = firstRect(for: textRange) element.accessibilityLabel = self.text(in: textRange) } linkElements.append(element) } return linkElements } }
mit
c6ccb7ea6e3d42c5cfdcaa5158572290
35.611111
109
0.633915
5.069231
false
false
false
false
sora0077/QiitaKit
QiitaKit/src/Utility/Item+JSON.swift
1
1303
// // Item+JSON.swift // QiitaKit // // Created by 林達也 on 2015/06/24. // Copyright (c) 2015年 林達也. All rights reserved. // import Foundation import APIKit func _Item(object: AnyObject!) throws -> Item { try validation(object) let object = object as! GetItem.SerializedObject return Item( rendered_body: object["rendered_body"] as! String, body: object["body"] as! String, coediting: object["coediting"] as! Bool, created_at: object["created_at"] as! String, id: object["id"] as! String, `private`: object["private"] as! Bool, tags: _Taggings(object["tags"]), title: object["title"] as! String, updated_at: object["updated_at"] as! String, url: object["url"] as! String, user: try _User(object["user"]) ) } func _Items(object: AnyObject!) throws -> [Item] { try validation(object) let object = object as! [GetItem.SerializedObject] return try object.map { try _Item($0) } } public extension QiitaRequestToken where Response == Item, SerializedObject == [String: AnyObject] { func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { return try _Item(object) } }
mit
775f1c20c32fd9fceebb9d5ef91efd35
26.425532
119
0.623739
3.906061
false
false
false
false
crossroadlabs/Boilerplate
Sources/Boilerplate/C.swift
2
5403
//===--- C.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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 extension UnsafeMutablePointer : NullEquatable { } extension UnsafePointer : NullEquatable { } extension UnsafeMutableRawPointer : NullEquatable { } extension UnsafeRawPointer : NullEquatable { } public func==(lhs:UnsafeMutableRawPointer, rhs:Null) -> Bool { return Int(bitPattern: lhs) == 0 } public func==(lhs:UnsafeRawPointer, rhs:Null) -> Bool { return Int(bitPattern: lhs) == 0 } #if swift(>=3.0) public func==<T>(lhs:UnsafeMutablePointer<T>, rhs:Null) -> Bool { return Int(bitPattern: lhs) == 0 } public func==<T>(lhs:UnsafePointer<T>, rhs:Null) -> Bool { return Int(bitPattern: lhs) == 0 } #else public func==<T>(lhs:UnsafeMutablePointer<T>, rhs:Null) -> Bool { return lhs == UnsafeMutablePointer(nil) } public func==<T>(lhs:UnsafePointer<T>, rhs:Null) -> Bool { return lhs == UnsafePointer(nil) } #endif #if swift(>=3.0) #else public typealias OpaquePointer = COpaquePointer public extension OpaquePointer { public init<T>(bitPattern:Unmanaged<T>) { self = bitPattern.toOpaque() } } public extension UnsafePointer { public typealias Pointee = Memory /// Access the `Pointee` instance referenced by `self`. /// /// - Precondition: the pointee has been initialized with an instance of /// type `Pointee`. public var pointee: Pointee { get { return self.memory } } } public extension UnsafeMutablePointer { public typealias Pointee = Memory /// Allocate and point at uninitialized aligned memory for `count` /// instances of `Pointee`. /// /// - Postcondition: The pointee is allocated, but not initialized. public init(allocatingCapacity count: Int) { self = UnsafeMutablePointer.alloc(count) } /// Deallocate uninitialized memory allocated for `count` instances /// of `Pointee`. /// /// - Precondition: The memory is not initialized. /// /// - Postcondition: The memory has been deallocated. public func deallocateCapacity(num: Int) { self.dealloc(num) } /// Access the `Pointee` instance referenced by `self`. /// /// - Precondition: the pointee has been initialized with an instance of /// type `Pointee`. public var pointee: Pointee { get { return self.memory } nonmutating set { self.memory = newValue } } public func initialize(with newValue: Pointee, count: Int = 1) { assert(count != 1, "NOT IMPLEMENTED: currently can initialize with 1 value only") self.initialize(newValue) } /// De-initialize the `count` `Pointee`s starting at `self`, returning /// their memory to an uninitialized state. /// /// - Precondition: The `Pointee`s at `self..<self + count` are /// initialized. /// /// - Postcondition: The memory is uninitialized. public func deinitialize(count count: Int = 1) { self.destroy(count) } } /// Returns an `UnsafePointer` to the storage used for `object`. There's /// not much you can do with this other than use it to identify the /// object. public func unsafeAddress(of object: AnyObject) -> UnsafePointer<Swift.Void> { return unsafeAddressOf(object) } /// Returns the bits of `x`, interpreted as having type `U`. /// /// - Warning: Breaks the guarantees of Swift's type system; use /// with extreme care. There's almost always a better way to do /// anything. /// public func unsafeBitCast<T, U>(x: T, to: U.Type) -> U { return unsafeBitCast(x, to) } /// - returns: `x as T`. /// /// - Precondition: `x is T`. In particular, in -O builds, no test is /// performed to ensure that `x` actually has dynamic type `T`. /// /// - Warning: Trades safety for performance. Use `unsafeDowncast` /// only when `x as T` has proven to be a performance problem and you /// are confident that, always, `x is T`. It is better than an /// `unsafeBitCast` because it's more restrictive, and because /// checking is still performed in debug builds. public func unsafeDowncast<T : AnyObject>(x: AnyObject, to: T.Type) -> T { return unsafeDowncast(x) } #endif
apache-2.0
017c333b1d9356551d62c3489522e40a
32.351852
93
0.588932
4.617949
false
false
false
false
ChrisAU/PapyrusCore
PapyrusCoreTests/SolutionTests.swift
1
1700
// // SolutionTests.swift // PapyrusCore // // Created by Chris Nevin on 10/06/2016. // Copyright © 2016 CJNevin. All rights reserved. // import XCTest @testable import PapyrusCore class SolutionTests : WordTests { var intersection: PapyrusCore.Word! override func setUp() { super.setUp() intersection = Word(word: "CAT", x: 7, y: 4, horizontal: false) _ = Solution(word: intersection, score: 0, intersections: [], blanks: []) word = Solution(word: word.word, x: word.x, y: word.y, horizontal: word.horizontal, score: 0, intersections: [intersection], blanks: []) } override func testEqual() { let comparison = Solution(word: word.word, x: word.x, y: word.y, horizontal: word.horizontal, score: 0, intersections: [intersection], blanks: []) XCTAssertEqual(comparison, (word as! Solution)) } override func testNotEqual() { let comparison = Solution(word: "RAT", x: word.x, y: word.y, horizontal: word.horizontal, score: 0, intersections: [intersection], blanks: []) XCTAssertNotEqual(comparison, (word as! Solution)) } func getXs(_ positions: [Position]) -> [Int] { return Array(Set(positions.map({ $0.x }))).sorted() } func getYs(_ positions: [Position]) -> [Int] { return Array(Set(positions.map({ $0.y }))).sorted() } func testGetPositions() { let positions = word.toPositions() + intersection.toPositions() let gotPositions = (word as! Solution).getPositions() XCTAssertEqual(getXs(positions), getXs(gotPositions)) XCTAssertEqual(getYs(positions), getYs(gotPositions)) } }
bsd-2-clause
21227e631dee5daed7f1168ed4fc41cd
33.673469
154
0.625074
3.969626
false
true
false
false
tranhieutt/Swiftz
Swiftz/TupleExt.swift
3
2373
// // TupleExt.swift // Swiftz // // Created by Maxwell Swadling on 7/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // /// Extracts the first value from a pair. public func fst<A, B>(ab : (A, B)) -> A { return ab.0 } /// Extracts the second value from a pair. public func snd<A, B>(ab : (A, B)) -> B { return ab.1 } //Not possible to extend like this currently. //extension () : Equatable {} //extension (T:Equatable, U:Equatable) : Equatable {} public func ==(lhs: (), rhs: ()) -> Bool { return true } public func !=(lhs: (), rhs: ()) -> Bool { return false } // Unlike Python a 1-tuple is just it's contained element. public func == <T:Equatable,U:Equatable>(lhs: (T,U), rhs: (T,U)) -> Bool { let (l0,l1) = lhs let (r0,r1) = rhs return l0 == r0 && l1 == r1 } public func != <T:Equatable,U:Equatable>(lhs: (T,U), rhs: (T,U)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable>(lhs: (T,U,V), rhs: (T,U,V)) -> Bool { let (l0,l1,l2) = lhs let (r0,r1,r2) = rhs return l0 == r0 && l1 == r1 && l2 == r2 } public func != <T:Equatable,U:Equatable,V:Equatable>(lhs: (T,U,V), rhs: (T,U,V)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable>(lhs: (T,U,V,W), rhs: (T,U,V,W)) -> Bool { let (l0,l1,l2,l3) = lhs let (r0,r1,r2,r3) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable>(lhs: (T,U,V,W), rhs: (T,U,V,W)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable>(lhs: (T,U,V,W,X), rhs: (T,U,V,W,X)) -> Bool { let (l0,l1,l2,l3,l4) = lhs let (r0,r1,r2,r3,r4) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 && l4 == r4 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable>(lhs: (T,U,V,W,X), rhs: (T,U,V,W,X)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable,Z:Equatable>(lhs: (T,U,V,W,X,Z), rhs: (T,U,V,W,X,Z)) -> Bool { let (l0,l1,l2,l3,l4,l5) = lhs let (r0,r1,r2,r3,r4,r5) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 && l4 == r4 && l5 == r5 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable,Z:Equatable>(lhs: (T,U,V,W,X,Z), rhs: (T,U,V,W,X,Z)) -> Bool { return !(lhs==rhs) }
bsd-3-clause
59a1204bd3b1f3ab5378440ffa9ded67
28.6625
138
0.591656
2.264313
false
false
false
false
yl-github/YLDYZB
YLDouYuZB/YLDouYuZB/Classes/Main/Controller/YLPageContentView.swift
1
6767
// // YLPageContentView.swift // YLDouYuZB // // Created by yl on 16/9/26. // Copyright © 2016年 yl. All rights reserved. // import UIKit private let cellID = "cellID"; protocol YLPageContentViewDelegate : class { func pageContentView(_ contentView:YLPageContentView, progress:CGFloat,beforeTitleIndex:Int,targetTitleIndex:Int); } class YLPageContentView: UIView { // MARK:- 定义属性,来保存传进来的内容 fileprivate var childVcs: [UIViewController]; fileprivate weak var parentViewControlle: UIViewController?; fileprivate var startOffsetX : CGFloat = 0; fileprivate var isForbidScrollDelegate : Bool = false; // 代理属性 weak var delegate : YLPageContentViewDelegate?; // MARK:- 懒加载属性 fileprivate lazy var collectionView: UICollectionView = {[weak self] in // 1.创建layout let layout = UICollectionViewFlowLayout(); layout.itemSize = (self?.bounds.size)!; layout.minimumLineSpacing = 0; layout.minimumInteritemSpacing = 0; layout.scrollDirection = .horizontal; // 2.创建UICollectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout); collectionView.showsHorizontalScrollIndicator = false; collectionView.isPagingEnabled = true; collectionView.bounces = false; collectionView.dataSource = self; collectionView.delegate = self; collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID); return collectionView; }(); // MARK:- 自定义构造函数 init(frame: CGRect,childVcs: [UIViewController],parentViewControlle: UIViewController?) { self.childVcs = childVcs; self.parentViewControlle = parentViewControlle; super.init(frame: frame); // 设置UI界面 setupUI(); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面 extension YLPageContentView { fileprivate func setupUI(){ // 1.将所欲的子控制器添加到父控制器当中 for childVc in childVcs{ parentViewControlle?.addChildViewController(childVc); } // 2.添加UICollectionView,用于在cell中存放控制器的View addSubview(collectionView); collectionView.frame = bounds; } } // MARK:- 遵守UICollectionView的datasource协议 extension YLPageContentView:UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count; } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath); // 2.给cell设置内容 let childVC = childVcs[(indexPath as NSIndexPath).item]; childVC.view.frame = self.bounds; cell.contentView.addSubview(childVC.view); return cell; } } // MARK:- 遵守UICollectionoViewDelegate协议 extension YLPageContentView:UICollectionViewDelegate { /* 这里我们要拿到collectionView的偏移量,要判断是向左滑动还是向右滑动(需要知道开始滑动的那一刻的偏移量和滑动过之后的偏移量这里就需要实现scrollView的begin代理方法了),还要拿到滑动后的Index和滑动进度progress 这里面我们需要监听ScrollView的滚动就可以,因为我们的collectionView在scrolleview上放着呢 */ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false; startOffsetX = scrollView.contentOffset.x; } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 0.判断是点击还是滑动(判断是否是点击事件) if isForbidScrollDelegate { return; } // 1.定义需要获取到的数据 var progress : CGFloat = 0; var beforeTitleIndex : Int = 0; var targetTitleIndex : Int = 0; // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x; // 当前的偏移量 let scrollViewW = scrollView.bounds.width; if startOffsetX < currentOffsetX { // 左滑 // 1.计算progress进度 (floor函数表示取整) progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW); // 2.计算beforeTitleIndex(之前的title的下标) beforeTitleIndex = Int(currentOffsetX / scrollViewW); // 3.计算targetTitleIndex(是要滑动到哪个位置的下标) targetTitleIndex = beforeTitleIndex + 1; // 这里要做一下判断,防止滚到最后的时候越界 if targetTitleIndex >= childVcs.count { targetTitleIndex = childVcs.count - 1; } // 4.如果完全滑过去的时候将要改变我们的progress/beforeTitleIndex/targetTitleIndex if currentOffsetX - startOffsetX == scrollViewW { progress = 1.0; targetTitleIndex = beforeTitleIndex; } } else { // 向右滑 // 1. 计算progress滚动进度 progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)); // 2.计算targetTitleIndex targetTitleIndex = Int(currentOffsetX / scrollViewW); // 3.计算beforeTitleIndex beforeTitleIndex = targetTitleIndex + 1; if beforeTitleIndex >= childVcs.count { beforeTitleIndex = childVcs.count - 1; } } // 4.将我们拿到的progress/beforeTitleIndex/targetTitleIndex传递给titleView delegate?.pageContentView(self, progress: progress, beforeTitleIndex: beforeTitleIndex, targetTitleIndex: targetTitleIndex); } } // MRAK:- 对外暴露的方法 extension YLPageContentView{ func setCurrentIndex(_ currentIndex : Int){ // 1.记录需要禁止的代理方法 isForbidScrollDelegate = true; // 2.contentView滚到正确的位置 let offsetX = CGFloat(currentIndex) * collectionView.frame.width; collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false); } }
mit
9bedf51585f601425373d6219c23e909
29.877551
132
0.636484
5.022407
false
false
false
false
hammond756/Shifty
Shifty/Shifty/AangebodenViewController.swift
1
3149
// // AangebodenViewController.swift // Shifty // // Created by Aron Hammond on 01/06/15. // Copyright (c) 2015 Aron Hammond. All rights reserved. // // The 'marketplace'. Shift that are supplied by users appear here. Others // can accept these if they want to work that shift. import UIKit import Parse import SwiftDate class AangebodenViewController: ContentViewController { @IBAction func logOutCurrentUser(sender: UIBarButtonItem) { helper.logOut(self) } // actions on ActionSheet call getData() when the corresponding changes are saved, so the view can reload properly override func getData() { setActivityViewActive(true) rooster.requestShifts(Status.supplied) { sections -> Void in self.refresh(sections) } } } extension AangebodenViewController: ActionSheetDelegate { // show UIAlertView that is created by a ActionSheet instance func showAlert(alertView: UIAlertController) { alertView.popoverPresentationController?.sourceView = self.view presentViewController(alertView, animated: true, completion: nil) } } extension AangebodenViewController: UITableViewDataSource { // information needs to come from another property than other ContentViewControllers override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rooster.suppliedShifts[section].count } // set labels and highlighting for cell override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) as UITableViewCell let shiftForCell = rooster.suppliedShifts[indexPath.section][indexPath.row] cell.textLabel?.text = shiftForCell.dateString cell.accessoryView = helper.createTimeLabel(shiftForCell.timeString) if shiftForCell.owner == PFUser.currentUser() { cell.backgroundColor = Highlight.supplied } return cell } } extension AangebodenViewController: UITableViewDelegate { // calls an ActionSheet that handles actions for the shift at the indexPath func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { let selectedShift = rooster.suppliedShifts[indexPath.section][indexPath.row] let actionSheet = ActionSheet(shift: selectedShift, delegate: self, request: nil) // action depends on current user if selectedShift.owner != PFUser.currentUser() { actionSheet.includeActions([Action.accept]) } else { actionSheet.includeActions([Action.revoke]) } let alertController = actionSheet.getAlertController() alertController.popoverPresentationController?.sourceView = self.view presentViewController(alertController, animated: true, completion: nil) tableView.deselectRowAtIndexPath(indexPath, animated: false) return indexPath } }
mit
6620df4c2d6fdaaa5d3d21f98c15191f
32.860215
118
0.701493
5.187809
false
false
false
false
brave/browser-ios
brave/src/page-hooks/BlankTargetLinkHandler.swift
2
2282
/* 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/. */ /* BraveWebView will, on new load, assume that blank link tap detection is required. On load finished, it runs a check to see if any links are _blank targets, and if not, disables this tap detection. */ class BlankTargetLinkHandler { fileprivate var tapLocation = CGPoint.zero func isBrowserTopmost() -> Bool { return getApp().rootViewController.visibleViewController as? BraveTopViewController != nil } func sendEvent(_ event: UIEvent, window: UIWindow) { guard let touchView = event.allTouches?.first?.view, let braveWebView = BraveApp.getCurrentWebView(), touchView.isDescendant(of: braveWebView) else { return } if !isBrowserTopmost() { return } if let touches = event.touches(for: window), let touch = touches.first, touches.count == 1 { guard let webView = BraveApp.getCurrentWebView(), let webViewSuperview = webView.superview else { return } if !webView.blankTargetLinkDetectionOn { return } let globalRect = webViewSuperview.convert(webView.frame, to: nil) if !globalRect.contains(touch.location(in: window)) { return } if touch.phase != .began && tapLocation == CGPoint.zero { webView.blankTargetUrl = nil return } switch touch.phase { case .began: tapLocation = touch.location(in: window) if let element = ElementAtPoint().getHit(tapLocation), let url = element.url, let t = element.urlTarget, t == "_blank" { webView.blankTargetUrl = url } else { tapLocation = CGPoint.zero } case .moved: tapLocation = CGPoint.zero webView.blankTargetUrl = nil case .ended, .cancelled: tapLocation = CGPoint.zero case .stationary: break } } } }
mpl-2.0
ee123ce00a0293d7e94f70d331f565ce
37.033333
198
0.57844
4.939394
false
false
false
false
kences/swift_weibo
Swift-SinaWeibo/Classes/Module/Home/Controller/LGHomeViewController.swift
1
13574
// // LGHomeViewController.swift // Swift-SinaWeibo // // Created by lu on 15/10/26. // Copyright © 2015年 lg. All rights reserved. // import UIKit import SVProgressHUD /// 管理cell重用标识 enum LGStautsCellIdentifier: String { case normalCell = "LGStatusNormalCell" case forwardCell = "LGStatusForwardCell" } class LGHomeViewController: LGBasicTableViewController { // 数据模型数组:保存加载到的微博信息 var statuses :[LGStatus]? { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() if !LGUserAccount.isLogin { // 没有登录就显示访客视图的内容 return } // 1.设置导航栏 setupNavigationBar() // 2.设置tableView setupTableView() // 3.**添加下拉刷新控件 self.refreshControl = refreshView // 一开始就让它旋转,因为一开始就要加载微博数据 refreshView.beginRefreshing() // 4.显示加载微博条数的label navigationController?.navigationBar.insertSubview(showRefreshCount, atIndex: 0) showRefreshCount.frame = (navigationController?.navigationBar.bounds)! // 居然可以直接赋值 showRefreshCount.frame.origin.y = 44 // 加载微博数据 print("开始加载微博数据") // loadStatus() // UIControl的方法,相当于触发了一次target的方法 refreshView.sendActionsForControlEvents(UIControlEvents.ValueChanged) /// 模拟加载微博数据 // loadLocalData() // 监听通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedPicture:", name: LGStatusPictureViewSelectedPictureNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "popoverViewControllerDismiss", name: LGPopoverViewControllerDismissNotification, object: nil) } deinit { // 移除通知 NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - 点击图片收到通知 func didSelectedPicture(notification: NSNotification) { // print("接收到通知: \(notification)") let userInfo = notification.userInfo as! [String: AnyObject] let indexPath = userInfo[LGStatusPictureViewSelectedPictureIndexPathKey] as? NSIndexPath let urls = userInfo[LGStatusPictureViewSelectedPictureURLKey] as? [NSURL] let photoVC = LGPhotoBrowserViewController(urls: urls!, indexPath: indexPath!) // 因为popoverVC的transitioningDelegate为self,如果photoVC也设置为self的话,那么photoVC的转场样式也会与popoverVC一样 photoVC.transitioningDelegate = photoVC photoVC.modalPresentationStyle = UIModalPresentationStyle.Custom presentViewController(photoVC, animated: true, completion: nil) } // MARK: - 退出popover控制器发送的通知 func popoverViewControllerDismiss() { let button = navigationItem.titleView as! UIButton titleButtonAction(button) } // MARK: - 加载微博数据 @objc private func loadStatus() { var since_id = statuses?.first?.id ?? 0 var max_id = 0 if pullUpView.isAnimating() { // 上拉到后面,上拉加载的菊花在转 since_id = 0 max_id = statuses?.last?.id ?? 0 } LGStatus.loadStatus(since_id, max_id: max_id) { (list, error) -> () in // 使菊花隐藏 self.refreshView.endRefreshing() self.pullUpView.stopAnimating() if error != nil { SVProgressHUD.showErrorWithStatus("加载微博数据出错", maskType: SVProgressHUDMaskType.Black) return } if since_id > 0 { // 如果是下拉刷新 // 将刷新到的数据放到数组的前面 print("刷新了 \(list?.count) 条微博") // 显示刷新的微博数 self.showRefreshCountAnimation(list!.count) self.statuses = list! + self.statuses! } else if max_id > 0 { // 将加载到的数据放到数组的后面 print("加载了 \(list?.count) 条微博") self.statuses = self.statuses! + list! } else { self.statuses = list } } } // MARK: - 模拟加载微博数据 /// 加载本地数据 private func loadLocalData() { /// 模拟加载微博数据 let path = NSBundle.mainBundle().pathForResource("statuses.json", ofType: nil) let data = NSData(contentsOfFile: path!) do { // 在这里要做异常处理 let jsons = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) let dict = jsons as? [String:AnyObject] let arr = dict!["statuses"] as! [[String: AnyObject]] var statuses = [LGStatus]() for d in arr { let status = LGStatus(dict: d) statuses.append(status) } self.statuses = statuses } catch { print("序列化数据异常") } } // MARK: - /// 配置tableView参数 private func setupTableView() { // 注册可重用的cell // 原创微博 tableView.registerClass(LGStatusNormalCell.self, forCellReuseIdentifier: LGStautsCellIdentifier.normalCell.rawValue) // 转发微博 tableView.registerClass(LGStatusForwardCell.self, forCellReuseIdentifier: LGStautsCellIdentifier.forwardCell.rawValue) // 去除分割线 tableView.separatorStyle = UITableViewCellSeparatorStyle.None // 下拉加载更多 tableView.tableFooterView = pullUpView } /// 设置导航栏 private func setupNavigationBar() { // 1.导航栏的按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch") navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop") // 2.导航栏标题 let homeTitleView = LGHomeButton() // ??: 如果前面有值,直接拆包并赋值,否则将后面的内容赋值 let titleName = LGUserAccount.loadUserAccount()?.name ?? "没有名称" homeTitleView.setTitle(titleName, forState: UIControlState.Normal) homeTitleView.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) homeTitleView.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Normal) homeTitleView.sizeToFit() // 添加按钮的点击事件 homeTitleView.addTarget(self, action: "titleButtonAction:", forControlEvents: UIControlEvents.TouchUpInside) navigationItem.titleView = homeTitleView } /// 返回cellId private func cellId(status: LGStatus) -> String { return (status.retweeted_status == nil) ? LGStautsCellIdentifier.normalCell.rawValue : LGStautsCellIdentifier.forwardCell.rawValue } // MARK: - tableView 数据源和代理方法 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return statuses?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> LGStatusCell { let status = statuses?[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(cellId(status!)) as? LGStatusCell cell?.status = status // 上拉加载更多数据 if indexPath.row == statuses!.count - 1 && !pullUpView.isAnimating() { pullUpView.startAnimating() // 加载数据 loadStatus() } return cell! } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } /// 系统是先计算好cell的高度后才会显示 override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // MARK: - important // 1.获取相应的模型 let status = statuses![indexPath.row] // 1.1.先判断对应模型中的行高是否有值 if let rowHeight = status.rowHeight { // print("缓存的行高---\(rowHeight)") return rowHeight } // 2.从缓存中任意取出一个cell,然后根据模型的内容计算出行高,并返回.(注意:这里的cell并不是相应indexPath下的cell,只是拿出来计算行高使用.但高度是相应indexPath下的高度,因为模型是对应的) let cell = tableView.dequeueReusableCellWithIdentifier(cellId(status)) as! LGStatusCell // 3.让cell根据模型的内容计算行高 let rowHeight = cell.cellHeight(status) // 3.1.将行高缓存到模型当中 status.rowHeight = rowHeight return rowHeight } // MARK: - 动画相关方法 /// 显示加载微博条数的动画 private func showRefreshCountAnimation(count: Int) { self.showRefreshCount.text = count == 0 ? "没有新的微博数据" : "加载了\(count)条新的微博" UIView.animateWithDuration(0.25, animations: { () -> Void in self.showRefreshCount.alpha = 1 }) { (_) -> Void in UIView.animateWithDuration(0.3, delay: 0.4, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.showRefreshCount.alpha = 0 }, completion: { (_) -> Void in }) } } // MARK: - 懒加载 /// 下拉刷新的菊花 private lazy var refreshView: LGRefreshControl = { let refresh = LGRefreshControl() // 添加事件 : 响应方法就是加载微博数据 refresh.addTarget(self, action: "loadStatus", forControlEvents: UIControlEvents.ValueChanged) return refresh }() /// 上拉加载更多 private lazy var pullUpView: UIActivityIndicatorView = { let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) view.color = UIColor.grayColor() return view }() /// 显示刷新的微博的视图 private lazy var showRefreshCount: UILabel = { let label = UILabel() label.backgroundColor = UIColor.orangeColor() label.textColor = UIColor.whiteColor() label.textAlignment = NSTextAlignment.Center label.font = UIFont.systemFontOfSize(14) label.alpha = 0 return label }() } // MARK: - 转场动画代理 extension LGHomeViewController: UIViewControllerTransitioningDelegate { // MARK: 按钮的响应事件 @objc private func titleButtonAction(button: UIButton) { button.selected = !button.selected var transform: CGAffineTransform? if button.selected { // 利用UIView动画的就近原则,旋转比180度略少,以便控制回转方向 transform = CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) } else { transform = CGAffineTransformIdentity } // 执行按钮图片的旋转动画 UIView.animateWithDuration(0.25) { () -> Void in button.imageView?.transform = transform! } if button.selected { // 弹出popover控制器 let popoverVC = LGPopoverViewController.popover() // 设置转场动画的代理 popoverVC.transitioningDelegate = self // 设置modal样式为自定义 popoverVC.modalPresentationStyle = UIModalPresentationStyle.Custom presentViewController(popoverVC, animated: true, completion: nil) } } // MARK: 转场动画代理方法 /** 设置 控制modal展现 的对象 */ func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { return LGPresentationController(presentedViewController: presented, presentingViewController: presenting) } /** modal动画时的对象: 该对象需要实现 UIViewControllerAnimatedTransitioning 协议 */ func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return LGModalAnimation() } /** 退出modal的控制器时使用的对象,需要实现 UIViewControllerAnimatedTransitioning 协议 */ func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return LGDismissAnimation() } }
apache-2.0
54633d8d52b0c24aec20b43118f75a49
32.153425
217
0.618792
4.96961
false
false
false
false
nanthi1990/SwiftCharts
SwiftCharts/Layers/ChartBarsLayer.swift
7
5502
// // ChartBarsLayer.swift // Examples // // Created by ischuetz on 17/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartBarModel { public let constant: ChartAxisValue public let axisValue1: ChartAxisValue public let axisValue2: ChartAxisValue public let bgColor: UIColor? public init(constant: ChartAxisValue, axisValue1: ChartAxisValue, axisValue2: ChartAxisValue, bgColor: UIColor? = nil) { self.constant = constant self.axisValue1 = axisValue1 self.axisValue2 = axisValue2 self.bgColor = bgColor } } enum ChartBarDirection { case LeftToRight, BottomToTop } class ChartBarsViewGenerator<T: ChartBarModel> { let xAxis: ChartAxisLayer let yAxis: ChartAxisLayer let chartInnerFrame: CGRect let direction: ChartBarDirection let barWidth: CGFloat init(horizontal: Bool, xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, chartInnerFrame: CGRect, barWidth barWidthMaybe: CGFloat?, barSpacing barSpacingMaybe: CGFloat?) { let direction: ChartBarDirection = { switch (horizontal: horizontal, yLow: yAxis.low, xLow: xAxis.low) { case (horizontal: true, yLow: true, _): return .LeftToRight case (horizontal: false, _, xLow: true): return .BottomToTop default: fatalError("Direction not supported - stacked bars must be from left to right or bottom to top") } }() let barWidth = barWidthMaybe ?? { let axis: ChartAxisLayer = { switch direction { case .LeftToRight: return yAxis case .BottomToTop: return xAxis } }() let spacing: CGFloat = barSpacingMaybe ?? 0 return axis.minAxisScreenSpace - spacing }() self.xAxis = xAxis self.yAxis = yAxis self.chartInnerFrame = chartInnerFrame self.direction = direction self.barWidth = barWidth } func viewPoints(barModel: T, constantScreenLoc: CGFloat) -> (p1: CGPoint, p2: CGPoint) { switch self.direction { case .LeftToRight: return ( CGPointMake(self.xAxis.screenLocForScalar(barModel.axisValue1.scalar), constantScreenLoc), CGPointMake(self.xAxis.screenLocForScalar(barModel.axisValue2.scalar), constantScreenLoc)) case .BottomToTop: return ( CGPointMake(constantScreenLoc, self.yAxis.screenLocForScalar(barModel.axisValue1.scalar)), CGPointMake(constantScreenLoc, self.yAxis.screenLocForScalar(barModel.axisValue2.scalar))) } } func constantScreenLoc(barModel: T) -> CGFloat { return (self.direction == .LeftToRight ? self.yAxis : self.xAxis).screenLocForScalar(barModel.constant.scalar) } // constantScreenLoc: (screen) coordinate that is equal in p1 and p2 - for vertical bar this is the x coordinate, for horizontal bar this is the y coordinate func generateView(barModel: T, constantScreenLoc constantScreenLocMaybe: CGFloat? = nil, bgColor: UIColor?, animDuration: Float) -> ChartPointViewBar { let constantScreenLoc = constantScreenLocMaybe ?? self.constantScreenLoc(barModel) let viewPoints = self.viewPoints(barModel, constantScreenLoc: constantScreenLoc) return ChartPointViewBar(p1: viewPoints.p1, p2: viewPoints.p2, width: self.barWidth, bgColor: bgColor, animDuration: animDuration) } } public class ChartBarsLayer: ChartCoordsSpaceLayer { private let bars: [ChartBarModel] private let barWidth: CGFloat? private let barSpacing: CGFloat? private let horizontal: Bool private let animDuration: Float public convenience init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, bars: [ChartBarModel], horizontal: Bool = false, barWidth: CGFloat, animDuration: Float) { self.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, bars: bars, horizontal: horizontal, barWidth: barWidth, barSpacing: nil, animDuration: animDuration) } public convenience init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, bars: [ChartBarModel], horizontal: Bool = false, barSpacing: CGFloat, animDuration: Float) { self.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, bars: bars, horizontal: horizontal, barWidth: nil, barSpacing: barSpacing, animDuration: animDuration) } private init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, bars: [ChartBarModel], horizontal: Bool = false, barWidth: CGFloat? = nil, barSpacing: CGFloat?, animDuration: Float) { self.bars = bars self.horizontal = horizontal self.barWidth = barWidth self.barSpacing = barSpacing self.animDuration = animDuration super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame) } public override func chartInitialized(#chart: Chart) { let barsGenerator = ChartBarsViewGenerator(horizontal: self.horizontal, xAxis: self.xAxis, yAxis: self.yAxis, chartInnerFrame: self.innerFrame, barWidth: self.barWidth, barSpacing: self.barSpacing) for barModel in self.bars { chart.addSubview(barsGenerator.generateView(barModel, bgColor: barModel.bgColor, animDuration: self.animDuration)) } } }
apache-2.0
25d305dc11538d9a1577dbc4cc0c8e40
41
205
0.676663
5.024658
false
false
false
false
apple/swift
stdlib/public/core/ContiguousArray.swift
3
55889
//===--- ContiguousArray.swift --------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Three generic, mutable array-like types with value semantics. // // - `ContiguousArray<Element>` is a fast, contiguous array of `Element` with // a known backing store. // //===----------------------------------------------------------------------===// /// A contiguously stored array. /// /// The `ContiguousArray` type is a specialized array that always stores its /// elements in a contiguous region of memory. This contrasts with `Array`, /// which can store its elements in either a contiguous region of memory or an /// `NSArray` instance if its `Element` type is a class or `@objc` protocol. /// /// If your array's `Element` type is a class or `@objc` protocol and you do /// not need to bridge the array to `NSArray` or pass the array to Objective-C /// APIs, using `ContiguousArray` may be more efficient and have more /// predictable performance than `Array`. If the array's `Element` type is a /// struct or enumeration, `Array` and `ContiguousArray` should have similar /// efficiency. /// /// For more information about using arrays, see `Array` and `ArraySlice`, with /// which `ContiguousArray` shares most properties and methods. @frozen public struct ContiguousArray<Element>: _DestructorSafeContainer { @usableFromInline internal typealias _Buffer = _ContiguousArrayBuffer<Element> @usableFromInline internal var _buffer: _Buffer /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer: _Buffer) { self._buffer = _buffer } } //===--- private helpers---------------------------------------------------===// extension ContiguousArray { @inlinable @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.immutableCount } @inlinable @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.immutableCapacity } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUnique() { if _slowPath(!_buffer.beginCOWMutation()) { _buffer = _buffer._consumeAndCreateNew() } } /// Marks the end of an Array mutation. /// /// After a call to `_endMutation` the buffer must not be mutated until a call /// to `_makeMutableAndUnique`. @_alwaysEmitIntoClient @_semantics("array.end_mutation") internal mutating func _endMutation() { _buffer.endCOWMutation() } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkSubscript_native(_ index: Int) { _buffer._checkValidSubscript(index) } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// - Precondition: The buffer must be uniquely referenced and native. @_alwaysEmitIntoClient @_semantics("array.check_subscript") internal func _checkSubscript_mutating(_ index: Int) { _buffer._checkValidSubscriptMutating(index) } /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`. @inlinable @_semantics("array.check_index") internal func _checkIndex(_ index: Int) { _precondition(index <= endIndex, "ContiguousArray index is out of range") _precondition(index >= startIndex, "Negative ContiguousArray index is out of range") } @inlinable @_semantics("array.get_element_address") internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> { return _buffer.firstElementAddress + index } } extension ContiguousArray: _ArrayProtocol { /// The total number of elements that the array can contain without /// allocating new storage. /// /// Every array reserves a specific amount of memory to hold its contents. /// When you add elements to an array and that array begins to exceed its /// reserved capacity, the array allocates a larger region of memory and /// copies its elements into the new storage. The new storage is a multiple /// of the old storage's size. This exponential growth strategy means that /// appending an element happens in constant time, averaging the performance /// of many append operations. Append operations that trigger reallocation /// have a performance cost, but they occur less and less often as the array /// grows larger. /// /// The following example creates an array of integers from an array literal, /// then appends the elements of another collection. Before appending, the /// array allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = [10, 20, 30, 40, 50] /// // numbers.count == 5 /// // numbers.capacity == 5 /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// // numbers.count == 10 /// // numbers.capacity == 10 @inlinable public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. @inlinable public // @testable var _owner: AnyObject? { return _buffer.owner } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. @inlinable public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { @inline(__always) // FIXME(TODO: JIRA): Hack around test failure get { return _buffer.firstElementAddressIfContiguous } } @inlinable internal var _baseAddress: UnsafeMutablePointer<Element> { return _buffer.firstElementAddress } } extension ContiguousArray: RandomAccessCollection, MutableCollection { /// The index type for arrays, `Int`. public typealias Index = Int /// The type that represents the indices that are valid for subscripting an /// array, in ascending order. public typealias Indices = Range<Int> /// The type that allows iteration over an array's elements. public typealias Iterator = IndexingIterator<ContiguousArray> /// The position of the first element in a nonempty array. /// /// For an instance of `ContiguousArray`, `startIndex` is always zero. If the array /// is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Int { return 0 } /// The array's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an array, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the array is empty, `endIndex` is equal to `startIndex`. public var endIndex: Int { @inlinable get { return _getCount() } } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index immediately after `i`. @inlinable public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index immediately before `i`. @inlinable public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. @inlinable public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. @inlinable public func index(_ i: Int, offsetBy distance: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + distance } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.index(numbers.startIndex, /// offsetBy: 4, /// limitedBy: numbers.endIndex) { /// print(numbers[i]) /// } /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` has no effect if it is less than `i`. /// Likewise, if `distance < 0`, `limit` has no effect if it is greater /// than `i`. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Int, offsetBy distance: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return i + distance } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. @inlinable public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } @inlinable public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } @inlinable public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an array's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an array is O(1). Writing is O(1) /// unless the array's storage is shared with another array, in which case /// writing is O(*n*), where *n* is the length of the array. @inlinable public subscript(index: Int) -> Element { get { _checkSubscript_native(index) return _buffer.getElement(index) } _modify { _makeMutableAndUnique() _checkSubscript_mutating(index) let address = _buffer.mutableFirstElementAddress + index defer { _endMutation() } yield &address.pointee } } /// Accesses a contiguous subrange of the array's elements. /// /// The returned `ArraySlice` instance uses the same indices for the same /// elements as the original array. In particular, that slice, unlike an /// array, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the array. @inlinable public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) return ArraySlice(_buffer: _buffer[bounds]) } set(rhs) { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) // If the replacement buffer has same identity, and the ranges match, // then this was a pinned in-place modification, nothing further needed. if self[bounds]._buffer.identity != rhs._buffer.identity || bounds != rhs.startIndex..<rhs.endIndex { self.replaceSubrange(bounds, with: rhs) } } } /// The number of elements in the array. @inlinable public var count: Int { return _getCount() } } extension ContiguousArray: ExpressibleByArrayLiteral { /// Creates an array from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you use an array literal. Instead, create a new array by using an array /// literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, an array of strings is created from an array literal holding only /// strings: /// /// let ingredients: ContiguousArray = /// ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. @inlinable public init(arrayLiteral elements: Element...) { self.init(_buffer: ContiguousArray(elements)._buffer) } } extension ContiguousArray: RangeReplaceableCollection { /// Creates a new, empty array. /// /// This is equivalent to initializing with an empty array literal. /// For example: /// /// var emptyArray = Array<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" /// /// emptyArray = [] /// print(emptyArray.isEmpty) /// // Prints "true" @inlinable @_semantics("array.init.empty") public init() { _buffer = _Buffer() } /// Creates an array containing the elements of a sequence. /// /// You can use this initializer to create an array from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create an array with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Array(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// You can also use this initializer to convert a complex sequence or /// collection type back to an array. For example, the `keys` property of /// a dictionary isn't an array with its own storage, it's a collection /// that maps its elements from the dictionary only when they're /// accessed, saving the time and space needed to allocate an array. If /// you need to pass those keys to a method that takes an array, however, /// use this initializer to convert that list from its type of /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple /// `[String]`. /// /// func cacheImagesWithNames(names: [String]) { /// // custom image loading and caching /// } /// /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// "Gold": 50, "Cerise": 320] /// let colorNames = Array(namedHues.keys) /// cacheImagesWithNames(colorNames) /// /// print(colorNames) /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// /// - Parameter s: The sequence of elements to turn into an array. @inlinable public init<S: Sequence>(_ s: S) where S.Element == Element { self.init(_buffer: s._copyToContiguousArray()._buffer) } /// Creates a new array containing the specified number of a single, repeated /// value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable @_semantics("array.init") public init(repeating repeatedValue: Element, count: Int) { var p: UnsafeMutablePointer<Element> (self, p) = ContiguousArray._allocateUninitialized(count) for _ in 0..<count { p.initialize(to: repeatedValue) p += 1 } _endMutation() } @inline(never) @usableFromInline internal static func _allocateBufferUninitialized( minimumCapacity: Int ) -> _Buffer { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: 0, minimumCapacity: minimumCapacity) return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// Construct a ContiguousArray of `count` uninitialized elements. @inlinable internal init(_uninitializedCount count: Int) { _precondition(count >= 0, "Can't construct ContiguousArray with count < 0") // Note: Sinking this constructor into an else branch below causes an extra // Retain/Release. _buffer = _Buffer() if count > 0 { // Creating a buffer instead of calling reserveCapacity saves doing an // unnecessary uniqueness check. We disable inlining here to curb code // growth. _buffer = ContiguousArray._allocateBufferUninitialized(minimumCapacity: count) _buffer.mutableCount = count } // Can't store count here because the buffer might be pointing to the // shared empty array. } /// Entry point for `Array` literal construction; builds and returns /// a ContiguousArray of `count` uninitialized elements. @inlinable @_semantics("array.uninitialized") internal static func _allocateUninitialized( _ count: Int ) -> (ContiguousArray, UnsafeMutablePointer<Element>) { let result = ContiguousArray(_uninitializedCount: count) return (result, result._buffer.firstElementAddress) } //===--- basic mutations ------------------------------------------------===// /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an array, use this method /// to avoid multiple reallocations. This method ensures that the array has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// For performance reasons, the size of the newly allocated storage might be /// greater than the requested capacity. Use the array's `capacity` property /// to determine the size of the new storage. /// /// Preserving an Array's Geometric Growth Strategy /// =============================================== /// /// If you implement a custom data structure backed by an array that grows /// dynamically, naively calling the `reserveCapacity(_:)` method can lead /// to worse than expected performance. Arrays need to follow a geometric /// allocation pattern for appending elements to achieve amortized /// constant-time performance. The `Array` type's `append(_:)` and /// `append(contentsOf:)` methods take care of this detail for you, but /// `reserveCapacity(_:)` allocates only as much space as you tell it to /// (padded to a round value), and no more. This avoids over-allocation, but /// can result in insertion not having amortized constant-time performance. /// /// The following code declares `values`, an array of integers, and the /// `addTenQuadratic()` function, which adds ten more values to the `values` /// array on each call. /// /// var values: [Int] = [0, 1, 2, 3] /// /// // Don't use 'reserveCapacity(_:)' like this /// func addTenQuadratic() { /// let newCount = values.count + 10 /// values.reserveCapacity(newCount) /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// The call to `reserveCapacity(_:)` increases the `values` array's capacity /// by exactly 10 elements on each pass through `addTenQuadratic()`, which /// is linear growth. Instead of having constant time when averaged over /// many calls, the function may decay to performance that is linear in /// `values.count`. This is almost certainly not what you want. /// /// In cases like this, the simplest fix is often to simply remove the call /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array /// for you. /// /// func addTen() { /// let newCount = values.count + 10 /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// If you need more control over the capacity of your array, implement your /// own geometric growth strategy, passing the size you compute to /// `reserveCapacity(_:)`. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the number of elements in the array. @inlinable @_semantics("array.mutate_unknown") public mutating func reserveCapacity(_ minimumCapacity: Int) { _reserveCapacityImpl(minimumCapacity: minimumCapacity, growForAppend: false) _endMutation() } /// Reserves enough space to store `minimumCapacity` elements. /// If a new buffer needs to be allocated and `growForAppend` is true, /// the new capacity is calculated using `_growArrayCapacity`. @_alwaysEmitIntoClient internal mutating func _reserveCapacityImpl( minimumCapacity: Int, growForAppend: Bool ) { let isUnique = _buffer.beginCOWMutation() if _slowPath(!isUnique || _buffer.mutableCapacity < minimumCapacity) { _createNewBuffer(bufferIsUnique: isUnique, minimumCapacity: Swift.max(minimumCapacity, _buffer.count), growForAppend: growForAppend) } _internalInvariant(_buffer.mutableCapacity >= minimumCapacity) _internalInvariant(_buffer.mutableCapacity == 0 || _buffer.isUniquelyReferenced()) } /// Creates a new buffer, replacing the current buffer. /// /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely /// referenced by this array and the elements are moved - instead of copied - /// to the new buffer. /// The `minimumCapacity` is the lower bound for the new capacity. /// If `growForAppend` is true, the new capacity is calculated using /// `_growArrayCapacity`. @_alwaysEmitIntoClient @inline(never) internal mutating func _createNewBuffer( bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool ) { _internalInvariant(!bufferIsUnique || _buffer.isUniquelyReferenced()) _buffer = _buffer._consumeAndCreateNew(bufferIsUnique: bufferIsUnique, minimumCapacity: minimumCapacity, growForAppend: growForAppend) } /// Copy the contents of the current buffer to a new unique mutable buffer. /// The count of the new buffer is set to `oldCount`, the capacity of the /// new buffer is big enough to hold 'oldCount' + 1 elements. @inline(never) @inlinable // @specializable internal mutating func _copyToNewBuffer(oldCount: Int) { let newCount = oldCount &+ 1 var newBuffer = _buffer._forceCreateUniqueMutableBuffer( countForNewBuffer: oldCount, minNewCapacity: newCount) _buffer._arrayOutOfPlaceUpdate( &newBuffer, oldCount, 0) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() { if _slowPath(!_buffer.beginCOWMutation()) { _createNewBuffer(bufferIsUnique: false, minimumCapacity: count &+ 1, growForAppend: true) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) { // Due to make_mutable hoisting the situation can arise where we hoist // _makeMutableAndUnique out of loop and use it to replace // _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the // array was empty _makeMutableAndUnique does not replace the empty array // buffer by a unique buffer (it just replaces it by the empty array // singleton). // This specific case is okay because we will make the buffer unique in this // function because we request a capacity > 0 and therefore _copyToNewBuffer // will be called creating a new buffer. let capacity = _buffer.mutableCapacity _internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced()) if _slowPath(oldCount &+ 1 > capacity) { _createNewBuffer(bufferIsUnique: capacity > 0, minimumCapacity: oldCount &+ 1, growForAppend: true) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _appendElementAssumeUniqueAndCapacity( _ oldCount: Int, newElement: __owned Element ) { _internalInvariant(_buffer.isMutableAndUniquelyReferenced()) _internalInvariant(_buffer.mutableCapacity >= _buffer.mutableCount &+ 1) _buffer.mutableCount = oldCount &+ 1 (_buffer.mutableFirstElementAddress + oldCount).initialize(to: newElement) } /// Adds a new element at the end of the array. /// /// Use this method to append a single element to the end of a mutable array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because arrays increase their allocated capacity using an exponential /// strategy, appending a single element to an array is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When an array /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When an array needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the array. /// /// - Parameter newElement: The element to append to the array. /// /// - Complexity: O(1) on average, over many calls to `append(_:)` on the /// same array. @inlinable @_semantics("array.append_element") public mutating func append(_ newElement: __owned Element) { // Separating uniqueness check and capacity check allows hoisting the // uniqueness check out of a loop. _makeUniqueAndReserveCapacityIfNotUnique() let oldCount = _buffer.mutableCount _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount) _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement) _endMutation() } /// Adds the elements of a sequence to the end of the array. /// /// Use this method to append the elements of a sequence to the end of this /// array. This example appends the elements of a `Range<Int>` instance /// to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the array. /// /// - Complexity: O(*m*) on average, where *m* is the length of /// `newElements`, over many calls to `append(contentsOf:)` on the same /// array. @inlinable @_semantics("array.append_contentsOf") public mutating func append<S: Sequence>(contentsOf newElements: __owned S) where S.Element == Element { defer { _endMutation() } let newElementsCount = newElements.underestimatedCount _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount, growForAppend: true) let oldCount = _buffer.mutableCount let startNewElements = _buffer.mutableFirstElementAddress + oldCount let buf = UnsafeMutableBufferPointer( start: startNewElements, count: _buffer.mutableCapacity - oldCount) var (remainder,writtenUpTo) = buf.initialize(from: newElements) // trap on underflow from the sequence's underestimate: let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo) _precondition(newElementsCount <= writtenCount, "newElements.underestimatedCount was an overestimate") // can't check for overflow as sequences can underestimate // This check prevents a data race writing to _swiftEmptyArrayStorage if writtenCount > 0 { _buffer.mutableCount = _buffer.mutableCount + writtenCount } if writtenUpTo == buf.endIndex { // there may be elements that didn't fit in the existing buffer, // append them in slow sequence-only mode var newCount = _buffer.mutableCount var nextItem = remainder.next() while nextItem != nil { _reserveCapacityAssumingUniqueBuffer(oldCount: newCount) let currentCapacity = _buffer.mutableCapacity let base = _buffer.mutableFirstElementAddress // fill while there is another item and spare capacity while let next = nextItem, newCount < currentCapacity { (base + newCount).initialize(to: next) newCount += 1 nextItem = remainder.next() } _buffer.mutableCount = newCount } } } @inlinable @_semantics("array.reserve_capacity_for_append") internal mutating func reserveCapacityForAppend(newElementsCount: Int) { // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique self even if newElements is empty. _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount, growForAppend: true) _endMutation() } @inlinable @_semantics("array.mutate_unknown") public mutating func _customRemoveLast() -> Element? { _makeMutableAndUnique() let newCount = _buffer.mutableCount - 1 _precondition(newCount >= 0, "Can't removeLast from an empty ContiguousArray") let pointer = (_buffer.mutableFirstElementAddress + newCount) let element = pointer.move() _buffer.mutableCount = newCount _endMutation() return element } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - 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. @inlinable @discardableResult @_semantics("array.mutate_unknown") public mutating func remove(at index: Int) -> Element { _makeMutableAndUnique() let currentCount = _buffer.mutableCount _precondition(index < currentCount, "Index out of range") _precondition(index >= 0, "Index out of range") let newCount = currentCount - 1 let pointer = (_buffer.mutableFirstElementAddress + index) let result = pointer.move() pointer.moveInitialize(from: pointer + 1, count: newCount - index) _buffer.mutableCount = newCount _endMutation() return result } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the array or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the array. If /// `i == endIndex`, this method is equivalent to `append(_:)`. @inlinable public mutating func insert(_ newElement: __owned Element, at i: Int) { _checkIndex(i) self.replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// 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. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// @inlinable @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable") public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeBufferPointer { (bufferPointer) -> R in return try body(bufferPointer) } } @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { if let n = _buffer.requestNativeBuffer() { return ContiguousArray(_buffer: n) } return _copyCollectionToContiguousArray(self) } } #if SWIFT_ENABLE_REFLECTION extension ContiguousArray: CustomReflectable { /// A mirror that reflects the array. public var customMirror: Mirror { return Mirror( self, unlabeledChildren: self, displayStyle: .collection) } } #endif extension ContiguousArray: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return _makeCollectionDescription() } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { return _makeCollectionDescription(withTypeName: "ContiguousArray") } } extension ContiguousArray { @usableFromInline @_transparent internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, UnsafeRawPointer(p)) } let n = ContiguousArray(self._buffer)._buffer return (n.owner, UnsafeRawPointer(n.firstElementAddress)) } } extension ContiguousArray { /// Creates an array with the specified capacity, then calls the given /// closure with a buffer covering the array's uninitialized memory. /// /// Inside the closure, set the `initializedCount` parameter to the number of /// elements that are initialized by the closure. The memory in the range /// `buffer[0..<initializedCount]` must be initialized at the end of the /// closure's execution, and the memory in the range /// `buffer[initializedCount...]` must be uninitialized. This postcondition /// must hold even if the `initializer` closure throws an error. /// /// - Note: While the resulting array may have a capacity larger than the /// requested amount, the buffer passed to the closure will cover exactly /// the requested number of elements. /// /// - Parameters: /// - unsafeUninitializedCapacity: The number of elements to allocate /// space for in the new array. /// - initializer: A closure that initializes elements and sets the count /// of the new array. /// - Parameters: /// - buffer: A buffer covering uninitialized memory with room for the /// specified number of elements. /// - initializedCount: The count of initialized elements in the array, /// which begins as zero. Set `initializedCount` to the number of /// elements you initialize. @_alwaysEmitIntoClient @inlinable public init( unsafeUninitializedCapacity: Int, initializingWith initializer: ( _ buffer: inout UnsafeMutableBufferPointer<Element>, _ initializedCount: inout Int) throws -> Void ) rethrows { self = try ContiguousArray(Array( _unsafeUninitializedCapacity: unsafeUninitializedCapacity, initializingWith: initializer)) } /// Calls a closure with a pointer to the array's contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how you can iterate over the contents of the /// buffer pointer: /// /// let numbers = [1, 2, 3, 4, 5] /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in /// var result = 0 /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) { /// result += buffer[i] /// } /// return result /// } /// // 'sum' == 9 /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the /// pointer for later use. /// /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that /// points to the contiguous storage for the array. If /// `body` has a return value, that value is also used as the return value /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is /// valid only for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Calls the given closure with a pointer to the array's mutable contiguous /// storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how modifying the contents of the /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of /// the array: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.withUnsafeMutableBufferPointer { buffer in /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) { /// buffer.swapAt(i, i + 1) /// } /// } /// print(numbers) /// // Prints "[2, 1, 4, 3, 5]" /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or /// return the pointer for later use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableBufferPointer` /// parameter that points to the contiguous storage for the array. /// If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBufferPointer(_:)` /// method. The pointer argument is valid only for the duration of the /// method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @_semantics("array.withUnsafeMutableBufferPointer") @inlinable // FIXME(inline-always) @inline(__always) // Performance: This method should get inlined into the // caller such that we can combine the partial apply with the apply in this // function saving on allocating a closure context. This becomes unnecessary // once we allocate noescape closures on the stack. public mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _makeMutableAndUnique() let count = _buffer.mutableCount // Create an UnsafeBufferPointer that we can pass to body let pointer = _buffer.mutableFirstElementAddress var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "ContiguousArray withUnsafeMutableBufferPointer: replacing the buffer is not allowed") _endMutation() _fixLifetime(self) } // Invoke the body. return try body(&inoutBufferPointer) } @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) } // It is not OK for there to be no pointer/not enough space, as this is // a precondition and Array never lies about its count. guard var p = buffer.baseAddress else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") } _precondition(self.count <= buffer.count, "Insufficient space allocated to copy array contents") if let s = _baseAddressIfContiguous { p.initialize(from: s, count: self.count) // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter // and all uses of the pointer it returns: _fixLifetime(self._owner) } else { for x in self { p.initialize(to: x) p += 1 } } var it = IndexingIterator(_elements: self) it._position = endIndex return (it,buffer.index(buffer.startIndex, offsetBy: self.count)) } } extension ContiguousArray { /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the array and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The start and end of /// a subrange must be valid indices of the array. /// - newElements: The new elements to add to the array. /// /// - Complexity: O(*n* + *m*), where *n* is length of the array and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the array, this method is /// equivalent to `append(contentsOf:)`. @inlinable @_semantics("array.mutate_unknown") public mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: __owned C ) where C: Collection, C.Element == Element { _precondition(subrange.lowerBound >= self._buffer.startIndex, "ContiguousArray replace: subrange start is negative") _precondition(subrange.upperBound <= _buffer.endIndex, "ContiguousArray replace: subrange extends past the end") let eraseCount = subrange.count let insertCount = newElements.count let growth = insertCount - eraseCount _reserveCapacityImpl(minimumCapacity: self.count + growth, growForAppend: true) _buffer.replaceSubrange(subrange, with: insertCount, elementsOf: newElements) _endMutation() } } extension ContiguousArray: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two arrays contain the same /// elements in the same order. /// /// You can use the equal-to operator (`==`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func ==(lhs: ContiguousArray<Element>, rhs: ContiguousArray<Element>) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } _internalInvariant(lhs.startIndex == 0 && rhs.startIndex == 0) _internalInvariant(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount) // We know that lhs.count == rhs.count, compare element wise. for idx in 0..<lhsCount { if lhs[idx] != rhs[idx] { return false } } return true } } extension ContiguousArray: Hashable where Element: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(count) // discriminator for element in self { hasher.combine(element) } } } extension ContiguousArray { /// Calls the given closure with a pointer to the underlying bytes of the /// array's mutable contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies bytes from the `byteValues` array into /// `numbers`, an array of `Int32`: /// /// var numbers: [Int32] = [0, 0] /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] /// /// numbers.withUnsafeMutableBytes { destBytes in /// byteValues.withUnsafeBytes { srcBytes in /// destBytes.copyBytes(from: srcBytes) /// } /// } /// // numbers == [1, 2] /// /// - Note: This example shows the behavior on a little-endian platform. /// /// The pointer passed as an argument to `body` is valid only for the /// lifetime of the closure. Do not escape it from the closure for later /// use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableRawBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBytes(_:)` method. /// The argument is valid only for the duration of the closure's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public mutating func withUnsafeMutableBytes<R>( _ body: (UnsafeMutableRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeMutableBufferPointer { return try body(UnsafeMutableRawBufferPointer($0)) } } /// Calls the given closure with a pointer to the underlying bytes of the /// array's contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies the bytes of the `numbers` array into a /// buffer of `UInt8`: /// /// var numbers: [Int32] = [1, 2, 3] /// var byteBuffer: [UInt8] = [] /// numbers.withUnsafeBytes { /// byteBuffer.append(contentsOf: $0) /// } /// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0] /// /// - Note: This example shows the behavior on a little-endian platform. /// /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter /// that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeBufferPointer { try body(UnsafeRawBufferPointer($0)) } } } extension ContiguousArray: @unchecked Sendable where Element: Sendable { }
apache-2.0
eeb1a8dc8ee7f209618e49606c6135d3
38.077622
99
0.660278
4.488434
false
false
false
false
cpimhoff/AntlerKit
Framework/AntlerKit/Built In/Convenience/QuickEventResponders.swift
1
1319
// // QuickEventResponders.swift // AntlerKit // // Created by Charlie Imhoff on 5/2/17. // Copyright © 2017 Charlie Imhoff. All rights reserved. // import Foundation // MARK: - Respond to Contact Quick Action internal class RespondToContactComponent : SimpleComponent, AnonymousComponent, RespondsToContact { let phase : PhysicsContactPhase let action : (_ other: GameObject?) -> Void init(phase: PhysicsContactPhase, action: @escaping (_ other: GameObject?) -> Void) { self.phase = phase self.action = action } func onContactBegan(with other: GameObject?) { if phase == .begin { self.action(other) } } func onContactEnded(with other: GameObject?) { if phase == .end { self.action(other) } } } public extension GameObject { /// Runs the closure whenever this GameObject makes contact with another. func defineOnContactsBegin(_ action: @escaping (_ other: GameObject?) -> Void) { let responseComponent = RespondToContactComponent(phase: .begin, action: action) self.add(responseComponent) } /// Runs the closure whenever this GameObject ends contact with another. func defineOnContactsEnd(_ action: @escaping (_ other: GameObject?) -> Void) { let responseComponent = RespondToContactComponent(phase: .end, action: action) self.add(responseComponent) } }
mit
83423c1fa4e17506a3b59ef8037c9aa5
24.843137
99
0.719272
3.640884
false
false
false
false
Monapp/Hryvna-backend
Sources/App/Request+Utils.swift
1
4346
// // ModelsUtils.swift // Hryvna // // Created by Vladimir Hulchenko on 12/29/16. // // import Foundation import Vapor import HTTP let ratesAvaragePoint = "/rates/averages" let ratesBankPoint = "/rates/banks" let ratesLandingPoint = "/rates/landing" let ratesTodayPoint = "/rates/today" let listCurrenciesPoint = "/list/currencies" let listBanksPoint = "/list/banks" let newsPoint = "/news" enum TypeRequest { case ratesAvarage case ratesBank case ratesLanding case ratesToday case listCurrencies case listBanks case news var point: String { switch self { case .ratesAvarage: return ratesAvaragePoint case .ratesBank: return ratesBankPoint case .ratesLanding: return ratesLandingPoint case .ratesToday: return ratesTodayPoint case .listCurrencies: return listCurrenciesPoint case .listBanks: return listBanksPoint case .news: return newsPoint } } func getModel() throws -> Model? { switch self { case .ratesAvarage: return try Avarage.query().first() case .ratesBank: return try BankAvarage.query().first() case .ratesLanding: return try Landing.query().first() case .ratesToday: return try TodayAvarage.query().first() case .listCurrencies: return try ListCurrency.query().first() case .listBanks: return try ListBank.query().first() case .news: return try News.query().first() } } func saveModel(nodeResponse: Node) throws -> Model? { var node: Node! if let nodeData = nodeResponse["data"]?.node { node = Node.init(nodeData) } else { node = nodeResponse } switch self { case .ratesAvarage: if let oldModel = try Avarage.query().first() { try oldModel.delete() } var model = Avarage.init(data: node) try model.save() return model case .ratesBank: if let oldModel = try BankAvarage.query().first() { try oldModel.delete() } var model = BankAvarage.init(data: node) try model.save() return model case .ratesLanding: if let oldModel = try Landing.query().first() { try oldModel.delete() } var model = Landing.init(data: node) try model.save() return model case .ratesToday: if let oldModel = try TodayAvarage.query().first() { try oldModel.delete() } var model = TodayAvarage.init(data: node) try model.save() return model case .listCurrencies: if let oldModel = try ListCurrency.query().first() { try oldModel.delete() } var model = ListCurrency.init(data: node) try model.save() return model case .listBanks: if let oldModel = try ListBank.query().first() { try oldModel.delete() } var model = ListBank.init(data: node) try model.save() return model case .news: if let oldModel = try News.query().first() { try oldModel.delete() } var model = News.init(data: node) try model.save() return model } } }
mit
90bc551dfbcd16b9bde4160f06bba375
22.879121
64
0.449609
5.223558
false
false
false
false
4taras4/totp-auth
TOTPTests/ViperModules/AddItemManualy/Assembly/AddItemManualyContainerTests.swift
1
2016
// // AddItemManualyAddItemManualyContainerTests.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import XCTest @testable import TOTP class AddItemManualyModuleConfiguratorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testConfigureModuleForViewController() { //given let viewController = AddItemManualyViewControllerMock() let presenter = container.resolve(AddItemManualyPresenter.self, argument: viewController as AddItemManualyViewController)! //when viewController.output = presenter //then XCTAssertNotNil(viewController.output, "AddItemManualyViewController is nil after configuration") XCTAssertTrue(viewController.output is AddItemManualyPresenter, "output is not AddItemManualyPresenter") let presenter: AddItemManualyPresenter = viewController.output as! AddItemManualyPresenter XCTAssertNotNil(presenter.view, "view in AddItemManualyPresenter is nil after configuration") XCTAssertNotNil(presenter.router, "router in AddItemManualyPresenter is nil after configuration") XCTAssertTrue(presenter.router is AddItemManualyRouter, "router is not AddItemManualyRouter") let interactor: AddItemManualyInteractor = presenter.interactor as! AddItemManualyInteractor XCTAssertNotNil(interactor.output, "output in AddItemManualyInteractor is nil after configuration") } class AddItemManualyViewControllerMock: AddItemManualyViewController { var setupInitialStateDidCall = false override func setupInitialState() { setupInitialStateDidCall = true } } }
mit
ab23f6d2c1df7ef3c4282e29b0789b61
36.314815
130
0.736476
5.445946
false
true
false
false
QuarkX/Quark
Sources/Quark/OpenSSL/Context.swift
1
3986
import COpenSSL public enum ContextError : Error { case context(description: String) case certificate(description: String) case key(description: String) } public class Context { let mode: SSLMethod.Mode var context: UnsafeMutablePointer<SSL_CTX>? var sniHostname: String? = nil public init(method: SSLMethod = .sslv23, mode: SSLMethod.Mode = .client) throws { self.mode = mode initialize() context = SSL_CTX_new(method.getMethod(mode: mode)) if context == nil { throw ContextError.context(description: lastSSLErrorDescription) } if mode == .client { SSL_CTX_set_verify(context, SSL_VERIFY_NONE, nil) // SSL_CTX_set_verify_depth(context, 4) // SSL_CTX_ctrl(context, SSL_CTRL_OPTIONS, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION, nil) // try useDefaultVerifyPaths() } else { SSL_CTX_set_verify(context, SSL_VERIFY_NONE, nil) } } public convenience init(method: SSLMethod = .sslv23, mode: SSLMethod.Mode = .client, verifyBundle: String? = nil, certificate: String? = nil, privateKey: String? = nil, certificateChain: String? = nil, sniHostname: String? = nil) throws { try self.init(method: method, mode: mode) if let verifyBundle = verifyBundle { try useVerifyBundle(verifyBundle: verifyBundle) } if let certificateChain = certificateChain { try useCertificateChainFile(certificateChainFile: certificateChain) } if let certificate = certificate { try useCertificateFile(certificateFile: certificate) } if let privateKey = privateKey { try usePrivateKeyFile(privateKeyFile: privateKey) } if let sniHostname = sniHostname { try setServerNameIndication(hostname: sniHostname) } } deinit { SSL_CTX_free(context) } public func useDefaultVerifyPaths() throws { if SSL_CTX_set_default_verify_paths(context) != 1 { throw ContextError.context(description: lastSSLErrorDescription) } } public func useVerifyBundle(verifyBundle: String) throws { if SSL_CTX_load_verify_locations(context, verifyBundle, nil) != 1 { throw ContextError.context(description: lastSSLErrorDescription) } } public func useCertificate(certificate: Certificate) throws { if SSL_CTX_use_certificate(context, certificate.certificate) != 1 { throw ContextError.certificate(description: lastSSLErrorDescription) } } public func useCertificateFile(certificateFile: String) throws { if SSL_CTX_use_certificate_file(context, certificateFile, SSL_FILETYPE_PEM) != 1 { throw ContextError.certificate(description: lastSSLErrorDescription) } } public func useCertificateChainFile(certificateChainFile: String) throws { if SSL_CTX_use_certificate_chain_file(context, certificateChainFile) != 1 { throw ContextError.certificate(description: lastSSLErrorDescription) } } public func usePrivateKey(privateKey: Key, check: Bool = true) throws { if SSL_CTX_use_PrivateKey(context, privateKey.key) != 1 { throw ContextError.key(description: lastSSLErrorDescription) } if check { try checkPrivateKey() } } public func usePrivateKeyFile(privateKeyFile: String, check: Bool = true) throws { if SSL_CTX_use_PrivateKey_file(context, privateKeyFile, SSL_FILETYPE_PEM) != 1 { throw ContextError.key(description: lastSSLErrorDescription) } if check { try checkPrivateKey() } } private func checkPrivateKey() throws { if SSL_CTX_check_private_key(context) != 1 { throw ContextError.key(description: lastSSLErrorDescription) } } public func setCipherSuites(cipherSuites: String) throws { if SSL_CTX_set_cipher_list(context, cipherSuites) != 1 { throw ContextError.context(description: lastSSLErrorDescription) } } public func setSrtpProfiles(srtpProfiles: String) throws { if SSL_CTX_set_tlsext_use_srtp(context, srtpProfiles) != 1 { throw ContextError.context(description: lastSSLErrorDescription) } } public func setServerNameIndication(hostname: String) throws { sniHostname = hostname } }
mit
911d595ab91712375e56f90def1d0179
29.427481
239
0.737331
3.472125
false
false
false
false
gzios/swift
SwiftBase/Swift函数.playground/Contents.swift
1
1672
//: Playground - noun: a place where people can play import UIKit //函数,,哈哈多么熟悉的名字啊! //无参无返回 func about() -> Void{ print("iPhone7") } about() func about1(){ print("iPhone7") } about1() //无参有返回 func readMessage() -> String{ return "你弄啥呢"; } print(readMessage()) var sdd = readMessage() //有参无返回 func callPhone(phoneNum:String){ print("打电话"+phoneNum) print("打电话\(phoneNum)") } callPhone(phoneNum: "+86 110") //有参有返回 func sum(num1:Int,num2:Int) -> Int{ return num1 + num2 } print(sum(num1: 2, num2: 4)) //使用注意 func sum(num1:Int,num2:Int,num3:Int) -> Int{ return num1 + num2 + num3 } sum(num1: 30, num2: 40) sum(num1: 30, num2: 40,num3: 30) //注意一:内部参数和外部参数 //默认所有的参数都是内部参数 //Swift中的默认参数 func makeCoffee(coffeeName:String = "雀巢") -> String{ return "制作了一杯\(coffeeName)咖啡" } makeCoffee(coffeeName: "拿铁") makeCoffee(coffeeName: "卡布奇诺") makeCoffee(coffeeName: "猫屎") makeCoffee() //可变参数 func sums(num:Int...) -> Int func sums(num:Int...) -> Int{ var result = 0 for n in num { result += n } return result } print(sums(num: 12,23,34)) //指针类型 var m = 20 var n = 40 //func swapNum(m: Int, n : Int){ // let tempNum = m // m = n // n = tempNum //} //func swapNum(inout m: Int,inout n : Int){ // let tempNum = m // m = n // n = tempNum //} //swapNum(m: &m, n: &n) //函数的嵌套使用 func test(){ func demo(){ print("demo") } print("test") demo() } test()
apache-2.0
591b378fc23fe5b80b8bef3a72e5f88e
13.755102
52
0.59751
2.463373
false
false
false
false
ACChe/eidolon
KioskTests/ListingsViewControllerTests.swift
1
5274
import Quick import Nimble @testable import Kiosk import ReactiveCocoa import Nimble_Snapshots import Foundation import Moya class ListingsViewControllerConfiguration: QuickConfiguration { override class func configure(configuration: Configuration) { sharedExamples("a listings controller", closure: { (sharedExampleContext: SharedExampleContext) in var subject: ListingsViewController! var viewModel: ListingsViewControllerTestsStubbedViewModel! beforeEach{ subject = sharedExampleContext()["subject"] as! ListingsViewController viewModel = subject.viewModel as! ListingsViewControllerTestsStubbedViewModel subject.loadViewProgrammatically() } it("grid") { subject.switchView[0]?.sendActionsForControlEvents(.TouchUpInside) expect(subject) == snapshot() } it("least bids") { subject.switchView[1]?.sendActionsForControlEvents(.TouchUpInside) viewModel.gridSelected = false expect(subject) == snapshot() } it("most bids") { subject.switchView[2]?.sendActionsForControlEvents(.TouchUpInside) viewModel.gridSelected = false expect(subject) == snapshot() } it("highest bid") { subject.switchView[3]?.sendActionsForControlEvents(.TouchUpInside) viewModel.gridSelected = false expect(subject) == snapshot() } it("lowest bid") { subject.switchView[4]?.sendActionsForControlEvents(.TouchUpInside) viewModel.gridSelected = false expect(subject) == snapshot() } it("alphabetical") { subject.switchView[5]?.sendActionsForControlEvents(.TouchUpInside) viewModel.gridSelected = false expect(subject) == snapshot() } }) } } class ListingsViewControllerTests: QuickSpec { override func spec() { describe("when displaying stubbed contents") { var subject: ListingsViewController! beforeEach { subject = testListingsViewController() } describe("without lot numbers") { itBehavesLike("a listings controller") { ["subject": subject] } } describe("with lot numbers") { beforeEach { let viewModel = ListingsViewControllerTestsStubbedViewModel() viewModel.lotNumber = 13 subject.viewModel = viewModel } itBehavesLike("a listings controller") { ["subject": subject] } } describe("with artworks not for sale") { beforeEach { let viewModel = ListingsViewControllerTestsStubbedViewModel() viewModel.soldStatus = "sold" subject.viewModel = viewModel } itBehavesLike("a listings controller") { ["subject": subject] } } } } } let listingsViewControllerTestsImage = UIImage.testImage(named: "artwork", ofType: "jpg") func testListingsViewController(storyboard: UIStoryboard = auctionStoryboard) -> ListingsViewController { let subject = ListingsViewController.instantiateFromStoryboard(storyboard) subject.viewModel = ListingsViewControllerTestsStubbedViewModel() subject.downloadImage = { (url, imageView) -> () in if let _ = url { imageView.image = listingsViewControllerTestsImage } else { imageView.image = nil } } subject.cancelDownloadImage = { (imageView) -> () in } return subject } class ListingsViewControllerTestsStubbedViewModel: NSObject, ListingsViewModelType { var auctionID = "los-angeles-modern-auctions-march-2015" var syncInterval = SyncInterval var pageSize = 10 var schedule: (RACSignal, RACScheduler) -> RACSignal = { signal, _ -> RACSignal in signal } var logSync: (AnyObject!) -> Void = { _ in} var numberOfSaleArtworks = 10 var showSpinnerSignal = RACSignal.`return`(false) var gridSelectedSignal: RACSignal! { return RACObserve(self, "gridSelected") } var updatedContentsSignal: RACSignal! { return RACSignal.`return`(NSDate()) } func saleArtworkViewModelAtIndexPath(indexPath: NSIndexPath) -> SaleArtworkViewModel { let saleArtwork = testSaleArtwork() saleArtwork.lotNumber = lotNumber if let soldStatus = soldStatus { saleArtwork.artwork.soldStatus = soldStatus } saleArtwork.openingBidCents = 1_000_00 * (indexPath.item + 1) return saleArtwork.viewModel } func showDetailsForSaleArtworkAtIndexPath(indexPath: NSIndexPath) { } func presentModalForSaleArtworkAtIndexPath(indexPath: NSIndexPath) { } func imageAspectRatioForSaleArtworkAtIndexPath(indexPath: NSIndexPath) -> CGFloat? { return nil } // Testing values var lotNumber: Int? var soldStatus: String? dynamic var gridSelected = true }
mit
c21fee2028e9b8a2ae7771699d39eb08
33.927152
106
0.618127
5.912556
false
true
false
false
chenkanck/iOSNoteBook
iOSNoteBook/iOSNoteBook/DetailViewController.swift
1
1518
// // DetailViewController.swift // iOSNoteBook // // Created by Kan Chen on 9/18/15. // Copyright (c) 2015 Zap. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() let nt = Notification() nt.addObservers() NSNotificationCenter.defaultCenter().postNotificationName("one", object: nil) // Do any additional setup after loading the view. let de = CIDetector(ofType: CIDetectorTypeText, context: nil, options: [:]) let image = UIImage(named: "card2") let ci = CIImage(image: image!) let fe = de.featuresInImage(ci!) if let f = fe[0] as? CITextFeature{ print("some \(f)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension DetailViewController: monsterSelectionDelegate{ func monsterSelected(newMonster: String) { label.text = newMonster } }
mit
762f4c1cd49766e1a5c5bc311b56e06a
26.6
106
0.644269
4.788644
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/InternalSchemeHandler/ErrorPageHelper.swift
2
16759
// 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 import GCDWebServers import Shared import Storage private let MozDomain = "mozilla" private let MozErrorDownloadsNotEnabled = 100 private let MessageOpenInSafari = "openInSafari" private let MessageCertVisitOnce = "certVisitOnce" // Regardless of cause, NSURLErrorServerCertificateUntrusted is currently returned in all cases. // Check the other cases in case this gets fixed in the future. private let CertErrors = [ NSURLErrorServerCertificateUntrusted, NSURLErrorServerCertificateHasBadDate, NSURLErrorServerCertificateHasUnknownRoot, NSURLErrorServerCertificateNotYetValid ] // Error codes copied from Gecko. The ints corresponding to these codes were determined // by inspecting the NSError in each of these cases. private let CertErrorCodes = [ -9813: "SEC_ERROR_UNKNOWN_ISSUER", -9814: "SEC_ERROR_EXPIRED_CERTIFICATE", -9843: "SSL_ERROR_BAD_CERT_DOMAIN", ] private func certFromErrorURL(_ url: URL) -> SecCertificate? { func getCert(_ url: URL) -> SecCertificate? { let components = URLComponents(url: url, resolvingAgainstBaseURL: false) if let encodedCert = components?.queryItems?.filter({ $0.name == "badcert" }).first?.value, let certData = Data(base64Encoded: encodedCert, options: []) { return SecCertificateCreateWithData(nil, certData as CFData) } return nil } let result = getCert(url) if result != nil { return result } // Fallback case when the error url is nested, this happens when restoring an error url, it will be inside a 'sessionrestore' url. // TODO: Investigate if we can restore directly as an error url and avoid the 'sessionrestore?url=' wrapping. if let internalUrl = InternalURL(url), let url = internalUrl.extractedUrlParam { return getCert(url) } return nil } private func cfErrorToName(_ err: CFNetworkErrors) -> String { switch err { case .cfHostErrorHostNotFound: return "CFHostErrorHostNotFound" case .cfHostErrorUnknown: return "CFHostErrorUnknown" case .cfsocksErrorUnknownClientVersion: return "CFSOCKSErrorUnknownClientVersion" case .cfsocksErrorUnsupportedServerVersion: return "CFSOCKSErrorUnsupportedServerVersion" case .cfsocks4ErrorRequestFailed: return "CFSOCKS4ErrorRequestFailed" case .cfsocks4ErrorIdentdFailed: return "CFSOCKS4ErrorIdentdFailed" case .cfsocks4ErrorIdConflict: return "CFSOCKS4ErrorIdConflict" case .cfsocks4ErrorUnknownStatusCode: return "CFSOCKS4ErrorUnknownStatusCode" case .cfsocks5ErrorBadState: return "CFSOCKS5ErrorBadState" case .cfsocks5ErrorBadResponseAddr: return "CFSOCKS5ErrorBadResponseAddr" case .cfsocks5ErrorBadCredentials: return "CFSOCKS5ErrorBadCredentials" case .cfsocks5ErrorUnsupportedNegotiationMethod: return "CFSOCKS5ErrorUnsupportedNegotiationMethod" case .cfsocks5ErrorNoAcceptableMethod: return "CFSOCKS5ErrorNoAcceptableMethod" case .cfftpErrorUnexpectedStatusCode: return "CFFTPErrorUnexpectedStatusCode" case .cfErrorHTTPAuthenticationTypeUnsupported: return "CFErrorHTTPAuthenticationTypeUnsupported" case .cfErrorHTTPBadCredentials: return "CFErrorHTTPBadCredentials" case .cfErrorHTTPConnectionLost: return "CFErrorHTTPConnectionLost" case .cfErrorHTTPParseFailure: return "CFErrorHTTPParseFailure" case .cfErrorHTTPRedirectionLoopDetected: return "CFErrorHTTPRedirectionLoopDetected" case .cfErrorHTTPBadURL: return "CFErrorHTTPBadURL" case .cfErrorHTTPProxyConnectionFailure: return "CFErrorHTTPProxyConnectionFailure" case .cfErrorHTTPBadProxyCredentials: return "CFErrorHTTPBadProxyCredentials" case .cfErrorPACFileError: return "CFErrorPACFileError" case .cfErrorPACFileAuth: return "CFErrorPACFileAuth" case .cfErrorHTTPSProxyConnectionFailure: return "CFErrorHTTPSProxyConnectionFailure" case .cfStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod: return "CFStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod" case .cfurlErrorBackgroundSessionInUseByAnotherProcess: return "CFURLErrorBackgroundSessionInUseByAnotherProcess" case .cfurlErrorBackgroundSessionWasDisconnected: return "CFURLErrorBackgroundSessionWasDisconnected" case .cfurlErrorUnknown: return "CFURLErrorUnknown" case .cfurlErrorCancelled: return "CFURLErrorCancelled" case .cfurlErrorBadURL: return "CFURLErrorBadURL" case .cfurlErrorTimedOut: return "CFURLErrorTimedOut" case .cfurlErrorUnsupportedURL: return "CFURLErrorUnsupportedURL" case .cfurlErrorCannotFindHost: return "CFURLErrorCannotFindHost" case .cfurlErrorCannotConnectToHost: return "CFURLErrorCannotConnectToHost" case .cfurlErrorNetworkConnectionLost: return "CFURLErrorNetworkConnectionLost" case .cfurlErrorDNSLookupFailed: return "CFURLErrorDNSLookupFailed" case .cfurlErrorHTTPTooManyRedirects: return "CFURLErrorHTTPTooManyRedirects" case .cfurlErrorResourceUnavailable: return "CFURLErrorResourceUnavailable" case .cfurlErrorNotConnectedToInternet: return "CFURLErrorNotConnectedToInternet" case .cfurlErrorRedirectToNonExistentLocation: return "CFURLErrorRedirectToNonExistentLocation" case .cfurlErrorBadServerResponse: return "CFURLErrorBadServerResponse" case .cfurlErrorUserCancelledAuthentication: return "CFURLErrorUserCancelledAuthentication" case .cfurlErrorUserAuthenticationRequired: return "CFURLErrorUserAuthenticationRequired" case .cfurlErrorZeroByteResource: return "CFURLErrorZeroByteResource" case .cfurlErrorCannotDecodeRawData: return "CFURLErrorCannotDecodeRawData" case .cfurlErrorCannotDecodeContentData: return "CFURLErrorCannotDecodeContentData" case .cfurlErrorCannotParseResponse: return "CFURLErrorCannotParseResponse" case .cfurlErrorInternationalRoamingOff: return "CFURLErrorInternationalRoamingOff" case .cfurlErrorCallIsActive: return "CFURLErrorCallIsActive" case .cfurlErrorDataNotAllowed: return "CFURLErrorDataNotAllowed" case .cfurlErrorRequestBodyStreamExhausted: return "CFURLErrorRequestBodyStreamExhausted" case .cfurlErrorFileDoesNotExist: return "CFURLErrorFileDoesNotExist" case .cfurlErrorFileIsDirectory: return "CFURLErrorFileIsDirectory" case .cfurlErrorNoPermissionsToReadFile: return "CFURLErrorNoPermissionsToReadFile" case .cfurlErrorDataLengthExceedsMaximum: return "CFURLErrorDataLengthExceedsMaximum" case .cfurlErrorSecureConnectionFailed: return "CFURLErrorSecureConnectionFailed" case .cfurlErrorServerCertificateHasBadDate: return "CFURLErrorServerCertificateHasBadDate" case .cfurlErrorServerCertificateUntrusted: return "CFURLErrorServerCertificateUntrusted" case .cfurlErrorServerCertificateHasUnknownRoot: return "CFURLErrorServerCertificateHasUnknownRoot" case .cfurlErrorServerCertificateNotYetValid: return "CFURLErrorServerCertificateNotYetValid" case .cfurlErrorClientCertificateRejected: return "CFURLErrorClientCertificateRejected" case .cfurlErrorClientCertificateRequired: return "CFURLErrorClientCertificateRequired" case .cfurlErrorCannotLoadFromNetwork: return "CFURLErrorCannotLoadFromNetwork" case .cfurlErrorCannotCreateFile: return "CFURLErrorCannotCreateFile" case .cfurlErrorCannotOpenFile: return "CFURLErrorCannotOpenFile" case .cfurlErrorCannotCloseFile: return "CFURLErrorCannotCloseFile" case .cfurlErrorCannotWriteToFile: return "CFURLErrorCannotWriteToFile" case .cfurlErrorCannotRemoveFile: return "CFURLErrorCannotRemoveFile" case .cfurlErrorCannotMoveFile: return "CFURLErrorCannotMoveFile" case .cfurlErrorDownloadDecodingFailedMidStream: return "CFURLErrorDownloadDecodingFailedMidStream" case .cfurlErrorDownloadDecodingFailedToComplete: return "CFURLErrorDownloadDecodingFailedToComplete" case .cfhttpCookieCannotParseCookieFile: return "CFHTTPCookieCannotParseCookieFile" case .cfNetServiceErrorUnknown: return "CFNetServiceErrorUnknown" case .cfNetServiceErrorCollision: return "CFNetServiceErrorCollision" case .cfNetServiceErrorNotFound: return "CFNetServiceErrorNotFound" case .cfNetServiceErrorInProgress: return "CFNetServiceErrorInProgress" case .cfNetServiceErrorBadArgument: return "CFNetServiceErrorBadArgument" case .cfNetServiceErrorCancel: return "CFNetServiceErrorCancel" case .cfNetServiceErrorInvalid: return "CFNetServiceErrorInvalid" case .cfNetServiceErrorTimeout: return "CFNetServiceErrorTimeout" case .cfNetServiceErrorDNSServiceFailure: return "CFNetServiceErrorDNSServiceFailure" default: return "Unknown" } } class ErrorPageHandler: InternalSchemeResponse { static let path = InternalURL.Path.errorpage.rawValue func response(forRequest request: URLRequest) -> (URLResponse, Data)? { guard let requestUrl = request.url, let originalUrl = InternalURL(requestUrl)?.originalURLFromErrorPage else { return nil } guard let url = request.url, let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let code = components.valueForQuery("code"), let errCode = Int(code), let errDescription = components.valueForQuery("description"), let errURLDomain = originalUrl.host, var errDomain = components.valueForQuery("domain") else { return nil } var asset = Bundle.main.path(forResource: "NetError", ofType: "html") var variables = [ "error_code": "\(errCode)", "error_title": errDescription, "short_description": errDomain, ] let tryAgain: String = .ErrorPageTryAgain var actions = "<script>function reloader() { location.replace((new URL(location.href)).searchParams.get(\"url\")); }" + "</script><button onclick='reloader()'>\(tryAgain)</button>" if errDomain == kCFErrorDomainCFNetwork as String { if let code = CFNetworkErrors(rawValue: Int32(errCode)) { errDomain = cfErrorToName(code) } } else if errDomain == MozDomain { if errCode == MozErrorDownloadsNotEnabled { let downloadInSafari: String = .ErrorPageOpenInSafari // Overwrite the normal try-again action. actions = "<button onclick='webkit.messageHandlers.errorPageHelperMessageManager.postMessage({type: \"\(MessageOpenInSafari)\"})'>\(downloadInSafari)</button>" } errDomain = "" } else if CertErrors.contains(errCode) { guard let url = request.url, let comp = URLComponents(url: url, resolvingAgainstBaseURL: false), let certError = comp.valueForQuery("certerror") else { assert(false) return nil } asset = Bundle.main.path(forResource: "CertError", ofType: "html") actions = "<button onclick='history.back()'>\(String.ErrorPagesGoBackButton)</button>" variables["error_title"] = .ErrorPagesCertWarningTitle variables["cert_error"] = certError variables["long_description"] = String(format: .ErrorPagesCertWarningDescription, "<b>\(errURLDomain)</b>") variables["advanced_button"] = .ErrorPagesAdvancedButton variables["warning_description"] = .ErrorPagesCertWarningDescription variables["warning_advanced1"] = .ErrorPagesAdvancedWarning1 variables["warning_advanced2"] = .ErrorPagesAdvancedWarning2 variables["warning_actions"] = "<p><a id='\(UserScriptManager.appIdToken)__firefox__visitOnce' href='#'>\(String.ErrorPagesVisitOnceButton)</button></p>" } variables["actions"] = actions let response = InternalSchemeHandler.response(forUrl: originalUrl) guard let file = asset, var html = try? String(contentsOfFile: file) else { assert(false) return nil } variables.forEach { (arg, value) in html = html.replacingOccurrences(of: "%\(arg)%", with: value) } guard let data = html.data(using: .utf8) else { return nil } return (response, data) } } class ErrorPageHelper { fileprivate weak var certStore: CertStore? init(certStore: CertStore?) { self.certStore = certStore } func loadPage(_ error: NSError, forUrl url: URL, inWebView webView: WKWebView) { guard var components = URLComponents(string: "\(InternalURL.baseUrl)/\(ErrorPageHandler.path)"), let webViewUrl = webView.url else { return } // Page has failed to load again, just return and keep showing the existing error page. if let internalUrl = InternalURL(webViewUrl), internalUrl.originalURLFromErrorPage == url { return } var queryItems = [ URLQueryItem(name: InternalURL.Param.url.rawValue, value: url.absoluteString), URLQueryItem(name: "code", value: String(error.code)), URLQueryItem(name: "domain", value: error.domain), URLQueryItem(name: "description", value: error.localizedDescription), // 'timestamp' is used for the js reload logic URLQueryItem(name: "timestamp", value: "\(Int(Date().timeIntervalSince1970 * 1000))") ] // If this is an invalid certificate, show a certificate error allowing the // user to go back or continue. The certificate itself is encoded and added as // a query parameter to the error page URL; we then read the certificate from // the URL if the user wants to continue. if CertErrors.contains(error.code), let certChain = error.userInfo["NSErrorPeerCertificateChainKey"] as? [SecCertificate], let cert = certChain.first, let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError, let certErrorCode = underlyingError.userInfo["_kCFStreamErrorCodeKey"] as? Int { let encodedCert = (SecCertificateCopyData(cert) as Data).base64EncodedString queryItems.append(URLQueryItem(name: "badcert", value: encodedCert)) let certError = CertErrorCodes[certErrorCode] ?? "" queryItems.append(URLQueryItem(name: "certerror", value: String(certError))) } components.queryItems = queryItems if let urlWithQuery = components.url { if let internalUrl = InternalURL(webViewUrl), internalUrl.isSessionRestore, let page = InternalURL.authorize(url: urlWithQuery) { // A session restore page is already on the history stack, so don't load another page on the history stack. webView.replaceLocation(with: page) } else { // A new page needs to be added to the history stack (i.e. the simple case // of trying to navigate to an url for the first time and it fails, without // pushing a page on the history stack, the webview will just show the // current page). webView.load(PrivilegedRequest(url: urlWithQuery) as URLRequest) } } } } extension ErrorPageHelper: TabContentScript { static func name() -> String { return "ErrorPageHelper" } func scriptMessageHandlerName() -> String? { return "errorPageHelperMessageManager" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { guard let errorURL = message.frameInfo.request.url, let internalUrl = InternalURL(errorURL), internalUrl.isErrorPage, let originalURL = internalUrl.originalURLFromErrorPage, let res = message.body as? [String: String], let type = res["type"] else { return } switch type { case MessageOpenInSafari: UIApplication.shared.open(originalURL, options: [:]) case MessageCertVisitOnce: if let cert = certFromErrorURL(errorURL), let host = originalURL.host { let origin = "\(host):\(originalURL.port ?? 443)" certStore?.addCertificate(cert, forOrigin: origin) message.webView?.replaceLocation(with: originalURL) // webview.reload will not change the error URL back to the original URL } default: assertionFailure("Unknown error message") } } }
mpl-2.0
e292f9c151ce91340c32cd0e66bb7bb1
52.372611
175
0.728265
5.219246
false
false
false
false
wireapp/wire-ios-sync-engine
Tests/Source/Integration/FileTransferTests+Swift.swift
1
28258
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import WireSyncEngine class FileTransferTests_Swift: ConversationTestsBase { func remotelyInsertAssetOriginalAndUpdate(updateMessage: GenericMessage, insertBlock: @escaping (_ data: Data, _ conversation: MockConversation, _ from: MockUserClient, _ to: MockUserClient) -> Void, nonce: UUID) -> ZMAssetClientMessage? { return remotelyInsertAssetOriginalWithMimeType(mimeType: "text/plain", updateMessage: updateMessage, insertBlock: insertBlock, nonce: nonce, isEphemeral: false) } func remotelyInsertAssetOriginalWithMimeType(mimeType: String, updateMessage: GenericMessage, insertBlock: @escaping (_ data: Data, _ conversation: MockConversation, _ from: MockUserClient, _ to: MockUserClient) -> Void, nonce: UUID, isEphemeral: Bool) -> ZMAssetClientMessage? { // given let selfClient = self.selfUser.clients.anyObject() as! MockUserClient let senderClient = self.user1.clients.anyObject() as! MockUserClient let mockConversation = self.selfToUser1Conversation XCTAssertNotNil(selfClient) XCTAssertNotNil(senderClient) let asset = WireProtos.Asset(original: WireProtos.Asset.Original(withSize: 256, mimeType: mimeType, name: "foo229"), preview: nil) let original = GenericMessage(content: asset, nonce: nonce, expiresAfterTimeInterval: isEphemeral ? 20 : 0) // when self.mockTransportSession.performRemoteChanges { (_) in mockConversation!.encryptAndInsertData(from: senderClient, to: selfClient, data: try! original.serializedData()) } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) let conversation = self.conversation(for: self.selfToUser1Conversation) if !conversation!.lastMessage!.isKind(of: ZMAssetClientMessage.self) { XCTFail(String(format: "Unexpected message type, expected ZMAssetClientMessage : %@", (conversation!.lastMessage as! ZMMessage).self)) return nil } let message = conversation?.lastMessage as! ZMAssetClientMessage as ZMAssetClientMessage XCTAssertEqual(message.size, 256) XCTAssertEqual(message.mimeType, mimeType) XCTAssertEqual(message.nonce, nonce) // perform update self.mockTransportSession.performRemoteChanges { (_) in let updateMessageData = MockUserClient.encrypted(data: try! updateMessage.serializedData(), from: senderClient, to: selfClient) insertBlock(updateMessageData, mockConversation!, senderClient, selfClient) } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then return message } } // MARK: Asset V2 - Downloading extension FileTransferTests_Swift { func testThatItSendsTheRequestToDownloadAFile_WhenItHasTheAssetID() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let token = UUID.create() let assetID = UUID.create() let otrKey = Data.randomEncryptionKey() let assetData = Data.secureRandomData(length: 256) let encryptedAsset = assetData.zmEncryptPrefixingPlainTextIV(key: otrKey) let sha256 = encryptedAsset.zmSHA256Digest() let remoteData = WireProtos.Asset.RemoteData(withOTRKey: otrKey, sha256: sha256, assetId: assetID.transportString(), assetToken: nil) let asset = WireProtos.Asset.with { $0.uploaded = remoteData } let uploaded = GenericMessage(content: asset, nonce: nonce) // when let message = self.remotelyInsertAssetOriginalAndUpdate(updateMessage: uploaded, insertBlock: { (data, conversation, from, to) in conversation.insertOTRMessage(from: from, to: to, data: data) }, nonce: nonce) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // creating the asset remotely self.mockTransportSession.performRemoteChanges { (session) in session.insertAsset(with: assetID, assetToken: token, assetData: encryptedAsset, contentType: "text/plain") } // then XCTAssertEqual(message?.downloadState, AssetDownloadState.remote) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // when self.mockTransportSession.resetReceivedRequests() self.userSession?.perform { message?.requestFileDownload() } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then XCTAssertEqual(message!.downloadState, AssetDownloadState.downloaded) } func testThatItSendsTheRequestToDownloadAFileWhenItHasTheAssetID_AndSetsTheStateTo_FailedDownload_AfterFailedDecryption() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let assetID = UUID.create() let otrKey = Data.randomEncryptionKey() let assetData = Data.secureRandomData(length: 256) let encryptedAsset = assetData.zmEncryptPrefixingPlainTextIV(key: otrKey) let sha256 = encryptedAsset.zmSHA256Digest() let uploaded = GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: otrKey, sha256: sha256), nonce: nonce) // when let message = self.remotelyInsertAssetOriginalAndUpdate(updateMessage: uploaded, insertBlock: { (data, conversation, from, to) in conversation.insertOTRAsset(from: from, to: to, metaData: data, imageData: assetData, assetId: assetID, isInline: false) }, nonce: nonce) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) let conversation = self.conversation(for: self.selfToUser1Conversation) // creating a wrong asset (different hash, will fail to decrypt) remotely self.mockTransportSession.performRemoteChanges { (session) in session.createAsset(with: Data.secureRandomData(length: 128), identifier: assetID.transportString(), contentType: "text/plain", forConversation: conversation!.remoteIdentifier!.transportString()) } // We no longer process incoming V2 assets so we need to manually set some properties to simulate having received the asset self.userSession?.perform { message!.version = 2 message!.assetId = assetID message!.updateTransferState(AssetTransferState.uploaded, synchronize: false) } // then XCTAssertEqual(message!.assetId, assetID) // We should have received an asset ID to be able to download the file XCTAssertEqual(message!.nonce, nonce) XCTAssertEqual(message!.transferState, AssetTransferState.uploaded) XCTAssertEqual(message!.downloadState, AssetDownloadState.remote) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // when self.performIgnoringZMLogError { self.userSession?.perform { message?.requestFileDownload() } XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5)) } // then let lastRequest = self.mockTransportSession.receivedRequests().last! as ZMTransportRequest let expectedPath = String(format: "/conversations/%@/otr/assets/%@", conversation!.remoteIdentifier!.transportString(), message!.assetId!.transportString()) XCTAssertEqual(lastRequest.path, expectedPath) XCTAssertEqual(message!.downloadState, AssetDownloadState.remote) } func testThatItSendsTheRequestToDownloadAFileWhenItHasTheAssetID_AndSetsTheStateTo_FailedDownload_AfterFailedDecryption_Ephemeral() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let assetID = UUID.create() let otrKey = Data.randomEncryptionKey() let assetData = Data.secureRandomData(length: 256) let encryptedAsset = assetData.zmEncryptPrefixingPlainTextIV(key: otrKey) let sha256 = encryptedAsset.zmSHA256Digest() let uploaded = GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: otrKey, sha256: sha256), nonce: nonce, expiresAfterTimeInterval: 30) // when let message = self.remotelyInsertAssetOriginalAndUpdate(updateMessage: uploaded, insertBlock: { (data, conversation, from, to) in conversation.insertOTRAsset(from: from, to: to, metaData: data, imageData: assetData, assetId: assetID, isInline: false) }, nonce: nonce) XCTAssertTrue(message!.isEphemeral) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) let conversation = self.conversation(for: self.selfToUser1Conversation) // creating a wrong asset (different hash, will fail to decrypt) remotely self.mockTransportSession.performRemoteChanges { (session) in session.createAsset(with: Data.secureRandomData(length: 128), identifier: assetID.transportString(), contentType: "text/plain", forConversation: conversation!.remoteIdentifier!.transportString()) } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // We no longer process incoming V2 assets so we need to manually set some properties to simulate having received the asset self.userSession?.perform { message!.version = 2 message!.assetId = assetID message!.updateTransferState(AssetTransferState.uploaded, synchronize: false) } // then XCTAssertEqual(message!.nonce, nonce) XCTAssertEqual(message!.transferState, AssetTransferState.uploaded) XCTAssertEqual(message!.downloadState, AssetDownloadState.remote) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // when self.userSession?.perform { message?.requestFileDownload() } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let lastRequest = self.mockTransportSession.receivedRequests().last! as ZMTransportRequest let expectedPath = String(format: "/conversations/%@/otr/assets/%@", conversation!.remoteIdentifier!.transportString(), message!.assetId!.transportString()) XCTAssertEqual(lastRequest.path, expectedPath) XCTAssertEqual(message!.downloadState, AssetDownloadState.remote) XCTAssertTrue(message!.isEphemeral) } } // MARK: Asset V3 - Receiving extension FileTransferTests_Swift { func testThatAFileUpload_AssetOriginal_MessageIsReceivedWhenSentRemotely_Ephemeral() { // given XCTAssertTrue(self.login()) self.establishSession(with: self.user1) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) let nonce = UUID.create() let original = GenericMessage(content: WireProtos.Asset(imageSize: .zero, mimeType: "text/plain", size: 256), nonce: nonce, expiresAfterTimeInterval: 30) // when self.mockTransportSession.performRemoteChanges { (_) in self.selfToUser1Conversation.encryptAndInsertData(from: self.user1.clients.anyObject() as! MockUserClient, to: self.selfUser.clients.anyObject() as! MockUserClient, data: try! original.serializedData()) } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let conversation = self.conversation(for: self.selfToUser1Conversation) if !conversation!.lastMessage!.isKind(of: ZMAssetClientMessage.self) { return XCTFail(String(format: "Unexpected message type, expected ZMAssetClientMessage : %@", (conversation!.lastMessage as! ZMMessage).self)) } let message = conversation?.lastMessage as! ZMAssetClientMessage XCTAssertTrue(message.isEphemeral) XCTAssertEqual(message.size, 256) XCTAssertEqual(message.mimeType, "text/plain") XCTAssertEqual(message.nonce, nonce) XCTAssertNil(message.assetId) XCTAssertEqual(message.transferState, AssetTransferState.uploading) } func testThatItDeletesAFileMessageWhenTheUploadIsCancelledRemotely_Ephemeral() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let cancelled = GenericMessage(content: WireProtos.Asset(withNotUploaded: .cancelled), nonce: nonce, expiresAfterTimeInterval: 30) // when let message = self.remotelyInsertAssetOriginalAndUpdate(updateMessage: cancelled, insertBlock: { (data, conversation, from, to) in conversation.insertOTRMessage(from: from, to: to, data: data) }, nonce: nonce) // then XCTAssertTrue(message!.isZombieObject) } func testThatItUpdatesAFileMessageWhenTheUploadFailesRemotlely_Ephemeral() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let failed = GenericMessage(content: WireProtos.Asset(withNotUploaded: .failed), nonce: nonce, expiresAfterTimeInterval: 30) // when let message = self.remotelyInsertAssetOriginalAndUpdate(updateMessage: failed, insertBlock: { (data, conversation, from, to) in conversation.insertOTRMessage(from: from, to: to, data: data) }, nonce: nonce) XCTAssertTrue(message!.isEphemeral) // then XCTAssertNil(message!.assetId) XCTAssertEqual(message!.transferState, AssetTransferState.uploadingFailed) XCTAssertTrue(message!.isEphemeral) } func testThatItReceivesAVideoFileMessageThumbnailSentRemotely_V3() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let thumbnailAssetID = UUID.create() let thumbnailIDString = thumbnailAssetID.transportString() let otrKey = Data.randomEncryptionKey() let encryptedAsset = self.mediumJPEGData().zmEncryptPrefixingPlainTextIV(key: otrKey) let sha256 = encryptedAsset.zmSHA256Digest() let remote = WireProtos.Asset.RemoteData(withOTRKey: otrKey, sha256: sha256, assetId: thumbnailIDString, assetToken: nil) let image = WireProtos.Asset.ImageMetaData(width: 1024, height: 2048) let preview = WireProtos.Asset.Preview(size: 256, mimeType: "image/jpeg", remoteData: remote, imageMetadata: image) let asset = WireProtos.Asset(original: nil, preview: preview) let updateMessage = GenericMessage(content: asset, nonce: nonce) // when var observer: MessageChangeObserver? var conversation: ZMConversation? let insertBlock = { (data: Data, mockConversation: MockConversation, from: MockUserClient, to: MockUserClient) -> Void in mockConversation.insertOTRMessage(from: from, to: to, data: data) conversation = self.conversation(for: mockConversation) observer = MessageChangeObserver.init(message: conversation?.lastMessage as? ZMMessage) } let message = self.remotelyInsertAssetOriginalWithMimeType(mimeType: "video/mp4", updateMessage: updateMessage, insertBlock: insertBlock, nonce: nonce, isEphemeral: false) // Mock the asset/v3 request self.mockTransportSession.responseGeneratorBlock = { request in let expectedPath = "/assets/v3/\(thumbnailIDString)" if request.path == expectedPath { return ZMTransportResponse.init(imageData: encryptedAsset, httpStatus: 200, transportSessionError: nil, headers: nil, apiVersion: APIVersion.v0.rawValue) } return nil } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) XCTAssertNotNil(message) XCTAssertNotNil(observer) XCTAssertNotNil(conversation) self.userSession?.perform { message?.fileMessageData?.requestImagePreviewDownload() } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) XCTAssertNotNil(message) let notifications = observer!.notifications XCTAssertEqual(notifications!.count, 2) let info = notifications?.lastObject as! MessageChangeInfo XCTAssertTrue(info.imageChanged) // then // We should have received an thumbnail asset ID to be able to download the thumbnail image XCTAssertEqual(message!.fileMessageData!.thumbnailAssetID, thumbnailIDString) XCTAssertEqual(message!.nonce, nonce) XCTAssertEqual(message!.transferState, AssetTransferState.uploading) } func testThatItReceivesAVideoFileMessageThumbnailSentRemotely_Ephemeral_V3() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let thumbnailAssetID = UUID.create() let thumbnailIDString = thumbnailAssetID.transportString() let otrKey = Data.randomEncryptionKey() let encryptedAsset = self.mediumJPEGData().zmEncryptPrefixingPlainTextIV(key: otrKey) let sha256 = encryptedAsset.zmSHA256Digest() let remote = WireProtos.Asset.RemoteData(withOTRKey: otrKey, sha256: sha256, assetId: thumbnailIDString, assetToken: nil) let image = WireProtos.Asset.ImageMetaData(width: 1024, height: 2048) let preview = WireProtos.Asset.Preview(size: 256, mimeType: "image/jpeg", remoteData: remote, imageMetadata: image) let asset = WireProtos.Asset(original: nil, preview: preview) let updateMessage = GenericMessage(content: asset, nonce: nonce, expiresAfterTimeInterval: 20) // when var observer: MessageChangeObserver? var conversation: ZMConversation? let insertBlock = { (data: Data, mockConversation: MockConversation, from: MockUserClient, to: MockUserClient) -> Void in mockConversation.insertOTRMessage(from: from, to: to, data: data) conversation = self.conversation(for: mockConversation) observer = MessageChangeObserver.init(message: conversation?.lastMessage as? ZMMessage) } let message = self.remotelyInsertAssetOriginalWithMimeType(mimeType: "video/mp4", updateMessage: updateMessage, insertBlock: insertBlock, nonce: nonce, isEphemeral: true) XCTAssertTrue(message!.isEphemeral) self.mockTransportSession.responseGeneratorBlock = { request in let expectedPath = "/assets/v3/\(thumbnailIDString)" if request.path == expectedPath { return ZMTransportResponse.init(imageData: encryptedAsset, httpStatus: 200, transportSessionError: nil, headers: nil, apiVersion: APIVersion.v0.rawValue) } return nil } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) XCTAssertNotNil(message) XCTAssertNotNil(observer) XCTAssertNotNil(conversation) self.userSession?.perform { message?.fileMessageData?.requestImagePreviewDownload() } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) XCTAssertNotNil(message) let notifications = observer!.notifications XCTAssertEqual(notifications!.count, 2) let info = notifications?.lastObject as! MessageChangeInfo XCTAssertTrue(info.imageChanged) // then // We should have received an thumbnail asset ID to be able to download the thumbnail image XCTAssertEqual(message!.fileMessageData!.thumbnailAssetID, thumbnailIDString) XCTAssertEqual(message!.nonce, nonce) XCTAssertEqual(message!.transferState, AssetTransferState.uploading) XCTAssertTrue(message!.isEphemeral) } func testThatAFileUpload_AssetUploaded_MessageIsReceivedAndUpdatesTheOriginalMessageWhenSentRemotely_V3() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let assetID = UUID.create() let otrKey = Data.randomEncryptionKey() let sha256 = Data.zmRandomSHA256Key() var uploaded = GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: otrKey, sha256: sha256), nonce: nonce) uploaded.updateUploaded(assetId: assetID.transportString(), token: nil, domain: nil) // when let message = self.remotelyInsertAssetOriginalAndUpdate(updateMessage: uploaded, insertBlock: { (data, conversation, from, to) in conversation.insertOTRMessage(from: from, to: to, data: data) }, nonce: nonce) // then XCTAssertNil(message!.assetId) // We do not store the asset ID in the DB for v3 assets XCTAssertEqual(message!.underlyingMessage!.assetData!.uploaded.assetID, assetID.transportString()) XCTAssertEqual(message!.version, 3) XCTAssertEqual(message!.nonce, nonce) XCTAssertEqual(message!.transferState, AssetTransferState.uploaded) } } // MARK: Downloading extension FileTransferTests_Swift { func testThatItSendsTheRequestToDownloadAFileWhenItHasTheAssetID_AndSetsTheStateTo_Downloaded_AfterSuccesfullDecryption_V3() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let assetID = UUID.create() let otrKey = Data.randomEncryptionKey() let assetData = Data.secureRandomData(length: 256) let encryptedAsset = assetData.zmEncryptPrefixingPlainTextIV(key: otrKey) let sha256 = encryptedAsset.zmSHA256Digest() var uploaded = GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: otrKey, sha256: sha256), nonce: nonce) uploaded.updateUploaded(assetId: assetID.transportString(), token: nil, domain: nil) // when let message = self.remotelyInsertAssetOriginalAndUpdate(updateMessage: uploaded, insertBlock: { (data, conversation, from, to) in conversation.insertOTRMessage(from: from, to: to, data: data) }, nonce: nonce) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) let conversation = self.conversation(for: self.selfToUser1Conversation) // then XCTAssertNotNil(message) XCTAssertNil(message!.assetId) // We do not store the asset ID in the DB for v3 assets XCTAssertEqual(message!.nonce, nonce) XCTAssertEqual(message!.transferState, AssetTransferState.uploaded) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // when // Mock the asset/v3 request self.mockTransportSession.responseGeneratorBlock = { request in let expectedPath = "/assets/v3/\(assetID.transportString())" if request.path == expectedPath { return ZMTransportResponse.init(imageData: encryptedAsset, httpStatus: 200, transportSessionError: nil, headers: nil, apiVersion: APIVersion.v0.rawValue) } return nil } // when we request the file download self.mockTransportSession.resetReceivedRequests() self.userSession?.perform { message?.requestFileDownload() } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let lastRequest = self.mockTransportSession.receivedRequests().last! as ZMTransportRequest let expectedPath = "/assets/v3/\(assetID.transportString())" XCTAssertEqual(lastRequest.path, expectedPath) XCTAssertEqual(message!.transferState, AssetTransferState.uploaded) } func testThatItSendsTheRequestToDownloadAFileWhenItHasTheAssetID_AndSetsTheStateTo_FailedDownload_AfterFailedDecryption_V3() { // given XCTAssertTrue(self.login()) let nonce = UUID.create() let assetID = UUID.create() let otrKey = Data.randomEncryptionKey() let assetData = Data.secureRandomData(length: 256) let encryptedAsset = assetData.zmEncryptPrefixingPlainTextIV(key: otrKey) let sha256 = encryptedAsset.zmSHA256Digest() var uploaded = GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: otrKey, sha256: sha256), nonce: nonce) uploaded.updateUploaded(assetId: assetID.transportString(), token: nil, domain: nil) // when let message = self.remotelyInsertAssetOriginalAndUpdate(updateMessage: uploaded, insertBlock: { (data, conversation, from, to) in conversation.insertOTRMessage(from: from, to: to, data: data) }, nonce: nonce) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) let conversation = self.conversation(for: self.selfToUser1Conversation) // then XCTAssertNotNil(message) XCTAssertNil(message!.assetId) // We do not store the asset ID in the DB for v3 assets XCTAssertEqual(message!.nonce, nonce) XCTAssertEqual(message!.transferState, AssetTransferState.uploaded) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // when // Mock the asset/v3 request self.mockTransportSession.responseGeneratorBlock = { request in let expectedPath = "/assets/v3/\(assetID.transportString())" if request.path == expectedPath { let wrongData = Data.secureRandomData(length: 128) return ZMTransportResponse.init(imageData: wrongData, httpStatus: 200, transportSessionError: nil, headers: nil, apiVersion: APIVersion.v0.rawValue) } return nil } // We log an error when we fail to decrypt the received data self.performIgnoringZMLogError { self.userSession?.perform { message?.requestFileDownload() } XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5)) } // then let lastRequest = self.mockTransportSession.receivedRequests().last! as ZMTransportRequest let expectedPath = "/assets/v3/\(assetID.transportString())" XCTAssertEqual(lastRequest.path, expectedPath) XCTAssertEqual(message!.downloadState, AssetDownloadState.remote) } }
gpl-3.0
152307b58d62755dceaecca515ee3adf
45.553542
175
0.655744
5.242672
false
false
false
false
KSMissQXC/KS_DYZB
KS_DYZB/KS_DYZB/Classes/Main/Model/KSAnchorModel.swift
1
916
// // KSAnchorModel.swift // KS_DYZB // // Created by 耳动人王 on 2016/11/2. // Copyright © 2016年 KS. All rights reserved. // import UIKit class KSAnchorModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间图片对应的URLString var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播(普通房间) 1 : 手机直播(秀场房间) var isVertical : Int = 0 /// 房间名称 var room_name : String = "" /// 主播昵称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
mit
fbb037092b167effa34852ae0d14bf6d
14.627451
72
0.498118
3.741784
false
false
false
false
YangYouYong/SwiftLearnLog01
SongsPlayer/SongsPlayer/Application/AppDelegate.swift
1
3334
// // AppDelegate.swift // SongsPlayer // // Created by yangyouyong on 15/8/7. // Copyright © 2015年 SongsPlayer. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
apache-2.0
c77e83a596bf23140fafd2c7452773c9
53.606557
285
0.765536
6.145756
false
false
false
false
qxuewei/XWSwiftWB
XWSwiftWB/XWSwiftWB/Classes/Compose/PicPicker/PicPickerCollection.swift
1
1900
// // PicPickerCollection.swift // XWSwiftWB // // Created by 邱学伟 on 2016/11/13. // Copyright © 2016年 邱学伟. All rights reserved. // import UIKit fileprivate let collectionCellID = "collectionCellID" fileprivate let edgeMargin : CGFloat = 12.0 class PicPickerCollection: UICollectionView { //MARK: - 共有属性 var picPickerS : [UIImage] = [UIImage]() { didSet{ self.reloadData() } } override func awakeFromNib() { super.awakeFromNib() //流水布局 let layout = collectionViewLayout as! UICollectionViewFlowLayout let itemWH : CGFloat = (UIScreen.main.bounds.width - edgeMargin * 4) / 3.0 layout.itemSize = CGSize(width: itemWH, height: itemWH) //最小行间距和最小列间距 layout.minimumLineSpacing = edgeMargin layout.minimumInteritemSpacing = edgeMargin //设置内边距 contentInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) //注册cell let PicPickerCollectionCellNib : UINib = UINib(nibName: "PicPickerCollectionCell", bundle: nil) register(PicPickerCollectionCellNib, forCellWithReuseIdentifier: collectionCellID) dataSource = self } } extension PicPickerCollection : UICollectionViewDataSource{ public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ let items : Int = picPickerS.count return items + 1 } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell : PicPickerCollectionCell = dequeueReusableCell(withReuseIdentifier: collectionCellID, for: indexPath) as! PicPickerCollectionCell cell.image = (indexPath.row + 1) <= picPickerS.count ? picPickerS[indexPath.row] : nil return cell } }
apache-2.0
b86866bfeacd3c9a3535c49b54aab884
36.408163
147
0.687398
4.712082
false
false
false
false
megha14/Lets-Code-Them-Up
Learning-Swift/Learning Swift - Collections [Dictionary].playground/Contents.swift
1
1063
/* 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/. */ //Dictionary //example a dictionary of antonyms : ["hot" : "cold", "dark" : "light", "big" : "small"] //Initializing Dictionary var antonyms = [String : String]() //print(antonyms) //var antonyms = [:] antonyms = [:] antonyms = ["hot" : "cold", "dark" : "light", "big" : "small"] print(antonyms) //var groceryList : [String:Int] = ["potatoes" : 4, "carrots" : 6, "onions" : 10] var groceryList = ["potatoes" : 4, "carrots" : 6, "onions" : 10] //Dictionary Operations //insert print(groceryList) groceryList["tomatoes"] = 12 groceryList["squash"] = 2 print(groceryList) //remove groceryList["squash"] = nil print(groceryList) groceryList.removeValue(forKey: "carrots") print(groceryList) //count print(groceryList.count) //Update print(groceryList) groceryList["tomatoes"] = 6 print(groceryList) groceryList.updateValue(5, forKey: "onions") print(groceryList)
gpl-3.0
5ce81e623505e5d4c60468da00fe5cd1
18.327273
133
0.682032
3.081159
false
false
false
false
AzenXu/Memo
Memo/Common/Extension/UIColor+Smart.swift
1
2058
// // UIColor+Smart.swift // Base // // Created by kenneth wang on 16/5/8. // Copyright © 2016年 st. All rights reserved. // import Foundation import UIKit // MARK: - color convert public extension UIColor { class func stec_color(withHex hex: Int) -> UIColor { return UIColor.stec_color(withHex: hex, alpha: 1) } class func stec_color(withHex hex: Int, alpha: CGFloat) -> UIColor { return UIColor(red: ((CGFloat)((hex & 0xFF0000) >> 16) / 255.0), green: ((CGFloat)((hex & 0xFF00) >> 8)) / 255.0, blue: ((CGFloat)(hex & 0xFF)) / 255.0, alpha: alpha) } class func stec_color(withHexString hex:String) -> UIColor { return UIColor.stec_color(withHexString: hex, alpha: 1) } class func stec_color(withHexString hex:String, alpha: CGFloat) -> UIColor { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString if (cString.hasPrefix("#")) { cString = (cString as NSString).substringFromIndex(1) } if (cString.characters.count != 6) { return UIColor.grayColor() } let rString = (cString as NSString).substringToIndex(2) let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2) let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; NSScanner(string: rString).scanHexInt(&r) NSScanner(string: gString).scanHexInt(&g) NSScanner(string: bString).scanHexInt(&b) return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha) } class func stec_randomColor() -> UIColor { return UIColor(red: CGFloat(Double(arc4random_uniform(100)) * 0.01), green: CGFloat(Double(arc4random_uniform(100)) * 0.01), blue: CGFloat(Double(arc4random_uniform(100)) * 0.01), alpha: 1) } }
mit
f6319a516560592f5e1323a2d30ac92b
39.313725
197
0.638929
3.892045
false
false
false
false
XSega/Words
Words/Scenes/Trainings/StartTraining/StartTrainingRouter.swift
1
2074
// // StartTrainingRouter.swift // Words // // Created by Sergey Ilyushin on 30/07/2017. // Copyright (c) 2017 Sergey Ilyushin. All rights reserved. // import UIKit @objc protocol IStartTrainingRouter { func routeToTraining() } protocol IStartTrainingDataPassing { var segueIdentifier: String! { get set } } class StartTrainingRouter: NSObject, IStartTrainingRouter, IStartTrainingDataPassing { weak var viewController: StartTrainingViewController! var dataStore: IStartTrainingDataStore! var segueIdentifier: String! // MARK: Routing func routeToTraining() { viewController.performSegue(withIdentifier: segueIdentifier, sender: self) } func routeToEngRuTraining(segue: UIStoryboardSegue) { if let destinationVC = segue.destination as? EngRuTrainingViewController, var destinationDS = destinationVC.router.dataStore { passDataToTraining(source: dataStore, destination: &destinationDS) } } func routeToRuEngTraining(segue: UIStoryboardSegue) { if let destinationVC = segue.destination as? RuEngTrainingViewController, var destinationDS = destinationVC.router.dataStore { passDataToTraining(source: dataStore, destination: &destinationDS) } } func routeToSprintTraining(segue: UIStoryboardSegue) { if let destinationVC = segue.destination as? SprintTrainingViewController, var destinationDS = destinationVC.router.dataStore { passDataToTraining(source: dataStore, destination: &destinationDS) } } func routeToListeningTraining(segue: UIStoryboardSegue) { if let destinationVC = segue.destination as? ListeningTrainingViewController, var destinationDS = destinationVC.router.dataStore { passDataToTraining(source: dataStore, destination: &destinationDS) } } // MARK: Passing data func passDataToTraining(source: IStartTrainingDataStore, destination: inout ITrainingDataStore) { destination.meanings = source.meanings } }
mit
342eb59aec08bd7edbedbf40f50d009a
33.566667
138
0.720347
4.891509
false
false
false
false
sprejjs/Virtual-Tourist-App
Virtual_Tourist/Virtual Tourist/ImageCache.swift
1
1875
// // File.swift // FavoriteActors // // Created by Jason on 1/31/15. // Copyright (c) 2015 Udacity. All rights reserved. // import UIKit class ImageCache { fileprivate var inMemoryCache = NSCache<AnyObject, AnyObject>() // MARK: - Retreiving images func imageWithIdentifier(_ identifier: String?) -> UIImage? { // If the identifier is nil, or empty, return nil if identifier == nil || identifier! == "" { return nil } let path = pathForIdentifier(identifier!) // First try the memory cache if let image = inMemoryCache.object(forKey: path as AnyObject) as? UIImage { return image } // Next Try the hard drive if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) { return UIImage(data: data) } return nil } // MARK: - Saving images func storeImage(_ image: UIImage?, withIdentifier identifier: String) { let path = pathForIdentifier(identifier) // If the image is nil, remove images from the cache if image == nil { inMemoryCache.removeObject(forKey: path as AnyObject) try! FileManager.default.removeItem(atPath: path) return } // Otherwise, keep the image in memory inMemoryCache.setObject(image!, forKey: path as AnyObject) // And in documents directory let data = UIImagePNGRepresentation(image!)! try! data.write(to: URL(fileURLWithPath: path), options: .atomic) } // MARK: - Helper func pathForIdentifier(_ identifier: String) -> String { let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let fullURL = documentsDirectoryURL.appendingPathComponent(identifier) return fullURL.path } }
apache-2.0
5491c6f812fcff90f7e6db4bf675e2aa
26.985075
113
0.625067
4.734848
false
false
false
false
rajeshmud/CLChart
CLApp/CLCharts/CLCharts/Charts/CLDrawer.swift
1
7382
// // CLContextDrawer.swift // CLCharts // // Created by Rajesh Mudaliyar on 11/09/15. // Copyright © 2015 Rajesh Mudaliyar. All rights reserved. // import UIKit public class CLContextDrawer { var hidden: Bool = false final func triggerDraw(context context: CGContextRef, chart: Chart) { if !hidden { self.draw(context: context, chart: chart) } } func draw(context context: CGContextRef, chart: Chart) {} } func CLDrawLine(context context: CGContextRef, p1: CGPoint, p2: CGPoint, width: CGFloat, color: UIColor) { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetLineWidth(context, width) CGContextMoveToPoint(context, p1.x, p1.y) CGContextAddLineToPoint(context, p2.x, p2.y) CGContextStrokePath(context) } func CLDrawDottedLine(context context: CGContextRef, p1: CGPoint, p2: CGPoint, width: CGFloat, color: UIColor, dotWidth: CGFloat, dotSpacing: CGFloat) { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetLineWidth(context, width) CGContextSetLineDash(context, 0, [dotWidth, dotSpacing], 2) CGContextMoveToPoint(context, p1.x, p1.y) CGContextAddLineToPoint(context, p2.x, p2.y) CGContextStrokePath(context) CGContextSetLineDash(context, 0, nil, 0) } public class CLLabelSettings { let font: UIFont let fontColor: UIColor let rotation: CGFloat let rotationKeep: CLLabelDrawerRotationKeep let shiftXOnRotation: Bool public init(font: UIFont = UIFont.systemFontOfSize(14), fontColor: UIColor = UIColor.blackColor(), rotation: CGFloat = 0, rotationKeep: CLLabelDrawerRotationKeep = .Center, shiftXOnRotation: Bool = true) { self.font = font self.fontColor = fontColor self.rotation = rotation self.rotationKeep = rotationKeep self.shiftXOnRotation = shiftXOnRotation } public func copy(font: UIFont? = nil, fontColor: UIColor? = nil, rotation: CGFloat? = nil, rotationKeep: CLLabelDrawerRotationKeep? = nil, shiftXOnRotation: Bool? = nil) -> CLLabelSettings { return CLLabelSettings( font: font ?? self.font, fontColor: fontColor ?? self.fontColor, rotation: rotation ?? self.rotation, rotationKeep: rotationKeep ?? self.rotationKeep, shiftXOnRotation: shiftXOnRotation ?? self.shiftXOnRotation) } } public extension CLLabelSettings { public func defaultVertical() -> CLLabelSettings { return self.copy(rotation: -90) } } // coordinate of original label which will be preserved after the rotation public enum CLLabelDrawerRotationKeep { case Center, Top, Bottom } public class CLLabelDrawer: CLContextDrawer { private let text: String private let settings: CLLabelSettings private let screenLoc: CGPoint private var transform: CGAffineTransform? var size: CGSize { return CLUtils.textSize(self.text, font: self.settings.font) } init(text: String, screenLoc: CGPoint, settings: CLLabelSettings) { self.text = text self.screenLoc = screenLoc self.settings = settings super.init() self.transform = self.transform(screenLoc, settings: settings) } override func draw(context context: CGContextRef, chart: Chart) { let labelSize = self.size let labelX = self.screenLoc.x let labelY = self.screenLoc.y func drawLabel() { self.drawLabel(x: labelX, y: labelY, text: self.text) } if let transform = self.transform { CGContextSaveGState(context) CGContextConcatCTM(context, transform) drawLabel() CGContextRestoreGState(context) } else { drawLabel() } } private func transform(screenLoc: CGPoint, settings: CLLabelSettings) -> CGAffineTransform? { let labelSize = self.size let labelX = screenLoc.x let labelY = screenLoc.y let labelHalfWidth = labelSize.width / 2 let labelHalfHeight = labelSize.height / 2 if settings.rotation != 0 { let centerX = labelX + labelHalfWidth let centerY = labelY + labelHalfHeight let rotation = settings.rotation * CGFloat(M_PI) / CGFloat(180) var transform = CGAffineTransformIdentity if settings.rotationKeep == .Center { transform = CGAffineTransformMakeTranslation(-(labelHalfWidth - labelHalfHeight), 0) } else { var transformToGetBounds = CGAffineTransformMakeTranslation(0, 0) transformToGetBounds = CGAffineTransformTranslate(transformToGetBounds, centerX, centerY) transformToGetBounds = CGAffineTransformRotate(transformToGetBounds, rotation) transformToGetBounds = CGAffineTransformTranslate(transformToGetBounds, -centerX, -centerY) let rect = CGRectMake(labelX, labelY, labelSize.width, labelSize.height) let newRect = CGRectApplyAffineTransform(rect, transformToGetBounds) let offsetTop: CGFloat = { switch settings.rotationKeep { case .Top: return labelY - newRect.origin.y case .Bottom: return newRect.origin.y + newRect.size.height - (labelY + rect.size.height) default: return 0 } }() // when the labels are diagonal we have to shift a little so they look aligned with axis value. We align origin of new rect with the axis value if settings.shiftXOnRotation { let xOffset: CGFloat = abs(settings.rotation) == 90 ? 0 : centerX - newRect.origin.x transform = CGAffineTransformTranslate(transform, xOffset, offsetTop) } } transform = CGAffineTransformTranslate(transform, centerX, centerY) transform = CGAffineTransformRotate(transform, rotation) transform = CGAffineTransformTranslate(transform, -centerX, -centerY) return transform } else { return nil } } private func drawLabel(x x: CGFloat, y: CGFloat, text: String) { let attributes = [NSFontAttributeName: self.settings.font, NSForegroundColorAttributeName: self.settings.fontColor] let attrStr = NSAttributedString(string: text, attributes: attributes) attrStr.drawAtPoint(CGPointMake(x, y)) } } class CLLineDrawer: CLContextDrawer { private let p1: CGPoint private let p2: CGPoint private let color: UIColor init(p1: CGPoint, p2: CGPoint, color: UIColor) { self.p1 = p1 self.p2 = p2 self.color = color } override func draw(context context: CGContextRef, chart: Chart) { //let lineColor = UIColor.redColor() CLDrawLine(context: context, p1: self.p1, p2: self.p2, width: 0.2, color:self.color) } }
mit
8bd72439c3ee344f9567c79f3c669489
35.004878
209
0.623222
4.89781
false
false
false
false
dche/FlatCG
Sources/Quaternion.swift
1
5303
// // FlatCG - Quaternion.swift // // Copyright (c) 2016 The FlatCG authors. // Licensed under MIT License. import simd import GLMath public struct Quaternion: Rotation { public typealias PointType = Point3D fileprivate let _rep: vec4 public var x: Float { return _rep.x } public var y: Float { return _rep.y } public var z: Float { return _rep.z } public var w: Float { return _rep.w } public func compose(_ other: Quaternion) -> Quaternion { return other * self } public static let identity = Quaternion(vec4(0, 0, 0, 1)) public var inverse: Quaternion { // NOTE: `self` is normalized. return Quaternion(vec4(-_rep.xyz, _rep.w)) } public func apply(_ vector: vec3) -> vec3 { return self * vector } public var conjugate: Quaternion { return self.inverse } public var real: Float { return _rep.w } public var imaginary: vec3 { return _rep.xyz } fileprivate init (_ v: vec4) { if v.isZero { self._rep = vec4(0, 0, 0, 1) } else { self._rep = v.normalize } } public init (_ x: Float, _ y: Float, _ z: Float, _ w: Float) { self.init(vec4(x, y, z, w)) } public init (imaginary: vec3, real: Float) { self.init(vec4(imaginary, real)) } } extension Quaternion: One { public static func * (lhs: Quaternion, rhs: Quaternion) -> Quaternion { let m = mat4( vec4(lhs.w, lhs.z, -lhs.y, -lhs.x), vec4(-lhs.z, lhs.w, lhs.x, -lhs.y), vec4(lhs.y, -lhs.x, lhs.w, -lhs.z), lhs._rep ) return Quaternion(m * rhs._rep) } public static var one: Quaternion { return self.identity } } extension Quaternion { public static func == (lhs: Quaternion, rhs: Quaternion) -> Bool { return lhs._rep == rhs._rep } /// Constructs a Quaternion from axis-angle representation. public init (axis: Normal3D, angle: Float) { let v = axis.vector let ha = angle * 0.5 let a = v * sin(ha) let w = cos(ha) self.init(imaginary: a, real: w) } /// Constructs a Quaternion that represents a rotation from direction /// `from` to direciton `to`. /// /// - note: `from` and `to` need _NOT_ be normalized. public init (fromDirection from: Normal3D, to: Normal3D) { // http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors let w = cross(from.vector, to.vector) self.init(imaginary: w, real: 1 + from.dot(to)) } // TODO: Constructs a `Quaternion` from a rotation matrix. /// Constructs a `Quaternion` that represents a rotation around x axis. /// /// - parameter angle: Angle to be rotated. /// /// - note: Right-hand rule is used. public static func pitch(_ angle: Float) -> Quaternion { return self.init(axis: Normal3D(vec3.x), angle: angle) } /// Constructs a `Quaternion` that represents a rotation around y axis. /// /// - parameter angle: Angle to be rotated. /// /// - note: Right-hand rule is used. public static func yaw(_ angle: Float) -> Quaternion { return self.init(axis: Normal3D(vec3.y), angle: angle) } /// Constructs a `Quaternion` that represents a rotation around z axis. /// /// - parameter angle: Angle to be rotated. /// /// - note: Right-hand rule is used. public static func roll(_ angle: Float) -> Quaternion { return self.init(axis: Normal3D(vec3.z), angle: angle) } } extension Quaternion { /// The axis-angle representation of `self`. public var axisAngle: (axis: vec3, angle: Float) { let a = acos(self.w) * 2 if a.isZero { // `self.w == 1`. return (vec3.zero, 0) } else { return (normalize(self.imaginary), a) } } public func pitch(_ angle: Float) -> Quaternion { return Quaternion.pitch(angle) * self } public func yaw(_ angle: Float) -> Quaternion { return Quaternion.yaw(angle) * self } public func roll(_ angle: Float) -> Quaternion { return Quaternion.roll(angle) * self } public var matrix: mat4 { let q = _rep let c1 = vec4(-(q.y * q.y + q.z * q.z) * 2 + 1, (q.x * q.y + q.w * q.z) * 2, (q.x * q.z - q.w * q.y) * 2, 0) let c2 = vec4((q.x * q.y - q.w * q.z) * 2, -(q.x * q.x + q.z * q.z) * 2 + 1, (q.y * q.z + q.w * q.x) * 2, 0) let c3 = vec4((q.x * q.z + q.w * q.y) * 2, (q.y * q.z - q.w * q.x) * 2, -(q.x * q.x + q.y * q.y) * 2 + 1, 0) return mat4(c1, c2, c3, vec4(0, 0, 0, 1)) } public static func * (lhs: Quaternion, rhs: vec3) -> vec3 { let r = lhs.real let q = lhs.imaginary let c = cross(q, rhs) return rhs + c * r * 2 + cross(q * 2, c) } } extension Quaternion: CustomDebugStringConvertible { public var debugDescription: String { return "Quaternion(x: \(x), y: \(y), z: \(z), w: \(w))" } } extension Quaternion { public typealias NumberType = Float public func isClose(to other: Quaternion, tolerance: Float) -> Bool { return self._rep.isClose(to: other._rep, tolerance: tolerance) } }
mit
a81d8b36e71b16eff4f8fff1b48afb7f
26.910526
116
0.561192
3.403723
false
false
false
false
kstaring/swift
stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift
1
4674
//===--- SwiftPrivatePthreadExtras.swift ----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file contains wrappers for pthread APIs that are less painful to use // than the C APIs. // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc #endif /// An abstract base class to encapsulate the context necessary to invoke /// a block from pthread_create. internal class PthreadBlockContext { /// Execute the block, and return an `UnsafeMutablePointer` to memory /// allocated with `UnsafeMutablePointer.alloc` containing the result of the /// block. func run() -> UnsafeMutableRawPointer { fatalError("abstract") } } internal class PthreadBlockContextImpl<Argument, Result>: PthreadBlockContext { let block: (Argument) -> Result let arg: Argument init(block: @escaping (Argument) -> Result, arg: Argument) { self.block = block self.arg = arg super.init() } override func run() -> UnsafeMutableRawPointer { let result = UnsafeMutablePointer<Result>.allocate(capacity: 1) result.initialize(to: block(arg)) return UnsafeMutableRawPointer(result) } } /// Entry point for `pthread_create` that invokes a block context. internal func invokeBlockContext( _ contextAsVoidPointer: UnsafeMutableRawPointer? ) -> UnsafeMutableRawPointer! { // The context is passed in +1; we're responsible for releasing it. let context = Unmanaged<PthreadBlockContext> .fromOpaque(contextAsVoidPointer!) .takeRetainedValue() return context.run() } #if CYGWIN || os(FreeBSD) public typealias _stdlib_pthread_attr_t = UnsafePointer<pthread_attr_t?> #else public typealias _stdlib_pthread_attr_t = UnsafePointer<pthread_attr_t> #endif /// Block-based wrapper for `pthread_create`. public func _stdlib_pthread_create_block<Argument, Result>( _ attr: _stdlib_pthread_attr_t?, _ start_routine: @escaping (Argument) -> Result, _ arg: Argument ) -> (CInt, pthread_t?) { let context = PthreadBlockContextImpl(block: start_routine, arg: arg) // We hand ownership off to `invokeBlockContext` through its void context // argument. let contextAsVoidPointer = Unmanaged.passRetained(context).toOpaque() var threadID = _make_pthread_t() let result = pthread_create(&threadID, attr, { invokeBlockContext($0) }, contextAsVoidPointer) if result == 0 { return (result, threadID) } else { return (result, nil) } } #if os(Linux) || os(Android) internal func _make_pthread_t() -> pthread_t { return pthread_t() } #else internal func _make_pthread_t() -> pthread_t? { return nil } #endif /// Block-based wrapper for `pthread_join`. public func _stdlib_pthread_join<Result>( _ thread: pthread_t, _ resultType: Result.Type ) -> (CInt, Result?) { var threadResultRawPtr: UnsafeMutableRawPointer? let result = pthread_join(thread, &threadResultRawPtr) if result == 0 { let threadResultPtr = threadResultRawPtr!.assumingMemoryBound( to: Result.self) let threadResult = threadResultPtr.pointee threadResultPtr.deinitialize() threadResultPtr.deallocate(capacity: 1) return (result, threadResult) } else { return (result, nil) } } public class _stdlib_Barrier { var _pthreadBarrier: _stdlib_pthread_barrier_t var _pthreadBarrierPtr: UnsafeMutablePointer<_stdlib_pthread_barrier_t> { return _getUnsafePointerToStoredProperties(self) .assumingMemoryBound(to: _stdlib_pthread_barrier_t.self) } public init(threadCount: Int) { self._pthreadBarrier = _stdlib_pthread_barrier_t() let ret = _stdlib_pthread_barrier_init( _pthreadBarrierPtr, nil, CUnsignedInt(threadCount)) if ret != 0 { fatalError("_stdlib_pthread_barrier_init() failed") } } deinit { let ret = _stdlib_pthread_barrier_destroy(_pthreadBarrierPtr) if ret != 0 { fatalError("_stdlib_pthread_barrier_destroy() failed") } } public func wait() { let ret = _stdlib_pthread_barrier_wait(_pthreadBarrierPtr) if !(ret == 0 || ret == _stdlib_PTHREAD_BARRIER_SERIAL_THREAD) { fatalError("_stdlib_pthread_barrier_wait() failed") } } }
apache-2.0
26d1d26fe7fb539a300271a43a993654
30.581081
80
0.677364
4.107206
false
false
false
false
BryanHoke/swift-corelibs-foundation
Foundation/NSRange.swift
3
3914
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // public struct _NSRange { public var location: Int public var length: Int public init() { location = 0 length = 0 } public init(location: Int, length: Int) { self.location = location self.length = length } } extension _NSRange { public init(_ x: Range<Int>) { if let start = x.first { if let end = x.last { self.init(location: start, length: end - start) return } } self.init(location: 0, length: 0) } @warn_unused_result public func toRange() -> Range<Int>? { return Range<Int>(start: location, end: location + length) } } public typealias NSRange = _NSRange public typealias NSRangePointer = UnsafeMutablePointer<NSRange> public func NSMakeRange(loc: Int, _ len: Int) -> NSRange { return NSRange(location: loc, length: len) } public func NSMaxRange(range: NSRange) -> Int { return range.location + range.length } public func NSLocationInRange(loc: Int, _ range: NSRange) -> Bool { return !(loc < range.location) && (loc - range.location) < range.length } public func NSEqualRanges(range1: NSRange, _ range2: NSRange) -> Bool { return range1.location == range2.location && range1.length == range2.length } public func NSUnionRange(range1: NSRange, _ range2: NSRange) -> NSRange { let max1 = range1.location + range1.length let max2 = range2.location + range2.length let maxend: Int if max1 > max2 { maxend = max1 } else { maxend = max2 } let minloc: Int if range1.location < range2.location { minloc = range1.location } else { minloc = range2.location } return NSMakeRange(minloc, maxend - minloc) } public func NSIntersectionRange(range1: NSRange, _ range2: NSRange) -> NSRange { let max1 = range1.location + range1.length let max2 = range2.location + range2.length let minend: Int if max1 < max2 { minend = max1 } else { minend = max2 } if range2.location <= range1.location && range1.location < max2 { return NSMakeRange(range1.location, minend - range1.location) } else if range1.location <= range2.location && range2.location < max1 { return NSMakeRange(range2.location, minend - range2.location) } return NSMakeRange(0, 0) } public func NSStringFromRange(range: NSRange) -> String { return "{\(range.location), \(range.length)}" } public func NSRangeFromString(aString: String) -> NSRange { let emptyRange = NSMakeRange(0, 0) if aString.isEmpty { // fail early if the string is empty return emptyRange } let scanner = NSScanner(string: aString) let digitSet = NSCharacterSet.decimalDigitCharacterSet() scanner.scanUpToCharactersFromSet(digitSet) if scanner.atEnd { // fail early if there are no decimal digits return emptyRange } guard let location = scanner.scanInteger() else { return emptyRange } let partialRange = NSMakeRange(location, 0) if scanner.atEnd { // return early if there are no more characters after the first int in the string return partialRange } scanner.scanUpToCharactersFromSet(digitSet) if scanner.atEnd { // return early if there are no integer characters after the first int in the string return partialRange } guard let length = scanner.scanInteger() else { return partialRange } return NSMakeRange(location, length) }
apache-2.0
cbbb4c4da4dfaa164585551c085c1c9d
28.885496
92
0.649719
4.089864
false
false
false
false
Johennes/firefox-ios
Sync/Synchronizers/ClientsSynchronizer.swift
3
15022
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred private let log = Logger.syncLogger let ClientsStorageVersion = 1 // TODO public protocol Command { static func fromName(command: String, args: [JSON]) -> Command? func run(synchronizer: ClientsSynchronizer) -> Success static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? } // Shit. // We need a way to wipe or reset engines. // We need a way to log out the account. // So when we sync commands, we're gonna need a delegate of some kind. public class WipeCommand: Command { public init?(command: String, args: [JSON]) { return nil } public class func fromName(command: String, args: [JSON]) -> Command? { return WipeCommand(command: command, args: args) } public func run(synchronizer: ClientsSynchronizer) -> Success { return succeed() } public static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? { let json = JSON.parse(syncCommand.value) if let name = json["command"].asString, args = json["args"].asArray { return WipeCommand.fromName(name, args: args) } return nil } } public class DisplayURICommand: Command { let uri: NSURL let title: String public init?(command: String, args: [JSON]) { if let uri = args[0].asString?.asURL, title = args[2].asString { self.uri = uri self.title = title } else { // Oh, Swift. self.uri = "http://localhost/".asURL! self.title = "" return nil } } public class func fromName(command: String, args: [JSON]) -> Command? { return DisplayURICommand(command: command, args: args) } public func run(synchronizer: ClientsSynchronizer) -> Success { synchronizer.delegate.displaySentTabForURL(uri, title: title) return succeed() } public static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? { let json = JSON.parse(syncCommand.value) if let name = json["command"].asString, args = json["args"].asArray { return DisplayURICommand.fromName(name, args: args) } return nil } } let Commands: [String: (String, [JSON]) -> Command?] = [ "wipeAll": WipeCommand.fromName, "wipeEngine": WipeCommand.fromName, // resetEngine // resetAll // logout "displayURI": DisplayURICommand.fromName, ] public class ClientsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "clients") } override var storageVersion: Int { return ClientsStorageVersion } var clientRecordLastUpload: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastClientUpload") } get { return self.prefs.unsignedLongForKey("lastClientUpload") ?? 0 } } // Sync Object Format (Version 1) for Form Factors: http://docs.services.mozilla.com/sync/objectformats.html#id2 private enum SyncFormFactorFormat: String { case phone = "phone" case tablet = "tablet" } public func getOurClientRecord() -> Record<ClientPayload> { let guid = self.scratchpad.clientGUID let formfactor = formFactorString() let json = JSON([ "id": guid, "version": AppInfo.appVersion, "protocols": ["1.5"], "name": self.scratchpad.clientName, "os": "iOS", "commands": [JSON](), "type": "mobile", "appPackage": NSBundle.mainBundle().bundleIdentifier ?? "org.mozilla.ios.FennecUnknown", "application": DeviceInfo.appName(), "device": DeviceInfo.deviceModel(), "formfactor": formfactor]) let payload = ClientPayload(json) return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds) } private func formFactorString() -> String { let userInterfaceIdiom = UIDevice.currentDevice().userInterfaceIdiom var formfactor: String switch userInterfaceIdiom { case .Phone: formfactor = SyncFormFactorFormat.phone.rawValue case .Pad: formfactor = SyncFormFactorFormat.tablet.rawValue default: formfactor = SyncFormFactorFormat.phone.rawValue } return formfactor } private func clientRecordToLocalClientEntry(record: Record<ClientPayload>) -> RemoteClient { let modified = record.modified let payload = record.payload return RemoteClient(json: payload, modified: modified) } // If this is a fresh start, do a wipe. // N.B., we don't wipe outgoing commands! (TODO: check this when we implement commands!) // N.B., but perhaps we should discard outgoing wipe/reset commands! private func wipeIfNecessary(localClients: RemoteClientsAndTabs) -> Success { if self.lastFetched == 0 { return localClients.wipeClients() } return succeed() } /** * Returns whether any commands were found (and thus a replacement record * needs to be uploaded). Also returns the commands: we run them after we * upload a replacement record. */ private func processCommandsFromRecord(record: Record<ClientPayload>?, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Deferred<Maybe<(Bool, [Command])>> { log.debug("Processing commands from downloaded record.") // TODO: short-circuit based on the modified time of the record we uploaded, so we don't need to skip ahead. if let record = record { let commands = record.payload.commands if !commands.isEmpty { func parse(json: JSON) -> Command? { if let name = json["command"].asString, args = json["args"].asArray, constructor = Commands[name] { return constructor(name, args) } return nil } // TODO: can we do anything better if a command fails? return deferMaybe((true, optFilter(commands.map(parse)))) } } return deferMaybe((false, [])) } private func uploadClientCommands(toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { return localClients.getCommands() >>== { clientCommands in return clientCommands.map { (clientGUID, commands) -> Success in self.syncClientCommands(clientGUID, commands: commands, clientsAndTabs: localClients, withServer: storageClient) }.allSucceed() } } private func syncClientCommands(clientGUID: GUID, commands: [SyncCommand], clientsAndTabs: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let deleteCommands: () -> Success = { return clientsAndTabs.deleteCommands(clientGUID).bind({ x in return succeed() }) } log.debug("Fetching current client record for client \(clientGUID).") let fetch = storageClient.get(clientGUID) return fetch.bind() { result in if let response = result.successValue where response.value.payload.isValid() { let record = response.value if var clientRecord = record.payload.asDictionary { clientRecord["commands"] = JSON(record.payload.commands + commands.map { JSON.parse($0.value) }) let uploadRecord = Record(id: clientGUID, payload: ClientPayload(JSON(clientRecord)), ttl: ThreeWeeksInSeconds) return storageClient.put(uploadRecord, ifUnmodifiedSince: record.modified) >>== { resp in log.debug("Client \(clientGUID) commands upload succeeded.") // Always succeed, even if we couldn't delete the commands. return deleteCommands() } } } else { if let failure = result.failureValue { log.warning("Failed to fetch record with GUID \(clientGUID).") if failure is NotFound<NSHTTPURLResponse> { log.debug("Not waiting to see if the client comes back.") // TODO: keep these around and retry, expiring after a while. // For now we just throw them away so we don't fail every time. return deleteCommands() } if failure is BadRequestError<NSHTTPURLResponse> { log.debug("We made a bad request. Throwing away queued commands.") return deleteCommands() } } } log.error("Client \(clientGUID) commands upload failed: No remote client for GUID") return deferMaybe(UnknownError()) } } /** * Upload our record if either (a) we know we should upload, or (b) * our own notes tell us we're due to reupload. */ private func maybeUploadOurRecord(should: Bool, ifUnmodifiedSince: Timestamp?, toServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let lastUpload = self.clientRecordLastUpload let expired = lastUpload < (NSDate.now() - (2 * OneDayInMilliseconds)) log.debug("Should we upload our client record? Caller = \(should), expired = \(expired).") if !should && !expired { return succeed() } let iUS: Timestamp? = ifUnmodifiedSince ?? ((lastUpload == 0) ? nil : lastUpload) return storageClient.put(getOurClientRecord(), ifUnmodifiedSince: iUS) >>== { resp in if let ts = resp.metadata.lastModifiedMilliseconds { // Protocol says this should always be present for success responses. log.debug("Client record upload succeeded. New timestamp: \(ts).") self.clientRecordLastUpload = ts } return succeed() } } private func applyStorageResponse(response: StorageResponse<[Record<ClientPayload>]>, toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { log.debug("Applying clients response.") let records = response.value let responseTimestamp = response.metadata.lastModifiedMilliseconds log.debug("Got \(records.count) client records.") let ourGUID = self.scratchpad.clientGUID var toInsert = [RemoteClient]() var ours: Record<ClientPayload>? = nil for (rec) in records { guard rec.payload.isValid() else { log.warning("Client record \(rec.id) is invalid. Skipping.") continue } if rec.id == ourGUID { if rec.modified == self.clientRecordLastUpload { log.debug("Skipping our own unmodified record.") } else { log.debug("Saw our own record in response.") ours = rec } } else { toInsert.append(self.clientRecordToLocalClientEntry(rec)) } } // Apply remote changes. // Collect commands from our own record and reupload if necessary. // Then run the commands and return. return localClients.insertOrUpdateClients(toInsert) >>== { self.processCommandsFromRecord(ours, withServer: storageClient) } >>== { (shouldUpload, commands) in return self.maybeUploadOurRecord(shouldUpload, ifUnmodifiedSince: ours?.modified, toServer: storageClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: storageClient) } >>> { log.debug("Running \(commands.count) commands.") for (command) in commands { command.run(self) } self.lastFetched = responseTimestamp! return succeed() } } } public func synchronizeLocalClients(localClients: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { log.debug("Synchronizing clients.") if let reason = self.reasonToNotSync(storageClient) { switch reason { case .EngineRemotelyNotEnabled: // This is a hard error for us. return deferMaybe(FatalError(message: "clients not mentioned in meta/global. Server wiped?")) default: return deferMaybe(SyncStatus.NotStarted(reason)) } } let keys = self.scratchpad.keys?.value let encoder = RecordEncoder<ClientPayload>(decode: { ClientPayload($0) }, encode: { $0 }) let encrypter = keys?.encrypter(self.collection, encoder: encoder) if encrypter == nil { log.error("Couldn't make clients encrypter.") return deferMaybe(FatalError(message: "Couldn't make clients encrypter.")) } let clientsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter!) if !self.remoteHasChanges(info) { log.debug("No remote changes for clients. (Last fetched \(self.lastFetched).)") return self.maybeUploadOurRecord(false, ifUnmodifiedSince: nil, toServer: clientsClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: clientsClient) } >>> { deferMaybe(.Completed) } } // TODO: some of the commands we process might involve wiping collections or the // entire profile. We should model this as an explicit status, and return it here // instead of .Completed. return clientsClient.getSince(self.lastFetched) >>== { response in return self.wipeIfNecessary(localClients) >>> { self.applyStorageResponse(response, toLocalClients: localClients, withServer: clientsClient) } } >>> { deferMaybe(.Completed) } } }
mpl-2.0
7bd8669464b80afcf3e0740017e1c907
39.710027
218
0.605645
5.306252
false
false
false
false
mlgoogle/iosstar
iOSStar/Model/ShareDataModel/BankCard.swift
3
1294
// // BankCard.swift // iOSStar // // Created by sum on 2017/7/5. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit class BankModel: BaseModel { //返回的列表的key var cardList : [BankListModel]? class func cardListModelClass() ->AnyClass { return BankListModel.classForCoder() } } class UnBindBank: BaseModel { //返回的列表的key var result: Int64 = 0 } class BankInfo: BaseModel { //返回的列表的key var bankId: Int64 = 0 var bankName: String = "-" var cardNO: String = "-" var cardName: String = "-" } class BindBank: BaseModel { //返回的列表的key var cardNO: String = "--" var name: String = "-" var bid: Int64 = 0 var bankName: String = "-" var bankId: String = "-" } // 银行卡返回列表model class BankListModel: BaseModel { // 银行卡id var bid: Int64 = 0 // 用户id // var account: Int64 = 0 // 银行名称 var bank: String = "--" // 支行名称 var account: String = "" // 银行卡号 // var account: String = "cardNo" // 开户名 var bankUsername: String = "--" var cardNo: String = "--" var cardName: String = "--" }
gpl-3.0
bdd307f4e8876072b101f0b53ccd3619
17.015152
51
0.549201
3.397143
false
false
false
false
pjcau/LocalNotifications_Over_iOS10
Pods/SwiftDate/Sources/SwiftDate/Date+Math.swift
2
7433
// SwiftDate // Manage Date/Time & Timezone in Swift // // Created by: Daniele Margutti // Email: <[email protected]> // Web: <http://www.danielemargutti.com> // // Licensed under MIT License. import Foundation // MARK: - Shortcuts to convert Date to DateInRegion public extension Date { /// Return the current absolute datetime in local's device region (timezone+calendar+locale) /// /// - returns: a new `DateInRegion` instance object which express passed absolute date in the context of the local device's region @available(*, deprecated: 4.1.2, message: "This method is deprecated. use inDefaultRegion instead") public func inLocalRegion() -> DateInRegion { return DateInRegion(absoluteDate: self) } /// Return the current absolute datetime in default's device region (timezone+calendar+locale) /// /// - returns: a new `DateInRegion` instance object which express passed absolute date in the context of the current default region public func inDefaultRegion() -> DateInRegion { return DateInRegion(absoluteDate: self) } /// Return the current absolute datetime in UTC/GMT timezone. `Calendar` and `Locale` are set automatically to the device's current settings. /// /// - returns: a new `DateInRegion` instance object which express passed absolute date in UTC timezone public func inGMTRegion() -> DateInRegion { return DateInRegion(absoluteDate: self, in: Region.GMT()) } /// Return the current absolute datetime in the context of passed `Region`. /// /// - parameter region: region you want to use to express `self` date. /// /// - returns: a new `DateInRegion` which represent `self` in the context of passed `Region` public func inRegion(region: Region? = nil) -> DateInRegion { return DateInRegion(absoluteDate: self, in: region) } /// Create a new Date object which is the sum of passed calendar components in `DateComponents` to `self` /// /// - parameter components: components to set /// /// - returns: a new `Date` public func add(components: DateComponents) -> Date { let date: DateInRegion = self.inDateDefaultRegion() + components return date.absoluteDate } /// Create a new Date object which is the sum of passed calendar components in dictionary of `Calendar.Component` values to `self` /// /// - parameter components: components to set /// /// - returns: a new `Date` public func add(components: [Calendar.Component: Int]) -> Date { let date: DateInRegion = self.inDateDefaultRegion() + components return date.absoluteDate } /// Enumerate dates between two intervals by adding specified time components and return an array of dates. /// `startDate` interval will be the first item of the resulting array. The last item of the array is evaluated automatically. /// /// - throws: throw `.DifferentCalendar` if dates are expressed in a different calendar, '.FailedToCalculate' /// /// - Parameters: /// - startDate: starting date /// - endDate: ending date /// - components: components to add /// - Returns: an array of DateInRegion objects public static func dates(between startDate: Date, and endDate: Date, increment components: DateComponents) -> [Date] { var dates: [Date] = [] var currentDate = startDate while (currentDate <= endDate) { dates.append(currentDate) currentDate = currentDate.add(components: components) } return dates } /// Return new date by rounding receiver to the next `value` interval. /// Interval can be `seconds` or `minutes` and you can specify the type of rounding function to use. /// /// - Parameters: /// - value: value to round /// - type: type of rounding public func roundedAt(_ value: IntervalType, type: IntervalRoundingType = .ceil) -> Date { var roundedInterval: TimeInterval = 0 let seconds = value.seconds switch type { case .round: roundedInterval = (self.timeIntervalSinceReferenceDate / seconds).rounded() * seconds case .ceil: roundedInterval = ceil(self.timeIntervalSinceReferenceDate / seconds) * seconds case .floor: roundedInterval = floor(self.timeIntervalSinceReferenceDate / seconds) * seconds } return Date(timeIntervalSinceReferenceDate: roundedInterval) } /// Returns a boolean value that indicates whether the represented absolute date uses daylight saving time when /// expressed in passed timezone. /// /// - Parameter tzName: destination timezone /// - Returns: `true` if date uses DST when represented in given timezone, `false` otherwise public func isDST(in tzName: TimeZoneName) -> Bool { return tzName.timeZone.isDaylightSavingTime(for: self) } /// The current daylight saving time offset of the represented date when expressed in passed timezone. /// /// - Parameter tzName: destination timezone /// - Returns: interval of DST expressed in seconds public func DSTOffset(in tzName: TimeZoneName) -> TimeInterval { return tzName.timeZone.daylightSavingTimeOffset(for: self) } /// The date of the next daylight saving time transition after currently represented date when expressed /// in given timezone. /// /// - Parameter tzName: destination timezone /// - Returns: next transition date public func nextDSTTransitionDate(in tzName: TimeZoneName) -> Date? { guard let next_date = tzName.timeZone.nextDaylightSavingTimeTransition(after: self) else { return nil } return next_date } /// Return the difference between two dates expressed using passed time components. /// /// - Parameters: /// - components: time units to get /// - refDate: reference date /// - calendar: calendar to use, `nil` to user `Date.defaultRegion.calendar` /// - Returns: components dictionary public func components(_ components: [Calendar.Component], to refDate: Date, calendar: Calendar? = nil) -> [Calendar.Component : Int] { let cal = calendar ?? Date.defaultRegion.calendar let cmps = cal.dateComponents(componentsToSet(components), from: self, to: refDate) return cmps.toComponentsDict() } /// Return the difference between two dates expressed in passed time unit. /// This operation take care of the calendar in which dates are expressed (must be equal) differently /// from the TimeInterval `in` function. /// /// - Parameters: /// - component: component to get /// - refDate: reference date /// - calendar: calendar to use, `nil` to user `Date.defaultRegion.calendar` /// - Returns: difference expressed in given component public func component(_ component: Calendar.Component, to refDate: Date, calendar: Calendar? = nil) -> Int? { return self.components([component], to: refDate)[component] } } // MARK: - Sum of Dates and Date & Components public func - (lhs: Date, rhs: DateComponents) -> Date { return lhs + (-rhs) } public func + (lhs: Date, rhs: DateComponents) -> Date { return lhs.add(components: rhs) } public func + (lhs: Date, rhs: TimeInterval) -> Date { return lhs.addingTimeInterval(rhs) } public func - (lhs: Date, rhs: TimeInterval) -> Date { return lhs.addingTimeInterval(-rhs) } public func + (lhs: Date, rhs: [Calendar.Component : Int]) -> Date { return lhs.add(components: DateInRegion.componentsFrom(values: rhs)) } public func - (lhs: Date, rhs: [Calendar.Component : Int]) -> Date { return lhs.add(components: DateInRegion.componentsFrom(values: rhs, multipler: -1)) } public func - (lhs: Date, rhs: Date) -> TimeInterval { return DateTimeInterval(start: rhs, end: lhs).duration }
mit
995627d52c2d57af50246f9b9cadae2e
37.117949
142
0.720301
4.022186
false
false
false
false
austinzheng/swift
stdlib/public/core/ContiguouslyStored.swift
1
3906
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @usableFromInline internal protocol _HasContiguousBytes { func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R var _providesContiguousBytesNoCopy: Bool { get } } extension _HasContiguousBytes { @inlinable var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return true } } } extension Array: _HasContiguousBytes { @inlinable var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { #if _runtime(_ObjC) return _buffer._isNative #else return true #endif } } } extension ContiguousArray: _HasContiguousBytes {} extension UnsafeBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { let ptr = UnsafeRawPointer(self.baseAddress._unsafelyUnwrappedUnchecked) let len = self.count &* MemoryLayout<Element>.stride return try body(UnsafeRawBufferPointer(start: ptr, count: len)) } } extension UnsafeMutableBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { let ptr = UnsafeRawPointer(self.baseAddress._unsafelyUnwrappedUnchecked) let len = self.count &* MemoryLayout<Element>.stride return try body(UnsafeRawBufferPointer(start: ptr, count: len)) } } extension UnsafeRawBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try body(self) } } extension UnsafeMutableRawBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try body(UnsafeRawBufferPointer(self)) } } extension String: _HasContiguousBytes { @inlinable internal var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return self._guts.isFastUTF8 } } @inlinable @inline(__always) internal func _withUTF8<R>( _ body: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { if _fastPath(self._guts.isFastUTF8) { return try self._guts.withFastUTF8 { try body($0) } } return try ContiguousArray(self.utf8).withUnsafeBufferPointer { try body($0) } } @inlinable @inline(__always) internal func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self._withUTF8 { return try body(UnsafeRawBufferPointer($0)) } } } extension Substring: _HasContiguousBytes { @inlinable internal var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return self._wholeGuts.isFastUTF8 } } @inlinable @inline(__always) internal func _withUTF8<R>( _ body: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { if _fastPath(_wholeGuts.isFastUTF8) { return try _wholeGuts.withFastUTF8(range: self._offsetRange) { return try body($0) } } return try ContiguousArray(self.utf8).withUnsafeBufferPointer { try body($0) } } @inlinable @inline(__always) internal func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self._withUTF8 { return try body(UnsafeRawBufferPointer($0)) } } }
apache-2.0
bbbcd079d916d98a6d2db12967bd31ad
28.816794
80
0.668203
4.552448
false
false
false
false
efeconirulez/daily-affirmation
Daily Affirmation/Controllers/ReportAffirmationViewController.swift
1
2317
// // ReportAffirmationVC.swift // Daily Affirmation // // Created by Efe Helvaci on 08/03/2017. // Copyright © 2017 efehelvaci. All rights reserved. // import UIKit protocol ReportAffirmationDelegate { func reportAffirmation(withCause cause: String) } class ReportAffirmationViewController: UIViewController { @IBOutlet var tableView: UITableView! var delegate: ReportAffirmationDelegate? override func viewDidLoad() { super.viewDidLoad() } @IBAction func cancelButtonClicked(_ sender: Any) { dismiss(animated: true, completion: nil) } } extension ReportAffirmationViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "reportOptionCell") as? ReportTableViewCell { switch indexPath.row { case 0: cell.label.text = NSLocalizedString("ReportOption1", comment: "Report Option 1") break case 1: cell.label.text = NSLocalizedString("ReportOption2", comment: "Report Option 2") break case 2: cell.label.text = NSLocalizedString("ReportOption3", comment: "Report Option 3") break default: cell.label.text = "" break } return cell } else { return UITableViewCell() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) var reportCause = "Not Specified" switch indexPath.row { case 0: reportCause = "Irrelevant" break case 1: reportCause = "Harrassing" break case 2: reportCause = "No Reason" break default: break } delegate?.reportAffirmation(withCause: reportCause) dismiss(animated: true, completion: nil) } }
apache-2.0
6db4ca39816120ef43dea85b8f52716c
27.592593
113
0.592832
5.067834
false
false
false
false
leizh007/HiPDA
HiPDA/Pods/Delta/Sources/ObservableProperty.swift
1
2041
/** This is the protocol that the state the store holds must implement. To use a custom state type, this protocol must be implemented on that object. This is useful if you want to plug in a reactive programming library and use that for state instead of the built-in ObservableProperty type. */ public protocol ObservablePropertyType { /** The type of the value that `Self` will hold. - note: This is inferred from the `value` property implementation. */ associatedtype ValueType /** The value to be observed and mutated. */ var value: ValueType { get set } } /** A basic implementation of a property whose `value` can be observed using callbacks. ```swift Example: var property = ObservableProperty(1) property.subscribe { newValue in print("newValue: \(newValue)") } property.value = 2 // Executing the above code prints: // "newValue: 2" ``` */ public class ObservableProperty<ValueType> { /** The type of the callback to be called when the `value` changes. */ public typealias CallbackType = ((ValueType) -> ()) private var subscriptions = [CallbackType]() /** The `value` stored in this instance. Setting it to a new value will notify any subscriptions registered through the `subscribe` method. */ public var value: ValueType { didSet { notifySubscriptions() } } /** - parameter value: The initial value to store. */ public init(_ value: ValueType) { self.value = value } /** Register a subscriber that will be called with the new value when the `value` changes. - parameter callback: The function to call when the value changes. */ public func subscribe(callback: @escaping CallbackType) { subscriptions.append(callback) } private func notifySubscriptions() { for subscription in subscriptions { subscription(value) } } } extension ObservableProperty: ObservablePropertyType { }
mit
9b7cbcf710c423a628186dd238dd1126
23.297619
92
0.660461
4.757576
false
false
false
false
gbuela/github-users-coord
github-users/HomeViewModel.swift
1
1904
// // HomeViewModel.swift // github-users // // Created by German Buela on 6/4/16. // Copyright © 2016 German Buela. All rights reserved. // import Foundation import ReactiveCocoa class HomeViewModel { let since: MutableProperty<String> = MutableProperty("") let name: MutableProperty<String> = MutableProperty("") var fetchByIDAction: Action<String, [User], FetchError>! var fetchByNameAction: Action<String, [User], FetchError>! private var api: GithubAPI! private var network: NetworkProtocol! private let sinceValid: MutableProperty<Bool> = MutableProperty(false) private let nameValid: MutableProperty<Bool> = MutableProperty(false) init(_ network: NetworkProtocol) { self.network = network self.api = GithubAPI(self.network) fetchByIDAction = Action<String, [User], FetchError>(enabledIf: sinceValid) { [unowned self] _ in return self.api.userFetchByIDSignalProducer(self.since.value) } fetchByNameAction = Action<String, [User], FetchError>(enabledIf: nameValid) { [unowned self] _ in return self.api.userFetchByNameSignalProducer(self.name.value) } sinceValid <~ since.producer.map(self.isValidSinceValue) nameValid <~ name.producer.map(self.isValidName) Signal.merge([fetchByIDAction.values, fetchByNameAction.values]) .observeNext { users in flowObserver.sendNext(FlowEvent.LoadedList(users: users)) } } private func isValidSinceValue(since:String) -> Bool { guard let sinceValue = Int(since) else { return false } return sinceValue >= 0 } private func isValidName(name:String) -> Bool { return !name.isEmpty && !name.containsWhitespace() } // MARK: - Exposed methods func title() -> String { return "GitHub users" } }
gpl-3.0
f8204b64f514a6f55b19dc3ee4f5e3bc
33.618182
106
0.661061
4.425581
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/AccountPicker/PaymentMethodCell/PaymentMethodCellPresenter.swift
1
1972
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import RxCocoa import RxSwift public final class PaymentMethodCellPresenter { // MARK: - Public Properties public let account: PaymentMethodAccount let badgeImageViewModel: Driver<BadgeImageViewModel> let title: Driver<LabelContent> let description: Driver<LabelContent> public let multiBadgeViewModel: Driver<MultiBadgeViewModel> // MARK: - Private Properties static let multiBadgeInsets: UIEdgeInsets = .init( top: 0, left: 72, bottom: 0, right: 0 ) private let badgeFactory = SingleAccountBadgeFactory() // MARK: - Init public init(account: PaymentMethodAccount, action: AssetAction) { self.account = account multiBadgeViewModel = badgeFactory .badge(account: account, action: action) .map { .init( layoutMargins: LinkedBankAccountCellPresenter.multiBadgeInsets, height: 24.0, badges: $0 ) } .asDriver(onErrorJustReturn: .init()) title = .just( .init( text: account.label, font: .main(.semibold, 16.0), color: .titleText, alignment: .left, accessibility: .none ) ) description = .just( .init( text: account.paymentMethodType.balance.displayString, font: .main(.medium, 14.0), color: .descriptionText, alignment: .left, accessibility: .none ) ) badgeImageViewModel = .just(.default( image: account.logoResource, backgroundColor: account.logoBackgroundColor, cornerRadius: .round, accessibilityIdSuffix: "" )) } }
lgpl-3.0
4620b366f12927a2a03208bc7d443b33
27.565217
83
0.562659
5.312668
false
false
false
false
skerkewitz/SwignalR
Example/Tests/Tests.swift
1
1158
// https://github.com/Quick/Quick import Quick import Nimble import SwignalR class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
e834489ddcd7e39ed13c306c85e6129d
22.04
60
0.356771
5.485714
false
false
false
false
dautermann/YodaSpeak
YodaSpeak/L33tTranslation.swift
1
1600
// // L33tTranslation.swift // YodaSpeak // // Created by Michael Dautermann on 2/1/16. // Copyright © 2016 Michael Dautermann. All rights reserved. // import UIKit class L33tTranslation: Translation { override init() { super.init() self.mashableKey = "o87pnEh1sKmshz8UgYKRrE1EmDuNp1KNPMEjsn7oJKTawBrw9j" self.reverseTranslationAvailable = true } override func getUpperTextPlaceholder() -> String { return "Enter in plain text English" } override func getLowerTextPlaceholder() -> String { return "7ru3 h@Ck3r text here." } override func translateFromEnglishToDestination(fromString: NSString, closure: (data :String) -> ()) { if let urlEncodedSentence = fromString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) { if let url = NSURL(string: "https://montanaflynn-l33t-sp34k.p.mashape.com/encode?text=\(urlEncodedSentence)") { performGetWithServer(url, closure: closure) } } } override func translateFromDestinationToEnglish(fromString: NSString, closure: (data :String) -> ()) { if let urlEncodedSentence = fromString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) { if let url = NSURL(string: "https://montanaflynn-l33t-sp34k.p.mashape.com/decode?text=\(urlEncodedSentence)") { performGetWithServer(url, closure: closure) } } } }
cc0-1.0
e3abd56461736f0ad0746c3368ce6866
29.169811
128
0.641026
4.241379
false
false
false
false
mmllr/CleanTweeter
CleanTweeter/Boundaries/DemoUserRepository.swift
1
2267
import Foundation func createUsers() -> [User] { let dateFormatter = DateFormatter() dateFormatter.timeStyle = .none dateFormatter.dateStyle = .full dateFormatter.dateFormat = "yyyy.MM.dd" let users = [ User(name: "Tim Cook", followedUsers: ["Jony Ive", "Craig Federighi", "Eddy Cue"], tweets: [ Tweet(author: "Tim Cook", content: "Super awesome!", publicationDate: dateFormatter.date(from: "2014.09.12")!), Tweet(author: "Tim Cook", content: "Incredible!", publicationDate: dateFormatter.date(from: "2014.11.3")!), Tweet(author: "Tim Cook", content: "Only #Apple can do this!", publicationDate: dateFormatter.date(from: "2014.11.2")!) ], avatar: "http://images.apple.com/leadership/tim-cook/bio/image_large_2x.png"), User(name: "Craig Federighi", followedUsers: ["Tim Cook", "Jony Ive"], tweets: [ Tweet(author: "Craig Federighi", content: "Forever #hairforceone", publicationDate: dateFormatter.date(from: "2014.10.29")!), Tweet(author: "Craig Federighi", content: "@Jony leather UI?", publicationDate:dateFormatter.date(from: "2014.11.1")!) ], avatar: "http://images.apple.com/leadership/craig-federighi/bio/image_large_2x.png"), User(name: "Jony Ive", followedUsers: ["Tim Cook"], tweets: [ Tweet(author: "Jony Ive", content: "Aluminum!", publicationDate: dateFormatter.date(from: "2014.10.30")!), Tweet(author: "Jony Ive", content: "Sire!", publicationDate: dateFormatter.date(from: "2014.11.1")!), ], avatar: "http://images.apple.com/leadership/jonathan-ive/bio/image_large_2x.png"), User(name: "Eddy Cue", followedUsers: ["Tim Cook", "Jony Ive", "Craig Federighi"], tweets: [ Tweet(author: "Eddy Cue", content: "Lets change the #iTunes UI", publicationDate: dateFormatter.date(from: "2014.08.3")!), Tweet(author: "Eddy Cue", content: "AppleTV #FTW!", publicationDate: dateFormatter.date(from: "2012.10.3")!), ], avatar: "http://images.apple.com/leadership/eddy-cue/bio/image_large_2x.png") ] return users } class DemoUserRepository : UserRepository { var store: Dictionary<String, User> = [:] init() { for user in createUsers() { updateUser(user) } } func findUser(_ userName: String) -> User? { return store[userName] } func updateUser(_ user: User) { store[user.name] = user } }
mit
102b31a306a168a399c01a000a656c19
46.229167
128
0.691663
3.092769
false
false
false
false
PureSwift/DBus
Tests/DBusTests/ObjectPathTests.swift
1
7473
// // ObjectPathTests.swift // DBusTests // // Created by Alsey Coleman Miller on 10/21/18. // import Foundation import XCTest @testable import DBus final class ObjectPathTests: XCTestCase { static let allTests: [(String, (ObjectPathTests) -> () -> Void)] = [ ("testInvalid", testInvalid), ("testValid", testValid), ("testEmpty", testEmpty), ("testMultithread", testMultithread) ] func testInvalid() { let strings = [ "", """ /com//example/ """, "/com/example/ñanó", "/com/example/b$@s1", "/com/example/bus1/", "/com/example/😀", "//", "///", "\\" ] for string in strings { XCTAssertNil(DBusObjectPath(rawValue: string), "\(string) should be invalid") XCTAssertThrowsError(try DBusObjectPath.validate(string)) do { try DBusObjectPath.validate(string) } catch let error as DBusError { XCTAssertEqual(error.name, .invalidArguments) print("\"\(string)\" is invalid: \(error.message)"); return } catch { XCTFail("\(error)"); return } XCTFail("Error expected for \(string)") } } func testValid() { let values: [(String, [String])] = [ ("/", []), ("/com", ["com"]), ("/com/example/bus1", ["com", "example", "bus1"]) ] for (string, elements) in values { XCTAssertNoThrow(try DBusObjectPath.validate(string)) // initialize guard let objectPath = DBusObjectPath(rawValue: string) else { XCTFail("Invalid string \(string)"); return } // test underlying values XCTAssertEqual(objectPath.map { $0.rawValue }, elements, "Invalid elements") XCTAssertEqual(objectPath.rawValue, string) XCTAssertEqual(objectPath.description, string) XCTAssertEqual(objectPath.hashValue, string.hashValue) // test collection / subscripting XCTAssertEqual(objectPath.count, elements.count) objectPath.enumerated().forEach { XCTAssertEqual(elements[$0.offset], $0.element.rawValue) } elements.enumerated().forEach { XCTAssertEqual(objectPath[$0.offset].rawValue, $0.element) } // initialize with elements let elementsObjectPath = DBusObjectPath(elements.compactMap({ DBusObjectPath.Element(rawValue: $0) })) XCTAssertEqual(elementsObjectPath.map { $0.rawValue }, elements) XCTAssertEqual(Array(elementsObjectPath), elements.compactMap({ DBusObjectPath.Element(rawValue: $0) })) XCTAssertEqual(elementsObjectPath, objectPath) // test equality XCTAssertEqual(objectPath, objectPath) XCTAssertEqual(elementsObjectPath, elementsObjectPath) XCTAssertEqual(objectPath, elementsObjectPath) XCTAssertEqual(objectPath.rawValue, elementsObjectPath.rawValue) XCTAssertEqual(Array(objectPath), Array(elementsObjectPath)) } } func testEmpty() { // empty object path let objectPath = DBusObjectPath() XCTAssertEqual(objectPath.rawValue, "/") XCTAssert(objectPath.isEmpty) XCTAssertEqual(objectPath, []) XCTAssertEqual(DBusObjectPath(), DBusObjectPath(rawValue: "/")) XCTAssertEqual(DBusObjectPath(), DBusObjectPath()) XCTAssertNotEqual(DBusObjectPath(), DBusObjectPath(rawValue: "/com/example")!) XCTAssertNotEqual(DBusObjectPath().rawValue, DBusObjectPath(rawValue: "/com/example")!.rawValue) XCTAssertNotEqual(DBusObjectPath().elements, DBusObjectPath(rawValue: "/com/example")!.elements) // don't break value semantics by modifying instance var mutable = DBusObjectPath() XCTAssertEqual(mutable, objectPath) mutable.append(DBusObjectPath.Element(rawValue: "mutation1")!) mutable.removeLast() XCTAssertEqual(mutable, objectPath) XCTAssertEqual(mutable.rawValue, objectPath.rawValue) } func testMultithread() { let string = "/com/example/bus1" let objectPath = DBusObjectPath([ DBusObjectPath.Element(rawValue: "com")!, DBusObjectPath.Element(rawValue: "example")!, DBusObjectPath.Element(rawValue: "bus1")! ]) // instance for initializing string let readStringCopy = objectPath // initialize string from another thread let queue = DispatchQueue(label: "\(#function) Queue", attributes: [.concurrent]) let end = Date() + 0.5 while Date() < end { for _ in 0 ..< 100 { let mutableArray = [""] var newObjectPath: DBusObjectPath = [] XCTAssertEqual(newObjectPath.rawValue, "/") newObjectPath.append(DBusObjectPath.Element(rawValue: "example")!) XCTAssertEqual(newObjectPath.rawValue, "/example") newObjectPath.append(DBusObjectPath.Element(rawValue: "mutation")!) queue.async { // access variable from different threads // trigger lazy initialization from another thread XCTAssertEqual(newObjectPath.rawValue, "/example/mutation") var mutableCopy1 = newObjectPath var mutableCopy2 = newObjectPath var arrayCopy1 = mutableArray var arrayCopy2 = mutableArray queue.async { mutableCopy1.append(DBusObjectPath.Element(rawValue: "1")!) XCTAssertEqual(mutableCopy1.rawValue, "/example/mutation/1") XCTAssertEqual(arrayCopy1, [""]) arrayCopy1.append("1") XCTAssertEqual(arrayCopy1, ["", "1"]) } queue.async { mutableCopy2.append(DBusObjectPath.Element(rawValue: "2")!) XCTAssertEqual(mutableCopy2.rawValue, "/example/mutation/2") XCTAssertEqual(arrayCopy2, [""]) arrayCopy2.append("2") XCTAssertEqual(arrayCopy2, ["", "2"]) } } } queue.async { XCTAssertEqual(readStringCopy.rawValue, string) } queue.async { var mutateCopy = readStringCopy mutateCopy.append(DBusObjectPath.Element(rawValue: "mutation")!) XCTAssertNotEqual(readStringCopy, mutateCopy) XCTAssertNotEqual(mutateCopy.rawValue, string) } } XCTAssertEqual(objectPath.rawValue, string) } }
mit
6214edddbe50799e4ab5b0cc41b66b9d
37.494845
116
0.534012
5.912906
false
true
false
false
wangchong321/tucao
WCWeiBo/WCWeiBo/Classes/Model/Home/QRCodeCreateView.swift
1
1738
// // QRCodeCreateView.swift // WCWeiBo // // Created by 王充 on 15/5/15. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class QRCodeCreateView: UIViewController { @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var imgView2: UIImageView! override func viewDidLoad() { super.viewDidLoad() // let urlString = NSURL(string: sharedUserAccount!.avatar_large!) // let imgView1 = UIImageView() // imgView.sd_setImageWithURL(urlString) let urlString = NSURL(string: sharedUserAccount!.avatar_large!) let data = NSData(contentsOfURL: urlString!) // //let img = UIImage( // imgView.sd_setImageWithURL(urlString) // imgView2.sd_setImageWithURL(urlString) let image = UIImage(data: data!) let rect = imgView2.bounds let scale = 0.3 as CGFloat UIGraphicsBeginImageContext(rect.size) let avatarSize = CGSizeMake(rect.size.width * scale, rect.size.height * scale) let x = (rect.width - avatarSize.width) * 0.5 let y = (rect.height - avatarSize.height) * 0.5 image!.drawInRect(CGRectMake(x, y, avatarSize.width, avatarSize.height)) let result = UIGraphicsGetImageFromCurrentImageContext() imgView2.image = result imgView.image = qrCode.generateImage("王充3000", avatarImage:image , avatarScale: 0.25, color: CIColor(red: 1, green: 1, blue: 1), backColor: CIColor(red: 0, green: 0, blue: 0)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
d249fb4d8aea3732023980ca022b6ccb
31.603774
183
0.629051
4.396947
false
false
false
false
ciiqr/contakt
contakt/contaktTests/Contact+fullName-Tests.swift
1
2317
// // Contact+fullName-Tests.swift // contakt // // Created by William Villeneuve on 2016-01-23. // Copyright © 2016 William Villeneuve. All rights reserved. // import XCTest class Contact_fullName_Tests: XCTestCase { func test_entireName() { let contact = Contact(firstName: "William", middleName: "Aaron", lastName: "Villeneuve") XCTAssertEqual(contact.fullName(), "William Aaron Villeneuve") XCTAssertEqual(contact.fullName(middleInitial: true), "William A. Villeneuve") } // MARK: Missing one name func test_firstMissing() { let contact = Contact(middleName: "Aaron", lastName: "Villeneuve") XCTAssertEqual(contact.fullName(), "Aaron Villeneuve") XCTAssertEqual(contact.fullName(middleInitial: true), "A. Villeneuve") } func test_middleMissing() { let contact = Contact(firstName: "William", lastName: "Villeneuve") XCTAssertEqual(contact.fullName(), "William Villeneuve") XCTAssertEqual(contact.fullName(middleInitial: true), "William Villeneuve") } func test_lastMissing() { let contact = Contact(firstName: "William", middleName: "Aaron") XCTAssertEqual(contact.fullName(), "William Aaron") XCTAssertEqual(contact.fullName(middleInitial: true), "William A.") } // MARK: Missing two names func test_firstMiddleMissing() { let contact = Contact(lastName: "Villeneuve") XCTAssertEqual(contact.fullName(), "Villeneuve") XCTAssertEqual(contact.fullName(middleInitial: true), "Villeneuve") } func test_firstLastMissing() { let contact = Contact(middleName: "Aaron") XCTAssertEqual(contact.fullName(), "Aaron") XCTAssertEqual(contact.fullName(middleInitial: true), "A.") } func test_middleLastMissing() { let contact = Contact(firstName: "William") XCTAssertEqual(contact.fullName(), "William") XCTAssertEqual(contact.fullName(middleInitial: true), "William") } // MARK: Empty contact func test_empty() { let contact = Contact() XCTAssertEqual(contact.fullName(), "") XCTAssertEqual(contact.fullName(middleInitial: true), "") } }
unlicense
72a5741fa7436e5f33d9b0ae4cba90df
31.166667
96
0.63601
4.428298
false
true
false
false
belatrix/iOSAllStarsRemake
AllStars/AllStars/iPhone/Classes/Ranking/UserRankingViewController.swift
1
3477
// // UserRankingViewController.swift // AllStars // // Created by Kenyi Rodriguez Vergara on 16/05/16. // Copyright © 2016 Belatrix SF. All rights reserved. // import UIKit class UserRankingViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tlbUsers : UITableView! @IBOutlet weak var viewLoading : UIView! @IBOutlet weak var lblErrorMessage : UILabel! @IBOutlet weak var acitivityEmployees : UIActivityIndicatorView! var arrayUsers = NSMutableArray() var kind : String? override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.listTotalScore() } // MARK: - Style override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } // MARK: - UITableViewDelegate, UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arrayUsers.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "UserRankingTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! UserRankingTableViewCell cell.objUser = self.arrayUsers[indexPath.row] as! UserRankingBE cell.indexPath = indexPath cell.updateData() return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.setSelected(false, animated: true) let objBE = self.arrayUsers[indexPath.row] as! UserRankingBE let objUser : User = User() objUser.user_pk = objBE.userRanking_pk objUser.user_username = objBE.userRanking_userName objUser.user_first_name = objBE.userRanking_firstName objUser.user_last_name = objBE.userRanking_lastName objUser.user_avatar = objBE.userRanking_avatar let storyBoard : UIStoryboard = UIStoryboard(name: "Profile", bundle:nil) let profileViewController = storyBoard.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController profileViewController.objUser = objUser profileViewController.backEnable = true self.navigationController?.pushViewController(profileViewController, animated: true) } //MARK: - WebService func listTotalScore(){ self.acitivityEmployees.startAnimating() self.viewLoading.alpha = CGFloat(!Bool(self.arrayUsers.count)) self.lblErrorMessage.text = "Loading employees" RankingBC.listUserRankingWithKind(self.kind) {(arrayUsersRanking) in self.acitivityEmployees.stopAnimating() self.arrayUsers = arrayUsersRanking! self.lblErrorMessage.text = "no_availables_employees".localized self.viewLoading.alpha = CGFloat(!Bool(self.arrayUsers.count)) self.tlbUsers.reloadData() } } }
mit
e4ab7eae1fc4c816f3678dad23541608
34.845361
137
0.660242
5.372488
false
false
false
false
hooman/swift
stdlib/public/core/UTF32.swift
13
2470
//===--- UTF32.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension Unicode { @frozen public enum UTF32: Sendable { case _swift3Codec } } extension Unicode.UTF32: Unicode.Encoding { public typealias CodeUnit = UInt32 public typealias EncodedScalar = CollectionOfOne<UInt32> @inlinable internal static var _replacementCodeUnit: CodeUnit { @inline(__always) get { return 0xFFFD } } @inlinable public static var encodedReplacementCharacter: EncodedScalar { return EncodedScalar(_replacementCodeUnit) } @inlinable @inline(__always) public static func _isScalar(_ x: CodeUnit) -> Bool { return true } /// Returns whether the given code unit represents an ASCII scalar @_alwaysEmitIntoClient public static func isASCII(_ x: CodeUnit) -> Bool { return x <= 0x7F } @inlinable @inline(__always) public static func decode(_ source: EncodedScalar) -> Unicode.Scalar { return Unicode.Scalar(_unchecked: source.first!) } @inlinable @inline(__always) public static func encode( _ source: Unicode.Scalar ) -> EncodedScalar? { return EncodedScalar(source.value) } @frozen public struct Parser: Sendable { @inlinable public init() { } } public typealias ForwardParser = Parser public typealias ReverseParser = Parser } extension UTF32.Parser: Unicode.Parser { public typealias Encoding = Unicode.UTF32 /// Parses a single Unicode scalar value from `input`. @inlinable public mutating func parseScalar<I: IteratorProtocol>( from input: inout I ) -> Unicode.ParseResult<Encoding.EncodedScalar> where I.Element == Encoding.CodeUnit { let n = input.next() if _fastPath(n != nil), let x = n { // Check code unit is valid: not surrogate-reserved and within range. guard _fastPath((x &>> 11) != 0b1101_1 && x <= 0x10ffff) else { return .error(length: 1) } // x is a valid scalar. return .valid(UTF32.EncodedScalar(x)) } return .emptyInput } }
apache-2.0
8d01b5b987529b19668eca792e4620c0
26.752809
80
0.649798
4.458484
false
false
false
false
bingFly/weibo
weibo/weibo/Classes/Tools/String+Hash.swift
6
1014
// // StringHash.swift // 黑马微博 // // Created by 刘凡 on 15/2/21. // Copyright (c) 2015年 joyios. All rights reserved. // /// 注意:要使用本分类,需要在 bridge.h 中添加以下头文件导入 /// #import <CommonCrypto/CommonCrypto.h> /// 如果使用了单元测试,项目 和 测试项目的 bridge.h 中都需要导入 import Foundation extension String { /// 返回字符串的 MD5 散列结果 var md5: String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) var hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.dealloc(digestLen) return hash.copy() as! String } }
mit
7d79089d3fc5f9e51890c6a521535c79
25.848485
83
0.621896
3.676349
false
false
false
false
processone/xmpp-messenger-ios
Example/xmpp-messenger-ios/OpenChatsTableViewController.swift
2
4534
// // GroupChatTableViewController.swift // OneChat // // Created by Paul on 02/03/2015. // Copyright (c) 2015 ProcessOne. All rights reserved. // import UIKit import xmpp_messenger_ios import XMPPFramework class OpenChatsTableViewController: UITableViewController, OneRosterDelegate { var chatList = NSArray() // Mark: Life Cycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) OneRoster.sharedInstance.delegate = self OneChat.sharedInstance.connect(username: kXMPP.myJID, password: kXMPP.myPassword) { (stream, error) -> Void in if let _ = error { self.performSegueWithIdentifier("One.HomeToSetting", sender: self) } else { //set up online UI } } tableView.rowHeight = 50 } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) OneRoster.sharedInstance.delegate = nil } // Mark: OneRoster Delegates func oneRosterContentChanged(controller: NSFetchedResultsController) { //Will reload the tableView to reflet roster's changes tableView.reloadData() } // Mark: UITableView Datasources override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return OneChats.getChatsList().count } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { //let sections: NSArray? = OneRoster.sharedInstance.fetchedResultsController()!.sections return 1//sections } // Mark: UITableView Delegates override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let user = OneChats.getChatsList().objectAtIndex(indexPath.row) as! XMPPUserCoreDataStorageObject cell!.textLabel!.text = user.displayName cell!.detailTextLabel?.hidden = true OneChat.sharedInstance.configurePhotoForCell(cell!, user: user) cell?.imageView?.layer.cornerRadius = 24 cell?.imageView?.clipsToBounds = true return cell! } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let refreshAlert = UIAlertController(title: "", message: "Are you sure you want to clear the entire message history? \n This cannot be undone.", preferredStyle: UIAlertControllerStyle.ActionSheet) refreshAlert.addAction(UIAlertAction(title: "Clear message history", style: .Destructive, handler: { (action: UIAlertAction!) in OneChats.removeUserAtIndexPath(indexPath) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left) })) refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in })) presentViewController(refreshAlert, animated: true, completion: nil) } } // Mark: Segue support override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if identifier == "chat.to.add" { if !OneChat.sharedInstance.isConnected() { let alert = UIAlertController(title: "Attention", message: "You have to be connected to start a chat", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) return false } } return true } override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { if segue?.identifier == "chats.to.chat" { if let controller = segue?.destinationViewController as? ChatViewController { if let cell: UITableViewCell? = sender as? UITableViewCell { let user = OneChats.getChatsList().objectAtIndex(tableView.indexPathForCell(cell!)!.row) as! XMPPUserCoreDataStorageObject controller.recipient = user } } } } // Mark: Memory Management override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
6b6222616e5b0667944c2df953f95052
32.835821
199
0.732025
4.543086
false
false
false
false
jhurray/JHChainableAnimations
Examples/JHChainableAnimations tvOS Swift Example/ViewController.swift
1
2836
// // ViewController.swift // JHChainableAnimations tvOS Swift Example // // Created by Jeff Hurray on 1/22/17. // Copyright © 2017 jhurray. All rights reserved. // import UIKit import ChainableAnimations class ViewController: UIViewController { let myView = UIView(frame: CGRect(x: 100, y: 150, width: 50, height: 50)) let button: UIButton = UIButton(type: .custom) let pauseButton: UIButton = UIButton(type: .custom) var animator: ChainableAnimator? override func viewDidLoad() { super.viewDidLoad() myView.backgroundColor = .blue view.addSubview(myView) button.backgroundColor = .blue button.setTitle("Action!", for: .normal) button.setTitleColor(.white, for: .normal) button.frame = CGRect(x: 0, y: view.bounds.height-50, width: view.bounds.width, height: 50) button.addTarget(self, action: #selector(animateView), for: .touchUpInside) view.addSubview(button) pauseButton.backgroundColor = .blue pauseButton.setTitle("Pause", for: .normal) pauseButton.setTitleColor(.white, for: .normal) pauseButton.frame = CGRect(x: 16, y: 32, width: 100, height: 50) pauseButton.addTarget(self, action: #selector(pauseSelected), for: .touchUpInside) view.addSubview(pauseButton) animator = ChainableAnimator(view: myView) } func pauseSelected() { guard let animator = animator else { return } if !animator.isPaused { pauseButton.setTitle("Resume", for: .normal) animator.pause() } else { pauseButton.setTitle("Pause", for: .normal) animator.resume() } } func animateView() { guard let animator = animator else { return } button.isUserInteractionEnabled = false let buttonAnimator = ChainableAnimator(view: button) animator.completion = { [unowned self] in self.myView.layer.transform = CATransform3DIdentity self.myView.frame = CGRect(x: 100, y: 150, width: 50, height: 50) self.animator?.transformIdentity.make(alpha: 1).make(backgroundColor: .blue).animate(t: 1.0) buttonAnimator.move(y: -50).easeInOutExpo.animate(t: 1.1, completion: { self.button.isUserInteractionEnabled = true }) } buttonAnimator.move(y: 50).easeInOutExpo.animate(t: 0.5) animator.move(width: 30).bounce.make(backgroundColor: .purple).easeIn.anchor(.topLeft) .repeat(t: 0.5, count: 3).rotateZ(angle: 95).easeBack.wait(t: 0.2) .thenAfter(t: 0.5).move(y: 300).easeIn.make(alpha: 0.0).animate(t: 0.4); } }
mit
91bb4f06dd3c5ecfa3e2f4ea214a267b
33.573171
104
0.604586
4.231343
false
false
false
false
umutbozkurt/Onboarding
Pod/Classes/OnboardingViewController.swift
1
6213
// // OnboardingViewController.swift // Onboarding // // Created by Umut Bozkurt on 08/01/16. // Copyright © 2016 Umut Bozkurt. All rights reserved. // import UIKit public class OnboardingViewController: UIViewController, UIScrollViewDelegate { public let scrollView = UIScrollView() public var pageControl = UIPageControl() public var contentViews = Array<OnboardingView>() { didSet { setupContentViews(contentViews) view.setNeedsLayout() } } private let containerView = UIView() // MARK: Page Control public var pageControlHeight: Float? = 35.0 public var bottomMargin: Float? = 15.0 /// The background image that will be seen in all content views. If this is set, content views should have `alpha < 1` public var image: UIImage? /// The background video that will be seen in all content views. If this is set, content views should have `alpha < 1` public var videoURL: NSURL? /// UIBlurEffectStyle on background image. public var blurStyle: UIBlurEffectStyle? /// UIVIbrancyEffect on blurred background image. Defaults to `false` public var vibrancy: Bool? = false /// Initializes OnboardingViewController with content views public init(contentViews: Array<OnboardingView>) { self.contentViews = contentViews super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func loadView() { super.loadView() setupScrollView() setupContainerView() setupBackgroungImage() setupContentViews(contentViews) setupPageControl() } private func setupScrollView() { scrollView.pagingEnabled = true scrollView.bounces = false scrollView.showsHorizontalScrollIndicator = false scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.delegate = self view.addSubview(scrollView) let bindings = ["scrollView": scrollView] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) } private func setupContainerView() { scrollView.addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false let bindings = ["containerView": containerView] scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[containerView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[containerView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) } private func setupBackgroungImage() { guard image != nil else { return } let backgroundImageView = UIImageView(image: image) let bindings = ["bgView": backgroundImageView] backgroundImageView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(backgroundImageView, belowSubview: scrollView) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[bgView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[bgView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) } private func setupContentViews(contentViews: Array<OnboardingView>) { guard contentViews.count > 0 else { return } let metrics = ["viewWidth": view.bounds.size.width, "viewHeight": view.bounds.size.height] var bindings = Dictionary<String, OnboardingView>() var horizontalFormat = "" for (index, contentView) in contentViews.enumerate() { let viewName = "contentView\(index)" bindings.updateValue(contentView, forKey: viewName) horizontalFormat += "[\(viewName)(viewWidth)]" contentView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(contentView) containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[\(viewName)(viewHeight)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: bindings)) } horizontalFormat = String(format: "H:|%@|", horizontalFormat) containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(horizontalFormat, options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: bindings)) } private func setupPageControl() { view.addSubview(pageControl) pageControl.translatesAutoresizingMaskIntoConstraints = false pageControl.pageIndicatorTintColor = UIColor.redColor() pageControl.currentPageIndicatorTintColor = UIColor.blueColor() pageControl.numberOfPages = contentViews.count let bindings = ["pageControl": pageControl] let metrics = ["margin": bottomMargin!, "height": pageControlHeight!] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[pageControl]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[pageControl(height)]-(margin)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: bindings)) } public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { pageControl.currentPage = Int(targetContentOffset.memory.x / scrollView.bounds.size.width) } }
mit
44668797bf88518892e1b7a2dae4af6d
42.440559
201
0.690277
5.882576
false
false
false
false
peterlafferty/LuasLife
Carthage/Checkouts/Decodable/Tests/Repository.swift
1
1946
// // RepositoryExample.swift // Decodable // // Created by Fran_DEV on 13/07/15. // Copyright © 2015 anviking. All rights reserved. // import Foundation @testable import Decodable struct Owner { let id: Int let login: String } struct Repository { let id: Int let name: String let description: String let htmlUrlString : String let owner: Owner // Struct conforming to Decodable let coverage: Double let files: Array<String> let optional: String? let active: Bool let optionalActive: Bool? } extension Owner : Decodable { static func decode(_ j: Any) throws -> Owner { return try Owner( id: j => "id", login: j => "login" ) } } extension Repository : Decodable { static func decode(_ j: Any) throws -> Repository { return try Repository( id: j => "id", name: j => "name", description: j => "description", htmlUrlString : j => "html_url", owner: j => "owner", coverage: j => "coverage", files: j => "files", optional: j => "optional", active: j => "active", optionalActive: j => "optionalActive" ) } } // MARK: Equatable func == (lhs: Owner, rhs: Owner) -> Bool { return lhs.id == rhs.id && lhs.login == rhs.login } extension Owner: Equatable { var hashValue: Int { return id.hashValue } } func == (lhs: Repository, rhs: Repository) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name && lhs.description == rhs.description && lhs.htmlUrlString == rhs.htmlUrlString && lhs.owner == rhs.owner && lhs.coverage == rhs.coverage && lhs.files == rhs.files && lhs.optional == rhs.optional && lhs.active == rhs.active && lhs.optionalActive == rhs.optionalActive } extension Repository: Equatable { var hashValue: Int { return id.hashValue } }
mit
b8edb373a6e8b1163adaf33f9dabbc56
23.012346
55
0.580977
3.929293
false
false
false
false
feighter09/Cloud9
SoundCloud Pro/Playlist.swift
1
2929
// // Playlist.swift // SoundCloud Pro // // Created by Austin Feight on 7/29/15. // Copyright © 2015 Lost in Flight. All rights reserved. // import UIKit import SwiftyJSON import Parse enum PlaylistType: String { case Normal, Shared } class Playlist { var name: String var tracks: [Track] var trackCount: Int { return tracks.count } private(set) var contributors: [PFUser]! var type: PlaylistType { return parseId == nil ? .Normal : .Shared } private var parseId: String! init(name: String, tracks: [Track]) { self.name = name self.tracks = tracks } init(json: JSON) { name = json["title"].string! tracks = json["tracks"].array!.filter { Track.isStreamable($0) } .map { Track(json: $0) } } init(parsePlaylist: ParsePlaylist) { name = parsePlaylist.name tracks = parsePlaylist.tracks.map { Track.serializeFromParseObject($0) } contributors = parsePlaylist.contributors parseId = parsePlaylist.objectId } } // MARK: - Interface extension Playlist { func addTrack(track: Track, onSuccess: (() -> Void)? = nil) { SoundCloud.addTrack(track, toPlaylist: self) { (success, error) -> Void in if success { self.tracks.append(track) onSuccess?() } else { ErrorHandler.handleNetworkingError("adding to playlist", error: nil) } } } func removeTrack(track: Track, onSuccess: (() -> Void)? = nil) { // TODO: move into network layer parsePlaylist { (playlist) -> Void in let indexToRemove = playlist.tracks.indexOf({ $0 == track })! playlist.tracks.removeAtIndex(indexToRemove) playlist.saveEventually({ (success, error) -> Void in if success { self.tracks.removeAtIndex(indexToRemove) onSuccess?() } else { ErrorHandler.handleNetworkingError("removing track", error: error) } }) } } func addContributor(contributor: PFUser, callback: SuccessCallback) { if contributors.contains({ $0.objectId == contributor.objectId }) { callback(success: true, error: nil) return } contributors.append(contributor) parsePlaylist { (playlist) -> Void in playlist.contributors.append(contributor) playlist.saveEventually(callback) } } func parsePlaylist(callback: (playlist: ParsePlaylist!) -> Void) { let query = ParsePlaylist.query()! query.includeKey("tracks") query.getObjectInBackgroundWithId(parseId, block: { (object, error) -> Void in if error == nil { callback(playlist: object as! ParsePlaylist) } else { callback(playlist: nil) } }) } } // MARK: - Equatable extension Playlist: Equatable { } func ==(lhs: Playlist, rhs: Playlist) -> Bool { return lhs.name == rhs.name && lhs.tracks == rhs.tracks && lhs.contributors == rhs.contributors }
lgpl-3.0
1175df1f9947e893923840d6222c1288
24.034188
97
0.62944
4.077994
false
false
false
false
crazypoo/PTools
Pods/CollectionViewPagingLayout/Lib/Scale/ScaleTransformView.swift
1
6926
// // ScaleTransformView.swift // CollectionViewPagingLayout // // Created by Amir on 15/02/2020. // Copyright © 2020 Amir Khorsandi. All rights reserved. // import UIKit /// A protocol for adding scale transformation to `TransformableView` public protocol ScaleTransformView: TransformableView { /// Options for controlling scale effect, see `ScaleTransformViewOptions.swift` var scaleOptions: ScaleTransformViewOptions { get } /// The view to apply scale effect on var scalableView: UIView { get } /// The view to apply blur effect on var scaleBlurViewHost: UIView { get } /// the main function for applying transforms func applyScaleTransform(progress: CGFloat) } public extension ScaleTransformView { /// The default value is the super view of `scalableView` var scaleBlurViewHost: UIView { scalableView.superview ?? scalableView } } public extension ScaleTransformView where Self: UICollectionViewCell { /// Default `scalableView` for `UICollectionViewCell` is the first subview of /// `contentView` or the content view itself if there is no subview var scalableView: UIView { contentView.subviews.first ?? contentView } } public extension ScaleTransformView { // MARK: Properties var scaleOptions: ScaleTransformViewOptions { .init() } // MARK: TransformableView func transform(progress: CGFloat) { applyScaleTransform(progress: progress) } // MARK: Public functions func applyScaleTransform(progress: CGFloat) { applyStyle(progress: progress) applyScaleAndTranslation(progress: progress) applyCATransform3D(progress: progress) if #available(iOS 10, *) { applyBlurEffect(progress: progress) } } // MARK: Private functions private func applyStyle(progress: CGFloat) { guard scaleOptions.shadowEnabled else { return } let layer = scalableView.layer layer.shadowColor = scaleOptions.shadowColor.cgColor let offset = CGSize( width: max(scaleOptions.shadowOffsetMin.width, (1 - abs(progress)) * scaleOptions.shadowOffsetMax.width), height: max(scaleOptions.shadowOffsetMin.height, (1 - abs(progress)) * scaleOptions.shadowOffsetMax.height) ) layer.shadowOffset = offset layer.shadowRadius = max(scaleOptions.shadowRadiusMin, (1 - abs(progress)) * scaleOptions.shadowRadiusMax) layer.shadowOpacity = max(scaleOptions.shadowOpacityMin, (1 - abs(Float(progress))) * scaleOptions.shadowOpacityMax) } private func applyScaleAndTranslation(progress: CGFloat) { var transform = CGAffineTransform.identity var xAdjustment: CGFloat = 0 var yAdjustment: CGFloat = 0 let scaleProgress = scaleOptions.scaleCurve.computeFromLinear(progress: abs(progress)) var scale = 1 - scaleProgress * scaleOptions.scaleRatio scale = max(scale, scaleOptions.minScale) scale = min(scale, scaleOptions.maxScale) if scaleOptions.keepHorizontalSpacingEqual { xAdjustment = ((1 - scale) * scalableView.bounds.width) / 2 if progress > 0 { xAdjustment *= -1 } } if scaleOptions.keepVerticalSpacingEqual { yAdjustment = ((1 - scale) * scalableView.bounds.height) / 2 } let translateProgress = scaleOptions.translationCurve.computeFromLinear(progress: abs(progress)) var translateX = scalableView.bounds.width * scaleOptions.translationRatio.x * (translateProgress * (progress < 0 ? -1 : 1)) - xAdjustment var translateY = scalableView.bounds.height * scaleOptions.translationRatio.y * abs(translateProgress) - yAdjustment if let min = scaleOptions.minTranslationRatio { translateX = max(translateX, scalableView.bounds.width * min.x) translateY = max(translateY, scalableView.bounds.height * min.y) } if let max = scaleOptions.maxTranslationRatio { translateX = min(translateX, scalableView.bounds.width * max.x) translateY = min(translateY, scalableView.bounds.height * max.y) } transform = transform .translatedBy(x: translateX, y: translateY) .scaledBy(x: scale, y: scale) scalableView.transform = transform } private func applyCATransform3D(progress: CGFloat) { var transform = CATransform3DMakeAffineTransform(scalableView.transform) if let options = self.scaleOptions.rotation3d { var angle = options.angle * progress angle = max(angle, options.minAngle) angle = min(angle, options.maxAngle) transform.m34 = options.m34 transform = CATransform3DRotate(transform, angle, options.x, options.y, options.z) scalableView.layer.isDoubleSided = options.isDoubleSided } if let options = self.scaleOptions.translation3d { var x = options.translateRatios.0 * progress * scalableView.bounds.width var y = options.translateRatios.1 * abs(progress) * scalableView.bounds.height var z = options.translateRatios.2 * abs(progress) * scalableView.bounds.width x = max(x, options.minTranslateRatios.0 * scalableView.bounds.width) x = min(x, options.maxTranslateRatios.0 * scalableView.bounds.width) y = max(y, options.minTranslateRatios.1 * scalableView.bounds.height) y = min(y, options.maxTranslateRatios.1 * scalableView.bounds.height) z = max(z, options.minTranslateRatios.2 * scalableView.bounds.width) z = min(z, options.maxTranslateRatios.2 * scalableView.bounds.width) transform = CATransform3DTranslate(transform, x, y, z) } scalableView.layer.transform = transform } private func applyBlurEffect(progress: CGFloat) { guard scaleOptions.blurEffectRadiusRatio > 0, scaleOptions.blurEffectEnabled else { scaleBlurViewHost.subviews.first(where: { $0 is BlurEffectView })?.removeFromSuperview() return } let blurView: BlurEffectView if let view = scaleBlurViewHost.subviews.first(where: { $0 is BlurEffectView }) as? BlurEffectView { blurView = view } else { blurView = BlurEffectView(effect: UIBlurEffect(style: scaleOptions.blurEffectStyle)) scaleBlurViewHost.fill(with: blurView) } blurView.setBlurRadius(radius: abs(progress) * scaleOptions.blurEffectRadiusRatio) blurView.transform = CGAffineTransform.identity.translatedBy(x: scalableView.transform.tx, y: scalableView.transform.ty) } }
mit
9fb6642d072b0d421b834840ec196d86
38.571429
146
0.65935
4.62283
false
false
false
false
crazypoo/PTools
Pods/JXSegmentedView/Sources/TitleImage/JXSegmentedTitleImageDataSource.swift
1
6025
// // JXSegmentedTitleImageDataSource.swift // JXSegmentedView // // Created by jiaxin on 2018/12/29. // Copyright © 2018 jiaxin. All rights reserved. // import UIKit public enum JXSegmentedTitleImageType { case topImage case leftImage case bottomImage case rightImage case onlyImage case onlyTitle } public typealias LoadImageClosure = ((UIImageView, String) -> Void) open class JXSegmentedTitleImageDataSource: JXSegmentedTitleDataSource { open var titleImageType: JXSegmentedTitleImageType = .rightImage /// 数量需要和item的数量保持一致。可以是ImageName或者图片网络地址 open var normalImageInfos: [String]? /// 数量需要和item的数量保持一致。可以是ImageName或者图片网络地址。如果不赋值,选中时就不会处理图片切换。 open var selectedImageInfos: [String]? /// 内部默认通过UIImage(named:)加载图片。如果传递的是图片网络地址或者想自己处理图片加载逻辑,可以通过该闭包处理。 open var loadImageClosure: LoadImageClosure? /// 图片尺寸 open var imageSize: CGSize = CGSize(width: 20, height: 20) /// title和image之间的间隔 open var titleImageSpacing: CGFloat = 5 /// 是否开启图片缩放 open var isImageZoomEnabled: Bool = false /// 图片缩放选中时的scale open var imageSelectedZoomScale: CGFloat = 1.2 open override func preferredItemModelInstance() -> JXSegmentedBaseItemModel { return JXSegmentedTitleImageItemModel() } open override func preferredRefreshItemModel(_ itemModel: JXSegmentedBaseItemModel, at index: Int, selectedIndex: Int) { super.preferredRefreshItemModel(itemModel, at: index, selectedIndex: selectedIndex) guard let itemModel = itemModel as? JXSegmentedTitleImageItemModel else { return } itemModel.titleImageType = titleImageType itemModel.normalImageInfo = normalImageInfos?[index] itemModel.selectedImageInfo = selectedImageInfos?[index] itemModel.loadImageClosure = loadImageClosure itemModel.imageSize = imageSize itemModel.isImageZoomEnabled = isImageZoomEnabled itemModel.imageNormalZoomScale = 1 itemModel.imageSelectedZoomScale = imageSelectedZoomScale itemModel.titleImageSpacing = titleImageSpacing if index == selectedIndex { itemModel.imageCurrentZoomScale = itemModel.imageSelectedZoomScale }else { itemModel.imageCurrentZoomScale = itemModel.imageNormalZoomScale } } open override func preferredSegmentedView(_ segmentedView: JXSegmentedView, widthForItemAt index: Int) -> CGFloat { var width = super.preferredSegmentedView(segmentedView, widthForItemAt: index) if itemWidth == JXSegmentedViewAutomaticDimension { switch titleImageType { case .leftImage, .rightImage: width += titleImageSpacing + imageSize.width case .topImage, .bottomImage: width = max(itemWidth, imageSize.width) case .onlyImage: width = imageSize.width case .onlyTitle: break } } return width } public override func segmentedView(_ segmentedView: JXSegmentedView, widthForItemContentAt index: Int) -> CGFloat { var width = super.segmentedView(segmentedView, widthForItemContentAt: index) switch titleImageType { case .leftImage, .rightImage: width += titleImageSpacing + imageSize.width case .topImage, .bottomImage: width = max(itemWidth, imageSize.width) case .onlyImage: width = imageSize.width case .onlyTitle: break } return width } //MARK: - JXSegmentedViewDataSource open override func registerCellClass(in segmentedView: JXSegmentedView) { segmentedView.collectionView.register(JXSegmentedTitleImageCell.self, forCellWithReuseIdentifier: "cell") } open override func segmentedView(_ segmentedView: JXSegmentedView, cellForItemAt index: Int) -> JXSegmentedBaseCell { let cell = segmentedView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) return cell } open override func refreshItemModel(_ segmentedView: JXSegmentedView, leftItemModel: JXSegmentedBaseItemModel, rightItemModel: JXSegmentedBaseItemModel, percent: CGFloat) { super.refreshItemModel(segmentedView, leftItemModel: leftItemModel, rightItemModel: rightItemModel, percent: percent) guard let leftModel = leftItemModel as? JXSegmentedTitleImageItemModel, let rightModel = rightItemModel as? JXSegmentedTitleImageItemModel else { return } if isImageZoomEnabled && isItemTransitionEnabled { leftModel.imageCurrentZoomScale = JXSegmentedViewTool.interpolate(from: imageSelectedZoomScale, to: 1, percent: CGFloat(percent)) rightModel.imageCurrentZoomScale = JXSegmentedViewTool.interpolate(from: 1, to: imageSelectedZoomScale, percent: CGFloat(percent)) } } open override func refreshItemModel(_ segmentedView: JXSegmentedView, currentSelectedItemModel: JXSegmentedBaseItemModel, willSelectedItemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) { super.refreshItemModel(segmentedView, currentSelectedItemModel: currentSelectedItemModel, willSelectedItemModel: willSelectedItemModel, selectedType: selectedType) guard let myCurrentSelectedItemModel = currentSelectedItemModel as? JXSegmentedTitleImageItemModel, let myWillSelectedItemModel = willSelectedItemModel as? JXSegmentedTitleImageItemModel else { return } myCurrentSelectedItemModel.imageCurrentZoomScale = myCurrentSelectedItemModel.imageNormalZoomScale myWillSelectedItemModel.imageCurrentZoomScale = myWillSelectedItemModel.imageSelectedZoomScale } }
mit
a9c7d6eddd1c4b5a08c6acd6e37ea886
43.169231
223
0.725705
5.494737
false
false
false
false
JohanEkblad/beacon-mountain
BeaconMountainIOS/BeaconMountainIOS/ClientSession.swift
1
2806
// // ClientSession.swift // BeaconMountainIOS // // Created by Jon Larsson on 2017-10-13. // Copyright © 2017 Jon Larsson. All rights reserved. // import Foundation import os.log class ClientSession: NSObject, StreamDelegate { var inputStream: InputStream var outputStream: OutputStream var data: Data public init(inputStream: InputStream, outputStream: OutputStream) { self.inputStream = inputStream self.outputStream = outputStream self.data = Data() super.init() inputStream.delegate = self inputStream.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode) inputStream.open() outputStream.delegate = self outputStream.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode) outputStream.open() } func handle(message: String) { if (message.starts(with: "HELO")) { let reply = "YOLO" let data = reply.data(using: String.Encoding.utf8)! data.withUnsafeBytes { (_ bytes: UnsafePointer<UInt8>) -> ssize_t in let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: data.count + 1) buffer.assign(from: bytes, count: data.count) buffer[data.count] = 0 return self.outputStream.write(buffer, maxLength: data.count + 1) } } } func handleBufferUpdate() { var eofStringIndex = self.data.index(of: 0) while(eofStringIndex != nil) { let subdata = self.data.subdata(in: 0..<eofStringIndex!) handle(message: String(data: subdata, encoding: String.Encoding.utf8)!) self.data = self.data.advanced(by: eofStringIndex! + 1) eofStringIndex = self.data.index(of: 0) } } func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if (aStream == self.inputStream && eventCode == .hasBytesAvailable) { let bufferSize = 1024 let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize + 1) while (self.inputStream.hasBytesAvailable) { let count = self.inputStream.read(buffer, maxLength: bufferSize) for index in 0..<count { os_log("%d %d", index, buffer[index]) } self.data.append(buffer, count: count) } buffer.deallocate(capacity: bufferSize) handleBufferUpdate() } } func close() { self.inputStream.remove(from: RunLoop.current, forMode: .defaultRunLoopMode) self.inputStream.close() self.outputStream.remove(from: RunLoop.current, forMode: .defaultRunLoopMode) self.inputStream.close() } }
gpl-3.0
03a5904e1ed6344c893531a9dc599f3e
34.961538
91
0.600713
4.560976
false
false
false
false
swift-lang/swift-k
tests/language-behaviour/math/intdivision.swift
2
322
type file; file outfile <"intdivision.out">; app (file o) echo (string s) { echo s stdout=@o; } int x = 7 %/ 5; // expect x = 1 float y = 1.0*@toFloat(x); // expect y = 1.0 string z = @strcat(y); string msg = @strcat("x = ", x, ", y = ", y, ", z = ", z); outfile = echo(msg);
apache-2.0
2b2a016a60d807c508ace5ce8978187f
23.769231
58
0.47205
2.849558
false
false
true
false
hyperconnect/Bond
Bond/Bond+Arrays.swift
1
17468
// // Bond+Arrays.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // MARK: - Vector Dynamic // MARK: Array Bond public class ArrayBond<T>: Bond<Array<T>> { public var willInsertListener: ((DynamicArray<T>, [Int]) -> Void)? public var didInsertListener: ((DynamicArray<T>, [Int]) -> Void)? public var willRemoveListener: ((DynamicArray<T>, [Int]) -> Void)? public var didRemoveListener: ((DynamicArray<T>, [Int]) -> Void)? public var willUpdateListener: ((DynamicArray<T>, [Int]) -> Void)? public var didUpdateListener: ((DynamicArray<T>, [Int]) -> Void)? public var willResetListener: (DynamicArray<T> -> Void)? public var didResetListener: (DynamicArray<T> -> Void)? override public init() { super.init() } override public func bind(dynamic: Dynamic<Array<T>>) { bind(dynamic, fire: true, strongly: true) } override public func bind(dynamic: Dynamic<Array<T>>, fire: Bool) { bind(dynamic, fire: fire, strongly: true) } override public func bind(dynamic: Dynamic<Array<T>>, fire: Bool, strongly: Bool) { super.bind(dynamic, fire: fire, strongly: strongly) } } // MARK: Dynamic array /** Note: Directly setting `DynamicArray.value` is not recommended. The array's count will not be updated and no array change notification will be emitted. Call `setArray:` instead. */ public class DynamicArray<T>: Dynamic<Array<T>>, SequenceType { public typealias Element = T public typealias Generator = DynamicArrayGenerator<T> public let dynCount: Dynamic<Int> public override init(_ v: Array<T>) { dynCount = Dynamic(0) super.init(v) dynCount.value = self.count } public override func bindTo(bond: Bond<Array<T>>) { bond.bind(self, fire: true, strongly: true) } public override func bindTo(bond: Bond<Array<T>>, fire: Bool) { bond.bind(self, fire: fire, strongly: true) } public override func bindTo(bond: Bond<Array<T>>, fire: Bool, strongly: Bool) { bond.bind(self, fire: fire, strongly: strongly) } public func setArray(newValue: [T]) { dispatchWillReset() value = newValue dispatchDidReset() } public var count: Int { return value.count } public var capacity: Int { return value.capacity } public var isEmpty: Bool { return value.isEmpty } public var first: T? { return value.first } public var last: T? { return value.last } public func append(newElement: T) { dispatchWillInsert([value.count]) value.append(newElement) dispatchDidInsert([value.count-1]) } public func append(array: Array<T>) { splice(array, atIndex: value.count) } public func removeLast() -> T { if self.count > 0 { dispatchWillRemove([value.count-1]) let last = value.removeLast() dispatchDidRemove([value.count]) return last } fatalError("Cannot removeLast() as there are no elements in the array!") } public func insert(newElement: T, atIndex i: Int) { dispatchWillInsert([i]) value.insert(newElement, atIndex: i) dispatchDidInsert([i]) } public func splice(array: Array<T>, atIndex i: Int) { if array.count > 0 { let indices = Array(i..<i+array.count) dispatchWillInsert(indices) value.splice(array, atIndex: i) dispatchDidInsert(indices) } } public func removeAtIndex(index: Int) -> T { dispatchWillRemove([index]) let object = value.removeAtIndex(index) dispatchDidRemove([index]) return object } public func removeAll(keepCapacity: Bool) { let count = value.count let indices = Array(0..<count) dispatchWillRemove(indices) value.removeAll(keepCapacity: keepCapacity) dispatchDidRemove(indices) } public subscript(index: Int) -> T { get { return value[index] } set(newObject) { if index == value.count { dispatchWillInsert([index]) value[index] = newObject dispatchDidInsert([index]) } else { dispatchWillUpdate([index]) value[index] = newObject dispatchDidUpdate([index]) } } } public func generate() -> DynamicArrayGenerator<T> { return DynamicArrayGenerator<T>(array: self) } private func dispatchWillInsert(indices: [Int]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.willInsertListener?(self, indices) } } } private func dispatchDidInsert(indices: [Int]) { if !indices.isEmpty { dynCount.value = count } for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.didInsertListener?(self, indices) } } } private func dispatchWillRemove(indices: [Int]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.willRemoveListener?(self, indices) } } } private func dispatchDidRemove(indices: [Int]) { if !indices.isEmpty { dynCount.value = count } for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.didRemoveListener?(self, indices) } } } private func dispatchWillUpdate(indices: [Int]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.willUpdateListener?(self, indices) } } } private func dispatchDidUpdate(indices: [Int]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.didUpdateListener?(self, indices) } } } private func dispatchWillReset() { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.willResetListener?(self) } } } private func dispatchDidReset() { dynCount.value = self.count for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.didResetListener?(self) } } } } public struct DynamicArrayGenerator<T>: GeneratorType { private var index = -1 private let array: DynamicArray<T> init(array: DynamicArray<T>) { self.array = array } typealias Element = T public mutating func next() -> T? { index++ return index < array.count ? array[index] : nil } } // MARK: Dynamic Array Map Proxy private class DynamicArrayMapProxy<T, U>: DynamicArray<U> { private unowned var sourceArray: DynamicArray<T> private var mapf: (T, Int) -> U private let bond: ArrayBond<T> private init(sourceArray: DynamicArray<T>, mapf: (T, Int) -> U) { self.sourceArray = sourceArray self.mapf = mapf self.bond = ArrayBond<T>() self.bond.bind(sourceArray, fire: false) super.init([]) bond.willInsertListener = { [unowned self] array, i in self.dispatchWillInsert(i) } bond.didInsertListener = { [unowned self] array, i in self.dispatchDidInsert(i) } bond.willRemoveListener = { [unowned self] array, i in self.dispatchWillRemove(i) } bond.didRemoveListener = { [unowned self] array, i in self.dispatchDidRemove(i) } bond.willUpdateListener = { [unowned self] array, i in self.dispatchWillUpdate(i) } bond.didUpdateListener = { [unowned self] array, i in self.dispatchDidUpdate(i) } bond.willResetListener = { [unowned self] array in self.dispatchWillReset() } bond.didResetListener = { [unowned self] array in self.dispatchDidReset() } } override var value: [U] { set(newValue) { fatalError("Modifying proxy array is not supported!") } get { fatalError("Getting proxy array value is not supported!") } } override var count: Int { return sourceArray.count } override var capacity: Int { return sourceArray.capacity } override var isEmpty: Bool { return sourceArray.isEmpty } override var first: U? { if let first = sourceArray.first { return mapf(first, 0) } else { return nil } } override var last: U? { if let last = sourceArray.last { return mapf(last, sourceArray.count - 1) } else { return nil } } override func setArray(newValue: [U]) { fatalError("Modifying proxy array is not supported!") } override func append(newElement: U) { fatalError("Modifying proxy array is not supported!") } override func append(array: Array<U>) { fatalError("Modifying proxy array is not supported!") } override func removeLast() -> U { fatalError("Modifying proxy array is not supported!") } override func insert(newElement: U, atIndex i: Int) { fatalError("Modifying proxy array is not supported!") } override func splice(array: Array<U>, atIndex i: Int) { fatalError("Modifying proxy array is not supported!") } override func removeAtIndex(index: Int) -> U { fatalError("Modifying proxy array is not supported!") } override func removeAll(keepCapacity: Bool) { fatalError("Modifying proxy array is not supported!") } override subscript(index: Int) -> U { get { return mapf(sourceArray[index], index) } set(newObject) { fatalError("Modifying proxy array is not supported!") } } } func indexOfFirstEqualOrLargerThan(x: Int, array: [Int]) -> Int { var idx: Int = -1 for (index, element) in enumerate(array) { if element < x { idx = index } else { break } } return idx + 1 } // MARK: Dynamic Array Filter Proxy private class DynamicArrayFilterProxy<T>: DynamicArray<T> { private unowned var sourceArray: DynamicArray<T> private var pointers: [Int] private var filterf: T -> Bool private let bond: ArrayBond<T> private init(sourceArray: DynamicArray<T>, filterf: T -> Bool) { self.sourceArray = sourceArray self.filterf = filterf self.bond = ArrayBond<T>() self.bond.bind(sourceArray, fire: false) self.pointers = DynamicArrayFilterProxy.pointersFromSource(sourceArray, filterf: filterf) super.init([]) bond.didInsertListener = { [unowned self] array, indices in var insertedIndices: [Int] = [] var pointers = self.pointers for idx in indices { for (index, element) in enumerate(pointers) { if element >= idx { pointers[index] = element + 1 } } let element = array[idx] if filterf(element) { let position = indexOfFirstEqualOrLargerThan(idx, pointers) pointers.insert(idx, atIndex: position) insertedIndices.append(position) } } if insertedIndices.count > 0 { self.dispatchWillInsert(insertedIndices) } self.pointers = pointers if insertedIndices.count > 0 { self.dispatchDidInsert(insertedIndices) } } bond.willRemoveListener = { [unowned self] array, indices in var removedIndices: [Int] = [] var pointers = self.pointers for idx in reverse(indices) { if let idx = find(pointers, idx) { pointers.removeAtIndex(idx) removedIndices.append(idx) } for (index, element) in enumerate(pointers) { if element >= idx { pointers[index] = element - 1 } } } if removedIndices.count > 0 { self.dispatchWillRemove(reverse(removedIndices)) } self.pointers = pointers if removedIndices.count > 0 { self.dispatchDidRemove(reverse(removedIndices)) } } bond.didUpdateListener = { [unowned self] array, indices in let idx = indices[0] let element = array[idx] var insertedIndices: [Int] = [] var removedIndices: [Int] = [] var updatedIndices: [Int] = [] var pointers = self.pointers if let idx = find(pointers, idx) { if filterf(element) { // update updatedIndices.append(idx) } else { // remove pointers.removeAtIndex(idx) removedIndices.append(idx) } } else { if filterf(element) { let position = indexOfFirstEqualOrLargerThan(idx, pointers) pointers.insert(idx, atIndex: position) insertedIndices.append(position) } else { // nothing } } if insertedIndices.count > 0 { self.dispatchWillInsert(insertedIndices) } if removedIndices.count > 0 { self.dispatchWillRemove(removedIndices) } if updatedIndices.count > 0 { self.dispatchWillUpdate(updatedIndices) } self.pointers = pointers if updatedIndices.count > 0 { self.dispatchDidUpdate(updatedIndices) } if removedIndices.count > 0 { self.dispatchDidRemove(removedIndices) } if insertedIndices.count > 0 { self.dispatchDidInsert(insertedIndices) } } bond.willResetListener = { [unowned self] array in self.dispatchWillReset() } bond.didResetListener = { [unowned self] array in self.pointers = DynamicArrayFilterProxy.pointersFromSource(array, filterf: filterf) self.dispatchDidReset() } } class func pointersFromSource(sourceArray: DynamicArray<T>, filterf: T -> Bool) -> [Int] { var pointers = [Int]() for (index, element) in enumerate(sourceArray) { if filterf(element) { pointers.append(index) } } return pointers } override var value: [T] { set(newValue) { fatalError("Modifying proxy array is not supported!") } get { fatalError("Getting proxy array value is not supported!") } } private override var count: Int { return pointers.count } private override var capacity: Int { return pointers.capacity } private override var isEmpty: Bool { return pointers.isEmpty } private override var first: T? { if let first = pointers.first { return sourceArray[first] } else { return nil } } private override var last: T? { if let last = pointers.last { return sourceArray[last] } else { return nil } } override private func setArray(newValue: [T]) { fatalError("Modifying proxy array is not supported!") } override private func append(newElement: T) { fatalError("Modifying proxy array is not supported!") } private override func append(array: Array<T>) { fatalError("Modifying proxy array is not supported!") } override private func removeLast() -> T { fatalError("Modifying proxy array is not supported!") } override private func insert(newElement: T, atIndex i: Int) { fatalError("Modifying proxy array is not supported!") } private override func splice(array: Array<T>, atIndex i: Int) { fatalError("Modifying proxy array is not supported!") } override private func removeAtIndex(index: Int) -> T { fatalError("Modifying proxy array is not supported!") } override private func removeAll(keepCapacity: Bool) { fatalError("Modifying proxy array is not supported!") } override private subscript(index: Int) -> T { get { return sourceArray[pointers[index]] } set { fatalError("Modifying proxy array is not supported!") } } } // MARK: Dynamic Array additions public extension DynamicArray { public func map<U>(f: (T, Int) -> U) -> DynamicArray<U> { return _map(self, f) } public func map<U>(f: T -> U) -> DynamicArray<U> { let mapf = { (o: T, i: Int) -> U in f(o) } return _map(self, mapf) } public func filter(f: T -> Bool) -> DynamicArray<T> { return _filter(self, f) } } // MARK: Map private func _map<T, U>(dynamicArray: DynamicArray<T>, f: (T, Int) -> U) -> DynamicArrayMapProxy<T, U> { return DynamicArrayMapProxy(sourceArray: dynamicArray, mapf: f) } // MARK: Filter private func _filter<T>(dynamicArray: DynamicArray<T>, f: T -> Bool) -> DynamicArray<T> { return DynamicArrayFilterProxy(sourceArray: dynamicArray, filterf: f) }
mit
4124b2a1376d6d63805ff31b7f7e7aa5
24.726068
177
0.633787
4.050081
false
false
false
false
rugheid/Swift-MathEagle
MathEagle/Linear Algebra/Matrix.swift
1
91195
// // Matrix.swift // SwiftMath // // Created by Rugen Heidbuchel on 22/12/14. // Copyright (c) 2014 Jorestha Solutions. All rights reserved. // import Foundation import Accelerate public protocol MatrixCompatible: Comparable, Addable, Negatable, Subtractable, Multiplicable, Dividable, NaturalPowerable, IntegerPowerable, RealPowerable, Conjugatable, Randomizable, ExpressibleByIntegerLiteral {} /** A generic class representing a 2-dimensional matrix of the given type. */ open class Matrix <T: MatrixCompatible> : ExpressibleByArrayLiteral, Equatable, CustomStringConvertible, Sequence { // MARK: Internal Elements /** The variable to store the inner structure of the matrix. */ open var elementsStructure: [T] = [] /** The variable to store the dimensions of the matrix. */ internal var innerDimensions: Dimensions = Dimensions() /** Gets or sets the dimensions of the matrix. :Set: When the new dimensions are smaller, the stored elements will simply be removed. When the dimensions are bigger, the matrix will be padded with zeros. */ open var dimensions: Dimensions { get { return self.innerDimensions } set(newDimensions) { self.resize(newDimensions) } } /** Returns a row major ordered list of all elements in the array. This should be used for high performance applications. */ open var elementsList: [T] { get { return elementsStructure } set (newElementsList) { elementsStructure = newElementsList } } /** Returns or sets a 2 dimensional array containing the elements of the matrix. The array contains array's that represent rows. :performance: This method scales O(n*m) for an nxm matrix, so elementsList should be used for high performance applications. */ open var elements: [[T]] { get { var elements = [[T]]() for r in 0 ..< self.dimensions.rows { var rowElements = [T]() for c in 0 ..< self.dimensions.columns { rowElements.append(elementsList[r * self.dimensions.columns + c]) } elements.append(rowElements) } if elements.count == 0 { elements.append([]) } return elements } set(newElements) { elementsList = [] for row in newElements { elementsList.append(contentsOf: row) } if newElements.count == 0 || newElements[0].count == 0 { self.innerDimensions = Dimensions() } else { self.innerDimensions = Dimensions(newElements.count, newElements[0].count) } } } // MARK: Initialisation /** Creates an empty matrix with elements [[]]. The dimensions will be (0, 0). */ public init() {} /** Creates a matrix with the given elements. - parameter elements: The elements of the matrix. Every element in this array should be an array representing a row in the matrix. */ public init(_ elements: [[T]]) { self.elements = elements } /** Creates a matrix with the given array literal. - parameter elements: The elements of the matrix. Every element in this array should be an array representing a row in the matrix. */ public required init(arrayLiteral elements: [T]...) { self.elements = elements } /** Creates a matrix with the given elementsList and the given number of rows. - parameter elementsList: A flat row majored list of all elements in the matrix. - parameter rows: The number of rows the matrix should have. :exception: An exception will be thrown when the number of elements in the elementsList is not a multiple of rows. */ public init(elementsList: [T], rows: Int) { if elementsList.count != 0 && elementsList.count % rows != 0 { NSException(name: NSExceptionName(rawValue: "Wrong number of elements"), reason: "The number of elements in the given list is not a multiple of rows.", userInfo: nil).raise() } self.innerDimensions = Dimensions(rows, rows == 0 ? 0 : elementsList.count / rows) self.elementsList = elementsList } /** Creates a matrix with the given elementsList and the given number of columns. - parameter elementsList: A flat row majored list of all elements in the matrix. - parameter columns: The number of columns the matrix should have. :exception: An exception will be thrown when the number of elements in the elementsList is not a multiple of columns. */ public init(elementsList: [T], columns: Int) { if elementsList.count != 0 && elementsList.count % columns != 0 { NSException(name: NSExceptionName(rawValue: "Wrong number of elements"), reason: "The number of elements in the given list is not a multiple of columns.", userInfo: nil).raise() } self.innerDimensions = Dimensions(columns == 0 ? 0 : elementsList.count / columns, columns) self.elementsList = elementsList } /** Creates a matrix with the given elementsList and the given dimensions. - parameter elementsList: A flat row majored list of all elements in the matrix. - parameter dimensions: The dimensions the matrix should have. :exception: An exception will be thrown when the number of elements in the elementsList is not equal to the product of the dimensions. */ public init(elementsList: [T], dimensions: Dimensions) { if elementsList.count != dimensions.product { NSException(name: NSExceptionName(rawValue: "Wrong number of elements"), reason: "The number of elements in the given list is not equal to the product of the dimensions.", userInfo: nil).raise() } self.innerDimensions = dimensions self.elementsList = elementsList } /** Creates a matrix with the given dimensions using the given generator. - parameter dimensions: The dimensions the matrix should have. - parameter generator: The generator used to generate the matrix. This function is called for every element passing the index of the element. */ public init(dimensions: Dimensions, generator: (Index) -> T) { self.elementsList = [] self.innerDimensions = dimensions for row in 0 ..< dimensions.rows { for col in 0 ..< dimensions.columns { self.elementsList.append(generator([row, col])) } } } /** Creates a square matrix with the given size using the given generator. - parameter size: The size the matrix should have. - parameter generator: The generator used to generate the matrix. This function is called for every element passing the index of the element. */ public convenience init(size: Int, generator: (Index) -> T) { self.init(dimensions: Dimensions(size, size), generator: generator) } /** Creates a random matrix with the given dimensions. This uses the `random` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter dimensions: The dimensions the matrix should have. */ public convenience init(randomWithDimensions dimensions: Dimensions) { self.init(elementsList: T.randomArray(dimensions.product), dimensions: dimensions) } /** Creates a random square matrix with the given size. This uses the `random` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter size: The size the matrix should have. */ public convenience init(randomWithSize size: Int) { self.init(randomWithDimensions: Dimensions(size, size)) } /** Creates a random matrix with the given dimensions. The values lie in the given range. This uses the `randomIn` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter dimensions: The dimensions the matrix should have. - parameter range: The range in which the values can lie. */ public convenience init(randomWithDimensions dimensions: Dimensions, range: Range<T.RandomRangeType>) { //TODO: Improve this implementation. self.init(dimensions: dimensions, generator: { i in T.random(range) }) } /** Creates a random matrix with the given dimensions. The values lie in the given range. This uses the `randomIn` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter dimensions: The dimensions the matrix should have. - parameter range: The range in which the values can lie. */ public convenience init(randomWithDimensions dimensions: Dimensions, range: ClosedRange<T.RandomRangeType>) { //TODO: Improve this implementation. self.init(dimensions: dimensions, generator: { i in T.random(range) }) } /** Creates a random matrix with the given dimensions. The values lie in the given range. This uses the `randomIn` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter dimensions: The dimensions the matrix should have. - parameter range: The range in which the values can lie. */ public convenience init(randomWithDimensions dimensions: Dimensions, range: CountableRange<T.RandomCountableRangeType>) { //TODO: Improve this implementation. self.init(dimensions: dimensions, generator: { i in T.random(range) }) } /** Creates a random matrix with the given dimensions. The values lie in the given range. This uses the `randomIn` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter dimensions: The dimensions the matrix should have. - parameter range: The range in which the values can lie. */ public convenience init(randomWithDimensions dimensions: Dimensions, range: CountableClosedRange<T.RandomCountableRangeType>) { //TODO: Improve this implementation. self.init(dimensions: dimensions, generator: { i in T.random(range) }) } /** Creates a random square matrix with the given size. The values lie in the given range. This uses the `randomIn` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter size: The dimensions the matrix should have. - parameter range: The range in which the values can lie. */ public convenience init(randomWithSize size: Int, range: Range<T.RandomRangeType>) { self.init(size: size, generator: { i in T.random(range) }) } /** Creates a random square matrix with the given size. The values lie in the given range. This uses the `randomIn` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter size: The dimensions the matrix should have. - parameter range: The range in which the values can lie. */ public convenience init(randomWithSize size: Int, range: ClosedRange<T.RandomRangeType>) { self.init(size: size, generator: { i in T.random(range) }) } /** Creates a random square matrix with the given size. The values lie in the given range. This uses the `randomIn` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter size: The dimensions the matrix should have. - parameter range: The range in which the values can lie. */ public convenience init(randomWithSize size: Int, range: CountableRange<T.RandomCountableRangeType>) { self.init(size: size, generator: { i in T.random(range) }) } /** Creates a random square matrix with the given size. The values lie in the given range. This uses the `randomIn` function of the type of the matrix. Note that for this initialiser to work the type must be known to the compiler. So you can either state the type of the variable explicitly or call the initialiser with the specific type like Matrix<Type>(...). - parameter size: The dimensions the matrix should have. - parameter range: The range in which the values can lie. */ public convenience init(randomWithSize size: Int, range: CountableClosedRange<T.RandomCountableRangeType>) { self.init(size: size, generator: { i in T.random(range) }) } public init(symmetrical elements: [T]) { //TODO: Remove this initialiser, move it to a SymmetricalMatrix class self.elementsList = [T]() let size = (elements.count + 1) / 2 self.innerDimensions = Dimensions(size, size) for row in 0 ..< size { for column in 0 ..< size { elementsList.append(elements[row + column]) } } } /** Creates a matrix of the given size filled with the given element. - parameter element: The element to fill the matrix with. - parameter size: The size the matrix should have. */ public convenience init(filledWith element: T, size: Int) { self.init(filledWith: element, dimensions: Dimensions(size: size)) } /** Creates a matrix with the given dimensions filled with the given element. - parameter element: The element to fill the matrix with. - parameter dimensions: The dimensions the matrix should have. */ public init(filledWith element: T, dimensions: Dimensions) { self.innerDimensions = dimensions self.elementsList = [T](repeating: element, count: dimensions.rows * dimensions.columns) } /** Creates an identity matrix of the given size. This means all diagonal elements are equal to 1 and all other elements are equal to 0. - parameter size: The size the matrix should have. */ public convenience init(identityOfSize size: Int) { //TODO: Remove this initialiser, move it to a IdentityMatrix subclass of DiagonalMatrix. self.init(filledWith: 0, size: size) self.fillDiagonal(1) } // MARK: Subscript Methods /** Gets or sets the element at the given row and column. - parameter row: The row of the desired element. - parameter column: The column of the desired element. - returns: The element at the given row and column. :exception: An exception will be thrown when either of the indices is out of bounds. */ open subscript(row: Int, column: Int) -> T { get { return self.element(row, column) } set(newElement) { self.setElement(atRow: row, atColumn: column, toElement: newElement) } } /** Gets or sets the row at the given element. - parameter index: The index of the desired row. - returns: A vector representing the row at the given index. :exception: An exception will be thrown when the given index is out of bounds. */ open subscript(index: Int) -> Vector<T> { get { return self.row(index) } set(newRow) { self.setRow(atIndex: index, toRow: newRow) } } open subscript(indices: AnyCollection<Int>) -> Matrix<T> { get { var matrixElements = [[T]]() for i in indices { matrixElements.append(self[i].elements) } return Matrix(matrixElements) } set(newMatrix) { if !indices.isEmpty { if newMatrix.isEmpty { for i in indices.sorted(by: >) { self.removeRow(atIndex: i) } } else { var diff = 0 for (index, i) in indices.enumerated() { if index < newMatrix.dimensions.rows { self.setRow(atIndex: i, toRow: newMatrix.row(index)) } else { self.removeRow(atIndex: i - diff) diff += 1 } } } } } } open subscript(indices: CountableRange<Int>) -> Matrix<T> { get { return self[AnyCollection(AnyRandomAccessCollection(indices))] } set(newMatrix) { self[AnyCollection(AnyRandomAccessCollection(indices))] = newMatrix } } open subscript(indices: CountableClosedRange<Int>) -> Matrix<T> { get { return self[AnyCollection(AnyRandomAccessCollection(indices))] } set(newMatrix) { self[AnyCollection(AnyRandomAccessCollection(indices))] = newMatrix } } /** Gets or sets the submatrix at the given index ranges. - parameter rowRange: The row index range of the desired submatrix. - parameter columnRange: The column index range of the desired submatrix. - returns: A matrix representing the submatrix at the given index ranges. :exception: Throws an exception when any of the index ranges is out of bounds. */ open subscript(rowRange: AnyCollection<Int>, columnRange: AnyCollection<Int>) -> Matrix<T> { get { return self.submatrix(rowRange, columnRange) } set(newMatrix) { self.setSubmatrix(rowRange, columnRange, toMatrix: newMatrix) } } open subscript(rowRange: CountableRange<Int>, columnRange: CountableRange<Int>) -> Matrix<T> { get { return self[AnyCollection(AnyRandomAccessCollection(rowRange)), AnyCollection(AnyRandomAccessCollection(columnRange))] } set(newMatrix) { self[AnyCollection(AnyRandomAccessCollection(rowRange)), AnyCollection(AnyRandomAccessCollection(columnRange))] = newMatrix } } open subscript(rowRange: CountableClosedRange<Int>, columnRange: CountableClosedRange<Int>) -> Matrix<T> { get { return self[AnyCollection(AnyRandomAccessCollection(rowRange)), AnyCollection(AnyRandomAccessCollection(columnRange))] } set(newMatrix) { self[AnyCollection(AnyRandomAccessCollection(rowRange)), AnyCollection(AnyRandomAccessCollection(columnRange))] = newMatrix } } /** Gets or sets the subvector at the given row index range at the given column. - parameter rowRange: The row index range of the desired subvector. - parameter column: The column of the desired subvector. - returns: A vector representing the subvector at the given row index range at the given column. :exception: Throws an exception when any of the indices is out of bounds. */ open subscript(rowRange: AnyCollection<Int>, column: Int) -> Vector<T> { get { return self.subvector(rowRange, column) } set(newVector) { self.setSubvector(rowRange, column, toVector: newVector) } } /** Gets or sets the subvector at the given row index range at the given column. - parameter rowRange: The row index range of the desired subvector. - parameter column: The column of the desired subvector. - returns: A vector representing the subvector at the given row index range at the given column. :exception: Throws an exception when any of the indices is out of bounds. */ open subscript(rowRange: CountableRange<Int>, column: Int) -> Vector<T> { // TODO: This implementation should not be necessary, since AnyCollection is supported? get { return self[AnyCollection(AnyRandomAccessCollection(rowRange)), column] } set(newVector) { self[AnyCollection(AnyRandomAccessCollection(rowRange)), column] = newVector } } /** Gets or sets the subvector at the given row index range at the given column. - parameter rowRange: The row index range of the desired subvector. - parameter column: The column of the desired subvector. - returns: A vector representing the subvector at the given row index range at the given column. :exception: Throws an exception when any of the indices is out of bounds. */ open subscript(rowRange: CountableClosedRange<Int>, column: Int) -> Vector<T> { // TODO: This implementation should not be necessary, since AnyCollection is supported? get { return self[AnyCollection(AnyRandomAccessCollection(rowRange)), column] } set(newVector) { self[AnyCollection(AnyRandomAccessCollection(rowRange)), column] = newVector } } /** Gets or sets the subvector at the given row at the given column index range. - parameter row: The row of the desired subvector. - parameter columnRange: The column index range of the desired subvector. - returns: A vector representing the subvector at the given row at the given columnn index range. :exception: Throws an exception when any of the indices is out of bounds. */ open subscript(row: Int, columnRange: AnyCollection<Int>) -> Vector<T> { get { return self.subvector(row, columnRange) } set(newVector) { self.setSubvector(row, columnRange, toVector: newVector) } } /** Gets or sets the subvector at the given row at the given column index range. - parameter row: The row of the desired subvector. - parameter columnRange: The column index range of the desired subvector. - returns: A vector representing the subvector at the given row at the given columnn index range. :exception: Throws an exception when any of the indices is out of bounds. */ open subscript(row: Int, columnRange: CountableRange<Int>) -> Vector<T> { get { return self[row, AnyCollection(AnyRandomAccessCollection(columnRange))] } set(newVector) { self[row, AnyCollection(AnyRandomAccessCollection(columnRange))] = newVector } } /** Gets or sets the subvector at the given row at the given column index range. - parameter row: The row of the desired subvector. - parameter columnRange: The column index range of the desired subvector. - returns: A vector representing the subvector at the given row at the given columnn index range. :exception: Throws an exception when any of the indices is out of bounds. */ open subscript(row: Int, columnRange: CountableClosedRange<Int>) -> Vector<T> { get { return self[row, AnyCollection(AnyRandomAccessCollection(columnRange))] } set(newVector) { self[row, AnyCollection(AnyRandomAccessCollection(columnRange))] = newVector } } // MARK: Sequence Type /** Returns a generator for this matrix. */ open func makeIterator() -> MatrixGenerator<T> { return MatrixGenerator(matrix: self) } // MARK: Class Behaviour /** Returns a copy of the matrix. */ open var copy: Matrix<T> { return Matrix(elementsList: self.elementsList, dimensions: self.dimensions) } // MARK: Basic Properties /** Returns a textual representation of the matrix. This conforms to the array literal. :example: [[1, 2], [3, 4], [5, 6]] */ open var description: String { return self.elements.description } /** Returns the size of the matrix if the matrix is square. If the matrix is not square it returns nil. - returns: The size of the matrix if the matrix is square or nil otherwise. */ open var size: Int? { return self.dimensions.size } /** Gives the rank of the matrix. This is not the tensor rank. - returns: The rank of the matrix. */ open var rank: Int { //FIXME: Implement this method! return 0 } /** Returns the trace of the matrix. This is the sum of the diagonal elements. If the matrix is empty nil is returned. - returns: The trace of the matrix if the matrix is not empty, otherwise nil. */ open var trace: T? { return self.isEmpty ? nil : sum(self.diagonalElements) } /** Returns the determinant of the matrix. */ open var determinant: T { let (_, _, _, det) = self.LUDecomposition(pivoting: true, optimalPivoting: true) return det } /** Gets or sets the diagonal elements of the matrix. - returns: An array with the diagonal elements of the matrix. :exception: Throws an exception when the given array countains too many elements. */ open var diagonalElements: [T] { get { var returnElements = [T]() for i in 0 ..< self.dimensions.minimum { returnElements.append(self.element(i, i)) } return returnElements } set(elements) { let nrOfDiagonals = self.dimensions.minimum if elements.count != nrOfDiagonals { NSException(name: NSExceptionName(rawValue: "Diagonal elements out of bounds"), reason: "\(elements.count) are too many diagonal elements, only \(nrOfDiagonals) needed.", userInfo: nil).raise() } for i in 0 ..< nrOfDiagonals { self.setElement(atRow: i, atColumn: i, toElement: elements[i]) } } } /** Returns the elements of the diagonal at the given index. 0 represents the main diagonal. -1 means the first subdiagonal, this is the one below the main diagonal. Other negative numbers represent lower subdiagonals. 1 means the first superdiagonal, this is the one above the main diagonal. Other positive numbers represent higher superdiagonals. - parameter n: The diagonal's index. - returns: An array representing the diagonal elements from top left to bottom right in the matrix. :exception: An exception will be raised if the diagonal at the given index does not exist. This means -n >= the number of rows or n >= the number of columns. */ open func diagonalElements(_ n: Int = 0) -> [T] { if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Index out the bounds."), reason: "The given index is out of bounds.", userInfo: nil).raise() } var returnElements = [T]() var row = Swift.max(-n, 0) var col = Swift.max(n, 0) while row < self.dimensions.rows && col < self.dimensions.columns { returnElements.append(self.element(row, col)) row += 1 col += 1 } return returnElements } /** Returns a copy of the matrix with all elements under the main diagonal set to zero. This also applies to non-square matrices. */ open var upperTriangle: Matrix<T> { return try! upperTriangle() } /** Returns the upper triangle part of the matrix. This is the part of above the diagonal with the given index. The diagonal itself is also included. The part below the diagonal contains zero. 0 represents the main diagonal. -1 means the first subdiagonal, this is the one below the main diagonal. Other negative numbers represent lower subdiagonals. 1 means the first superdiagonal, this is the one above the main diagonal. Other positive numbers represent higher superdiagonals. :note: Note that this method also works for non-square matrices, but the returned matrix will thus be not upper triangular because only square matrices are upper triangular. - parameter n: The diagonal's index. - returns: A matrix where all elements under the diagonal with the given index are zero. :exception: An exception will be raised if the diagonal at the given index does not exist. This means -n >= the number of rows or n >= the number of columns. */ open func upperTriangle(_ n: Int = 0) throws -> Matrix<T> { if n != 0 && (-n >= self.dimensions.rows || n >= self.dimensions.columns) { throw MatrixError.indexOutOfBounds(received: n, allowedRange: -(self.dimensions.rows + 1) ... self.dimensions.columns - 1, description: nil) } var row = Swift.max(-n, 0) var col = Swift.max(n, 0) if n > 0 { var elementsList = [T](repeating: 0, count: self.dimensions.product) while row < self.dimensions.rows && col < self.dimensions.columns { for c in col ..< self.dimensions.columns { elementsList[row * self.dimensions.columns + c] = self.element(row, c) } row += 1 col += 1 } return Matrix(elementsList: elementsList, dimensions: self.dimensions) } else { var elementsList = Array(self.elementsList) while row + 1 < self.dimensions.rows && col < self.dimensions.columns { for r in row + 1 ..< self.dimensions.rows { elementsList[r * self.dimensions.columns + col] = 0 } row += 1 col += 1 } return Matrix(elementsList: elementsList, dimensions: self.dimensions) } } /** Returns a copy of the matrix with all elements above the main diagonal set to zero. This also applies to non-square matrices. */ open var lowerTriangle: Matrix<T> { get { return lowerTriangle() } } /** Returns the lower triangle part of the matrix. This is the part of below the diagonal with the given index. The diagonal itself is also included. The part below the diagonal contains zero. 0 represents the main diagonal. -1 means the first subdiagonal, this is the one below the main diagonal. Other negative numbers represent lower subdiagonals. 1 means the first superdiagonal, this is the one above the main diagonal. Other positive numbers represent higher superdiagonals. :note: Note that this method also works for non-square matrices, but the returned matrix will thus be not lower triangular because only square matrices are lower triangular. - parameter n: The diagonal's index. - returns: A matrix where all elements above the diagonal with the given index are zero. :exception: An exception will be raised if the diagonal at the given index does not exist. This means -n >= the number of rows or n >= the number of columns. */ open func lowerTriangle(_ n: Int = 0) -> Matrix<T> { if n == 0 && self.dimensions.isEmpty { return Matrix() } if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Index out the bounds."), reason: "The given index is out of bounds.", userInfo: nil).raise() } var row = Swift.max(-n, 0) var col = Swift.max(n, 0) if n >= 0 { var elementsList = Array(self.elementsList) while row < self.dimensions.rows && col + 1 < self.dimensions.columns { for c in col + 1 ..< self.dimensions.columns { elementsList[row * self.dimensions.columns + c] = 0 } row += 1 col += 1 } return Matrix(elementsList: elementsList, dimensions: dimensions) } else { var elementsList = [T](repeating: 0, count: self.dimensions.product) while row < self.dimensions.rows && col < self.dimensions.columns { for r in row ..< self.dimensions.rows { elementsList[r * self.dimensions.columns + col] = self.element(r, col) } row += 1 col += 1 } return Matrix(elementsList: elementsList, dimensions: self.dimensions) } } /** Returns the maximum element in the matrix if the matrix is not empty, otherwise it returns nil. */ open var maxElement: T? { return self.isEmpty ? nil : MathEagle.max(self.elementsList) } /** Returns the minimum element in the matrix if the matrix is not empty, otherwise it returns nil. */ open var minElement: T? { return self.isEmpty ? nil : MathEagle.min(self.elementsList) } /** Returns the transpose of the matrix. */ open var transpose: Matrix<T> { return MathEagle.transpose(self) } /** Returns the conjugate of the matrix. */ open var conjugate: Matrix<T> { return mmap(self){ $0.conjugate } } /** Returns the conjugate transpose of the matrix. This is also called the Hermitian transpose. */ open var conjugateTranspose: Matrix<T> { return self.transpose.conjugate } /** Returns whether the matrix is empty. This means the dimensions are (0, 0). - returns: true if the matrix is empty. */ open var isEmpty: Bool { return self.dimensions.isEmpty } /** Returns whether all elements are zero. */ open var isZero: Bool { for element in self.elementsList { if element != 0 { return false } } return true } /** Returns whether the matrix is square. - returns: true if the matrix is square. */ open var isSquare: Bool { return self.dimensions.isSquare } /** Returns whether the matrix is diagonal. This means all elements that are not on the main diagonal are zero. */ open var isDiagonal: Bool { for (index, element) in self.enumerated() { if index / self.dimensions.rows != index % self.dimensions.rows && element != 0 { return false } } return true } /** Returns whether the matrix is symmetrical. This method works O(2n) for symmetrical (square) matrixes of size n. - returns: true if the matrix is symmetrical. */ open var isSymmetrical: Bool { // If it's not square, it's impossible to be symmetrical if !self.isSquare { return false } let size = self.dimensions[0] // If the size is not bigger than 1, it's always symmetrical if size <= 1 { return true } let nrOfSecondDiagonals = 2 * self.dimensions.rows - 1 for i in 1 ..< nrOfSecondDiagonals - 1 { var k = i/2 + 1 let d = Swift.min(i, size-1) while k <= d { let j = i - k if self.element(k, j) != self.element(j, k) { return false } k += 1 } } return true } /** Returns whether the matrix is upper triangular. This means the matrix is square and all elements below the main diagonal are zero. */ open var isUpperTriangular: Bool { return isUpperTriangular() } /** Returns whether the matrix is upper triangular according to the given diagonal index. This means all elements below the diagonal at the given index n must be zero. When mustBeSquare is set to true the matrix must be square. - parameter n: The diagonal's index. - parameter mustBeSquare: Whether the matrix must be square to be upper triangular. */ open func isUpperTriangular(_ n: Int = 0, mustBeSquare: Bool = true) -> Bool { if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Index out the bounds."), reason: "The given diagonal index is out of bounds.", userInfo: nil).raise() } // A non-square matrix can't be upper triangular if mustBeSquare && !self.isSquare { return false } if self.dimensions.rows <= 1 { return true } var row = Swift.max(-n, 0) var col = Swift.max(n, 0) for c in 0 ..< col { for r in 0 ..< self.dimensions.rows { if self.element(r, c) != 0 { return false } } } while row + 1 < self.dimensions.rows && col + 1 < self.dimensions.columns { for r in row + 1 ..< self.dimensions.rows { if self.element(r, col) != 0 { return false } } row += 1 col += 1 } return true } /** Returns whether the matrix is upper Hessenberg. This means all elements below the first subdiagonal are zero. */ open var isUpperHessenberg: Bool { return isUpperTriangular(-1) } /** Returns whether the matrix is lower triangular. This means the matrix is square and all elements above the main diagonal are zero. */ open var isLowerTriangular: Bool { return isLowerTriangular() } /** Returns whether the matrix is lower triangular according to the given diagonal index. This means all elements above the diagonal at the given index n must be zero. When mustBeSquare is set to true the matrix must be square. - parameter n: The diagonal's index. - parameter mustBeSquare: Whether the matrix must be square to be lower triangular. */ open func isLowerTriangular(_ n: Int = 0, mustBeSquare: Bool = true) -> Bool { if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Index out the bounds."), reason: "The given diagonal index is out of bounds.", userInfo: nil).raise() } // A non-square matrix can't be upper triangular if mustBeSquare && !self.isSquare { return false } if self.dimensions.rows <= 1 { return true } var row = Swift.max(-n, 0) var col = Swift.max(n, 0) for r in 0 ..< row { for c in 0 ..< self.dimensions.columns { if self.element(r, c) != 0 { return false } } } while row + 1 < self.dimensions.rows && col + 1 < self.dimensions.columns { for c in col + 1 ..< self.dimensions.columns { if self.element(row, c) != 0 { return false } } row += 1 col += 1 } return true } /** Returns whether the matrix is a lower Hessenberg matrix. This means all elements above the first superdiagonal are zero. */ open var isLowerHessenberg: Bool { return isLowerTriangular(1) } /** Returns whether the matrix is Hermitian. This means the matrix is equal to it's own conjugate transpose. */ open var isHermitian: Bool { if !self.isSquare { return false } var row = 0, col = 1 while row < self.dimensions.rows && col < self.dimensions.columns { for c in col ..< self.dimensions.columns { if self.element(row, c).conjugate != self.element(c, row) { return false } } row += 1 col += 1 } return true } // MARK: Element Methods /** Returns the element at the given index (row, column). - parameter row: The row index of the requested element - parameter column: The column index of the requested element - returns: The element at the given index (row, column). :exception: Throws an exception when either of the given indices is out of bounds. */ open func element(_ row: Int, _ column: Int) -> T { if row < 0 || row >= self.dimensions.rows { NSException(name: NSExceptionName(rawValue: "Row index out of bounds"), reason: "The requested element's row index is out of bounds.", userInfo: nil).raise() } if column < 0 || column >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Column index out of bounds"), reason: "The requested element's column index is out of bounds.", userInfo: nil).raise() } return self.elementsList[row * self.dimensions.columns + column] } /** Sets the element at the given indexes. - parameter row: The row index of the element - parameter column: The column index of the element - parameter element: The element to set at the given indexes :exception: Throws an exception when either of the given indices is out of bounds. */ open func setElement(atRow row: Int, atColumn column: Int, toElement element: T) { if row < 0 || row >= self.dimensions.rows { NSException(name: NSExceptionName(rawValue: "Row index out of bounds"), reason: "The row index at which the element should be set is out of bounds.", userInfo: nil).raise() } if column < 0 || column >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Column index out of bounds"), reason: "The column index at which the element should be set is out of bounds.", userInfo: nil).raise() } self.elementsList[row * self.dimensions.columns + column] = element } /** Sets the element at the given index. - parameter index: A tuple containing the indexes of the element (row, column) - parameter element: The element to set at the given index :exception: Throws an exception when either of the given indices is out of bounds. */ open func setElement(atIndex index: (Int, Int), toElement element: T) { let (row, column) = index self.setElement(atRow: row, atColumn: column, toElement: element) } /** Returns the row at the given index. The first row has index 0. - returns: The row at the given index. :exception: Throws an exception when the given index is out of bounds. */ open func row(_ index: Int) -> Vector<T> { if index < 0 || index >= self.dimensions.rows { NSException(name: NSExceptionName(rawValue: "Row index out of bounds"), reason: "The requested row's index is out of bounds.", userInfo: nil).raise() } var elementsList = [T]() for i in index * self.dimensions.columns ..< (index + 1) * self.dimensions.columns { elementsList.append(self.elementsList[i]) } return Vector(elementsList) } /** Sets the row at the given index to the given row. - parameter index: The index of the row to change. - parameter newRow: The row to set at the given index. :exception: Throws an exception when the given index is out of bounds. :exception: Throws an exception when the given vector is of the wrong length. */ open func setRow(atIndex index: Int, toRow newRow: Vector<T>) { // If the index is out of bounds if index < 0 || index >= self.dimensions.rows { NSException(name: NSExceptionName(rawValue: "Row index out of bounds"), reason: "The index at which the row should be set is out of bounds.", userInfo: nil).raise() } // If the row's length is not correct if newRow.length != self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "New row wrong length"), reason: "The new row's length is not equal to the matrix's number of columns.", userInfo: nil).raise() } self.elementsList.replaceSubrange(index * self.dimensions.columns ..< (index + 1) * self.dimensions.columns, with: newRow.elements) } /** Removes the row at the given index. - parameter index: The index of the row to remove. :exception: Throws an exception when the given index is out of bounds. */ open func removeRow(atIndex index: Int) { // If the index is out of bounds if index < 0 || index >= self.dimensions.rows { fatalError("The index of the row that should be removed is out of bounds.") } if self.dimensions.rows == 1 { self.elementsList = [] self.innerDimensions = Dimensions() } else { self.elementsList.removeSubrange(self.dimensions.columns * index ..< self.dimensions.columns * (index + 1)) self.innerDimensions = Dimensions(self.dimensions.rows - 1, self.dimensions.columns) } } /** Switches the rows at the given indexes. - parameter i: The index of the first row. - parameter j: The index of the second row. :exception: Throws an exception when the given index is out of bounds. */ open func switchRows(_ i: Int, _ j: Int) { if i < 0 || i >= self.dimensions.rows || j < 0 || j >= self.dimensions.rows { NSException(name: NSExceptionName(rawValue: "Row index out of bounds"), reason: "The index of the row that should be switched is out of bounds.", userInfo: nil).raise() } let intermediate = self[i] self[i] = self[j] self[j] = intermediate } /** Returns the column at the given index. The first column has index 0. - returns: The column at the given index. :exception: Throws an exception when the given index is out of bounds. */ open func column(_ index: Int) -> Vector<T> { if index < 0 || index >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Column index out of bounds"), reason: "The requested column's index is out of bounds.", userInfo: nil).raise() } var column = [T]() for i in 0 ..< self.dimensions.rows { column.append(self.elementsList[i * self.dimensions.columns + index]) } return Vector(column) } /** Sets the column at the given index to the given column. - parameter index: The index of the column to change. - parameter column: The column to set at the given index. :exception: Throws an exception when the given index is out of bounds. :exception: Throws an exception when the given vector is of the wrong length. */ open func setColumn(atIndex index: Int, toColumn newColumn: Vector<T>) { // If the index is out of bounds if index < 0 || index >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Column index out of bounds"), reason: "The index at which the column should be set is out of bounds.", userInfo: nil).raise() } // If the column's length is not correct if newColumn.length != self.dimensions.rows { NSException(name: NSExceptionName(rawValue: "New column wrong length"), reason: "The new column's length is not equal to the matrix's number of rows.", userInfo: nil).raise() } for i in 0 ..< self.dimensions.rows { self.elementsList[i * self.dimensions.columns + index] = newColumn[i] } } /** Removes the column at the given index. - parameter index: The index of the column to remove. :exception: Throws an exception when the given index is out of bounds. */ open func removeColumn(atIndex index: Int) { if index < 0 || index >= self.dimensions.columns { NSException(name: NSExceptionName(rawValue: "Column index out of bounds"), reason: "The index of the column that should be removed is out of bounds.", userInfo: nil).raise() } if self.dimensions.columns == 1 { self.elementsList = [] self.innerDimensions = Dimensions() } else { for r in 0 ..< self.dimensions.rows { self.elementsList.remove(at: r * (self.dimensions.columns - 1) + index) } self.innerDimensions = Dimensions(self.dimensions.rows, self.dimensions.columns - 1) } } /** Switches the columns at the given indexes. - parameter i: The index of the first column. - parameter j: The index of the second column. */ open func switchColumns(_ i: Int, _ j: Int) { let intermediate = self.column(i) self.setColumn(atIndex: i, toColumn: self.column(j)) self.setColumn(atIndex: j, toColumn: intermediate) } /** Returns the submatrix for the given row and column ranges. - parameter rowCollection: The range with rows included in the submatrix. - parameter columnCollection: The range with columns included in the submatrix. - returns: The submatrix for the given row and column ranges. */ open func submatrix(_ rowCollection: AnyCollection<Int>, _ columnCollection: AnyCollection<Int>) -> Matrix<T> { var elementsList = [T]() for row in rowCollection { for column in columnCollection { elementsList.append(self.element(row, column)) } } return Matrix(elementsList: elementsList, rows: Int(rowCollection.count)) } /** Returns the submatrix for the given row and column ranges. - parameter rowCollection: The range with rows included in the submatrix. - parameter columnCollection: The range with columns included in the submatrix. - returns: The submatrix for the given row and column ranges. */ open func submatrix(_ rowRange: CountableRange<Int>, _ columnRange: CountableRange<Int>) -> Matrix<T> { return self.submatrix(AnyCollection(AnyRandomAccessCollection(rowRange)), AnyCollection(AnyRandomAccessCollection(columnRange))) } /** Returns the submatrix for the given row and column ranges. - parameter rowCollection: The range with rows included in the submatrix. - parameter columnCollection: The range with columns included in the submatrix. - returns: The submatrix for the given row and column ranges. */ open func submatrix(_ rowRange: CountableClosedRange<Int>, _ columnRange: CountableClosedRange<Int>) -> Matrix<T> { return self.submatrix(AnyCollection(AnyRandomAccessCollection(rowRange)), AnyCollection(AnyRandomAccessCollection(columnRange))) } /** Replaces the current submatrix for the given row and column ranges with the given matrix. - parameter rowRange: The range with rows included in the submatrix. - parameter columnRange: The range with columns included in the submatrix. - parameter matrix: The matrix to replace the submatrix with. :exceptions: Expections will be thrown if the given ranges are out of bounds or if the given matrix's dimensions don't match the given ranges' lengths. */ open func setSubmatrix(_ rowRange: AnyCollection<Int>, _ columnRange: AnyCollection<Int>, toMatrix matrix: Matrix<T>) { if matrix.dimensions.rows != Int(rowRange.count) || matrix.dimensions.columns != Int(columnRange.count) { fatalError("The dimensions of the given matrix don't match the dimensions of the row and/or column ranges.") } for (rowIndex, row) in rowRange.enumerated() { for (columnIndex, column) in columnRange.enumerated() { self.setElement(atRow: row, atColumn: column, toElement: matrix.element(rowIndex, columnIndex)) } } } /** Replaces the current submatrix for the given row and column ranges with the given matrix. - parameter rowRange: The range with rows included in the submatrix. - parameter columnRange: The range with columns included in the submatrix. - parameter matrix: The matrix to replace the submatrix with. :exceptions: Expections will be thrown if the given ranges are out of bounds or if the given matrix's dimensions don't match the given ranges' lengths. */ open func setSubmatrix(_ rowRange: CountableRange<Int>, _ columnRange: CountableRange<Int>, toMatrix matrix: Matrix<T>) { self.setSubmatrix(AnyCollection(AnyRandomAccessCollection(rowRange)), AnyCollection(AnyRandomAccessCollection(columnRange)), toMatrix: matrix) } /** Replaces the current submatrix for the given row and column ranges with the given matrix. - parameter rowRange: The range with rows included in the submatrix. - parameter columnRange: The range with columns included in the submatrix. - parameter matrix: The matrix to replace the submatrix with. :exceptions: Expections will be thrown if the given ranges are out of bounds or if the given matrix's dimensions don't match the given ranges' lengths. */ open func setSubmatrix(_ rowRange: CountableClosedRange<Int>, _ columnRange: CountableClosedRange<Int>, toMatrix matrix: Matrix<T>) { self.setSubmatrix(AnyCollection(AnyRandomAccessCollection(rowRange)), AnyCollection(AnyRandomAccessCollection(columnRange)), toMatrix: matrix) } /** Returns the subvector for the given row range at the given column. - parameter rowRange: The range with rows included in the subvector. - parameter column: The column of the subvector. :exceptions: Exceptions will be thrown if the given row range and/or column are out of bounds. */ open func subvector(_ rowRange: AnyCollection<Int>, _ column: Int) -> Vector<T> { var vectorElements = [T]() for row in rowRange { vectorElements.append(self.element(row, column)) } return Vector(vectorElements) } /** Returns the subvector for the given row range at the given column. - parameter rowRange: The range with rows included in the subvector. - parameter column: The column of the subvector. :exceptions: Exceptions will be thrown if the given row range and/or column are out of bounds. */ open func subvector(_ rowRange: CountableRange<Int>, _ column: Int) -> Vector<T> { return self.subvector(AnyCollection(AnyRandomAccessCollection(rowRange)), column) } /** Returns the subvector for the given row range at the given column. - parameter rowRange: The range with rows included in the subvector. - parameter column: The column of the subvector. :exceptions: Exceptions will be thrown if the given row range and/or column are out of bounds. */ open func subvector(_ rowRange: CountableClosedRange<Int>, _ column: Int) -> Vector<T> { return self.subvector(AnyCollection(AnyRandomAccessCollection(rowRange)), column) } /** Replaces the current subvector for the given row range and column with the given vector. - parameter rowRange: The range with rows included in the subvector. - parameter column: The column of the subvector. - parameter vector: The vector to replace the subvector with. :exceptions: Exceptions will be thrown if the given row range and/or column are out of bounds or if the vector's length does not match the row range's length. */ open func setSubvector(_ rowRange: AnyCollection<Int>, _ column: Int, toVector vector: Vector<T>) { if vector.length != Int(rowRange.count) { fatalError("The length of the given vector is not equal to the length in the given row range. Vector length = \(vector.length), row range length = \(rowRange.count).") } for (rowIndex, row) in rowRange.enumerated() { self.setElement(atRow: row, atColumn: column, toElement: vector[rowIndex]) } } /** Replaces the current subvector for the given row range and column with the given vector. - parameter rowRange: The range with rows included in the subvector. - parameter column: The column of the subvector. - parameter vector: The vector to replace the subvector with. :exceptions: Exceptions will be thrown if the given row range and/or column are out of bounds or if the vector's length does not match the row range's length. */ open func setSubvector(_ rowRange: CountableRange<Int>, _ column: Int, toVector vector: Vector<T>) { self.setSubvector(AnyCollection(AnyRandomAccessCollection(rowRange)), column, toVector: vector) } /** Replaces the current subvector for the given row range and column with the given vector. - parameter rowRange: The range with rows included in the subvector. - parameter column: The column of the subvector. - parameter vector: The vector to replace the subvector with. :exceptions: Exceptions will be thrown if the given row range and/or column are out of bounds or if the vector's length does not match the row range's length. */ open func setSubvector(_ rowRange: CountableClosedRange<Int>, _ column: Int, toVector vector: Vector<T>) { self.setSubvector(AnyCollection(AnyRandomAccessCollection(rowRange)), column, toVector: vector) } /** Returns the subvector for the given column range at the given row. - parameter row: The row of the subvector. - parameter columnRange: The range with columns included in the subvector. :exceptions: Exceptions will be thrown if the given row and/or column range are out of bounds. */ open func subvector(_ row: Int, _ columnRange: AnyCollection<Int>) -> Vector<T> { var vectorElements = [T]() for column in columnRange { vectorElements.append(self.element(row, column)) } return Vector(vectorElements) } /** Returns the subvector for the given column range at the given row. - parameter row: The row of the subvector. - parameter columnRange: The range with columns included in the subvector. :exceptions: Exceptions will be thrown if the given row and/or column range are out of bounds. */ open func subvector(_ row: Int, _ columnRange: CountableRange<Int>) -> Vector<T> { return self.subvector(row, AnyCollection(AnyRandomAccessCollection(columnRange))) } /** Returns the subvector for the given column range at the given row. - parameter row: The row of the subvector. - parameter columnRange: The range with columns included in the subvector. :exceptions: Exceptions will be thrown if the given row and/or column range are out of bounds. */ open func subvector(_ row: Int, _ columnRange: CountableClosedRange<Int>) -> Vector<T> { return self.subvector(row, AnyCollection(AnyRandomAccessCollection(columnRange))) } /** Replaces the current subvector for the given row and column range with the given vector. - parameter row: The row of the subvector. - parameter columnRange: The range with columns included in the subvector. - parameter vector: The vector to replace the subvector with. :exceptions: Exceptions will be thrown if the given row and/or column range are out of bounds or if the vector's length does not match the column range's length. */ open func setSubvector(_ row: Int, _ columnRange: AnyCollection<Int>, toVector vector: Vector<T>) { if vector.length != Int(columnRange.count) { NSException(name: NSExceptionName(rawValue: "Unequal length"), reason: "The length of the given vector is not equal to the length in the given column range. Vector length = \(vector.length), column range = \(columnRange).", userInfo: nil).raise() } for (columnIndex, column) in columnRange.enumerated() { self.setElement(atRow: row, atColumn: column, toElement: vector[columnIndex]) } } /** Replaces the current subvector for the given row and column range with the given vector. - parameter row: The row of the subvector. - parameter columnRange: The range with columns included in the subvector. - parameter vector: The vector to replace the subvector with. :exceptions: Exceptions will be thrown if the given row and/or column range are out of bounds or if the vector's length does not match the column range's length. */ open func setSubvector(_ row: Int, _ columnRange: CountableRange<Int>, toVector vector: Vector<T>) { self.setSubvector(row, AnyCollection(AnyRandomAccessCollection(columnRange)), toVector: vector) } /** Replaces the current subvector for the given row and column range with the given vector. - parameter row: The row of the subvector. - parameter columnRange: The range with columns included in the subvector. - parameter vector: The vector to replace the subvector with. :exceptions: Exceptions will be thrown if the given row and/or column range are out of bounds or if the vector's length does not match the column range's length. */ open func setSubvector(_ row: Int, _ columnRange: CountableClosedRange<Int>, toVector vector: Vector<T>) { self.setSubvector(row, AnyCollection(AnyRandomAccessCollection(columnRange)), toVector: vector) } /** Fills the diagonal with the given value. - parameter value: The value to fill the diagonal with. */ open func fillDiagonal(_ value: T) { for i in 0 ..< self.dimensions.minimum { self.setElement(atRow: i, atColumn: i, toElement: value) } } /** Resizes the matrix to the given dimensions. If elements need to be added, zeros will be added on the right and bottom sides of the matrix. - parameter newDimensions: The new dimensions for the matrix. */ open func resize(_ newDimensions: Dimensions) { if newDimensions.columns < self.dimensions.columns { for r in 0 ..< Swift.min(newDimensions.rows, self.dimensions.rows) { self.elementsStructure.removeSubrange((r + 1) * newDimensions.columns ..< r * newDimensions.columns + self.dimensions.columns) } } else if newDimensions.columns > self.dimensions.columns { for r in 0 ..< Swift.min(newDimensions.rows, self.dimensions.rows) { self.elementsStructure.insert(contentsOf: [T](repeating: 0, count: newDimensions.columns - self.dimensions.columns), at: r * newDimensions.columns + self.dimensions.columns) } } if newDimensions.rows < self.dimensions.rows { self.elementsStructure.removeSubrange(newDimensions.product ..< self.elementsStructure.count) } else if newDimensions.rows > self.dimensions.rows { self.elementsStructure.append(contentsOf: [T](repeating: 0, count: (newDimensions.rows - self.dimensions.rows) * newDimensions.columns)) } self.innerDimensions = newDimensions } // MARK: Factorisations /** Returns the LU decomposition of the matrix. This is only possible if the matrix is square. - returns: (L, U, P) with L being a lower triangular matrix with 1 on the diagonal, U an upper triangular matrix and P a permutation matrix. This way PA = LU. */ open var LUDecomposition: (Matrix<T>, Matrix<T>, Matrix<T>) { let (L, U, P, _) = self.LUDecomposition() return (L, U, P) } /** Returns the LU decomposition of the matrix. This is only possible if the matrix is square. - parameter pivoting: Determines whether the algorithm should use row pivoting. Note that if note pivoting is disabled, the algorithm might not find the LU decomposition. - parameter optimalPivoting: Determines whether the algorithm should use optimal row pivoting when pivoting is enabled. This means the biggest element in the current column is chosen to get more numerical stability. - returns: (L, U, P, det) with L being a lower triangular matrix with 1 on the diagonal, U an upper triangular matrix and P a permutation matrix. This way PA = LU. det gives the determinant of the matrix */ open func LUDecomposition(pivoting: Bool = true, optimalPivoting: Bool = true) -> (Matrix<T>, Matrix<T>, Matrix<T>, T) { if !self.isSquare { NSException(name: NSExceptionName(rawValue: "Not square"), reason: "A non-square matrix does not have a LU decomposition.", userInfo: nil).raise() } let n = self.size! let L = Matrix(identityOfSize: n) let U = self.copy let P = Matrix(identityOfSize: n) var detP: T = 1; for i in 0 ..< n { if pivoting { var p = i, max = U[i][i] for j in i ..< n { if U[i, j] > max { max = U[i, j]; p = j } } if p != i { detP = -detP } U.switchRows(p, i) P.switchRows(p, i) } L[i+1 ..< n, i] = U[i+1 ..< n, i]/U[i, i] U[i+1 ..< n, i+1 ..< n] = U[i+1 ..< n, i+1 ..< n] - L[i+1 ..< n, i].directProduct(U[i, i+1 ..< n]) U[i+1 ..< n, i] = Vector(filledWith: 0, length: n-i-1) } let detU = product(U.diagonalElements) return (L, U, P, detP * detU) } } // MARK: Matrix Equality /** Returns whether the two given matrices are equal. This means corresponding elements are equal. - parameter left: The left matrix in the equation. - parameter right: The right matrix in the equation. - returns: true if the two matrices are equal. */ public func == <T: MatrixCompatible> (left: Matrix<T>, right: Matrix<T>) -> Bool { if left.dimensions != right.dimensions { return false } for i in 0 ..< left.dimensions.product { if left.elementsList[i] != right.elementsList[i] { return false } } return true } // MARK: Matrix Addition /** Returns the sum of the two matrices. - parameter left: The left matrix in the sum. - parameter right: The right matrix in the sum. - returns: A matrix of the same dimensions as the two given matrices. :exception: Throws an exception when the dimensions of the two matrices are not equal. */ public func + <T: MatrixCompatible> (left: Matrix<T>, right: Matrix<T>) -> Matrix<T> { if left.dimensions != right.dimensions { NSException(name: NSExceptionName(rawValue: "Unequal dimensions"), reason: "The dimensions of the two matrices are not equal.", userInfo: nil).raise() } return mcombine(left, right){ $0 + $1 } } /** Returns the sum of the two matrices. - parameter left: The left matrix in the sum. - parameter right: The right matrix in the sum. - returns: A matrix of the same dimensions as the two given matrices. :exception: Throws an exception when the dimensions of the two matrices are not equal. */ public func + (left: Matrix<Float>, right: Matrix<Float>) -> Matrix<Float> { if left.dimensions != right.dimensions { NSException(name: NSExceptionName(rawValue: "Unequal dimensions"), reason: "The dimensions of the two matrices are not equal.", userInfo: nil).raise() } // var elementsList = [Float](count: left.dimensions.product, repeatedValue: 0) // // vDSP_vadd(left.elementsList, 1, right.elementsList, 1, &elementsList, 1, vDSP_Length(left.dimensions.product)) // // return Matrix(elementsList: elementsList, dimensions: left.dimensions) var elementsList = right.elementsList cblas_saxpy(Int32(left.dimensions.product), 1.0, left.elementsList, 1, &elementsList, 1) return Matrix(elementsList: elementsList, dimensions: left.dimensions) // var elementsList = right.elementsList // // catlas_saxpby(Int32(left.dimensions.product), 1.0, left.elementsList, 1, 1.0, &elementsList, 1) // // return Matrix(elementsList: elementsList, dimensions: left.dimensions) } /** Returns the sum of the two matrices. - parameter left: The left matrix in the sum. - parameter right: The right matrix in the sum. - returns: A matrix of the same dimensions as the two given matrices. :exception: Throws an exception when the dimensions of the two matrices are not equal. */ public func + (left: Matrix<Double>, right: Matrix<Double>) -> Matrix<Double> { if left.dimensions != right.dimensions { NSException(name: NSExceptionName(rawValue: "Unequal dimensions"), reason: "The dimensions of the two matrices are not equal.", userInfo: nil).raise() } // var elementsList = [Float](count: left.dimensions.product, repeatedValue: 0) // // vDSP_vaddD(left.elementsList, 1, right.elementsList, 1, &elementsList, 1, vDSP_Length(left.dimensions.product)) // // return Matrix(elementsList: elementsList, dimensions: left.dimensions) var elementsList = right.elementsList cblas_daxpy(Int32(left.dimensions.product), 1.0, left.elementsList, 1, &elementsList, 1) return Matrix(elementsList: elementsList, dimensions: left.dimensions) // var elementsList = right.elementsList // // catlas_daxpby(Int32(left.dimensions.product), 1.0, left.elementsList, 1, 1.0, &elementsList, 1) // // return Matrix(elementsList: elementsList, dimensions: left.dimensions) } // MARK: Matrix Negation /** Returns the negation of the given matrix. - parameter matrix: The matrix to negate. - returns: A matrix with the given dimensions as the given matrix where every element is the negation of the corresponding element in the given matrix. */ public prefix func - <T: MatrixCompatible> (matrix: Matrix<T>) -> Matrix<T> { return mmap(matrix){ -$0 } } // MARK: Matrix Subtraction /** Returns the subtraction of the two given matrices. - parameter left: The left matrix in the subtraction. - parameter right: The right matrix in the subtraction. - returns: A matrix with the same dimensions as the two given matrices where every element is the difference of the corresponding elements in the left and right matrices. :exception: Throws an exception when the dimensions of the two given matrices are not equal. */ public func - <T: MatrixCompatible> (left: Matrix<T>, right: Matrix<T>) -> Matrix<T> { if left.dimensions != right.dimensions { NSException(name: NSExceptionName(rawValue: "Unequal dimensions"), reason: "The dimensions of the two given matrices are not equal. Left dimensions: \(left.dimensions), right dimensions: \(right.dimensions).", userInfo: nil).raise() } return mcombine(left, right){ $0 - $1 } } // MARK: Matrix Scalar Multiplication /** Returns the product of the given scalar and the given matrix. - parameter scalar: The scalar with which to multiply the given matrix. - parameter matrix: The matrix to multiply with the given scalar. - returns: A matrix of the same dimensions as the given matrix where every element is calculated as the product of the corresponding element in the given matrix and the given scalar. */ public func * <T: MatrixCompatible> (scalar: T, matrix: Matrix<T>) -> Matrix<T> { return Matrix(matrix.elements.map{ $0.map{ scalar * $0 } }) } /** Returns the product of the given scalar and the given matrix. - parameter scalar: The scalar with which to multiply the given matrix. - parameter matrix: The matrix to multiply with the given scalar. - returns: A matrix of the same dimensions as the given matrix where every element is calculated as the product of the corresponding element in the given matrix and the given scalar. */ public func * <T: MatrixCompatible> (matrix: Matrix<T>, scalar: T) -> Matrix<T> { return scalar * matrix } // MARK: Matrix Multiplication /** Returns the product of the two given matrices. - parameter left: The left matrix in the multiplication. - parameter right: The right matrix in the multiplication. - returns: A matrix with the same number of rows as the left matrix and the same number of columns as the right matrix. :exception: Throws an exception when the number of columns of the left matrix is not equal to the number of rows of the right matrix. */ public func * <T: MatrixCompatible> (left: Matrix<T>, right: Matrix<T>) -> Matrix<T> { if left.dimensions.columns != right.dimensions.rows { NSException(name: NSExceptionName(rawValue: "Wrong dimensions"), reason: "The left matrix's number of columns is not equal to the right matrix's rows.", userInfo: nil).raise() } var matrixElements = [[T]]() for row in 0 ..< left.dimensions.rows { var rowElements = [T]() for column in 0 ..< right.dimensions.columns { var element:T = left[row, 0] * right[0][column] for i in 1 ..< left.dimensions.columns { element = element + left[row, i] * right[i, column] } rowElements.append(element) } matrixElements.append(rowElements) } return Matrix(matrixElements) } // MARK: Matrix Functional Methods /** Returns a new matrix of the same dimensions where the elements are generated by calling the transform with the elements in this matrix. - parameter matrix: The matrix to map with the original elements. - parameter transform: The transform to map on the elements of matrix. */ public func mmap <T: MatrixCompatible, U: MatrixCompatible> (_ matrix: Matrix<T>, transform: (T) -> U) -> Matrix<U> { let elementsList = matrix.elementsList.map(transform) return Matrix(elementsList: elementsList, dimensions: matrix.dimensions) } /** Returns a single value generated by systematically reducing the matrix using the combine closure. For the first element initial will be used. Then the last generated element will be used to combine with the next element in the matrix. The elements will be looped through row per row, column per column. - parameter matrix: The matrix to reduce. - parameter initial: The element to combine with the first element of the matrix. - parameter combine: The closure to combine two values to generate a new value. */ public func mreduce <T: MatrixCompatible, U> (_ matrix: Matrix<T>, initial: U, combine: (U, T) -> U) -> U { return matrix.elementsList.reduce(initial, combine) } /** Returns a new matrix by combining the two given matrices using the combine closure. The two given matrices have to have the same dimensions, since the combination will happen element per element. - parameter left: The left matrix in the combination. - parameter right: The right matrix in the combination. - parameter combine: The closure to combine two elements from the two matrices. :exceptions: Throws an exception when the dimensions of the two given matrices are not equal. */ public func mcombine <T: MatrixCompatible, U: MatrixCompatible, V: MatrixCompatible> (_ left: Matrix<T>, _ right: Matrix<U>, combine: (T, U) -> V) -> Matrix<V> { if left.dimensions != right.dimensions { NSException(name: NSExceptionName(rawValue: "Unequal dimensions"), reason: "The dimensions of the two matrices are not equal.", userInfo: nil).raise() } var elementsList = [V]() for i in 0 ..< left.dimensions.product { elementsList.append(combine(left.elementsList[i], right.elementsList[i])) } return Matrix(elementsList: elementsList, dimensions: left.dimensions) } // MARK: High Perfomance Functions /** Returns the transpose of the given matrix. - parameter matrix: The matrix to transpose. - returns: The transpose of the given matrix. */ public func transpose <T: MatrixCompatible> (_ matrix: Matrix<T>) -> Matrix<T> { if let floatMatrix = matrix as? Matrix<Float> { return transpose(floatMatrix) as! Matrix<T> } if let doubleMatrix = matrix as? Matrix<Double> { return transpose(doubleMatrix) as! Matrix<T> } var elementsList = [T]() for col in 0 ..< matrix.dimensions.columns { for row in 0 ..< matrix.dimensions.rows { elementsList.append(matrix.element(row, col)) } } return Matrix(elementsList: elementsList, rows: matrix.dimensions.columns) } /** Returns the transpose of the given matrix. - parameter matrix: The matrix to transpose. - returns: The transpose of the given matrix. */ public func transpose(_ matrix: Matrix<Float>) -> Matrix<Float> { var elementsList = [Float](repeating: 0, count: matrix.dimensions.product) vDSP_mtrans(matrix.elementsList, 1, &elementsList, 1, vDSP_Length(matrix.dimensions.columns), vDSP_Length(matrix.dimensions.rows)) return Matrix(elementsList: elementsList, columns: matrix.dimensions.rows) } /** Returns the transpose of the given matrix. - parameter matrix: The matrix to transpose. - returns: The transpose of the given matrix. */ public func transpose(_ matrix: Matrix<Double>) -> Matrix<Double> { var elementsList = [Double](repeating: 0, count: matrix.dimensions.product) vDSP_mtransD(matrix.elementsList, 1, &elementsList, 1, vDSP_Length(matrix.dimensions.columns), vDSP_Length(matrix.dimensions.rows)) return Matrix(elementsList: elementsList, columns: matrix.dimensions.rows) } // MARK: - Objective-C Bridged methods // MARK: Decompositions / Factorisations /** Returns the LU decomposition of the given matrix. - parameter matrix: The matrix to compute the LU decomposition of. - returns: (L, U, P) A tuple containing three matrices. The first matrix is a lower triangular matrix with ones on the main diagonal. The second matrix is an upper triangular matrix and the third matrix is a permutations matrix. Here is A = PLU. */ public func LUDecomposition(_ matrix: Matrix<Float>) -> (Matrix<Float>, Matrix<Float>, PermutationMatrix<Float>)? { var elementsList = transpose(matrix).elementsList var pivotArray = [Int32](repeating: 0, count: matrix.dimensions.minimum) var info: Int32 = 0 Matrix_OBJC.luDecomposition(ofFloatMatrix: &elementsList, nrOfRows: Int32(matrix.dimensions.rows), nrOfColumns: Int32(matrix.dimensions.columns), withPivotArray: &pivotArray, withInfo: &info) if info != 0 { return nil } let result = Matrix(elementsList: elementsList, columns: matrix.dimensions.rows).transpose //FIXME: L and U are always of the dimensions of result, which is not correct. let L = result.lowerTriangle L.resize(Dimensions(size: matrix.dimensions.rows)) L.fillDiagonal(1) let permutation = Permutation(identity: matrix.dimensions.minimum) for (index, element) in pivotArray.enumerated() { permutation.switchElements(Int(element-1), index) } permutation.inverseInPlace() return (L, result.upperTriangle, PermutationMatrix(permutation: permutation)) } /** Returns the LU decomposition of the given matrix. - parameter matrix: The matrix to compute the LU decomposition of. - returns: (L, U, P) A tuple containing three matrices. The first matrix is a lower triangular matrix with ones on the main diagonal. The second matrix is an upper triangular matrix and the third matrix is a permutations matrix. Here is A = PLU. */ public func LUDecomposition(_ matrix: Matrix<Double>) -> (Matrix<Double>, Matrix<Double>, PermutationMatrix<Double>)? { var elementsList = transpose(matrix).elementsList var pivotArray = [Int32](repeating: 0, count: matrix.dimensions.minimum) var info: Int32 = 0 Matrix_OBJC.luDecomposition(ofDoubleMatrix: &elementsList, nrOfRows: Int32(matrix.dimensions.rows), nrOfColumns: Int32(matrix.dimensions.columns), withPivotArray: &pivotArray, withInfo: &info) if info != 0 { return nil } let result = Matrix(elementsList: elementsList, columns: matrix.dimensions.rows).transpose //FIXME: L and U are always of the dimensions of result, which is not correct. let L = result.lowerTriangle L.resize(Dimensions(size: matrix.dimensions.rows)) L.fillDiagonal(1) let permutation = Permutation(identity: matrix.dimensions.minimum) for (index, element) in pivotArray.enumerated() { permutation.switchElements(Int(element-1), index) } permutation.inverseInPlace() return (L, result.upperTriangle, PermutationMatrix(permutation: permutation)) } // MARK: - Additional Structs // MARK: - MatrixGenerator /** A struct representing a generator for iterating over a matrix. */ public struct MatrixGenerator <T: MatrixCompatible> : IteratorProtocol { /** The generator of the elements list of the matrix. */ fileprivate var generator: IndexingIterator<Array<T>> /** Creates a new matrix generator to iterator over the given matrix. - parameter The: matrix to iterate over. */ public init(matrix: Matrix<T>) { self.generator = matrix.elementsList.makeIterator() } /** Returns the next element in the matrix or nil if there are no elements left. */ public mutating func next() -> T? { return self.generator.next() } } // MARK: - Index public struct Index: ExpressibleByArrayLiteral { public let row, column: Int public init(arrayLiteral elements: Int...) { if elements.count < 2 { NSException(name: NSExceptionName(rawValue: "Not enough elements provided"), reason: "Only \(elements.count) elements provided, but 2 elements needed for Index initialisation.", userInfo: nil).raise() } if elements.count > 2 { NSException(name: NSExceptionName(rawValue: "Too many elements provided"), reason: "\(elements.count) elements provided, but only 2 elements needed for Index initialisation.", userInfo: nil).raise() } self.row = elements[0] self.column = elements[1] } } // MARK: - Errors /** A struct containing the different types of Matrix errors. */ public enum MatrixError: Error { /** Caused by an index being out of bounds. - parameter received: The index passed by the user. - parameter allowedRange: The allowed range of indices. The error is thrown when the index does not lie in this range. - parameter description: A description describing what exactly went wrong. */ case indexOutOfBounds(received: Int, allowedRange: CountableClosedRange<Int>, description: String?) /** Caused by providing a wrong number of elements. - parameter received: The number passed by the user. - parameter expected: The expected number. - parameter description: A description describing what exactly went wrong. */ case wrongNumberOfElements(received: Int, expected: Int, description: String?) }
mit
68e7e7d74b490187dc140a086971d075
34.498248
258
0.604584
4.820032
false
false
false
false
hirokimu/EMTLoadingIndicator
EMTLoadingIndicator/Classes/EMTTimer.swift
1
1822
// // EMTTimer.swift // // Created by Hironobu Kimura on 2016/08/04. // Copyright (C) 2016 emotionale. All rights reserved. // import WatchKit typealias EMTTimerCallback = (Timer) -> Void public final class EMTTimer: NSObject { private var timer: EMTTimerInternal? private var callback: EMTTimerCallback init(interval: TimeInterval, callback: @escaping EMTTimerCallback, userInfo: AnyObject?, repeats: Bool) { self.callback = callback super.init() timer = EMTTimerInternal( interval: interval, callback: { [weak self] timer in self?.callback(timer) }, userInfo: userInfo, repeats: repeats) } func invalidate() { timer?.invalidate() } deinit { timer?.invalidate() } } internal class EMTTimerInternal: NSObject { private var timer: Timer? private var callback: (Timer) -> Void init(interval: TimeInterval, callback: @escaping EMTTimerCallback, userInfo: AnyObject?, repeats: Bool) { self.callback = callback super.init() self.timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: repeats ? #selector(repeatTimerFired(timer:)) : #selector(timerFired(timer:)), userInfo: userInfo, repeats: repeats) } @objc func repeatTimerFired(timer: Timer) { self.callback(timer) } @objc func timerFired(timer: Timer) { self.callback(timer) timer.invalidate() } func invalidate() { timer?.invalidate() } }
mit
de92fcfbd20de1092b9987017d73baf0
25.794118
130
0.545554
4.911051
false
false
false
false
Daniel-Lopez/EZSwiftExtensions
Sources/NSAttributedStringExtensions.swift
1
2184
// // NSAttributedStringExtensions.swift // EZSwiftExtensions // // Created by Lucas Farah on 18/02/16. // Copyright (c) 2016 Lucas Farah. All rights reserved. // import UIKit extension NSAttributedString { /// EZSE: Adds bold attribute to NSAttributedString and returns it func bold() -> NSAttributedString { guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self } let range = (self.string as NSString).rangeOfString(self.string) copy.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(UIFont.systemFontSize())], range: range) return copy } /// EZSE: Adds underline attribute to NSAttributedString and returns it func underline() -> NSAttributedString { guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self } let range = (self.string as NSString).rangeOfString(self.string) copy.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue], range: range) return copy } /// EZSE: Adds italic attribute to NSAttributedString and returns it func italic() -> NSAttributedString { guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self } let range = (self.string as NSString).rangeOfString(self.string) copy.addAttributes([NSFontAttributeName: UIFont.italicSystemFontOfSize(UIFont.systemFontSize())], range: range) return copy } /// EZSE: Adds color attribute to NSAttributedString and returns it func color(color: UIColor) -> NSAttributedString { guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self } let range = (self.string as NSString).rangeOfString(self.string) copy.addAttributes([NSForegroundColorAttributeName: color], range: range) return copy } } /// EZSE: Appends one NSAttributedString to another NSAttributedString and returns it public func += (inout left: NSAttributedString, right: NSAttributedString) { let ns = NSMutableAttributedString(attributedString: left) ns.appendAttributedString(right) left = ns }
mit
506f9f41b423b73cc9ca71e2549fcc47
40.207547
119
0.719322
5.25
false
false
false
false
bmsimons/itunescli
itunescli/main.swift
1
1182
// // main.swift // itunescli // // Created by Bart Simons on 25/04/2017. // Copyright © 2017 Bart Simons. All rights reserved. // import Foundation let arguments = CommandLine.arguments if (arguments.count == 1) { printHelp() } else if (arguments.count >= 2) { if (arguments[1] == "pause") { pauseSong() } if (arguments[1] == "play") { playSong() } if (arguments[1] == "playlists") { getPlaylists() } if (arguments[1] == "info") { print(currentSongInfo()) } if (arguments[1] == "volume") { if (arguments.count == 3) { let volumeString: String = arguments[2] let volumeInteger = Int(volumeString) if (volumeInteger != nil) { setVolume(volume: volumeInteger!) } } else { print(getVolume()) } } if (arguments[1] == "delplaylist") { delPlaylist(specifiedPlaylist: arguments[2]) } if (arguments[1] == "playlisttracks") { getPlaylistTracks(specifiedPlaylist: arguments[2]) } }
gpl-3.0
c6379145c4ef8e33b6a612074bf0cde0
17.169231
58
0.502117
3.846906
false
false
false
false
andykkt/BFWControls
BFWControls/Modules/Layer/View/UIView+Layer.swift
1
1564
// // LayerView.swift // BFWControls // // Created by Tom Brodhurst-Hill on 9/01/2016. // Copyright © 2016 BareFeetWare. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit public extension UIView { public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } public var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } public var borderColor: UIColor? { get { return layer.borderColor.map { UIColor(cgColor: $0) } } set { layer.borderColor = newValue?.cgColor } } public var shadowColor: UIColor? { get { return layer.shadowColor.map { UIColor(cgColor: $0) } } set { layer.shadowColor = newValue?.cgColor } } public var shadowOffset: CGSize { get { return layer.shadowOffset } set { layer.shadowOffset = newValue } } public var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } public var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } }
mit
b0b7839f22c0894d01a81bd102f3c645
19.298701
71
0.502879
5.074675
false
false
false
false
paulgriffiths/macplanetpos
MacAstroTests/OrbitalElementsTests.swift
1
3030
// // OrbitalElementsTests.swift // MacAstro // // Created by Paul Griffiths on 5/3/15. // Copyright (c) 2015 Paul Griffiths. All rights reserved. // import Cocoa import XCTest private let accuracy = 1e-6 class OrbitalElementsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testHelioOrbCoords() { let oe = PointOrbitalElements(sma: 1.5237098724978781, ecc: 0.09339210495304585, inc: 0.03228679757582795, ml: -8.535041810818056, lp: -0.4180914976406765, lan: 0.8651063792705691); let hoc = oe.helioOrbCoords() XCTAssertEqualWithAccuracy(-0.6657481021889328, hoc.x, accuracy: accuracy) XCTAssertEqualWithAccuracy(-1.424723224035724, hoc.y, accuracy: accuracy) XCTAssertEqualWithAccuracy(1.5725955616988474, hoc.z, accuracy: accuracy) } func testHelioEclCoords() { let oe = PointOrbitalElements(sma: 0.7233349755491102, ecc: 0.006783927794370295, inc: 0.0592506905566204, ml: -176.0672590160593, lp: 2.296888136969044, lan: 1.3391663154600715); let hec = oe.helioEclCoords() XCTAssertEqualWithAccuracy(0.7180208300043192, hec.x, accuracy: accuracy) XCTAssertEqualWithAccuracy(-0.10607733560942739, hec.y, accuracy: accuracy) XCTAssertEqualWithAccuracy(-0.04290011049715045, hec.z, accuracy: accuracy) } func testDateOrbitalElementsMars() { if let date = getUTCDate(1997, month: 6, day: 21, hour: 0, minute: 0, second: 0) { let oe = J2000DateElements.newElementsForPlanet(.Mars, date: date) let hoc = oe.helioOrbCoords() XCTAssertEqualWithAccuracy(-0.6657481021889328, hoc.x, accuracy: accuracy) XCTAssertEqualWithAccuracy(-1.424723224035724, hoc.y, accuracy: accuracy) XCTAssertEqualWithAccuracy(1.5725955616988474, hoc.z, accuracy: accuracy) } else { XCTFail("Couldn't get date") } } func testDateOrbitalElementsVenus() { if let date = getUTCDate(1982, month: 6, day: 14, hour: 8, minute: 30, second: 0) { let oe = J2000DateElements.newElementsForPlanet(.Venus, date: date) let hec = oe.helioEclCoords() XCTAssertEqualWithAccuracy(0.7180208300043192, hec.x, accuracy: accuracy) XCTAssertEqualWithAccuracy(-0.10607733560942739, hec.y, accuracy: accuracy) XCTAssertEqualWithAccuracy(-0.04290011049715045, hec.z, accuracy: accuracy) } else { XCTFail("Couldn't get date") } } }
gpl-3.0
b74fb2abcf7e89c9934198531f717c2e
39.4
111
0.630363
3.7875
false
true
false
false
sarvex/SwiftRecepies
Basics/Grouping Compact Options with UISegmentedControl/Grouping Compact Options with UISegmentedControl/ViewController.swift
1
3810
// // ViewController.swift // Grouping Compact Options with UISegmentedControl // // Created by Vandad Nahavandipoor on 6/28/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 /* 1 */ //import UIKit // //class ViewController: UIViewController { // // var segmentedControl:UISegmentedControl! // // override func viewDidLoad() { // super.viewDidLoad() // // let segments = [ // "iPhone", // "iPad", // "iPod", // "iMac"] // // segmentedControl = UISegmentedControl(items: segments) // segmentedControl.center = view.center // self.view.addSubview(segmentedControl) // // } // //} /* 2 */ //import UIKit // //class ViewController: UIViewController { // // var segmentedControl:UISegmentedControl! // // func segmentedControlValueChanged(sender: UISegmentedControl){ // // let selectedSegmentIndex = sender.selectedSegmentIndex // // let selectedSegmentText = // sender.titleForSegmentAtIndex(selectedSegmentIndex) // // println("Segment \(selectedSegmentIndex) with text" + // " of \(selectedSegmentText) is selected") // } // // override func viewDidLoad() { // super.viewDidLoad() // // let segments = [ // "iPhone", // "iPad", // "iPod", // "iMac"] // // segmentedControl = UISegmentedControl(items: segments) // segmentedControl.center = view.center // // segmentedControl.addTarget(self, // action: "segmentedControlValueChanged:", // forControlEvents: .ValueChanged) // // self.view.addSubview(segmentedControl) // // } // //} /* 3 */ //import UIKit // //class ViewController: UIViewController { // // var segmentedControl:UISegmentedControl! // // func segmentedControlValueChanged(sender: UISegmentedControl){ // // let selectedSegmentIndex = sender.selectedSegmentIndex // // let selectedSegmentText = // sender.titleForSegmentAtIndex(selectedSegmentIndex) // // println("Segment \(selectedSegmentIndex) with text" + // " of \(selectedSegmentText) is selected") // } // // override func viewDidLoad() { // super.viewDidLoad() // // let segments = [ // "iPhone", // "iPad", // "iPod", // "iMac"] // // segmentedControl = UISegmentedControl(items: segments) // segmentedControl.center = view.center // segmentedControl.momentary = true // segmentedControl.addTarget(self, // action: "segmentedControlValueChanged:", // forControlEvents: .ValueChanged) // // self.view.addSubview(segmentedControl) // // } // //} /* 4 */ import UIKit class ViewController: UIViewController { var segmentedControl:UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() let segments = [ "Red", UIImage(named: "blueDot")!, "Green", "Yellow"] segmentedControl = UISegmentedControl(items: segments) segmentedControl.center = view.center self.view.addSubview(segmentedControl) } }
isc
00daec0e81d470b164088f1764469443
24.4
83
0.654331
4.031746
false
false
false
false
Ascoware/get-iplayer-automator
ITVDownload.swift
1
13762
// // ITVDownload.swift // Get iPlayer Automator // // Created by Scott Kovatch on 1/1/18. // import Foundation import Kanna import SwiftyJSON import CocoaLumberjackSwift @objc public class ITVDownload : Download { override public var description: String { return "ITV Download (ID=\(show.pid))" } @objc public init(programme: Programme, proxy: HTTPProxy?) { super.init() self.proxy = proxy self.show = programme self.defaultsPrefix = "ITV_" self.downloadPath = UserDefaults.standard.string(forKey: "DownloadPath") ?? "" self.running = true setCurrentProgress("Retrieving Programme Metadata... \(show.showName)") setPercentage(102) programme.status = "Initialising..." DDLogInfo("Downloading \(show.showName)") DispatchQueue.main.async { guard let requestURL = URL(string: self.show.url) else { return } self.currentRequest?.cancel() var downloadRequest = URLRequest(url:requestURL) downloadRequest.timeoutInterval = 10 var session = URLSession.shared if let proxy = self.proxy { // Create an NSURLSessionConfiguration that uses the proxy var proxyDict: [AnyHashable : Any] = [kCFNetworkProxiesHTTPEnable : true, kCFNetworkProxiesHTTPProxy : proxy.host, kCFNetworkProxiesHTTPPort : proxy.port, kCFNetworkProxiesHTTPSEnable : true, kCFNetworkProxiesHTTPSProxy : proxy.host, kCFNetworkProxiesHTTPSPort : proxy.port] if let user = proxy.user, let password = proxy.password { proxyDict[kCFProxyUsernameKey] = user proxyDict[kCFProxyPasswordKey] = password } let configuration = URLSessionConfiguration.ephemeral configuration.connectionProxyDictionary = proxyDict // Create a NSURLSession with our proxy aware configuration session = URLSession(configuration:configuration, delegate:nil, delegateQueue:OperationQueue.main) } DDLogVerbose("ITV: Requesting Metadata") self.currentRequest = session.dataTask(with: downloadRequest) { (data, response, error) in if let httpResponse = response as? HTTPURLResponse { self.metaRequestFinished(response: httpResponse, data: data, error: error) } } self.currentRequest?.resume() } } func metaRequestFinished(response: HTTPURLResponse, data: Data?, error: Error?) { guard self.running else { return } guard response.statusCode != 0 || response.statusCode == 200, let data = data, let responseString = String(data:data, encoding:.utf8) else { var message: String = "" if response.statusCode == 0 { message = "ERROR: No response received (probably a proxy issue): \(error?.localizedDescription ?? "Unknown error")" self.show.reasonForFailure = "Internet_Connection" self.show.status = "Failed: Bad Proxy" } else { message = "ERROR: Could not retrieve programme metadata: \(error?.localizedDescription ?? "Unknown error")" self.show.status = "Download Failed" } self.show.successful = false self.show.complete = true DDLogError(message) NotificationCenter.default.post(name: NSNotification.Name(rawValue:"DownloadFinished"), object:self.show) return } DDLogDebug("DEBUG: Metadata response status code: \(response.statusCode)") let showMetadata = ITVMetadataExtractor.getShowMetadata(htmlPageContent: responseString) self.show.desc = showMetadata.desc self.show.episode = showMetadata.episode self.show.season = showMetadata.season self.show.episodeName = showMetadata.episodeName self.show.thumbnailURLString = showMetadata.thumbnailURLString DDLogInfo("INFO: Metadata processed.") //Create Download Path self.createDownloadPath() // show.path will be set when youtube-dl tells us the destination. DispatchQueue.main.async { self.launchYoutubeDL() } } @objc public func youtubeDLProgress(progressNotification: Notification?) { guard let fileHandle = progressNotification?.object as? FileHandle else { return } guard let data = progressNotification?.userInfo?[NSFileHandleNotificationDataItem] as? Data, data.count > 0, let s = String(data: data, encoding: .utf8) else { return } fileHandle.readInBackgroundAndNotify() let lines = s.components(separatedBy: .newlines) for line in lines { DDLogInfo(line) if line.contains("Writing video subtitles") { //ITV Download (ID=2a4910a0046): [info] Writing video subtitles to: /Users/skovatch/Movies/TV Shows/LA Story/LA Story - Just Friends - 2a4910a0046.en.vtt let scanner = Scanner(string: line) scanner.scanUpToString("to: ") scanner.scanString("to: ") subtitlePath = scanner.scanUpToString("\n") ?? "" DDLogDebug("Subtitle path = \(subtitlePath)") } if line.contains("Destination: ") { let scanner = Scanner(string: line) scanner.scanUpToString("Destination: ") scanner.scanString("Destination: ") self.show.path = scanner.scanUpToString("\n") ?? "" DDLogDebug("Downloading to \(self.show.path)") } // youtube-dl native download generates a percentage complete and ETA remaining var progress: String? = nil var remaining: String? = nil if line.contains("[download]") { let scanner = Scanner(string: line) scanner.scanUpToString("[download]") scanner.scanString("[download]") progress = scanner.scanUpToString("%")?.trimmingCharacters(in: .whitespaces) scanner.scanUpToString("ETA ") scanner.scanString("ETA ") remaining = scanner.scanUpToCharactersFromSet(set: .whitespacesAndNewlines) if let progress = progress, let progressVal = Double(progress) { setPercentage(progressVal) show.status = "Downloaded \(progress)%" } if let remaining = remaining { setCurrentProgress("Downloading \(show.showName) -- \(remaining) until done") } } if line.hasSuffix("has already been downloaded") { let scanner = Scanner(string: line) scanner.scanUpToString("[download]") scanner.scanString("[download]") self.show.path = scanner.scanUpToString("has already been downloaded")?.trimmingCharacters(in: .whitespaces) ?? "" } if line.hasPrefix("WARNING: Failed to download m3u8 information") { self.show.reasonForFailure = "proxy" } } } public func youtubeDLTaskFinished(_ proc: Process) { DDLogInfo("yt-dlp finished downloading") self.task = nil self.pipe = nil self.errorPipe = nil let exitCode = proc.terminationStatus if exitCode == 0 { self.show.complete = true self.show.successful = true let info = ["Programme" : self.show] DispatchQueue.main.async { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "AddProgToHistory"), object:self, userInfo:info) self.youtubeDLFinishedDownload() } } else { self.show.complete = true self.show.successful = false // Something went wrong inside youtube-dl. NotificationCenter.default.removeObserver(self) NotificationCenter.default.post(name: NSNotification.Name(rawValue:"DownloadFinished"), object:self.show) } } @objc public func youtubeDLFinishedDownload() { if UserDefaults.standard.bool(forKey: "TagShows") { tagDownloadWithMetadata() } else { atomicParsleyFinished(nil) } } private func launchYoutubeDL() { setCurrentProgress("Downloading \(show.showName)") setPercentage(102) show.status = "Downloading..." task = Process() pipe = Pipe() errorPipe = Pipe() task?.standardInput = FileHandle.nullDevice task?.standardOutput = pipe task?.standardError = errorPipe let fh = pipe?.fileHandleForReading let errorFh = errorPipe?.fileHandleForReading guard let youtubeDLFolder = Bundle.main.path(forResource: "yt-dlp_macos", ofType:nil), let cacertFile = Bundle.main.url(forResource: "cacert", withExtension: "pem") else { return } let youtubeDLBinary = youtubeDLFolder + "/yt-dlp_macos" var args: [String] = [show.url, "--user-agent", "Mozilla/5.0", "-f", "mp4/best", "-o", downloadPath] if UserDefaults.standard.bool(forKey: "DownloadSubtitles") { args.append("--write-sub") if UserDefaults.standard.bool(forKey: "EmbedSubtitles") { args.append("--embed-subs") } else { args.append("-k") } } if UserDefaults.standard.bool(forKey: "Verbose") { args.append("--verbose") } if UserDefaults.standard.bool(forKey: "TagShows") { args.append("--embed-thumbnail") } if let proxyHost = self.proxy?.host { var proxyString = "" if let user = self.proxy?.user, let password = self.proxy?.password { proxyString += "\(user):\(password)@" } proxyString += proxyHost if let port = self.proxy?.port { proxyString += ":\(port)" } args.append("--proxy") args.append(proxyString) } DDLogVerbose("DEBUG: youtube-dl args:\(args)") task?.launchPath = youtubeDLBinary task?.arguments = args let extraBinaryPath = AppController.shared().extraBinariesPath var envVariableDictionary = [String : String]() envVariableDictionary["PATH"] = "\(youtubeDLFolder):\(extraBinaryPath)" envVariableDictionary["SSL_CERT_FILE"] = cacertFile.path task?.environment = envVariableDictionary DDLogVerbose("DEBUG: youtube-dl environment: \(envVariableDictionary)") NotificationCenter.default.addObserver(self, selector: #selector(self.youtubeDLProgress), name: FileHandle.readCompletionNotification, object: fh) NotificationCenter.default.addObserver(self, selector: #selector(self.youtubeDLProgress), name: FileHandle.readCompletionNotification, object: errorFh) task?.terminationHandler = youtubeDLTaskFinished task?.launch() fh?.readInBackgroundAndNotify() errorFh?.readInBackgroundAndNotify() } func createDownloadPath() { var fileName = show.showName // XBMC naming is always used on ITV shows to ensure unique names. if !show.seriesName.isEmpty { fileName = show.seriesName; } if show.season == 0 { show.season = 1 if show.episode == 0 { show.episode = 1 } } let format = !show.episodeName.isEmpty ? "%@.s%02lde%02ld.%@" : "%@.s%02lde%02ld" fileName = String(format: format, fileName, show.season, show.episode, show.episodeName) //Create Download Path var dirName = show.seriesName if dirName.isEmpty { dirName = show.showName } downloadPath = UserDefaults.standard.string(forKey:"DownloadPath") ?? "" dirName = dirName.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: " -") downloadPath = (downloadPath as NSString).appendingPathComponent(dirName) var filepart = String(format:"%@.%%(ext)s",fileName).replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: " -") do { try FileManager.default.createDirectory(atPath: downloadPath, withIntermediateDirectories: true) let dateRegex = try NSRegularExpression(pattern: "(\\d{2})[-_](\\d{2})[-_](\\d{4})") filepart = dateRegex.stringByReplacingMatches(in: filepart, range: NSRange(location: 0, length: filepart.count), withTemplate: "$3-$2-$1") } catch { DDLogError("Failed to create download directory! ") } downloadPath = (downloadPath as NSString).appendingPathComponent(filepart) } }
gpl-3.0
7a04130cdf9fe219e74909a8d50c1c51
37.875706
169
0.572809
5.150449
false
false
false
false
sseitov/v-Chess-Swift
v-Chess/Model/AppUser+CoreDataClass.swift
1
2997
// // AppUser+CoreDataClass.swift // v-Chess // // Created by Сергей Сейтов on 25.06.17. // Copyright © 2017 V-Channel. All rights reserved. // import Foundation import CoreData import Firebase import CoreData import SDWebImage enum SocialType:Int { case email = 0 case facebook = 1 case google = 2 } enum AvailableStatus:Int { case closed = 0 case available = 1 case invited = 2 case playing = 3 } public class AppUser: NSManagedObject { lazy var socialType: SocialType = { if let val = SocialType(rawValue: Int(self.accountType)) { return val } else { return .email } }() func socialTypeName() -> String { switch socialType { case .email: return "Email" case .facebook: return "Facebook" case .google: return "Google +" } } func setAvailable(_ status:AvailableStatus, onlineGame:String? = nil) { availableStatus = Int16(status.rawValue) Model.shared.saveContext() let ref = Database.database().reference() var data:[String:Any] = ["status": status.rawValue] if onlineGame != nil { data["game"] = onlineGame! } ref.child("available").child(uid!).setValue(data) } func isAvailable() -> Bool { return (availableStatus > 0) } func getData() -> [String:Any] { var profile:[String : Any] = ["socialType" : Int(accountType)] if email != nil { profile["email"] = email! } if name != nil { profile["name"] = name! } if avatarURL != nil { profile["avatarURL"] = avatarURL! } return profile } func setData(_ profile:[String : Any], completion: @escaping() -> ()) { if let typeVal = profile["socialType"] as? Int { accountType = Int16(typeVal) } else { accountType = 0 } email = profile["email"] as? String name = profile["name"] as? String avatarURL = profile["avatarURL"] as? String if avatarURL != nil { if accountType > 0, let url = URL(string: avatarURL!) { SDWebImageDownloader.shared().downloadImage(with: url, options: [], progress: nil, completed: { _, data, error, _ in self.avatar = data as NSData? Model.shared.saveContext() completion() }) } else { let ref = Model.shared.storageRef.child(avatarURL!) ref.getData(maxSize: INT64_MAX, completion: { data, error in self.avatar = data as NSData? Model.shared.saveContext() completion() }) } } else { avatar = nil completion() } } }
gpl-3.0
8738e4ef83e0b47b3cf9d76de4176fe5
25.642857
132
0.517091
4.569678
false
false
false
false
mozilla-mobile/firefox-ios
WidgetKit/Helpers.swift
2
1432
// 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 SwiftUI import UIKit import Shared var scheme: String { return URL.mozInternalScheme } func linkToContainingApp(_ urlSuffix: String = "", query: String) -> URL { let urlString = "\(scheme)://\(query)\(urlSuffix)" return URL(string: urlString)! } func getImageForUrl(_ url: URL, completion: @escaping (Image?) -> Void) { let queue = DispatchQueue.global() var fetchImageWork: DispatchWorkItem? fetchImageWork = DispatchWorkItem { if let data = try? Data(contentsOf: url) { if let image = UIImage(data: data) { DispatchQueue.main.async { if fetchImageWork?.isCancelled == true { return } completion(Image(uiImage: image)) fetchImageWork = nil } } } } if let imageWork = fetchImageWork { queue.async(execute: imageWork) } // Timeout the favicon fetch request if it's taking too long queue.asyncAfter(deadline: .now() + 2) { // If we've already successfully called the completion block, early return if fetchImageWork == nil { return } fetchImageWork?.cancel() completion(nil) } }
mpl-2.0
9c92327fafa428767c392b9ba649d481
28.22449
82
0.621508
4.447205
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Home/CustomizeHome/CustomizeHomepageSectionViewModel.swift
2
2560
// 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 /// Customize button is always present at the bottom of the page class CustomizeHomepageSectionViewModel { var theme: Theme var onTapAction: ((UIButton) -> Void)? init(theme: Theme) { self.theme = theme } } // MARK: HomeViewModelProtocol extension CustomizeHomepageSectionViewModel: HomepageViewModelProtocol { var sectionType: HomepageSectionType { return .customizeHome } var headerViewModel: LabelButtonHeaderViewModel { return .emptyHeader } func section(for traitCollection: UITraitCollection) -> NSCollectionLayoutSection { let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(100)) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(100)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 1) let leadingInset = HomepageViewModel.UX.leadingInset(traitCollection: traitCollection) let section = NSCollectionLayoutSection(group: group) section.contentInsets = NSDirectionalEdgeInsets( top: 0, leading: leadingInset, bottom: HomepageViewModel.UX.spacingBetweenSections, trailing: 0) return section } func numberOfItemsInSection() -> Int { return 1 } var isEnabled: Bool { return true } func refreshData(for traitCollection: UITraitCollection, isPortrait: Bool = UIWindow.isPortrait, device: UIUserInterfaceIdiom = UIDevice.current.userInterfaceIdiom) {} func setTheme(theme: Theme) { self.theme = theme } } // MARK: FxHomeSectionHandler extension CustomizeHomepageSectionViewModel: HomepageSectionHandler { func configure(_ cell: UICollectionViewCell, at indexPath: IndexPath) -> UICollectionViewCell { guard let customizeHomeCell = cell as? CustomizeHomepageSectionCell else { return UICollectionViewCell() } customizeHomeCell.configure(onTapAction: onTapAction, theme: theme) return customizeHomeCell } }
mpl-2.0
bc17493b351db6dafea8b884c603286a
33.594595
114
0.674609
5.458422
false
false
false
false
mrdepth/EVEOnlineAPI
EVEAPI/EVEAPI/CRAPI.swift
1
10008
// // CRAPI.swift // EVEAPI // // Created by Artem Shimanski on 06.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import Foundation import AFNetworking public enum CRAPIError: Error { case internalError case invalidResponse case unauthorized(String?) case server(String?, String?) case serviceUnavailable(String?) } public struct CRScope { public static let characterFittingsRead = CRScope("characterFittingsRead") public static let characterFittingsWrite = CRScope("characterFittingsWrite") public static let characterKillsRead = CRScope("characterKillsRead") let rawValue: String init(_ value: String) { rawValue = value } public static var all: [CRScope] { get { return [.characterFittingsRead, .characterFittingsWrite, .characterKillsRead] } } } public class CRAPI: NSObject { public let cachePolicy: URLRequest.CachePolicy public let token: OAuth2Token? public lazy var sessionManager: EVEHTTPSessionManager = { let manager = EVEHTTPSessionManager(baseURL: URL(string: "https://crest.eveonline.com")!, sessionConfiguration: nil) manager.responseSerializer = AFJSONResponseSerializer() manager.requestSerializer = AFHTTPRequestSerializer() manager.requestSerializer.cachePolicy = self.cachePolicy if let token = self.token { manager.requestSerializer.setValue("\(token.tokenType) \(token.accessToken)", forHTTPHeaderField: "Authorization") } return manager }() public init(token: OAuth2Token?, cachePolicy: URLRequest.CachePolicy) { if token?.tokenType != nil && token?.accessToken != nil { self.token = token } else { self.token = nil } self.cachePolicy = cachePolicy super.init() } // public class func oauth(clientID: String, secretKey: String, callbackURL: URL, scope: [CRScope]) -> OAuth { // let scope = scope.map {$0.rawValue} // return OAuth(clientID: clientID, secretKey: secretKey, callbackURL: callbackURL, scope: scope, realm: nil) // } public func fittings(completionBlock:((CRFittingCollection?, Error?) -> Void)?) { if let token = token { get("characters/\(token.characterID)/fittings/", parameters: nil, completionBlock: completionBlock) } else { completionBlock?(nil, CRAPIError.unauthorized(nil)) } //get("CalendarEventAttendees", scope: "Char", parameters: nil, completionBlock: completionBlock) } //MARK: Private private func validate<T:CRResult>(result: Any?) throws -> T { if let array = result as? [Any] { let result = ["items": array] if let obj = T.init(dictionary:result) { return obj } else { throw CRAPIError.invalidResponse } } else if let result = result as? [String: Any] { if let exceptionType = result["exceptionType"] as? String { let message = result["message"] as? String switch exceptionType { case "UnauthorizedError": throw CRAPIError.unauthorized(message) case "ServiceUnavailableError": throw CRAPIError.serviceUnavailable(message) default: throw CRAPIError.server(exceptionType, message) } } else if let obj = T.init(dictionary:result) { return obj } else { throw CRAPIError.invalidResponse } } else { throw CRAPIError.internalError } } private func get<T:CRResult>(_ path: String, parameters: [String:Any]?, completionBlock: ((T?, Error?) -> Void)?) -> Void { /*let contentType = "\(T.contentType); charset=utf-8" self.sessionManager.requestSerializer.setValue(contentType, forHTTPHeaderField: "Accept") self.sessionManager.responseSerializer.acceptableContentTypes = nil self.sessionManager.get(path, parameters: parameters, responseSerializer: nil, completionBlock: {(result, error) -> Void in if let error = error { completionBlock?(nil, error) } else { do { let obj: T = try self.validate(result: result) completionBlock?(obj, nil) } catch CRAPIError.unauthorized(let message) { if let token = self.token { token.refresh(completionBlock: { (error) in if let error = error { completionBlock?(nil, error) } else { self.sessionManager.requestSerializer.setValue("\(token.tokenType) \(token.accessToken)", forHTTPHeaderField: "Authorization") self.sessionManager.requestSerializer.setValue(contentType, forHTTPHeaderField: "Accept") self.sessionManager.responseSerializer.acceptableContentTypes = Set([T.contentType]) self.sessionManager.get(path, parameters: parameters, responseSerializer: nil, completionBlock: {(result, error) -> Void in if let error = error { completionBlock?(nil, error) } else { do { let obj: T = try self.validate(result: result) completionBlock?(obj, nil) } catch let error { completionBlock?(nil, error) } } }) } }) } else { completionBlock?(nil, CRAPIError.unauthorized(message)) } } catch let error { completionBlock?(nil, error ?? CRAPIError.internalError) } } }) */ } } /* Requested Scopes List characterAccountRead: Read your account subscription status. characterAssetsRead: Read your asset list. characterBookmarksRead: List your bookmarks and their coordinates. characterCalendarRead: Read your calendar events and attendees. characterChatChannelsRead: List chat channels you own or operate. characterClonesRead: List your jump clones, implants, attributes, and jump fatigue timer. characterContactsRead: Allows access to reading your characters contacts. characterContactsWrite: Allows applications to add, modify, and delete contacts for your character. characterContractsRead: Read your contracts. characterFactionalWarfareRead: Read your factional warfare statistics. characterFittingsRead: Allows an application to view all of your character's saved fits. characterFittingsWrite: Allows an application to create and delete the saved fits for your character. characterIndustryJobsRead: List your industry jobs. characterKillsRead: Read your kill mails. characterLocationRead: Allows an application to read your characters real time location in EVE. characterLoyaltyPointsRead: List loyalty points your character has for the different corporations. characterMailRead: Read your EVE Mail. characterMarketOrdersRead: Read your market orders. characterMedalsRead: List your public and private medals. characterNavigationWrite: Allows an application to set your ships autopilot destination. characterNotificationsRead: Receive in-game notifications. characterOpportunitiesRead: List the opportunities your character has completed. characterResearchRead: List your research agents working for you and research progress. characterSkillsRead: Read your skills and skill queue. characterStatsRead: Yearly aggregated stats about your character. characterWalletRead: Read your wallet status, transaction, and journal history. corporationAssetsRead: Read your corporation's asset list. corporationBookmarksRead: List your corporation's bookmarks and their coordinates. corporationContactsRead: Read your corporation’s contact list and standings corporationContractsRead: List your corporation's contracts. corporationFactionalWarfareRead: Read your corporation's factional warfare statistics. corporationIndustryJobsRead: List your corporation's industry jobs. corporationKillsRead: Read your corporation's kill mails. corporationMarketOrdersRead: List your corporation's market orders. corporationMedalsRead: List your corporation's issued medals. corporationMembersRead: List your corporation's members, their titles, and roles. corporationShareholdersRead: List your corporation's shareholders and their shares. corporationStructuresRead: List your corporation's structures, outposts, and starbases. corporationWalletRead: Read your corporation's wallet status, transaction, and journal history. fleetRead: Allows real time reading of your fleet information (members, ship types, etc.) if you're the boss of the fleet. fleetWrite: Allows the ability to invite, kick, and update fleet information if you're the boss of the fleet. esi-planets.manage_planets.v1: Allows reading a list of a characters planetary colonies, and the details of those colonies publicData: Allows access to public data. esi-assets.read_assets.v1: Allows reading a list of assets that the character owns esi-calendar.read_calendar_events.v1: Allows reading a character's calendar, including corporation events esi-bookmarks.read_character_bookmarks.v1: Allows reading of a character's bookmarks and bookmark folders esi-wallet.read_character_wallet.v1: Allows reading of a character's wallet, journal and transaction history. esi-clones.read_clones.v1: Allows reading the locations of a character's jump clones and their implants. esi-characters.read_contacts.v1: Allows reading of a characters contacts list, and calculation of CSPA charges esi-corporations.read_corporation_membership.v1: Allows reading a list of the ID's and roles of a character's fellow corporation members esi-killmails.read_killmails.v1: Allows reading of a character's kills and losses esi-location.read_location.v1: Allows reading of a character's active ship location esi-location.read_ship_type.v1: Allows reading of a character's active ship class esi-skills.read_skillqueue.v1: Allows reading of a character's currently training skill queue. esi-skills.read_skills.v1: Allows reading of a character's currently known skills. esi-universe.read_structures.v1: Allows querying the location and type of structures that the character has docking access at. remoteClientUI: Allows applications to control the UI of your EVE Online client. esi-calendar.respond_calendar_events.v1: Allows updating of a character's calendar event responses esi-search.search_structures.v1: Allows searching over all structures that a character can see in the structure browser. structureVulnUpdate: Allows updating your structures' vulnerability timers. */
mit
f67cedc353c018d3ef71bfd8562531f8
41.75641
136
0.761319
4.144573
false
false
false
false
codepgq/LearningSwift
PresentTumblrAnimator/PresentTumblrAnimator/ViewController.swift
1
1994
// // ViewController.swift // PresentTumblrAnimator // // Created by ios on 16/9/23. // Copyright © 2016年 ios. All rights reserved. // import UIKit struct model { var icon = "animator1.jpg" var name = "default" var backImage = "animator1.jpg" } class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{ @IBOutlet weak var collectionView: UICollectionView! let data = [ model(icon: "Chat", name: "小明", backImage: "animator1.jpg"), model(icon: "Quote", name: "老王", backImage: "animator2.jpg"), model(icon: "Audio", name: "隔壁大叔", backImage: "animator3.jpg"), model(icon: "Link", name: "邻家淑女", backImage: "animator4.jpg") ] override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } @IBAction func unwindToMainViewController (sender: UIStoryboardSegue){ self.dismissViewControllerAnimated(true, completion: nil) } } extension ViewController { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return 10 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collCell", forIndexPath: indexPath) as! CollectionViewCell let model = data[indexPath.row % 4] cell.backImage.image = UIImage(named: model.backImage) cell.icon.image = UIImage(named:model.icon) cell.nameLabel.text = model.name return cell } }
apache-2.0
a9fb8ce29d8d07e2eabca8bcccfff079
29.734375
132
0.671581
4.785888
false
false
false
false
duck57/Swift-Euchre
Swift Euchre/Card Core/Deck.swift
1
3039
// // Deck.swift // Swift Euchre // // Created by Chris Matlak on 12/6/15. // Copyright © 2015 Euchre US!. All rights reserved. // import Foundation class Deck: CardCollection { // Make Deck var collective = [Card]() convenience required init() { self.init() } init(_ lowRank: Int, _ highRank: Int, number: Int?=1) { for _ in 1...number! { for suit in 1...4 { for rank in lowRank...highRank { collective.append(Card(rnk: rank, sut: suit)) } } } } convenience init(lowRank: Rank, highRank: Rank, number: Int?=1) { self.init(lowRank.rawValue, highRank.rawValue, number: number) } // Deal func deal(hands: [Player], var kitty: Hand?=nil, deadSize: Int?=0) { collective.shuffleInPlace() // Make sure the deal will work guard deadSize < self.count else { print("No cards dealt, as reserved card count (\(deadSize)) is more than the deck size (\(self.count)).") return } // Set aside a guaranteed number of cards that will not be dealt let loc = deadSize // Give all players an equivalent number of cards while self.count-deadSize! >= hands.count { for var player in hands { // is there a way to treat self like hand and use it as a var instead of a let? player.hand.append(self.collective.removeAtIndex(loc!)) } } // Everyone sort your hands! for var player in hands { player.sort() } // Shove the remaining cards into the kitty (if provided) /* If a kitty is not provided, all remaining cards will remain in the deck and be visible to AI. To have a separate kitty and discard piles, call this function twice */ guard kitty != nil else { return } for _ in self { kitty?.append(self.collective.removeFirst()) } } // Since Swift does not yet have splats /*func deal(hands: Hand..., kitty: Hand?, deadSize: Int?) { deal(hands, kitty: kitty, deadSize: deadSize) }*/ // can't even use this anyway, since trying to do so causes the compiler to segfault 11 } // Dislpay a deck extension Deck: CustomStringConvertible { var description: String { let lines = 4 let number = self.count / lines var out = "" for line in 0..<lines { for pos in 0..<number { out += self[line*number + pos].shortName() out += " " } out += "\n" } return out } } func makeEuchreDeck(number: Int?=1) -> Deck { return Deck.init(lowRank: (Rank).Nine, highRank: (Rank).HiAce, number: number!) } func makeDoubleEuchreDeck() -> Deck { return makeEuchreDeck(2) } func makePinochleDeck() -> Deck { return makeDoubleEuchreDeck() } func makeStandardDeck(number: Int?=1) -> Deck { return Deck.init(lowRank: (Rank).Two, highRank: (Rank).HiAce, number: number!) } enum deckType { case Poker, Standard, Euchre, DoubleEuchre, Pinochle, other func makeDeck() -> Deck { switch self { case Poker: return makeStandardDeck() case Standard: return makeStandardDeck() case DoubleEuchre: return makeDoubleEuchreDeck() case Pinochle: return makePinochleDeck() default: return Deck.init() } } }
isc
d5d09bc664d68636630acd05017fe4ab
23.909836
108
0.666228
3.084264
false
false
false
false
hujiaweibujidao/Gank
Gank/Class/Mine/AHPersonalPageViewController.swift
2
2554
// // AHPersonalPageViewController.swift // Gank // // Created by AHuaner on 2017/2/16. // Copyright © 2017年 CoderAhuan. All rights reserved. // import UIKit class AHPersonalPageViewController: BaseViewController { fileprivate lazy var tableView: UITableView = { let tabelView = UITableView(frame: CGRect(x: 0, y: 0, width: kScreen_W, height: kScreen_H - kNavBarHeight), style: .grouped) tabelView.backgroundColor = UIColorMainBG tabelView.delegate = self tabelView.dataSource = self tabelView.contentInset.bottom = kBottomBarHeight return tabelView }() override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.statusBarStyle = .default self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } fileprivate func setupUI() { title = "编辑个人主页" setNavigationBarStyle(BarColor: UIColor.white, backItemColor: .blue) view.addSubview(tableView) } } extension AHPersonalPageViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = cellForValue1() cell.textLabel?.text = "昵称" cell.detailTextLabel?.text = User.info?.object(forKey: "nickName") as? String return cell } fileprivate func cellForValue1() -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "personalCell") if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: "personalCell") cell!.accessoryType = .disclosureIndicator cell!.textLabel?.textColor = UIColorTextGray } return cell! } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 15 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let vc = AHUpdateNickViewController() navigationController?.pushViewController(vc, animated: true) } }
mit
de6627a98a819ea3b09291e40c03f617
29.542169
132
0.64931
5.162933
false
false
false
false
LoopKit/LoopKit
LoopKit/SampleValue.swift
1
3234
// // SampleValue.swift // Naterade // // Created by Nathan Racklyeft on 1/24/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit public protocol TimelineValue { var startDate: Date { get } var endDate: Date { get } } public extension TimelineValue { var endDate: Date { return startDate } } public protocol SampleValue: TimelineValue { var quantity: HKQuantity { get } } public extension Sequence where Element: TimelineValue { /** Returns the closest element in the sorted sequence prior to the specified date - parameter date: The date to use in the search - returns: The closest element, if any exist before the specified date */ func closestPrior(to date: Date) -> Iterator.Element? { return elementsAdjacent(to: date).before } /// Returns the elements immediately before and after the specified date /// /// - Parameter date: The date to use in the search /// - Returns: The closest elements, if found func elementsAdjacent(to date: Date) -> (before: Iterator.Element?, after: Iterator.Element?) { var before: Iterator.Element? var after: Iterator.Element? for value in self { if value.startDate <= date { before = value } else { after = value break } } return (before, after) } /// Returns all elements inmmediately adjacent to the specified date /// /// Use Sequence.elementsAdjacent(to:) if specific before/after references are necessary /// /// - Parameter date: The date to use in the search /// - Returns: The closest elements, if found func allElementsAdjacent(to date: Date) -> [Iterator.Element] { let (before, after) = elementsAdjacent(to: date) return [before, after].compactMap({ $0 }) } /** Returns an array of elements filtered by the specified date range. This behavior mimics HKQueryOptionNone, where the value must merely overlap the specified range, not strictly exist inside of it. - parameter startDate: The earliest date of elements to return - parameter endDate: The latest date of elements to return - returns: A new array of elements */ func filterDateRange(_ startDate: Date?, _ endDate: Date?) -> [Iterator.Element] { return filter { (value) -> Bool in if let startDate = startDate, value.endDate < startDate { return false } if let endDate = endDate, value.startDate > endDate { return false } return true } } } public extension Sequence where Element: SampleValue { func average(unit: HKUnit) -> HKQuantity? { let (sum, count) = reduce(into: (sum: 0.0, count: 0)) { result, element in result.0 += element.quantity.doubleValue(for: unit) result.1 += 1 } guard count > 0 else { return nil } let average = sum / Double(count) return HKQuantity(unit: unit, doubleValue: average) } }
mit
568db3166db7ed680a405eac45f89013
27.113043
101
0.610578
4.665224
false
false
false
false
UIKonf/uikonf-app
UIKonfApp/UIKonfApp/Cells.swift
1
8618
// // Cells.swift // UIKonfApp // // Created by Maxim Zaks on 15.02.15. // Copyright (c) 2015 Maxim Zaks. All rights reserved. // import Foundation import UIKit import Entitas protocol EntityCell { func updateWithEntity(entity : Entity, context : Context) } class EventCell: UITableViewCell, EntityCell { @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var lineImage: UIImageView! weak var entity : Entity! var startTime : NSTimeInterval! var endTime : NSTimeInterval! var timer : NSTimer! func updateWithEntity(entity : Entity, context : Context){ descriptionLabel.text = entity.get(DescriptionComponent)?.description let startDate = entity.get(StartTimeComponent)!.date let endDate = entity.get(EndTimeComponent)!.date self.startTime = startDate.timeIntervalSince1970 self.endTime = endDate.timeIntervalSince1970 let dateFormater = NSDateFormatter() dateFormater.setLocalizedDateFormatFromTemplate("ddMMM") let dateString = dateFormater.stringFromDate(startDate) dateFormater.setLocalizedDateFormatFromTemplate("hhmm") let startTimeString = dateFormater.stringFromDate(startDate) let endTimeString = dateFormater.stringFromDate(endDate) dateLabel.text = "\(dateString)\n\(startTimeString) - \(endTimeString)" self.entity = entity if(timer == nil){ timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("setupLine"), userInfo: nil, repeats: true) } setupLine() } func setupLine(){ let now = NSDate().timeIntervalSince1970 if now >= startTime && now < endTime { let factorElapsed = CGFloat((now - startTime) / (endTime - startTime)) let cellHeight = self.frame.height let cellWidth = self.frame.width self.lineImage.frame = CGRect(x: 15, y: cellHeight * factorElapsed, width: cellWidth - 20, height: 1) self.lineImage!.hidden = false } else { self.lineImage!.hidden = true } } } class BeforeConferenceCell: UITableViewCell, EntityCell { @IBOutlet weak var countDownLabel: UILabel! func updateWithEntity(entity : Entity, context : Context){ let endDate = entity.get(EndTimeComponent)!.date let secondsLeft = Int(endDate.timeIntervalSinceReferenceDate - NSDate.timeIntervalSinceReferenceDate()) let secondsInHour = 60*60 let secondsInDay = secondsInHour*24 let count : Int let sufix : String switch secondsLeft { case _ where secondsLeft / secondsInDay > 0 : count = secondsLeft / secondsInDay sufix = count == 1 ? "day" : "days" case _ where secondsLeft / secondsInHour > 0 : count = secondsLeft / secondsInHour sufix = count == 1 ? "hour" : "hours" default : count = 0 sufix = "" } let timeText : String if secondsLeft <= 0 { timeText = "We started" } else { if count == 0 { timeText = "We will start shortly" } else { timeText = "\(count) \(sufix) to go..." } } countDownLabel.text = timeText } } class AfterConferenceCell: UITableViewCell, EntityCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! func updateWithEntity(entity : Entity, context : Context){ if let startDate = entity.get(StartTimeComponent)?.date { if NSDate().timeIntervalSince1970 >= startDate.timeIntervalSince1970 { titleLabel.text = "That's all folks!!!" descriptionLabel.text = "Don't forget to Send Ratings" } else { titleLabel.text = "Now scroll up!!!" descriptionLabel.text = "Or tap on the Now button" } } } } class TalkCell: UITableViewCell, EntityCell { @IBOutlet weak var talkTitleLabel: UILabel! @IBOutlet weak var speakerNameLabel: UILabel! @IBOutlet weak var speakerPhoto: UIImageView! @IBOutlet var stars: [UIButton]! private weak var context : Context! weak var personEntity : Entity? weak var talkEntity : Entity? lazy var photoManager : PhotoManager = PhotoManager(imageView: self.speakerPhoto) deinit { photoManager.disconnect() } func updateWithEntity(entity : Entity, context : Context){ self.context = context talkEntity = entity talkTitleLabel.text = entity.get(TitleComponent)!.title speakerNameLabel.text = "by \(entity.get(SpeakerNameComponent)!.name)" personEntity = Lookup.get(context).personLookup[entity.get(SpeakerNameComponent)!.name].first photoManager.entity = personEntity updateStars() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if context == nil || personEntity == nil { return } if selected { personEntity?.set(SelectedComponent()) } else { for e in context.entityGroup(Matcher.All(NameComponent, PhotoComponent, SelectedComponent)){ e.remove(SelectedComponent) } } } @IBAction func rate(sender : UIButton) { let selectedTimeSlot = context.entityGroup(Matcher.All(StartTimeComponent, SelectedComponent)).sortedEntities.first if let endTimeComponent = selectedTimeSlot?.get(EndTimeComponent) { println("Rated with: \(sender.tag)") if NSDate().timeIntervalSince1970 < endTimeComponent.date.timeIntervalSince1970 { let alertView = UIAlertView(title: "Don't cheat", message: "You can rate after session is over.", delegate: nil, cancelButtonTitle: "OK") alertView.show() } else { talkEntity?.set(RatingComponent(rating:sender.tag), overwrite: true) updateStars() } } } func updateStars(){ if let rating = talkEntity?.get(RatingComponent)?.rating { for button in stars { if rating >= button.tag { button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal) } else { button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) } } } } } class OrganizerCell: UITableViewCell, EntityCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var photoImageView: UIImageView! private weak var context : Context! weak var personEntity : Entity? lazy var photoManager : PhotoManager = PhotoManager(imageView: self.photoImageView) deinit { photoManager.disconnect() } func updateWithEntity(entity : Entity, context : Context){ self.context = context personEntity = entity nameLabel.text = personEntity!.get(NameComponent)!.name photoManager.entity = personEntity } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if context == nil || personEntity == nil { return } if selected { personEntity?.set(SelectedComponent()) } else { for e in context.entityGroup(Matcher.All(NameComponent, PhotoComponent, SelectedComponent)){ e.remove(SelectedComponent) } } } } class LocationCell: UITableViewCell, EntityCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UITextView! func updateWithEntity(entity : Entity, context : Context){ nameLabel.text = entity.get(NameComponent)!.name let descriptionText = entity.get(DescriptionComponent)?.description let address = entity.get(AddressComponent)!.address descriptionLabel.text = descriptionText != nil ? descriptionText! + "\n" + address : address } }
mit
5531fafc4614c76cff18c2420a356ca2
30.567766
153
0.602808
5.179087
false
false
false
false
skyfe79/RxGitSearch
RxGitSearch/scenes/SearchViewController.swift
1
4686
// // ViewController.swift // RxGitSearch // // Created by burt.k(Sungcheol Kim) on 2016. 2. 5.. // Copyright © 2016년 burt. All rights reserved. // // [email protected] // http://blog.burt.pe.kr // http://github.com/skyfe79 import UIKit import RxSwift import RxCocoa class SearchViewController: BaseViewController { // widgets @IBOutlet weak var tableView : UITableView! var searchBar: SearchBar! // vm var viewModel: SearchViewModel! deinit { searchBar = nil viewModel = nil } override func viewDidLoad() { super.viewDidLoad() setupViewModel() setupSearchBar() setupTableView() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) searchBar.resignFirstResponder() } override func setViewModel(viewModel: ViewModelType) { if let vm = viewModel as? SearchViewModel { self.viewModel = vm self.viewModel.activated() } } } extension SearchViewController { func setupViewModel() { viewModel = SearchViewModel() viewModel.activated() viewModel .rx_onError .asObservable() .observeOn(MainScheduler.instance) .subscribeOn(MainScheduler.instance) .subscribeNext { [unowned self] (error) -> Void in let alert = UIAlertController(title: error.localizedDescription, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { action in self.setupViewModel() self.setupSearchBar() alert.dismissViewControllerAnimated(true, completion: nil) }) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } .addDisposableTo(disposeBag) self.tableView.dataSource = viewModel.adapter viewModel .rx_updatedAdapter .subscribeOn(MainScheduler.instance) .subscribe { [unowned self] event in if let _ = event.element { self.tableView.reloadData() } } .addDisposableTo(disposeBag) } func setupSearchBar() { searchBar = SearchBar.view() self.navigationItem.titleView = searchBar searchBar.becomeFirstResponder() searchBar .rx_searchText .throttle(0.3, scheduler: MainScheduler.instance) .bindTo(viewModel.rx_fetchSearchSuggestRepository) .addDisposableTo(disposeBag) searchBar .rx_pressSearchButton .throttle(0.3, scheduler: MainScheduler.instance) .bindTo(viewModel.rx_fetchSearchRepository) .addDisposableTo(disposeBag) } func setupTableView() { tableView .rx_itemSelected .subscribeOn(MainScheduler.instance) .subscribeNext { [unowned self] (indexPath) -> Void in if let repo = self.viewModel.repositoryAtIndex(indexPath.row) { let id = repo.id // We can not send the repo data via url, so that we post the repo data to the DataCenter self.viewModel.post(String(id), value: repo) Route.push(self, url: "http://repository/detail/\(id)") { (vc, result) in vc.navigationController?.popViewControllerAnimated(true) let alert = UIAlertController(title: "WOW", message: String(result!), preferredStyle: UIAlertControllerStyle.ActionSheet) let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { action in alert.dismissViewControllerAnimated(true, completion: nil) }) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } } self.tableView.deselectRowAtIndexPath(indexPath, animated: true) } .addDisposableTo(disposeBag) } }
mit
7609bc89e8ac58d8f26538432bf276b4
31.978873
146
0.557335
5.690158
false
false
false
false
MainasuK/Bangumi-M
Percolator/Percolator/SubjectCollectionViewNotBookCell.swift
1
1648
// // SubjectCollectionViewNotBookCell.swift // Percolator // // Created by Cirno MainasuK on 2016-6-20. // Copyright © 2016年 Cirno MainasuK. All rights reserved. // import UIKit class SubjectCollectionViewNotBookCell: SubjectCollectionViewCell { @IBOutlet weak var coverImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var nameCNLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() nameLabel.layer.masksToBounds = true nameCNLabel.layer.masksToBounds = true } override func prepareForReuse() { super.prepareForReuse() coverImageView.af_cancelImageRequest() coverImageView.layer.removeAllAnimations() coverImageView.image = nil } override func configure(with item: ItemType) { let subjectItem = item.0 nameLabel.text = subjectItem.title nameCNLabel.text = subjectItem.subtitle coverImageView.backgroundColor = .systemFill let size = CGSize(width: 1, height: 1) if let url = URL(string: subjectItem.coverUrlPath) { coverImageView.af_setImage(withURL: url, placeholderImage: UIImage(), progressQueue: DispatchQueue.global(qos: .userInitiated), imageTransition: .crossDissolve(0.2)) } else { coverImageView.image = nil } // Set iamge view corner coverImageView.layer.borderColor = UIColor.percolatorGray.cgColor coverImageView.layer.borderWidth = 0.5 backgroundColor = .secondarySystemGroupedBackground } }
mit
66ac570c27c355379ef6cfaab08d5138
30.037736
177
0.659574
5
false
false
false
false
RunsCode/API-Swift
API_Swift/Runs/Swift3/Features/RunsObserver.swift
1
2104
// // RunsObserver.swift // QiuQiuGram // // Created by Dev_Wang on 2016/12/28. // Copyright © 2016年 iOS. All rights reserved. // import UIKit typealias HandNotificationCallBack = (_ notification: NSNotification) -> Void class RunsObserver: NSObject { private var listNotification: [NSNotification]? private var callback: HandNotificationCallBack? // private var isRunning deinit { listNotification?.removeAll() listNotification = nil callback = nil } override init() { super.init() } func shutdown() { self.unRegisterObserver() } func startUpListenNames(_ notificationNameList: [NSNotification.Name], event: @escaping HandNotificationCallBack) { var notifications = [NSNotification]() for name in notificationNameList { notifications.append(NSNotification(name: name, object: nil)) } self.startUpListen(notifications, event) } func startUpListen(_ notificationList: [NSNotification], _ event: @escaping HandNotificationCallBack) { self.callback = event self.registerObserver(notificationList) } private func registerObserver(_ list: [NSNotification]) { self.unRegisterObserver() if list.count <= 0 { return } for notification in list { NotificationCenter.default.addObserver(self, selector: #selector(self.handNotification(notification:)), name: notification.name, object: notification.object) } self.listNotification = list } private func unRegisterObserver() { if self.listNotification == nil || (self.listNotification?.count)! <= 0 { return } for notification in self.listNotification! { NotificationCenter.default.removeObserver(self, name: notification.name, object: notification.object) } } @objc private func handNotification(notification: NSNotification) { if (callback != nil) { self.callback!(notification) } } }
mit
0524d46853c4efffdf57f94530ec984d
27.780822
169
0.641123
4.863426
false
false
false
false
ktatroe/MPA-Horatio
Horatio/Horatio/Classes/Services/ServiceRequestStatus.swift
2
3206
// // Copyright © 2016 Kevin Tatroe. All rights reserved. // See LICENSE.txt for this sample’s licensing information import Foundation /** Provides a mechanism for updating and remembering the last status for each endpoint/payload. Typically used for debugging, a concrete implementation might also be used to replay failed attempts when circumstances change (for example, converting a task to a background task when switching to the background). */ public protocol ServiceStatusHandler: class { var statuses: [ServiceEndpointResponseStatus] { get } func isIdle(_ identifier: ServiceRequestIdentifier) -> Bool func updateStatus(_ identifier: ServiceRequestIdentifier, status: ServiceEndpointStatus) func lastStatus(_ identifier: ServiceRequestIdentifier) -> (ServiceEndpointStatus, Date?) } /// The current state of a request within this `Service`. public enum ServiceEndpointState: Int16 { case waiting case fetching case parsing case complete } /// The last-known status for a given endpoint within this `Service`. public enum ServiceEndpointStatus: Int16 { case unknown case failure case success } /** Encapsulates the current state of a fetches against a specific request (`ServiceEndpoint` and `ServiceRequestPayload` combination) in an informal state machine. */ open class ServiceEndpointResponseStatus { // MARK: - Properties public let identifier: ServiceRequestIdentifier public var updateDate: Date public var activityState: ServiceEndpointState = .waiting public var status: ServiceEndpointStatus = .unknown public var error: NSError? public var urlResponse: URLResponse? // MARK: - Initialization public init(identifier: ServiceRequestIdentifier) { self.identifier = identifier self.updateDate = Date.distantPast } // MARK: - Public // MARK: Status Updates /** Indicate that this status has moved from Idle to starting a fetch. */ open func startFetch() { changeState(.fetching) } /** Indicate that this status has completed fetching and has begun parsing. - parameter response: The `NSURLResponse` that completed, causing the status to transition to the parsing state. */ open func startParse(_ response: URLResponse? = nil) { urlResponse = response changeState(.parsing) } /** Indicate that this status completed with the provided error. - parameter completionError: The error that prevented the status from completing successfilly. */ open func completeWithError(_ completionError: NSError?) { status = .failure error = completionError changeState(.complete) } /** Indicate that this status has completed successfully. */ open func completeWithSuccess() { status = .success changeState(.complete) } // MARK: - Private fileprivate func changeState(_ state: ServiceEndpointState) { guard activityState != .complete else { return } guard state != activityState else { return } activityState = state updateDate = Date() } }
mit
e85f962aa78b99beb302b404bc9352c1
25.04065
93
0.699032
5.060032
false
false
false
false
Antidote-for-Tox/Antidote-for-Mac
Antidote/ContactListViewController.swift
1
2151
// // ContactListViewController.swift // Antidote // // Created by Yoba on 18/12/2016. // Copyright © 2016 Dmytro Vorobiov. All rights reserved. // import Cocoa /** ContactsTableViewController is a controller which handles tableView containing user's contacts. It's responsible for handling tableView's events and for communication with parent splitViewController. */ protocol ConstactListViewControllerDelegate { func contactSelected(contact: OCTFriend) } class ContactListViewController: NSViewController { let contactView = ContactListView() let friends = FriendManager.getFriends() var delegate: ConstactListViewControllerDelegate? override func loadView() { contactView.tableView.delegate = self contactView.tableView.dataSource = self contactView.scrollView.verticalScroller?.alphaValue = 0 view = contactView } } extension ContactListViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = ContactCellView() // Example: // TODO: fill with real data cell.usernameLabel.stringValue = friends[row].nickname cell.userAvatar.image = NSImage(named: "placeholder") cell.lastMessageTextLabel.stringValue = "Last message" cell.lastMessageDateLabel.stringValue = "Date" cell.lastSeenLabel.stringValue = "last seen" cell.lastSenderAvatar.image = NSImage(named: "placeholder") return cell } func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 68 } func tableViewSelectionDidChange(_ notification: Notification) { if let tableView = notification.object as? NSTableView { let friend = friends[tableView.selectedRow] delegate?.contactSelected(contact: friend) } } } extension ContactListViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { // TODO: fill with real data return friends.count } }
gpl-3.0
9510ed0b0ed41d9df99785abd7e13383
30.617647
107
0.690233
5.193237
false
false
false
false
LiveFlightApp/Connect-OSX
LiveFlight/Joystick/JoystickHelper.swift
1
9414
// // JoystickHelper.swift // LiveFlight // // Created by Cameron Carmichael Alonso on 29/12/2015. // Copyright © 2015 Cameron Carmichael Alonso. All rights reserved. // import Cocoa class JoystickConfig { var joystickConnected:Bool = false var connectedJoystickName:String = "" init(connected:Bool, name:String) { self.joystickConnected = connected self.connectedJoystickName = name } } var joystickConfig = JoystickConfig(connected: false, name: "") class JoystickHelper: NSObject, JoystickNotificationDelegate { let connector = InfiniteFlightAPIConnector() let controls = FlightControls() //joystick values var rollValue = 0; var pitchValue = 0; var rudderValue = 0; var throttleValue = 0; var tryPitch = false var tryRoll = false var tryThrottle = false var tryRudder = false override init() { super.init() /* Init Joystick Manager ======================== */ let joystick:JoystickManager = JoystickManager.sharedInstance() joystick.joystickAddedDelegate = self; /* NotificationCenter setup ======================== */ NotificationCenter.default.addObserver(self, selector: #selector(tryPitch(notification:)), name:NSNotification.Name(rawValue: "tryPitch"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(tryRoll(notification:)), name:NSNotification.Name(rawValue: "tryRoll"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(tryThrottle(notification:)), name:NSNotification.Name(rawValue: "tryThrottle"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(tryRudder(notification:)), name:NSNotification.Name(rawValue: "tryRudder"), object: nil) } @objc func tryPitch(notification: NSNotification) { tryPitch = true } @objc func tryRoll(notification: NSNotification) { tryRoll = true } @objc func tryThrottle(notification: NSNotification) { tryThrottle = true } @objc func tryRudder(notification: NSNotification) { tryRudder = true } //joystick work func joystickAdded(_ joystick: Joystick!) { joystick.register(forNotications: self) if UserDefaults.standard.integer(forKey: "lastJoystick") != Int(joystick.productId) { // different joystick. Reset // remove last map UserDefaults.standard.removeObject(forKey: "mapStatus") // set axesSet to false UserDefaults.standard.set(false, forKey: "axesSet") } // set last joystick name and connected joystickConfig = JoystickConfig(connected: true, name: ("\(joystick.manufacturerName) \(joystick.productName)")) let axesSet = UserDefaults.standard.bool(forKey: "axesSet") // this is to reset axes when upgrading. Since there is a common pattern, there shouldn't be much impact. let axesSet11 = UserDefaults.standard.bool(forKey: "axesSet11") if axesSet != true || axesSet11 != true { // axes haven't been set yet // check to see if json exists with joystick name guard let path = Bundle.main.path(forResource: "JoystickMapping/\(joystick.manufacturerName) \(joystick.productName)", ofType: "json") else { // No map found NSLog("No map found - setting default values...") // Default values UserDefaults.standard.set(49, forKey: "pitch") UserDefaults.standard.set(48, forKey: "roll") UserDefaults.standard.set(50, forKey: "throttle") UserDefaults.standard.set(53, forKey: "rudder") // using generic values UserDefaults.standard.set(0, forKey: "mapStatus") return } // if this point is reached, a map exists let fileData = NSData(contentsOfFile: path) do { if let response:NSDictionary = try JSONSerialization.jsonObject(with: fileData! as Data, options:JSONSerialization.ReadingOptions.mutableContainers) as? Dictionary<String, AnyObject> as! NSDictionary { let pitchAxis = response.value(forKey: "Pitch-OSX") as! Int let rollAxis = response.value(forKey: "Roll-OSX") as! Int let throttleAxis = response.value(forKey: "Throttle-OSX") as! Int let rudderAxis = response.value(forKey: "Rudder-OSX") as! Int //save values UserDefaults.standard.set(pitchAxis, forKey: "pitch") UserDefaults.standard.set(rollAxis, forKey: "roll") UserDefaults.standard.set(throttleAxis, forKey: "throttle") UserDefaults.standard.set(rudderAxis, forKey: "rudder") // using mapped values UserDefaults.standard.set(1, forKey: "mapStatus") } else { NSLog("Failed to parse JSON") } } catch let serializationError as NSError { NSLog(String(describing: serializationError)) } } // change labels and mark as axes set NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeLabelValues"), object:nil) UserDefaults.standard.set(true, forKey: "axesSet") UserDefaults.standard.set(true, forKey: "axesSet11") UserDefaults.standard.set(Int(joystick.productId), forKey: "lastJoystick") } func joystickRemoved(_ joystick: Joystick!) { joystickConfig = JoystickConfig(connected: false, name: "") // change label values NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeLabelValues"), object:nil) } func joystickStateChanged(_ joystick: Joystick!, axis:Int32) { //check to see if calibrating if (tryPitch == true) { //detect axis then save UserDefaults.standard.set(Int(axis), forKey: "pitch") tryPitch = false NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeLabelValues"), object:nil) } else if (tryRoll == true) { //detect axis then save UserDefaults.standard.set(Int(axis), forKey: "roll") tryRoll = false NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeLabelValues"), object:nil) } else if (tryThrottle == true) { //detect axis then save UserDefaults.standard.set(Int(axis), forKey: "throttle") tryThrottle = false NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeLabelValues"), object:nil) } else if (tryRudder == true) { //detect axis then save UserDefaults.standard.set(Int(axis), forKey: "rudder") tryRudder = false NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeLabelValues"), object:nil) } var value:Int32 = 0 // print relVal - this is useful for debugging let relVal = joystick.getRelativeValue(ofAxesIndex: axis) NSLog("RelVal: \(relVal)") if UserDefaults.standard.bool(forKey: "gamepadMode") == true { // is a gamepad // values are [-128, 128] value = Int32(joystick.getRelativeValue(ofAxesIndex: axis) * 2048) } else { // raw values are [0, 1024] value = Int32(((joystick.getRelativeValue(ofAxesIndex: axis) * 2) - 1) * 1024) } if (Int(axis) == UserDefaults.standard.integer(forKey: "pitch")) { controls.pitchChanged(value: value) } else if (Int(axis) == UserDefaults.standard.integer(forKey: "roll")) { controls.rollChanged(value: value) } else if (Int(axis) == UserDefaults.standard.integer(forKey: "throttle")) { controls.throttleChanged(value: value) } else if (Int(axis) == UserDefaults.standard.integer(forKey: "rudder")) { controls.rudderChanged(value: value) } } func joystickButtonReleased(_ buttonIndex: Int32, on joystick: Joystick!) { NSLog("Button --> Released \(buttonIndex)") connector.didPressButton(buttonIndex, state: 1) } func joystickButtonPushed(_ buttonIndex: Int32, on joystick: Joystick!) { NSLog("Button --> Pressed \(buttonIndex)") connector.didPressButton(buttonIndex, state: 0) } }
gpl-3.0
92941d1cd1882011c0f6371210563105
36.059055
217
0.573462
4.751641
false
false
false
false
amujic5/AFEA
AFEA-EndProject/AFEA-EndProject/List/ListItemCollectionViewCell.swift
1
1101
// // ListItemCollectionViewCell.swift // AFEA-StarterProject // // Created by Azzaro Mujic on 10/09/2017. // Copyright © 2017 Azzaro Mujic. All rights reserved. // import UIKit class ListItemCollectionViewCell: UICollectionViewCell { @IBOutlet weak var circleView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! var animatedCircleView: CircleView! override func awakeFromNib() { super.awakeFromNib() circleView.layer.cornerRadius = circleView.frame.width/2 circleView.layer.borderWidth = 6 circleView.layer.borderColor = UIColor.wheat.cgColor animatedCircleView = CircleView(frame: circleView.frame, lineWidth: 7, backLayerColor: UIColor.clear, frontLayerColor: UIColor.white) contentView.addSubview(animatedCircleView) } func configure(with foodModel: FoodModel) { imageView.image = foodModel.photo titleLabel.text = foodModel.title circleView.layer.borderColor = UIColor.darkGrey.cgColor } }
mit
1c50bd9ec2fab2f0350a4ab984210b67
28.72973
141
0.691818
4.680851
false
false
false
false
zoeyzhong520/SlidingMenu
SlidingMenu/SlidingMenu/SlidingMenuKit/View/NoteListView.swift
1
3653
// // NoteListView.swift // SlidingMenu // // Created by JOE on 2017/10/12. // Copyright © 2017年 Hongyear Information Technology (Shanghai) Co.,Ltd. All rights reserved. // import UIKit class NoteListView: UIView { ///UITableView fileprivate var tableView:UITableView! ///HeaderViewHeight fileprivate let HeaderViewHeight:CGFloat = fontSizeScale(100) ///NoteList JumpClosure. var jumpClosure:StringJumpClosure? var model:NoteListModel? { didSet { self.tableView?.reloadData() } } override init(frame: CGRect) { super.init(frame: frame) createView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension NoteListView { ///UI fileprivate func createView() { backgroundColor = UIColor.white tableView = UITableView(frame: zzj_CGRectZero, style: .plain) tableView.delegate = self tableView.dataSource = self //tableView.separatorStyle = .none tableView.register(NoteListTableViewCell.self, forCellReuseIdentifier: "NoteListCellId") tableView.register(SlidingMenuHeaderViewCell.self, forCellReuseIdentifier: "SlidingMenuHeaderViewCellId") addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalTo(self) } } } //MARK: - UITableViewDelegate, UITableViewDataSource extension NoteListView: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let cnt = model?.notes?.count { return cnt + 1 } return 0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return fontSizeScale(100) }else{ return NoteListTableViewCell.heightForCell(model: model?.notes?[indexPath.row-1]) } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = SlidingMenuHeaderViewCell.createSlidingMenuCell(tableView: tableView, atIndexPath: indexPath, model: model) cell.selectionStyle = .none return cell }else{ let cell = NoteListTableViewCell.createNoteListCell(tableView: tableView, atIndexPath: indexPath, model: model?.notes?[indexPath.row-1]) cell.selectionStyle = .none return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.row > 0 { guard let note = model?.notes?[indexPath.row-1].note else { return } if self.jumpClosure != nil { jumpClosure!(note) } } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if indexPath.row > 0 { model?.notes?.remove(at: indexPath.row-1) tableView.deleteRows(at: [indexPath], with: .fade) } } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.row > 0 { return true } return false } }
mit
3a682bee3a03845e86aaca43c75ea32c
27.968254
148
0.622192
5.048409
false
false
false
false
krad/buffie
Sources/Buffie/Capture/Displays/Display.swift
1
3399
import Foundation import AVFoundation #if os(macOS) @available (macOS 10.11, *) internal enum DisplayType { case active case drawable } @available (macOS 10.11, *) public struct Display { public let displayID: CGDirectDisplayID public init(displayID: CGDirectDisplayID) { self.displayID = displayID } public var name: String { return displayName(for: self.displayID) } internal var input: AVCaptureScreenInput { return AVCaptureScreenInput(displayID: displayID) } public static func getAll() -> [Display] { let allIDs = self.getIDs(for: .active) return allIDs.map { Display(displayID: $0) } } internal static func getIDs(for displayType: DisplayType) -> [CGDirectDisplayID] { // If you have more than 10 screens, please send me a pic of your setup. let maxDisplays = 10 var displays = [CGDirectDisplayID](repeating: 0, count: maxDisplays) var displayCount: UInt32 = 0 switch displayType { case .active: CGGetOnlineDisplayList(UInt32(maxDisplays), &displays, &displayCount) case .drawable: CGGetActiveDisplayList(UInt32(maxDisplays), &displays, &displayCount) } return Array(displays[0..<Int(displayCount)]) } } internal func displayName(for displayID: CGDirectDisplayID) -> String { var result = "" var object : io_object_t var serialPortIterator = io_iterator_t() let matching = IOServiceMatching("IODisplayConnect") let kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &serialPortIterator) if KERN_SUCCESS == kernResult && serialPortIterator != 0 { repeat { object = IOIteratorNext(serialPortIterator) let info = IODisplayCreateInfoDictionary(object, UInt32(kIODisplayOnlyPreferredName)).takeRetainedValue() as NSDictionary as! [String : AnyObject] let vendorID = info[kDisplayVendorID] as? UInt32 let productID = info[kDisplayProductID] as? UInt32 if vendorID == CGDisplayVendorNumber(displayID) { if productID == CGDisplayModelNumber(displayID) { if let productNameLocalizationDict = info[kDisplayProductName] as? [String: String] { let pre = Locale.autoupdatingCurrent if let language = pre.languageCode, let region = pre.regionCode { if let name = productNameLocalizationDict["\(language)_\(region)"] { result = name } } } } } } while object != 0 } IOObjectRelease(serialPortIterator) return result } #endif
mit
668e0d1040cf70a3d500f4301c1c065a
35.945652
162
0.514563
5.544861
false
false
false
false
miroslavkovac/Lingo
Sources/Lingo/DataSources/FileDataSource.swift
1
3780
import Foundation /// Class providing file backed data source for Lingo in case localizations are stored in JSON files. public final class FileDataSource: LocalizationDataSource { enum Error: Swift.Error { case parsingFailure(message: String) } public let rootPath: String /// `rootPath` should contain localization files in JSON format named based on relevant locale. For example: en.json, de.json etc. public init(rootPath: String) { self.rootPath = rootPath } // MARK: LocalizationDataSource public func availableLocales() throws -> [LocaleIdentifier] { return try FileManager().contentsOfDirectory(atPath: self.rootPath).filter { $0.hasSuffix(".json") }.map { $0.components(separatedBy: ".").first! // It is safe to use force unwrap here as $0 will always contain the "." } } public func localizations(forLocale locale: LocaleIdentifier) throws -> [LocalizationKey : Localization] { let jsonFilePath = "\(self.rootPath)/\(locale).json" var localizations = [LocalizationKey: Localization]() // Parse localizations. Note that valid `object` in the for-loop can be either: // - a String, in case there are no pluralizations defined (one, few, many, other,..) // - a dictionary [String: String], in case pluralizations are defined for (localizationKey, object) in try self.loadLocalizations(atPath: jsonFilePath) { if let stringValue = object as? String { let localization = Localization.universal(value: stringValue) localizations[localizationKey] = localization } else if let rawPluralizedValues = object as? [String: String] { let pluralizedValues = try self.pluralizedValues(fromRaw: rawPluralizedValues) let localization = Localization.pluralized(values: pluralizedValues) localizations[localizationKey] = localization } else { throw Error.parsingFailure(message: "Unsupported pluralization format for key: \(localizationKey).") } } return localizations } } private extension FileDataSource { /// Parses a dictionary which has string plural categories as keys ([String: String]) and returns a typed dictionary ([PluralCategory: String]) /// An example dictionary looks like: /// { /// "one": "You have an unread message." /// "many": "You have %{count} unread messages." /// } func pluralizedValues(fromRaw rawPluralizedValues: [String: String]) throws -> [PluralCategory: String] { var result = [PluralCategory: String]() for (rawPluralCategory, value) in rawPluralizedValues { guard let pluralCategory = PluralCategory(rawValue: rawPluralCategory) else { throw Error.parsingFailure(message: "Unsupported plural category: \(rawPluralCategory)") } result[pluralCategory] = value } return result } /// Loads a localizations file from disk if it exists and parses it. func loadLocalizations(atPath path: String) throws -> [String: Any] { let fileContent = try Data(contentsOf: URL(fileURLWithPath: path)) let jsonObject = try JSONSerialization.jsonObject(with: fileContent, options: []) guard let localizations = jsonObject as? [String: Any] else { throw Error.parsingFailure(message: "Invalid localization file format at path: \(path). Expected string indexed dictionary at the root level.") } return localizations } }
mit
b3f4b86d210bc53128abd07c107946ce
41.954545
155
0.637037
5.235457
false
false
false
false
qkrqjadn/SoonChat
source/View/ExtensionTabBar.swift
2
2510
// // ExtensionTabBar.swift // soonchat // // Created by 박범우 on 2017. 2. 5.. // Copyright © 2017년 bumwoo. All rights reserved. // import UIKit import BATabBarController class ExtensionTabBar : BATabBarController { private let option1 : BATabBarItem = { let attributeString = NSMutableAttributedString(string: "카드") attributeString.addAttributes([NSForegroundColorAttributeName:UIColor.white], range: NSRange(location: 0, length: attributeString.string.characters.count)) let bt = BATabBarItem(image: UIImage(named: "icon1_unselected"), selectedImage: UIImage(named: "icon1_selected"), title: attributeString) return bt! }() private let option2 : BATabBarItem = { let attributeString = NSMutableAttributedString(string: "채팅") attributeString.addAttributes([NSForegroundColorAttributeName:UIColor.white], range: NSRange(location: 0, length: attributeString.string.characters.count)) let bt = BATabBarItem(image: UIImage(named: "icon2_unselected"), selectedImage: UIImage(named: "icon2_selected"), title: attributeString) return bt! }() private let option3 : BATabBarItem = { let attributeString = NSMutableAttributedString(string: "매칭") attributeString.addAttributes([NSForegroundColorAttributeName:UIColor.white], range: NSRange(location: 0, length: attributeString.string.characters.count)) let bt = BATabBarItem(image: UIImage(named: "icon3_unselected"), selectedImage: UIImage(named: "icon3_selected"), title: attributeString) return bt! }() override func viewDidLoad() { super.viewDidLoad() self.tabBarItemLineWidth = 3 tabBar.backgroundColor = .darkGray if isLoggedIn() { self.tabBarItems = [option1,option2,option3] } else if isLoggedIn() == false { print("false!!!") perform(#selector(showLoginController), with: nil, afterDelay: 0.02) } } @objc fileprivate func logOut() { UserDefaults.standard.set(false, forKey: "isLoggedIn") UserDefaults.standard.synchronize() showLoginController() } fileprivate func isLoggedIn() -> Bool { return UserDefaults.standard.bool(forKey: "isLoggedIn") } @objc fileprivate func showLoginController() { let loginController = LoginController() present(loginController, animated: true, completion: { }) } }
mit
65dfd35b18d6bd3f2de0c9655f79d847
36.712121
163
0.673363
4.592251
false
true
false
false
carabina/Reachability.swift
Reachability Sample/Reachability Sample/ViewController.swift
5
2350
// // ViewController.swift // Reachability Sample // // Created by Ashley Mills on 22/09/2014. // Copyright (c) 2014 Joylord Systems. All rights reserved. // import UIKit let useClosures = false class ViewController: UIViewController { @IBOutlet weak var networkStatus: UILabel! let reachability = Reachability.reachabilityForInternetConnection() override func viewDidLoad() { super.viewDidLoad() if (useClosures) { reachability.whenReachable = { reachability in self.updateLabelColourWhenReachable(reachability) } reachability.whenUnreachable = { reachability in self.updateLabelColourWhenNotReachable(reachability) } } else { NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability) } reachability.startNotifier() // Initial reachability check if reachability.isReachable() { updateLabelColourWhenReachable(reachability) } else { updateLabelColourWhenNotReachable(reachability) } } deinit { reachability.stopNotifier() if (!useClosures) { NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil) } } func updateLabelColourWhenReachable(reachability: Reachability) { if reachability.isReachableViaWiFi() { self.networkStatus.textColor = UIColor.greenColor() } else { self.networkStatus.textColor = UIColor.blueColor() } self.networkStatus.text = reachability.currentReachabilityString } func updateLabelColourWhenNotReachable(reachability: Reachability) { self.networkStatus.textColor = UIColor.redColor() self.networkStatus.text = reachability.currentReachabilityString } func reachabilityChanged(note: NSNotification) { let reachability = note.object as! Reachability if reachability.isReachable() { updateLabelColourWhenReachable(reachability) } else { updateLabelColourWhenNotReachable(reachability) } } }
bsd-2-clause
fcc777a8eaf59a87b38b179ac4007c98
28.375
161
0.649787
6.151832
false
false
false
false
rchatham/SwiftyTypeForm
Pods/PhoneNumberKit/PhoneNumberKit/UI/TextField.swift
2
8257
// // TextField.swift // PhoneNumberKit // // Created by Roy Marmelstein on 07/11/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation import UIKit /// Custom text field that formats phone numbers open class PhoneNumberTextField: UITextField, UITextFieldDelegate { let phoneNumberKit = PhoneNumberKit() /// Override region to set a custom region. Automatically uses the default region code. public var defaultRegion = PhoneNumberKit.defaultRegionCode() { didSet { partialFormatter.defaultRegion = defaultRegion } } public var withPrefix: Bool = true { didSet { partialFormatter.withPrefix = withPrefix if withPrefix == false { self.keyboardType = UIKeyboardType.numberPad } else { self.keyboardType = UIKeyboardType.phonePad } } } let partialFormatter: PartialFormatter let nonNumericSet: NSCharacterSet = { var mutableSet = NSMutableCharacterSet.decimalDigit().inverted mutableSet.remove(charactersIn: PhoneNumberConstants.plusChars) return mutableSet as NSCharacterSet }() weak private var _delegate: UITextFieldDelegate? override open var delegate: UITextFieldDelegate? { get { return _delegate } set { self._delegate = newValue } } //MARK: Status public var currentRegion: String { get { return partialFormatter.currentRegion } } public var isValidNumber: Bool { get { let rawNumber = self.text ?? String() do { let _ = try phoneNumberKit.parse(rawNumber, withRegion: currentRegion) return true } catch { return false } } } //MARK: Lifecycle /** Init with frame - parameter frame: UITextfield F - returns: UITextfield */ override public init(frame:CGRect) { self.partialFormatter = PartialFormatter(phoneNumberKit: phoneNumberKit, defaultRegion: defaultRegion, withPrefix: withPrefix) super.init(frame:frame) self.setup() } /** Init with coder - parameter aDecoder: decoder - returns: UITextfield */ required public init(coder aDecoder: NSCoder) { self.partialFormatter = PartialFormatter(phoneNumberKit: phoneNumberKit, defaultRegion: defaultRegion, withPrefix: withPrefix) super.init(coder: aDecoder)! self.setup() } func setup(){ self.autocorrectionType = .no self.keyboardType = UIKeyboardType.phonePad super.delegate = self } // MARK: Phone number formatting /** * To keep the cursor position, we find the character immediately after the cursor and count the number of times it repeats in the remaining string as this will remain constant in every kind of editing. */ internal struct CursorPosition { let numberAfterCursor: String let repetitionCountFromEnd: Int } internal func extractCursorPosition() -> CursorPosition? { var repetitionCountFromEnd = 0 // Check that there is text in the UITextField guard let text = text, let selectedTextRange = selectedTextRange else { return nil } let textAsNSString = text as NSString let cursorEnd = offset(from: beginningOfDocument, to: selectedTextRange.end) // Look for the next valid number after the cursor, when found return a CursorPosition struct for i in cursorEnd ..< textAsNSString.length { let cursorRange = NSMakeRange(i, 1) let candidateNumberAfterCursor: NSString = textAsNSString.substring(with: cursorRange) as NSString if (candidateNumberAfterCursor.rangeOfCharacter(from: nonNumericSet as CharacterSet).location == NSNotFound) { for j in cursorRange.location ..< textAsNSString.length { let candidateCharacter = textAsNSString.substring(with: NSMakeRange(j, 1)) if candidateCharacter == candidateNumberAfterCursor as String { repetitionCountFromEnd += 1 } } return CursorPosition(numberAfterCursor: candidateNumberAfterCursor as String, repetitionCountFromEnd: repetitionCountFromEnd) } } return nil } // Finds position of previous cursor in new formatted text internal func selectionRangeForNumberReplacement(textField: UITextField, formattedText: String) -> NSRange? { let textAsNSString = formattedText as NSString var countFromEnd = 0 guard let cursorPosition = extractCursorPosition() else { return nil } for i in stride(from: (textAsNSString.length - 1), through: 0, by: -1) { let candidateRange = NSMakeRange(i, 1) let candidateCharacter = textAsNSString.substring(with: candidateRange) if candidateCharacter == cursorPosition.numberAfterCursor { countFromEnd += 1 if countFromEnd == cursorPosition.repetitionCountFromEnd { return candidateRange } } } return nil } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = text else { return false } // allow delegate to intervene guard _delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true else { return false } let textAsNSString = text as NSString let changedRange = textAsNSString.substring(with: range) as NSString let modifiedTextField = textAsNSString.replacingCharacters(in: range, with: string) let formattedNationalNumber = partialFormatter.formatPartial(modifiedTextField as String) var selectedTextRange: NSRange? let nonNumericRange = (changedRange.rangeOfCharacter(from: nonNumericSet as CharacterSet).location != NSNotFound) if (range.length == 1 && string.isEmpty && nonNumericRange) { selectedTextRange = selectionRangeForNumberReplacement(textField: textField, formattedText: modifiedTextField) textField.text = modifiedTextField } else { selectedTextRange = selectionRangeForNumberReplacement(textField: textField, formattedText: formattedNationalNumber) textField.text = formattedNationalNumber } sendActions(for: .editingChanged) if let selectedTextRange = selectedTextRange, let selectionRangePosition = textField.position(from: beginningOfDocument, offset: selectedTextRange.location) { let selectionRange = textField.textRange(from: selectionRangePosition, to: selectionRangePosition) textField.selectedTextRange = selectionRange } return false } //MARK: UITextfield Delegate public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldBeginEditing?(textField) ?? true } public func textFieldDidBeginEditing(_ textField: UITextField) { _delegate?.textFieldDidBeginEditing?(textField) } public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldEndEditing?(textField) ?? true } public func textFieldDidEndEditing(_ textField: UITextField) { _delegate?.textFieldDidEndEditing?(textField) } public func textFieldShouldClear(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldClear?(textField) ?? true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldReturn?(textField) ?? true } }
mit
5348945890a1725ee2fe2ff7292efffe
35.052402
207
0.639172
5.693793
false
false
false
false
rnystrom/GitHawk
FreetimeTests/BookmarkViewControllerTests.swift
1
9756
// // BookmarkViewControllerTests.swift // FreetimeTests // // Created by Ryan Nystrom on 11/24/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import XCTest import IGListKit import StyledTextKit @testable import Freetime private class FakeBookmarkViewControllerClient: BookmarkViewControllerClient, BookmarkCloudMigratorClient { let migratorResult: BookmarkCloudMigratorClientResult let clientResult: Result<[BookmarkModelType]> let infiniteMigration: Bool var migratorFetches = 0 var clientFetches = 0 init( migratorResult: BookmarkCloudMigratorClientResult, clientResult: Result<[BookmarkModelType]>, infiniteMigration: Bool = false ) { self.migratorResult = migratorResult self.clientResult = clientResult self.infiniteMigration = infiniteMigration } func fetch( bookmarks: [BookmarkCloudMigratorClientBookmarks], completion: @escaping (BookmarkCloudMigratorClientResult) -> Void ) { migratorFetches += 1 if infiniteMigration { DispatchQueue.main.asyncAfter(deadline: .now() + 60) { completion(self.migratorResult) } } else { completion(migratorResult) } } func fetch(graphQLIDs: [String], completion: @escaping (Result<[BookmarkModelType]>) -> Void) { clientFetches += 1 completion(clientResult) } } class BookmarkViewControllerTests: XCTestCase { override func setUp() { // clearing cloud store let domain = Bundle.main.bundleIdentifier! UserDefaults.standard.removePersistentDomain(forName: domain) } func test_whenNoMigration_withNoData_thatEmptyViewDisplayed() { let store = BookmarkIDCloudStore(username: "foo", iCloudStore: UserDefaults.standard) let client = FakeBookmarkViewControllerClient( migratorResult: .noMigration, clientResult: .success([]) ) let utils = ViewControllerTestUtil(viewController: BookmarkViewController( client: client, cloudStore: store, oldBookmarks: [] )) let expectation = XCTestExpectation(description: #function) DispatchQueue.main.async { XCTAssertNotNil(utils.view(with: "initial-empty-view")) XCTAssertNotNil(utils.view(with: "feed-collection-view")) XCTAssertNil(utils.view(with: "feed-loading-view")) XCTAssertNil(utils.view(with: "bookmark-migration-cell")) XCTAssertNil(utils.view(with: "base-empty-view")) XCTAssertEqual(client.migratorFetches, 0) XCTAssertEqual(client.clientFetches, 1) expectation.fulfill() } wait(for: [expectation], timeout: 30) } func test_whenEmptyMigrationResults_withNoData_thatEmptyViewDisplayed() { let store = BookmarkIDCloudStore(username: "foo", iCloudStore: UserDefaults.standard) let client = FakeBookmarkViewControllerClient( migratorResult: .success([]), clientResult: .success([]) ) let utils = ViewControllerTestUtil(viewController: BookmarkViewController( client: client, cloudStore: store, oldBookmarks: [] )) let expectation = XCTestExpectation(description: #function) DispatchQueue.main.async { XCTAssertNotNil(utils.view(with: "initial-empty-view")) XCTAssertNotNil(utils.view(with: "feed-collection-view")) XCTAssertNil(utils.view(with: "feed-loading-view")) XCTAssertNil(utils.view(with: "bookmark-migration-cell")) XCTAssertNil(utils.view(with: "base-empty-view")) XCTAssertEqual(client.migratorFetches, 0) XCTAssertEqual(client.clientFetches, 1) expectation.fulfill() } wait(for: [expectation], timeout: 30) } func test_whenMigrationError_thatMigrationButtonDisplayed() { let store = BookmarkIDCloudStore(username: "foo", iCloudStore: UserDefaults.standard) let client = FakeBookmarkViewControllerClient( migratorResult: .error(nil), clientResult: .success([]) ) let utils = ViewControllerTestUtil(viewController: BookmarkViewController( client: client, cloudStore: store, oldBookmarks: [Bookmark(type: .repo, name: "foo", owner: "bar")] )) let expectation = XCTestExpectation(description: #function) DispatchQueue.main.async { XCTAssertNil(utils.view(with: "initial-empty-view")) XCTAssertNotNil(utils.view(with: "feed-collection-view")) XCTAssertNil(utils.view(with: "feed-loading-view")) XCTAssertNotNil(utils.view(with: "bookmark-migration-cell")) XCTAssertNil(utils.view(with: "base-empty-view")) XCTAssertEqual(client.migratorFetches, 1) XCTAssertEqual(client.clientFetches, 0) expectation.fulfill() } wait(for: [expectation], timeout: 30) } func test_whenMigrationInProgress_thatLoadingViewDisplayed() { let store = BookmarkIDCloudStore(username: "foo", iCloudStore: UserDefaults.standard) let client = FakeBookmarkViewControllerClient( migratorResult: .success([]), clientResult: .success([]), infiniteMigration: true ) let utils = ViewControllerTestUtil(viewController: BookmarkViewController( client: client, cloudStore: store, oldBookmarks: [Bookmark(type: .repo, name: "foo", owner: "bar")] )) let expectation = XCTestExpectation(description: #function) DispatchQueue.main.async { XCTAssertNil(utils.view(with: "initial-empty-view")) XCTAssertNotNil(utils.view(with: "feed-collection-view")) XCTAssertNotNil(utils.view(with: "feed-loading-view")) XCTAssertNil(utils.view(with: "bookmark-migration-cell")) XCTAssertNil(utils.view(with: "base-empty-view")) XCTAssertEqual(client.migratorFetches, 1) XCTAssertEqual(client.clientFetches, 0) expectation.fulfill() } wait(for: [expectation], timeout: 30) } func test_whenFetchError_thatEmptyViewDisplayed() { let store = BookmarkIDCloudStore(username: "foo", iCloudStore: UserDefaults.standard) let client = FakeBookmarkViewControllerClient( migratorResult: .success([]), clientResult: .error(nil) ) let utils = ViewControllerTestUtil(viewController: BookmarkViewController( client: client, cloudStore: store, oldBookmarks: [] )) let expectation = XCTestExpectation(description: #function) DispatchQueue.main.async { XCTAssertNil(utils.view(with: "initial-empty-view")) XCTAssertNotNil(utils.view(with: "feed-collection-view")) XCTAssertNil(utils.view(with: "feed-loading-view")) XCTAssertNil(utils.view(with: "bookmark-migration-cell")) XCTAssertNotNil(utils.view(with: "base-empty-view")) XCTAssertEqual(client.migratorFetches, 0) XCTAssertEqual(client.clientFetches, 1) expectation.fulfill() } wait(for: [expectation], timeout: 30) } func test_whenFetchReturnsModels_thatCellsExist() { let models: [BookmarkModelType] = [ BookmarkModelType.issue(BookmarkIssueViewModel( repo: Repository(owner: "GitHawkApp", name: "GitHawk"), number: 42, isPullRequest: false, state: .open, text: StyledTextRenderer( string: StyledTextBuilder(text: "Foo bar").build(), contentSizeCategory: .medium) )), BookmarkModelType.issue(BookmarkIssueViewModel( repo: Repository(owner: "GitHawkApp", name: "GitHawk"), number: 12, isPullRequest: true, state: .closed, text: StyledTextRenderer( string: StyledTextBuilder(text: "Foo bar").build(), contentSizeCategory: .medium) )), BookmarkModelType.repo(RepositoryDetails( owner: "GitHawkApp", name: "GitHawk" )) ] let store = BookmarkIDCloudStore(username: "foo", iCloudStore: UserDefaults.standard) let client = FakeBookmarkViewControllerClient( migratorResult: .success([]), clientResult: .success(models) ) let utils = ViewControllerTestUtil(viewController: BookmarkViewController( client: client, cloudStore: store, oldBookmarks: [] )) let expectation = XCTestExpectation(description: #function) DispatchQueue.main.async { XCTAssertNil(utils.view(with: "initial-empty-view")) XCTAssertNotNil(utils.view(with: "feed-collection-view")) XCTAssertNil(utils.view(with: "feed-loading-view")) XCTAssertNil(utils.view(with: "bookmark-migration-cell")) XCTAssertNil(utils.view(with: "base-empty-view")) XCTAssertEqual(utils.views(with: "bookmark-cell").count, 2) XCTAssertEqual(utils.views(with: "bookmark-repo-cell").count, 1) XCTAssertEqual(client.migratorFetches, 0) XCTAssertEqual(client.clientFetches, 1) expectation.fulfill() } wait(for: [expectation], timeout: 30) } }
mit
b553c6e09ef6bcfb7db72b6654a2bc40
38.493927
99
0.625115
4.889724
false
true
false
false
sydvicious/firefox-ios
Client/Frontend/Browser/Browser.swift
2
12111
/* 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 import Storage import Shared protocol BrowserHelper { static func name() -> String func scriptMessageHandlerName() -> String? func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) } @objc protocol BrowserDelegate { func browser(browser: Browser, didAddSnackbar bar: SnackBar) func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) optional func browser(browser: Browser, didCreateWebView webView: WKWebView) optional func browser(browser: Browser, willDeleteWebView webView: WKWebView) } class Browser: NSObject { var webView: WKWebView? = nil var browserDelegate: BrowserDelegate? = nil var bars = [SnackBar]() var favicons = [Favicon]() var lastExecutedTime: Timestamp? var sessionData: SessionData? var screenshot: UIImage? private var helperManager: HelperManager? = nil var lastRequest: NSURLRequest? = nil private var configuration: WKWebViewConfiguration? = nil init(configuration: WKWebViewConfiguration) { self.configuration = configuration } class func toTab(browser: Browser) -> RemoteTab? { if let displayURL = browser.displayURL { let history = browser.historyList.filter(RemoteTab.shouldIncludeURL).reverse() return RemoteTab(clientGUID: nil, URL: displayURL, title: browser.displayTitle, history: history, lastUsed: NSDate.now(), icon: nil) } else if let sessionData = browser.sessionData { let history = sessionData.urls.reverse() return RemoteTab(clientGUID: nil, URL: history[0], title: browser.displayTitle, history: history, lastUsed: sessionData.lastUsedTime, icon: nil) } return nil } weak var navigationDelegate: WKNavigationDelegate? { didSet { if let webView = webView { webView.navigationDelegate = navigationDelegate } } } func createWebview() { if webView == nil { assert(configuration != nil, "Create webview can only be called once") configuration!.userContentController = WKUserContentController() configuration!.preferences = WKPreferences() configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false let webView = WKWebView(frame: CGRectZero, configuration: configuration!) configuration = nil webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.allowsBackForwardNavigationGestures = true webView.backgroundColor = UIColor.lightGrayColor() // Turning off masking allows the web content to flow outside of the scrollView's frame // which allows the content appear beneath the toolbars in the BrowserViewController webView.scrollView.layer.masksToBounds = false webView.navigationDelegate = navigationDelegate helperManager = HelperManager(webView: webView) // Pulls restored session data from a previous SavedTab to load into the Browser. If it's nil, a session restore // has already been triggered via custom URL, so we use the last request to trigger it again; otherwise, // we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL // to trigger the session restore via custom handlers if let sessionData = self.sessionData { var updatedURLs = [String]() for url in sessionData.urls { let updatedURL = WebServer.sharedInstance.updateLocalURL(url)!.absoluteString! updatedURLs.append(updatedURL) } let currentPage = sessionData.currentPage self.sessionData = nil var jsonDict = [String: AnyObject]() jsonDict["history"] = updatedURLs jsonDict["currentPage"] = currentPage let escapedJSON = JSON.stringify(jsonDict, pretty: false).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! let restoreURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)") webView.loadRequest(NSURLRequest(URL: restoreURL!)) } else if let request = lastRequest { webView.loadRequest(request) } self.webView = webView browserDelegate?.browser?(self, didCreateWebView: webView) } } deinit { if let webView = webView { browserDelegate?.browser?(self, willDeleteWebView: webView) } } var loading: Bool { return webView?.loading ?? false } var estimatedProgress: Double { return webView?.estimatedProgress ?? 0 } var backList: [WKBackForwardListItem]? { return webView?.backForwardList.backList as? [WKBackForwardListItem] } var forwardList: [WKBackForwardListItem]? { return webView?.backForwardList.forwardList as? [WKBackForwardListItem] } var historyList: [NSURL] { func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL } var tabs = self.backList?.map(listToUrl) ?? [NSURL]() tabs.append(self.url!) return tabs } var title: String? { return webView?.title } var displayTitle: String { if let title = webView?.title { if !title.isEmpty { return title } } return displayURL?.absoluteString ?? "" } var displayFavicon: Favicon? { var width = 0 var largest: Favicon? for icon in favicons { if icon.width > width { width = icon.width! largest = icon } } return largest } var url: NSURL? { return webView?.URL ?? lastRequest?.URL } var displayURL: NSURL? { if let url = url { if ReaderModeUtils.isReaderModeURL(url) { return ReaderModeUtils.decodeURL(url) } if ErrorPageHelper.isErrorPageURL(url) { let decodedURL = ErrorPageHelper.decodeURL(url) if !AboutUtils.isAboutURL(decodedURL) { return decodedURL } else { return nil } } if !AboutUtils.isAboutURL(url) { return url } } return nil } var canGoBack: Bool { return webView?.canGoBack ?? false } var canGoForward: Bool { return webView?.canGoForward ?? false } func goBack() { webView?.goBack() } func goForward() { webView?.goForward() } func goToBackForwardListItem(item: WKBackForwardListItem) { webView?.goToBackForwardListItem(item) } func loadRequest(request: NSURLRequest) -> WKNavigation? { lastRequest = request if let webView = webView { return webView.loadRequest(request) } return nil } func stop() { webView?.stopLoading() } func reload() { webView?.reload() } func addHelper(helper: BrowserHelper, name: String) { helperManager!.addHelper(helper, name: name) } func getHelper(#name: String) -> BrowserHelper? { return helperManager?.getHelper(name: name) } func hideContent(animated: Bool = false) { webView?.userInteractionEnabled = false if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.webView?.alpha = 0.0 }) } else { webView?.alpha = 0.0 } } func showContent(animated: Bool = false) { webView?.userInteractionEnabled = true if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.webView?.alpha = 1.0 }) } else { webView?.alpha = 1.0 } } func addSnackbar(bar: SnackBar) { bars.append(bar) browserDelegate?.browser(self, didAddSnackbar: bar) } func removeSnackbar(bar: SnackBar) { if let index = find(bars, bar) { bars.removeAtIndex(index) browserDelegate?.browser(self, didRemoveSnackbar: bar) } } func removeAllSnackbars() { // Enumerate backwards here because we'll remove items from the list as we go. for var i = bars.count-1; i >= 0; i-- { let bar = bars[i] removeSnackbar(bar) } } func expireSnackbars() { // Enumerate backwards here because we may remove items from the list as we go. for var i = bars.count-1; i >= 0; i-- { let bar = bars[i] if !bar.shouldPersist(self) { removeSnackbar(bar) } } } } private class HelperManager: NSObject, WKScriptMessageHandler { private var helpers = [String: BrowserHelper]() private weak var webView: WKWebView? init(webView: WKWebView) { self.webView = webView } @objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { for helper in helpers.values { if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { if scriptMessageHandlerName == message.name { helper.userContentController(userContentController, didReceiveScriptMessage: message) return } } } } func addHelper(helper: BrowserHelper, name: String) { if let existingHelper = helpers[name] { assertionFailure("Duplicate helper added: \(name)") } helpers[name] = helper // If this helper handles script messages, then get the handler name and register it. The Browser // receives all messages and then dispatches them to the right BrowserHelper. if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName) } } func getHelper(#name: String) -> BrowserHelper? { return helpers[name] } } extension WKWebView { func runScriptFunction(function: String, fromScript: String, callback: (AnyObject?) -> Void) { if let path = NSBundle.mainBundle().pathForResource(fromScript, ofType: "js") { if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String { evaluateJavaScript(source, completionHandler: { (obj, err) -> Void in if let err = err { println("Error injecting \(err)") return } self.evaluateJavaScript("__firefox__.\(fromScript).\(function)", completionHandler: { (obj, err) -> Void in self.evaluateJavaScript("delete window.__firefox__.\(fromScript)", completionHandler: { (obj, err) -> Void in }) if let err = err { println("Error running \(err)") return } callback(obj) }) }) } } } }
mpl-2.0
197f075100809207ce939b4a1c92bcb3
33.211864
171
0.597226
5.505
false
false
false
false
nghialv/MaterialKit
Source/MKSideDrawerViewController.swift
2
14315
// // MKSideDrawerViewController.swift // MaterialKit // // Created by Rahul Iyer on 10/02/16. // Copyright © 2016 Le Van Nghia. All rights reserved. // // Based on KYDrawerController (https://github.com/ykyouhei/KYDrawerController) import UIKit public extension UIViewController { /** A convenience property that provides access to the SideNavigationViewController. This is the recommended method of accessing the SideNavigationViewController through child UIViewControllers. */ public var sideDrawerViewController: MKSideDrawerViewController? { var viewController: UIViewController? = self while viewController != nil { if viewController is MKSideDrawerViewController { return viewController as? MKSideDrawerViewController } viewController = viewController?.parentViewController } return nil } } @objc public protocol MKSideDrawerControllerDelegate { optional func drawerController(drawerController: MKSideDrawerViewController, stateChanged state: MKSideDrawerViewController.DrawerState) } public class MKSideDrawerViewController: UIViewController, UIGestureRecognizerDelegate { // MARK: - Types @objc public enum DrawerDirection: Int { case Left, Right } @objc public enum DrawerState: Int { case Opened, Closed } private let _kContainerViewMaxAlpha : CGFloat = 0.2 private let _kDrawerAnimationDuration: NSTimeInterval = 0.25 // MARK: - Properties @IBInspectable var mainSegueIdentifier: String? @IBInspectable var drawerSegueIdentifier: String? private var _drawerConstraint: NSLayoutConstraint! private var _drawerWidthConstraint: NSLayoutConstraint! private var _panStartLocation = CGPointZero private var _panDelta: CGFloat = 0 lazy private var _containerView: UIView = { let view = UIView(frame: self.view.frame) let tapGesture = UITapGestureRecognizer( target: self, action: "didtapContainerView:" ) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor(white: 0.0, alpha: 0) view.addGestureRecognizer(tapGesture) tapGesture.delegate = self return view }() public var screenEdgePanGestreEnabled = true lazy private(set) var screenEdgePanGesture: UIScreenEdgePanGestureRecognizer = { let gesture = UIScreenEdgePanGestureRecognizer( target: self, action: "handlePanGesture:" ) switch self.drawerDirection { case .Left: gesture.edges = .Left case .Right: gesture.edges = .Right } gesture.delegate = self return gesture }() lazy private(set) var panGesture: UIPanGestureRecognizer = { let gesture = UIPanGestureRecognizer( target: self, action: "handlePanGesture:" ) gesture.delegate = self return gesture }() public weak var delegate: MKSideDrawerControllerDelegate? public var drawerDirection: DrawerDirection = .Left { didSet { switch drawerDirection { case .Left: screenEdgePanGesture.edges = .Left case .Right: screenEdgePanGesture.edges = .Right } let tmp = drawerViewController drawerViewController = tmp } } public var drawerState: DrawerState { get { return _containerView.hidden ? .Closed : .Opened } set { setDrawerState(drawerState, animated: false) } } @IBInspectable public var drawerWidth: CGFloat = 240 { didSet { _drawerWidthConstraint?.constant = drawerWidth } } public var mainViewController: UIViewController! { didSet { if let oldController = oldValue { oldController.willMoveToParentViewController(nil) oldController.view.removeFromSuperview() oldController.removeFromParentViewController() } guard let mainViewController = mainViewController else { return } let viewDictionary = ["mainView" : mainViewController.view] mainViewController.view.translatesAutoresizingMaskIntoConstraints = false addChildViewController(mainViewController) view.insertSubview(mainViewController.view, atIndex: 0) view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[mainView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "H:|-0-[mainView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) mainViewController.didMoveToParentViewController(self) } } public var drawerViewController : UIViewController? { didSet { if let oldController = oldValue { oldController.willMoveToParentViewController(nil) oldController.view.removeFromSuperview() oldController.removeFromParentViewController() } guard let drawerViewController = drawerViewController else { return } let viewDictionary = ["drawerView" : drawerViewController.view] let itemAttribute: NSLayoutAttribute let toItemAttribute: NSLayoutAttribute switch drawerDirection { case .Left: itemAttribute = .Right toItemAttribute = .Left case .Right: itemAttribute = .Left toItemAttribute = .Right } drawerViewController.view.layer.shadowColor = UIColor.blackColor().CGColor drawerViewController.view.layer.shadowOpacity = 0.4 drawerViewController.view.layer.shadowRadius = 5.0 drawerViewController.view.translatesAutoresizingMaskIntoConstraints = false addChildViewController(drawerViewController) _containerView.addSubview(drawerViewController.view) _drawerWidthConstraint = NSLayoutConstraint( item: drawerViewController.view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: drawerWidth ) drawerViewController.view.addConstraint(_drawerWidthConstraint) _drawerConstraint = NSLayoutConstraint( item: drawerViewController.view, attribute: itemAttribute, relatedBy: NSLayoutRelation.Equal, toItem: _containerView, attribute: toItemAttribute, multiplier: 1, constant: 0 ) _containerView.addConstraint(_drawerConstraint) _containerView.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[drawerView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) _containerView.updateConstraints() drawerViewController.updateViewConstraints() drawerViewController.didMoveToParentViewController(self) } } // MARK: - initialize public convenience init(drawerDirection: DrawerDirection, drawerWidth: CGFloat) { self.init() self.drawerDirection = drawerDirection self.drawerWidth = drawerWidth } // MARK: - Life Cycle override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let viewDictionary = ["_containerView": _containerView] view.addGestureRecognizer(screenEdgePanGesture) view.addGestureRecognizer(panGesture) view.addSubview(_containerView) view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "H:|-0-[_containerView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[_containerView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) _containerView.hidden = true if let mainSegueID = mainSegueIdentifier { performSegueWithIdentifier(mainSegueID, sender: self) } if let drawerSegueID = drawerSegueIdentifier { performSegueWithIdentifier(drawerSegueID, sender: self) } } // MARK: - Public Method public func setDrawerState(state: DrawerState, animated: Bool) { _containerView.hidden = false let duration: NSTimeInterval = animated ? _kDrawerAnimationDuration : 0 setWindowLevel(state == .Opened ? UIWindowLevelStatusBar + 1 : UIWindowLevelNormal) UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { () -> Void in switch state { case .Closed: self._drawerConstraint.constant = 0 self._containerView.backgroundColor = UIColor(white: 0, alpha: 0) case .Opened: let constant: CGFloat switch self.drawerDirection { case .Left: constant = self.drawerWidth case .Right: constant = -self.drawerWidth } self._drawerConstraint.constant = constant self._containerView.backgroundColor = UIColor( white: 0 , alpha: self._kContainerViewMaxAlpha ) } self._containerView.layoutIfNeeded() }) { (finished: Bool) -> Void in if state == .Closed { self._containerView.hidden = true } self.delegate?.drawerController?(self, stateChanged: state) } } public func transitionFromMainViewController(toViewController: UIViewController, duration: NSTimeInterval, options: UIViewAnimationOptions, animations: (() -> Void)?, completion: ((Bool) -> Void)?) { mainViewController.willMoveToParentViewController(nil) addChildViewController(toViewController) toViewController.view.frame = view.bounds transitionFromViewController( mainViewController, toViewController: toViewController, duration: duration, options: options, animations: animations, completion: { [unowned self](result: Bool) in toViewController.didMoveToParentViewController(self) self.mainViewController.removeFromParentViewController() self.mainViewController = toViewController if let completion = completion { completion(result) } }) } public func toggleDrawer(animated: Bool = true) { setDrawerState( drawerState == .Opened ? .Closed : .Opened, animated: animated) } // MARK: - Private Method final func handlePanGesture(sender: UIGestureRecognizer) { _containerView.hidden = false if sender.state == .Began { _panStartLocation = sender.locationInView(view) } let delta = CGFloat(sender.locationInView(view).x - _panStartLocation.x) let constant : CGFloat let backGroundAlpha : CGFloat let drawerState : DrawerState switch drawerDirection { case .Left: drawerState = _panDelta < 0 ? .Closed : .Opened constant = min(_drawerConstraint.constant + delta, drawerWidth) backGroundAlpha = min( _kContainerViewMaxAlpha, _kContainerViewMaxAlpha * (abs(constant) / drawerWidth) ) case .Right: drawerState = _panDelta > 0 ? .Closed : .Opened constant = max(_drawerConstraint.constant + delta, -drawerWidth) backGroundAlpha = min( _kContainerViewMaxAlpha, _kContainerViewMaxAlpha * (abs(constant) / drawerWidth) ) } if (sender.state == .Began) { if drawerState == .Closed { setWindowLevel(UIWindowLevelStatusBar + 1) } } _drawerConstraint.constant = constant _containerView.backgroundColor = UIColor( white: 0, alpha: backGroundAlpha ) switch sender.state { case .Changed: _panStartLocation = sender.locationInView(view) _panDelta = delta case .Ended, .Cancelled: setDrawerState(drawerState, animated: true) default: break } } final func didtapContainerView(gesture: UITapGestureRecognizer) { setDrawerState(.Closed, animated: true) } private func setWindowLevel(windowLevel: UIWindowLevel) { if let delegate = UIApplication.sharedApplication().delegate { if let window = delegate.window { if let window = window { window.windowLevel = windowLevel } } } } // MARK: - UIGestureRecognizerDelegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { switch gestureRecognizer { case panGesture: return drawerState == .Opened case screenEdgePanGesture: return screenEdgePanGestreEnabled ? drawerState == .Closed : false default: return touch.view == gestureRecognizer.view } } }
mit
6761578c81bed7fec056e7e171944eba
34.606965
203
0.60123
5.936956
false
false
false
false