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
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/Service/QiscusCommentClient.swift
1
13623
// // QiscusCommentClient.swift // QiscusSDK // // Created by ahmad athaullah on 7/17/16. // Copyright © 2016 qiscus. All rights reserved. // import Foundation import UIKit import Alamofire import AlamofireImage import SwiftyJSON import AVFoundation import Photos import UserNotifications import CocoaMQTT fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } let qiscus = Qiscus.sharedInstance open class QiscusCommentClient: NSObject { open static let sharedInstance = QiscusCommentClient() class var shared:QiscusCommentClient{ get{ return QiscusCommentClient.sharedInstance } } open var commentDelegate: QCommentDelegate? open var roomDelegate: QiscusRoomDelegate? open var linkRequest: Alamofire.Request? public static var isRegisteringDeviceToken: Bool = false // MARK: - Login or register open func loginOrRegister(_ email:String, password:String, username:String? = nil, avatarURL:String? = nil, reconnect:Bool = false, extras:String? = nil, onSuccess:(()->Void)? = nil){ if email.isEmpty || password.isEmpty { #if DEBUG fatalError("parameters cant be empty") #endif Qiscus.printLog(text: "parameters cant be empty") } var parameters:[String: AnyObject] = [String: AnyObject]() parameters = [ "email" : email as AnyObject, "password" : password as AnyObject, ] if let name = username{ parameters["username"] = name as AnyObject? } if let avatar = avatarURL{ parameters["avatar_url"] = avatar as AnyObject? } if let extras = extras{ parameters["extras"] = extras as AnyObject? } DispatchQueue.global().async(execute: { Qiscus.printLog(text: "login url: \(QiscusConfig.LOGIN_REGISTER)") Qiscus.printLog(text: "post parameters: \(parameters)") Qiscus.printLog(text: "post headers: \(QiscusConfig.sharedInstance.requestHeader)") QiscusService.session.request(QiscusConfig.LOGIN_REGISTER, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: QiscusConfig.sharedInstance.requestHeader).responseJSON(completionHandler: { response in Qiscus.printLog(text: "login register result: \(response)") Qiscus.printLog(text: "login url: \(QiscusConfig.LOGIN_REGISTER)") Qiscus.printLog(text: "post parameters: \(parameters)") Qiscus.printLog(text: "post headers: \(QiscusConfig.sharedInstance.requestHeader)") switch response.result { case .success: if let result = response.result.value{ let json = JSON(result) let success:Bool = (json["status"].intValue == 200) if success { let userData = json["results"]["user"] let _ = QiscusClient.saveData(fromJson: userData, reconnect: reconnect) Qiscus.setupReachability() if let delegate = Qiscus.shared.delegate { Qiscus.uiThread.async { autoreleasepool{ delegate.qiscus?(didConnect: true, error: nil) delegate.qiscusConnected?() }} } Qiscus.registerNotification() if let successAction = onSuccess { Qiscus.uiThread.async { autoreleasepool{ successAction() }} } }else{ if let delegate = Qiscus.shared.delegate { Qiscus.uiThread.async { autoreleasepool{ delegate.qiscusFailToConnect?("\(json["error"]["message"].stringValue)") delegate.qiscus?(didConnect: false, error: "\(json["error"]["message"].stringValue)") }} } } }else{ if let delegate = Qiscus.shared.delegate { Qiscus.uiThread.async { autoreleasepool{ let error = "Cant get data from qiscus server" delegate.qiscusFailToConnect?(error) delegate.qiscus?(didConnect: false, error: error) }} } } break case .failure(let error): if let delegate = Qiscus.shared.delegate { Qiscus.uiThread.async {autoreleasepool{ delegate.qiscusFailToConnect?("\(error)") delegate.qiscus?(didConnect: false, error: "\(error)") }} } break } }) }) } // MARK: - Register deviceToken func registerDevice(withToken deviceToken: String){ func register(){ QiscusCommentClient.isRegisteringDeviceToken = true let parameters:[String: AnyObject] = [ "token" : qiscus.config.USER_TOKEN as AnyObject, "device_token" : deviceToken as AnyObject, "device_platform" : "ios" as AnyObject ] Qiscus.printLog(text: "registerDevice url: \(QiscusConfig.SET_DEVICE_TOKEN_URL)") Qiscus.printLog(text: "post parameters: \(parameters)") QiscusService.session.request(QiscusConfig.SET_DEVICE_TOKEN_URL, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: QiscusConfig.sharedInstance.requestHeader).responseJSON(completionHandler: { response in Qiscus.printLog(text: "registerDevice result: \(response)") Qiscus.printLog(text: "registerDevice url: \(QiscusConfig.LOGIN_REGISTER)") Qiscus.printLog(text: "registerDevice parameters: \(parameters)") Qiscus.printLog(text: "registerDevice headers: \(QiscusConfig.sharedInstance.requestHeader)") QiscusCommentClient.isRegisteringDeviceToken = false switch response.result { case .success: DispatchQueue.main.async(execute: { if let result = response.result.value{ let json = JSON(result) let success:Bool = (json["status"].intValue == 200) if success { QiscusClient.hasRegisteredDeviceToken = true let pnData = json["results"] let configured = pnData["pn_ios_configured"].boolValue if configured { if let delegate = Qiscus.shared.delegate { delegate.qiscus?(didRegisterPushNotification: true, deviceToken: deviceToken, error: nil) } }else{ if let delegate = Qiscus.shared.delegate { delegate.qiscus?(didRegisterPushNotification: false, deviceToken: deviceToken, error: "unsuccessful register deviceToken : pushNotification not configured") } } }else{ if let delegate = Qiscus.shared.delegate { delegate.qiscus?(didRegisterPushNotification: false, deviceToken: deviceToken, error: "unsuccessful register deviceToken") } } }else{ if let delegate = Qiscus.shared.delegate { delegate.qiscus?(didRegisterPushNotification: false, deviceToken: deviceToken, error: "unsuccessful register deviceToken") } } }) break case .failure(let error): QiscusClient.hasRegisteredDeviceToken = false if let delegate = Qiscus.shared.delegate{ delegate.qiscus?(didRegisterPushNotification: false, deviceToken: deviceToken, error: "unsuccessful register deviceToken: \(error)") } break } }) } if Qiscus.isLoggedIn && !QiscusClient.hasRegisteredDeviceToken && !QiscusCommentClient.isRegisteringDeviceToken { register() }else{ reconnect { if !QiscusClient.hasRegisteredDeviceToken && !QiscusCommentClient.isRegisteringDeviceToken { register() } } } } private func reconnect(onSuccess:@escaping (()->Void)){ let email = Qiscus.client.userData.value(forKey: "qiscus_param_email") as? String let userKey = Qiscus.client.userData.value(forKey: "qiscus_param_pass") as? String let userName = Qiscus.client.userData.value(forKey: "qiscus_param_username") as? String let avatarURL = Qiscus.client.userData.value(forKey: "qiscus_param_avatar") as? String let extras = Qiscus.client.userData.value(forKey: "qiscus_param_extras") as? String if email != nil && userKey != nil && userName != nil { QiscusCommentClient.sharedInstance.loginOrRegister(email!, password: userKey!, username: userName!, avatarURL: avatarURL, reconnect: true, extras: extras, onSuccess: onSuccess) } } // MARK: - Remove deviceToken public func unRegisterDevice(){ if Qiscus.client.deviceToken != "" { let parameters:[String: AnyObject] = [ "token" : qiscus.config.USER_TOKEN as AnyObject, "device_token" : Qiscus.client.deviceToken as AnyObject, "device_platform" : "ios" as AnyObject ] QiscusService.session.request(QiscusConfig.REMOVE_DEVICE_TOKEN_URL, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: QiscusConfig.sharedInstance.requestHeader).responseJSON(completionHandler: { response in switch response.result { case .success: DispatchQueue.main.async(execute: { if let result = response.result.value{ let json = JSON(result) let success:Bool = (json["status"].intValue == 200) if success { let pnData = json["results"] let success = pnData["success"].boolValue if success { if let delegate = Qiscus.shared.delegate{ delegate.qiscus?(didUnregisterPushNotification: true, error: nil) Qiscus.client.deviceToken = "" } }else{ if let delegate = Qiscus.shared.delegate{ delegate.qiscus?(didUnregisterPushNotification: false, error: "cannot unregister device") } DispatchQueue.global().async { autoreleasepool{ self.unRegisterDevice() }} } }else{ if let delegate = Qiscus.shared.delegate { delegate.qiscus?(didUnregisterPushNotification: false, error: "cannot unregister device") } } }else{ if let delegate = Qiscus.shared.delegate { delegate.qiscus?(didUnregisterPushNotification: false, error: "cannot unregister device") } } }) break case .failure( _): if let delegate = Qiscus.shared.delegate { delegate.qiscus?(didUnregisterPushNotification: false, error: "cannot unregister device") } break } }) } } }
mit
b79add74b23639353f3dd2caa64c3033
47.476868
247
0.496036
5.821368
false
true
false
false
Latyntsev/bumper
bumper/NSImage+extension.swift
1
2761
// // NSImage+extension.swift // bumper // // Created by Aleksandr Latyntsev on 1/5/16. // Copyright © 2016 Aleksandr Latyntsev. All rights reserved. // import Foundation import CoreImage import AppKit extension NSImage { func unscaledBitmapImageRep() -> NSBitmapImageRep { let rep = NSBitmapImageRep.init( bitmapDataPlanes: nil, pixelsWide: Int(self.size.width), pixelsHigh: Int(self.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)! NSGraphicsContext.saveGraphicsState() NSGraphicsContext.setCurrentContext(NSGraphicsContext(bitmapImageRep: rep)) self .drawAtPoint(NSMakePoint(0, 0), fromRect: NSZeroRect, operation: .CompositeSourceOver, fraction: 1) NSGraphicsContext.restoreGraphicsState() return rep } func addText(text: String, inRect:NSRect, attributes: [String:NSObject]) -> NSImage { let size = text.sizeWithAttributes(attributes) let rect = CGRectInset(inRect, (inRect.width - size.width) / 2, (inRect.height - size.height) / 2) let textImage = NSImage.init(size: self.size) textImage.lockFocus() self.drawInRect(CGRectMake(0, 0, self.size.width, self.size.height)) text.drawInRect(rect, withAttributes: attributes) textImage.unlockFocus() return textImage } func addBlure(rect:NSRect, radisu: CGFloat)->NSImage { let drawRect = CGRectMake(0, 0, self.size.width, self.size.height) let inputImage = self.unscaledBitmapImageRep() let filter = CIFilter(name: "CIGaussianBlur")! filter.setDefaults() filter.setValue(CIImage(bitmapImageRep: inputImage), forKey: kCIInputImageKey) filter.setValue(radisu, forKey: "inputRadius") let outputImage = filter.valueForKey(kCIOutputImageKey) as! CIImage let blurredImage = NSImage.init(size: self.size) blurredImage.lockFocus() self.drawInRect(drawRect) outputImage.drawInRect(rect, fromRect: rect, operation: .CompositeSourceOver, fraction: 1) blurredImage.unlockFocus() return blurredImage; } func saveImage(path: String) { let bitmapRep = self.unscaledBitmapImageRep() let pngData = bitmapRep.representationUsingType(.NSPNGFileType, properties: [:])! pngData .writeToFile(path, atomically: true) } }
mit
3f2bdfd6a2ea45f4eeea72717a562674
31.104651
112
0.619203
5
false
false
false
false
hmusaddiquie27/SwiftSuccessCheck
SwiftSuccessCheckExaple/SwiftSuccessCheckExaple/ViewController.swift
1
2251
// // ViewController.swift // SwiftSuccessCheckExaple // // Created by Musaddiquie Husain on 18/08/17. // Copyright © 2017 MHusain. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var successCheckView: UIView! @IBOutlet weak var durationSlider: UISlider! @IBOutlet weak var lblStatus: UILabel! @IBOutlet weak var shapeSegment: UISegmentedControl! var scView: SuccessCheck! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //add a target on slider durationSlider.addTarget(self, action: #selector(onDurationChange), for: .valueChanged) //add success check view scView = SuccessCheck(frame: successCheckView.bounds) //play animation playSuccessCheck(withDuration: Double(durationSlider.value)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //callback called when duration value change @objc func onDurationChange(){ scView.removeFromSuperview() playSuccessCheck(withDuration: Double(durationSlider.value)) } func playSuccessCheck(withDuration duration: Double) { successCheckView.addSubview(scView) lblStatus.text = "Animating..." lblStatus.textColor = .green scView.initWithTime(withDuration: duration, bgCcolor: .orange, colorOfStroke: .white, widthOfTick: 5) { //do additional work after completion self.lblStatus.text = "Completed" self.lblStatus.textColor = .orange } } @IBAction func indexChanged(sender: UISegmentedControl) { switch shapeSegment.selectedSegmentIndex { case 0://square successCheckView.layer.cornerRadius = 0 break default://circle successCheckView.layer.cornerRadius = successCheckView.frame.size.width / 2 break } successCheckView.layer.masksToBounds = true playSuccessCheck(withDuration: Double(durationSlider.value)) } }
mit
339986a368ea043850b20b247f8e44d3
32.58209
111
0.66
4.83871
false
false
false
false
1aurabrown/eidolon
Kiosk/Bid Fulfillment/FulfillmentContainerViewController.swift
1
2302
import UIKit class FulfillmentContainerViewController: UIViewController { var allowAnimations:Bool = true; @IBOutlet var cancelButton: UIButton! @IBOutlet var contentView: UIView! @IBOutlet var backgroundView: UIView! override func viewDidLoad() { super.viewDidLoad() modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext contentView.alpha = 0 backgroundView.alpha = 0 cancelButton.alpha = 0 } // We force viewDidAppear to access the PlaceBidViewController // so this allow animations in the modal // This is mostly a placeholder for a more complex animation in the future func viewDidAppearAnimation(animated: Bool) { self.contentView.frame = CGRectOffset(self.contentView.frame, 0, 100) UIView.animateTwoStepIf(animated, withDuration: 0.3, { () -> Void in self.backgroundView.alpha = 1 }, midway: { () -> Void in self.contentView.alpha = 1 self.cancelButton.alpha = 1 self.contentView.frame = CGRectOffset(self.contentView.frame, 0, -100) }) { (complete) -> Void in } } @IBAction func closeModalTapped(sender: AnyObject) { closeFulfillmentModal() } func closeFulfillmentModal(completion: (() -> ())? = nil) -> Void { UIView.animateIf(allowAnimations, withDuration: 0.4, { () -> Void in self.contentView.alpha = 0 self.backgroundView.alpha = 0 self.cancelButton.alpha = 0 }) { (completed:Bool) -> Void in let presentingVC = self.presentingViewController! presentingVC.dismissViewControllerAnimated(false, completion: nil) completion?() } } func internalNavigationController() -> FulfillmentNavigationController? { self.loadViewProgrammatically() return self.childViewControllers.first as? FulfillmentNavigationController } class func instantiateFromStoryboard() -> FulfillmentContainerViewController { return UIStoryboard(name: "Fulfillment", bundle: nil) .instantiateViewControllerWithIdentifier(ViewControllerStoryboardIdentifier.FulfillmentContainer.rawValue) as FulfillmentContainerViewController } }
mit
abce1cdc73a186b4dde9028f4785c4e3
33.878788
156
0.667246
5.416471
false
false
false
false
grantjbutler/Artikolo
Carthage/Checkouts/Dip/DipPlayground.playground/Sources/Models.swift
2
2439
import Foundation public protocol Service: class {} public class ServiceImp1: Service { public init() {} } public class ServiceImp2: Service { public init() {} } public class ServiceImp3: Service { public init() {} } public class ServiceImp4: Service { public let name: String public init(name: String, baseURL: NSURL, port: Int) { self.name = name } } public protocol Client: class { var service: Service {get} init(service: Service) } public class ClientImp1: Client { public var service: Service public required init(service: Service) { self.service = service } } public class ClientImp2: Client { public var service: Service public required init(service: Service) { self.service = service } } public class ServiceFactory { public init() {} public func someService() -> Service { return ServiceImp1() } } public class ClientServiceImp: Service { public weak var client: Client? public init() {} } public protocol Logger {} public protocol Tracker {} public protocol DataProvider {} public protocol Router {} public class LoggerImp: Logger { public init() {} } public class TrackerImp: Tracker { public init() {} } public class RouterImp: Router { public init() {} } public class DataProviderImp: DataProvider { public init() {} } public protocol ListInteractorOutput: class {} public protocol ListModuleInterface: class {} public protocol ListInteractorInput: class {} public class ListPresenter: NSObject { public var listInteractor : ListInteractorInput? public var listWireframe : ListWireframe? public override init() {} } public class ListInteractor: NSObject { public var output : ListInteractorOutput? public override init() {} } public class ListWireframe : NSObject { public let addWireframe: AddWireframe public let listPresenter: ListPresenter public init(addWireFrame: AddWireframe, listPresenter: ListPresenter) { self.addWireframe = addWireFrame self.listPresenter = listPresenter } } public protocol AddModuleDelegate: class {} public protocol AddModuleInterface: class {} public class AddWireframe: NSObject { let addPresenter : AddPresenter public init(addPresenter: AddPresenter) { self.addPresenter = addPresenter } } public class AddPresenter: NSObject { public var addModuleDelegate : AddModuleDelegate? public override init() {} }
mit
669e45754affff71210c416dbf42471b
21.172727
75
0.715867
4.5
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/Photo/EditorImageResizerControlView.swift
1
24214
// // EditorImageResizerControlView.swift // HXPHPicker // // Created by Slience on 2021/3/22. // import UIKit protocol EditorImageResizerControlViewDelegate: AnyObject { func controlView(beganChanged controlView: EditorImageResizerControlView, _ rect: CGRect) func controlView(endChanged controlView: EditorImageResizerControlView, _ rect: CGRect) func controlView(didChanged controlView: EditorImageResizerControlView, _ rect: CGRect) } class EditorImageResizerControlView: UIView { weak var delegate: EditorImageResizerControlViewDelegate? lazy var topControl: UIView = { let view = UIView.init() let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerHandler(pan:))) view.addGestureRecognizer(pan) return view }() lazy var bottomControl: UIView = { let view = UIView.init() let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerHandler(pan:))) view.addGestureRecognizer(pan) return view }() lazy var leftControl: UIView = { let view = UIView.init() let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerHandler(pan:))) view.addGestureRecognizer(pan) return view }() lazy var rightControl: UIView = { let view = UIView.init() let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerHandler(pan:))) view.addGestureRecognizer(pan) return view }() lazy var leftTopControl: UIView = { let view = UIView.init() let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerHandler(pan:))) view.addGestureRecognizer(pan) return view }() lazy var rightTopControl: UIView = { let view = UIView.init() let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerHandler(pan:))) view.addGestureRecognizer(pan) return view }() lazy var rightBottomControl: UIView = { let view = UIView.init() let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerHandler(pan:))) view.addGestureRecognizer(pan) return view }() lazy var leftBottomControl: UIView = { let view = UIView.init() let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerHandler(pan:))) view.addGestureRecognizer(pan) return view }() /// 固定比例 var fixedRatio: Bool = false var aspectRatio: CGSize = .zero var maxImageresizerFrame: CGRect = .zero var imageresizerFrame: CGRect = .zero var currentFrame: CGRect = .zero var panning: Bool = false var controls: [ UIGestureRecognizer ] = [] init() { super.init(frame: .zero) addSubview(topControl) addSubview(bottomControl) addSubview(leftControl) addSubview(rightControl) addSubview(leftTopControl) addSubview(leftBottomControl) addSubview(rightTopControl) addSubview(rightBottomControl) controls.append(topControl.gestureRecognizers!.first!) controls.append(bottomControl.gestureRecognizers!.first!) controls.append(leftControl.gestureRecognizers!.first!) controls.append(rightControl.gestureRecognizers!.first!) controls.append(leftTopControl.gestureRecognizers!.first!) controls.append(leftBottomControl.gestureRecognizers!.first!) controls.append(rightTopControl.gestureRecognizers!.first!) controls.append(rightBottomControl.gestureRecognizers!.first!) } func changeControl(enabled: Bool, index: Int) { for (item, control) in controls.enumerated() where item != index { (control as? UIPanGestureRecognizer)?.isEnabled = enabled } } func topControlHandler(_ point: CGPoint) { var rectX = currentFrame.minX var rectY = currentFrame.minY var rectW = currentFrame.width var rectH = currentFrame.height let widthRatio = aspectRatio.width / aspectRatio.height let heightRatio = aspectRatio.height / aspectRatio.width rectH -= point.y rectY += point.y if rectH < 50 { rectH = 50 rectY = currentFrame.maxY - 50 } if rectY < maxImageresizerFrame.minY { rectY = maxImageresizerFrame.minY rectH = currentFrame.maxY - maxImageresizerFrame.minY } if fixedRatio && !aspectRatio.equalTo(.zero) { var w = rectH * widthRatio if currentFrame.width > currentFrame.height { if rectH < 50 { rectH = 50 rectY = currentFrame.maxY - rectH w = rectH * widthRatio } }else { if w < 50 { w = 50 rectH = w * heightRatio rectY = currentFrame.maxY - rectH } } rectX = currentFrame.minX + (rectW - w) * 0.5 rectW = w if rectX < maxImageresizerFrame.minX { rectX = maxImageresizerFrame.minX } if rectX + rectW > maxImageresizerFrame.maxX { rectX = maxImageresizerFrame.maxX - rectW } if rectW >= maxImageresizerFrame.width { rectX = maxImageresizerFrame.minX rectW = maxImageresizerFrame.width let h = rectW * heightRatio rectY += (rectH - h) * 0.5 rectH = h let minY = currentFrame.maxY - rectH if rectY < minY { rectY = minY } } } frame = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) } func leftControlHandler(_ point: CGPoint) { var rectX = currentFrame.minX var rectY = currentFrame.minY var rectW = currentFrame.width var rectH = currentFrame.height let widthRatio = aspectRatio.width / aspectRatio.height let heightRatio = aspectRatio.height / aspectRatio.width rectX += point.x rectW -= point.x if rectW < 50 { rectW = 50 rectX = currentFrame.maxX - 50 } if rectX < maxImageresizerFrame.minX { rectX = maxImageresizerFrame.minX rectW = currentFrame.maxX - maxImageresizerFrame.minX } if fixedRatio && !aspectRatio.equalTo(.zero) { var h = rectW * heightRatio if currentFrame.width > currentFrame.height { if h < 50 { h = 50 rectW = h * widthRatio rectX = currentFrame.maxX - rectW } }else { if rectW < 50 { rectW = 50 rectX = currentFrame.maxX - rectW h = rectW * heightRatio } } rectY = currentFrame.minY + (rectH - h) * 0.5 rectH = h if rectY < maxImageresizerFrame.minY { rectY = maxImageresizerFrame.minY } if rectY + rectH > maxImageresizerFrame.maxY { rectY = maxImageresizerFrame.maxY - rectH } if rectH >= maxImageresizerFrame.height { rectY = maxImageresizerFrame.minY rectH = maxImageresizerFrame.height let w = rectH * widthRatio rectX += (rectW - w) * 0.5 rectW = w let minX = currentFrame.maxX - rectW if rectX < minX { rectX = minX } } } frame = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) } func rightControlHandler(_ point: CGPoint) { var rectX = currentFrame.minX var rectY = currentFrame.minY var rectW = currentFrame.width var rectH = currentFrame.height let widthRatio = aspectRatio.width / aspectRatio.height let heightRatio = aspectRatio.height / aspectRatio.width rectW += point.x if rectW < 50 { rectW = 50 } if rectW > maxImageresizerFrame.maxX - currentFrame.minX { rectW = maxImageresizerFrame.maxX - currentFrame.minX } if fixedRatio && !aspectRatio.equalTo(.zero) { var h = rectW * heightRatio if currentFrame.width > currentFrame.height { if h < 50 { h = 50 rectW = h * widthRatio } }else { if rectW < 50 { rectW = 50 h = rectW * heightRatio } } rectY = currentFrame.minY + (rectH - h) * 0.5 rectH = h if rectY < maxImageresizerFrame.minY { rectY = maxImageresizerFrame.minY } if rectY + rectH > maxImageresizerFrame.maxY { rectY = maxImageresizerFrame.maxY - rectH } if rectH >= maxImageresizerFrame.height { rectY = maxImageresizerFrame.minY rectH = maxImageresizerFrame.height let w = rectH * widthRatio rectX += (rectW - w) * 0.5 rectW = w let maxX = currentFrame.minX + rectW if rectX + rectW > maxX { rectX = maxX - rectW } } } frame = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) } func bottomControlHandler(_ point: CGPoint) { var rectX = currentFrame.minX var rectY = currentFrame.minY var rectW = currentFrame.width var rectH = currentFrame.height let widthRatio = aspectRatio.width / aspectRatio.height let heightRatio = aspectRatio.height / aspectRatio.width rectH += point.y if rectH < 50 { rectH = 50 } if rectH > maxImageresizerFrame.maxY - currentFrame.minY { rectH = maxImageresizerFrame.maxY - currentFrame.minY } if fixedRatio && !aspectRatio.equalTo(.zero) { var w = rectH * widthRatio if currentFrame.width > currentFrame.height { if rectH < 50 { rectH = 50 w = rectH * widthRatio } }else { if w < 50 { w = 50 rectH = w * heightRatio } } rectX = currentFrame.minX + (rectW - w) * 0.5 rectW = w if rectX < maxImageresizerFrame.minX { rectX = maxImageresizerFrame.minX } if rectX + rectW > maxImageresizerFrame.maxX { rectX = maxImageresizerFrame.maxX - rectW } if rectW >= maxImageresizerFrame.width { rectX = maxImageresizerFrame.minX rectW = maxImageresizerFrame.width let h = rectW * heightRatio rectY += (rectH - h) * 0.5 rectH = h let maxY = currentFrame.minY + rectH if rectY + rectH > maxY { rectY = maxY - rectH } } } frame = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) } func leftTopControlHandler(_ point: CGPoint) { var rectX = currentFrame.minX var rectY = currentFrame.minY var rectW = currentFrame.width var rectH = currentFrame.height let widthRatio = aspectRatio.width / aspectRatio.height let heightRatio = aspectRatio.height / aspectRatio.width if fixedRatio && !aspectRatio.equalTo(.zero) { if aspectRatio.width > aspectRatio.height { rectW -= point.x rectH = rectW * heightRatio }else { rectH -= point.y rectW = rectH * widthRatio } if currentFrame.width > currentFrame.height { if rectH < 50 { rectH = 50 rectW = rectH * widthRatio } }else { if rectW < 50 { rectW = 50 rectH = rectW * heightRatio } } if rectW > currentFrame.maxX - maxImageresizerFrame.minX { rectW = currentFrame.maxX - maxImageresizerFrame.minX rectH = rectW * heightRatio } if rectH > currentFrame.maxY - maxImageresizerFrame.minY { rectH = currentFrame.maxY - maxImageresizerFrame.minY rectW = rectH * widthRatio } rectX = currentFrame.maxX - rectW rectY = currentFrame.maxY - rectH }else { rectX += point.x rectY += point.y rectW -= point.x rectH -= point.y if rectW < 50 { rectW = 50 rectX = currentFrame.maxX - 50 } if rectH < 50 { rectH = 50 rectY = currentFrame.maxY - 50 } if rectX < maxImageresizerFrame.minX { rectX = maxImageresizerFrame.minX rectW = currentFrame.maxX - maxImageresizerFrame.minX } if rectY < maxImageresizerFrame.minY { rectY = maxImageresizerFrame.minY rectH = currentFrame.maxY - maxImageresizerFrame.minY } } frame = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) } func leftBottomControlHandler(_ point: CGPoint) { var rectX = currentFrame.minX let rectY = currentFrame.minY var rectW = currentFrame.width var rectH = currentFrame.height let widthRatio = aspectRatio.width / aspectRatio.height let heightRatio = aspectRatio.height / aspectRatio.width if fixedRatio && !aspectRatio.equalTo(.zero) { if aspectRatio.width > aspectRatio.height { rectW -= point.x rectH = rectW * heightRatio }else { rectH += point.y rectW = rectH * widthRatio } if currentFrame.width > currentFrame.height { if rectH < 50 { rectH = 50 rectW = rectH * widthRatio } }else { if rectW < 50 { rectW = 50 rectH = rectW * heightRatio } } if rectW > currentFrame.maxX - maxImageresizerFrame.minX { rectW = currentFrame.maxX - maxImageresizerFrame.minX rectH = rectW * heightRatio } if rectH > maxImageresizerFrame.maxY - currentFrame.minY { rectH = maxImageresizerFrame.maxY - currentFrame.minY rectW = rectH * widthRatio } rectX = currentFrame.maxX - rectW }else { rectX += point.x rectW -= point.x rectH += point.y if rectW < 50 { rectW = 50 rectX = currentFrame.maxX - 50 } if rectH < 50 { rectH = 50 } if rectX < maxImageresizerFrame.minX { rectX = maxImageresizerFrame.minX rectW = currentFrame.maxX - maxImageresizerFrame.minX } if rectH > maxImageresizerFrame.maxY - currentFrame.minY { rectH = maxImageresizerFrame.maxY - currentFrame.minY } } frame = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) } func rightTopControlHandler(_ point: CGPoint) { let rectX = currentFrame.minX var rectY = currentFrame.minY var rectW = currentFrame.width var rectH = currentFrame.height let widthRatio = aspectRatio.width / aspectRatio.height let heightRatio = aspectRatio.height / aspectRatio.width if fixedRatio && !aspectRatio.equalTo(.zero) { if aspectRatio.width > aspectRatio.height { rectW += point.x rectH = rectW * heightRatio }else { rectH -= point.y rectW = rectH * widthRatio } if currentFrame.width > currentFrame.height { if rectH < 50 { rectH = 50 rectW = rectH * widthRatio } }else { if rectW < 50 { rectW = 50 rectH = rectW * heightRatio } } if rectW > maxImageresizerFrame.maxX - currentFrame.minX { rectW = maxImageresizerFrame.maxX - currentFrame.minX rectH = rectW * heightRatio } rectY = currentFrame.maxY - rectH if rectY < maxImageresizerFrame.minY { rectY = maxImageresizerFrame.minY rectH = currentFrame.maxY - maxImageresizerFrame.minY rectW = rectH * widthRatio } }else { rectW += point.x rectY += point.y rectH -= point.y if rectW < 50 { rectW = 50 } if rectH < 50 { rectH = 50 rectY = currentFrame.maxY - 50 } if rectW > maxImageresizerFrame.maxX - currentFrame.minX { rectW = maxImageresizerFrame.maxX - currentFrame.minX } if rectY < maxImageresizerFrame.minY { rectY = maxImageresizerFrame.minY rectH = currentFrame.maxY - maxImageresizerFrame.minY } } frame = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) } func rightBottomControlHandler(_ point: CGPoint) { let rectX = currentFrame.minX let rectY = currentFrame.minY var rectW = currentFrame.width var rectH = currentFrame.height let widthRatio = aspectRatio.width / aspectRatio.height let heightRatio = aspectRatio.height / aspectRatio.width if fixedRatio && !aspectRatio.equalTo(.zero) { if aspectRatio.width > aspectRatio.height { rectW += point.x rectH = rectW * heightRatio }else { rectH += point.y rectW = rectH * widthRatio } if currentFrame.width > currentFrame.height { if rectH < 50 { rectH = 50 rectW = rectH * widthRatio } }else { if rectW < 50 { rectW = 50 rectH = rectW * heightRatio } } if rectW > maxImageresizerFrame.maxX - currentFrame.minX { rectW = maxImageresizerFrame.maxX - currentFrame.minX rectH = rectW * heightRatio } if rectH > maxImageresizerFrame.maxY - currentFrame.minY { rectH = maxImageresizerFrame.maxY - currentFrame.minY rectW = rectH * widthRatio } }else { rectW += point.x rectH += point.y if rectW < 50 { rectW = 50 } if rectH < 50 { rectH = 50 } if rectW > maxImageresizerFrame.maxX - currentFrame.minX { rectW = maxImageresizerFrame.maxX - currentFrame.minX } if rectH > maxImageresizerFrame.maxY - currentFrame.minY { rectH = maxImageresizerFrame.maxY - currentFrame.minY } } frame = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) } @objc func panGestureRecognizerHandler(pan: UIPanGestureRecognizer) { let view = pan.view let point = pan.translation(in: view) if pan.state == .began { changeControl(enabled: false, index: controls.firstIndex(of: pan)!) panning = true delegate?.controlView(beganChanged: self, frame) currentFrame = self.frame } if view == topControl { topControlHandler(point) }else if view == leftControl { leftControlHandler(point) }else if view == rightControl { rightControlHandler(point) }else if view == bottomControl { bottomControlHandler(point) }else if view == leftTopControl { leftTopControlHandler(point) }else if view == leftBottomControl { leftBottomControlHandler(point) }else if view == rightTopControl { rightTopControlHandler(point) }else if view == rightBottomControl { rightBottomControlHandler(point) } delegate?.controlView(didChanged: self, frame) if pan.state == .cancelled || pan.state == .ended || pan.state == .failed { delegate?.controlView(endChanged: self, frame) panning = false changeControl(enabled: true, index: controls.firstIndex(of: pan)!) } } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if !isUserInteractionEnabled { return nil } if topControl.frame.contains(point) { return topControl }else if leftControl.frame.contains(point) { return leftControl }else if rightControl.frame.contains(point) { return rightControl }else if bottomControl.frame.contains(point) { return bottomControl }else if leftTopControl.frame.contains(point) { return leftTopControl }else if leftBottomControl.frame.contains(point) { return leftBottomControl }else if rightTopControl.frame.contains(point) { return rightTopControl }else if rightBottomControl.frame.contains(point) { return rightBottomControl } return nil } override func layoutSubviews() { super.layoutSubviews() let lineMarign: CGFloat = 20 topControl.frame = CGRect(x: lineMarign, y: -lineMarign, width: width - lineMarign * 2, height: lineMarign * 2) leftControl.frame = CGRect( x: -lineMarign, y: lineMarign, width: lineMarign * 2, height: height - lineMarign * 2 ) rightControl.frame = CGRect( x: width - lineMarign, y: lineMarign, width: lineMarign * 2, height: height - lineMarign * 2 ) bottomControl.frame = CGRect( x: lineMarign, y: height - lineMarign, width: width - lineMarign * 2, height: lineMarign * 2 ) leftTopControl.frame = CGRect( x: -lineMarign, y: -lineMarign, width: lineMarign * 2, height: lineMarign * 2 ) leftBottomControl.frame = CGRect( x: -lineMarign, y: height - lineMarign, width: lineMarign * 2, height: lineMarign * 2 ) rightTopControl.frame = CGRect( x: width - lineMarign, y: -lineMarign, width: lineMarign * 2, height: lineMarign * 2 ) rightBottomControl.frame = CGRect( x: width - lineMarign, y: height - lineMarign, width: lineMarign * 2, height: lineMarign * 2 ) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
084a974508ebc19a2c27857e61c3bbb4
36.762871
119
0.53495
4.720359
false
false
false
false
JGiola/swift-corelibs-foundation
Foundation/NSConcreteValue.swift
2
6087
// 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 // import CoreFoundation #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif internal class NSConcreteValue : NSValue { struct TypeInfo : Equatable { let size : Int let name : String init?(objCType spec: String) { var size: Int = 0 var align: Int = 0 var count : Int = 0 var type = _NSSimpleObjCType(spec) guard type != nil else { print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'") return nil } if type == .StructBegin { fatalError("NSConcreteValue.TypeInfo: cannot encode structs") } else if type == .ArrayBegin { let scanner = Scanner(string: spec) scanner.scanLocation = 1 guard scanner.scanInt(&count) && count > 0 else { print("NSConcreteValue.TypeInfo: array count is missing or zero") return nil } guard let elementType = _NSSimpleObjCType(scanner.scanUpToString(String(_NSSimpleObjCType.ArrayEnd))) else { print("NSConcreteValue.TypeInfo: array type is missing") return nil } guard _NSGetSizeAndAlignment(elementType, &size, &align) else { print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'") return nil } type = elementType } guard _NSGetSizeAndAlignment(type!, &size, &align) else { print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'") return nil } self.size = count != 0 ? size * count : size self.name = spec } } private static var _cachedTypeInfo = Dictionary<String, TypeInfo>() private static var _cachedTypeInfoLock = NSLock() private var _typeInfo : TypeInfo private var _storage : UnsafeMutableRawPointer required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) { let spec = String(cString: type) var typeInfo : TypeInfo? = nil NSConcreteValue._cachedTypeInfoLock.synchronized { typeInfo = NSConcreteValue._cachedTypeInfo[spec] if typeInfo == nil { typeInfo = TypeInfo(objCType: spec) NSConcreteValue._cachedTypeInfo[spec] = typeInfo } } guard typeInfo != nil else { fatalError("NSConcreteValue.init: failed to initialize from type encoding spec '\(spec)'") } self._typeInfo = typeInfo! self._storage = UnsafeMutableRawPointer.allocate(byteCount: self._typeInfo.size, alignment: 1) self._storage.copyMemory(from: value, byteCount: self._typeInfo.size) } deinit { // Cannot deinitialize raw memory. self._storage.deallocate() } override func getValue(_ value: UnsafeMutableRawPointer) { value.copyMemory(from: self._storage, byteCount: self._size) } override var objCType : UnsafePointer<Int8> { return NSString(self._typeInfo.name).utf8String! // XXX leaky } override var classForCoder: AnyClass { return NSValue.self } override var description : String { let boundBytes = self.value.bindMemory(to: UInt8.self, capacity: self._size) return Data(bytes: boundBytes, count: self._size).description } convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let type = aDecoder.decodeObject() as? NSString else { return nil } let typep = type._swiftObject // FIXME: This will result in reading garbage memory. self.init(bytes: [], objCType: typep) aDecoder.decodeValue(ofObjCType: typep, at: self.value) } override func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(String(cString: self.objCType)._bridgeToObjectiveC()) aCoder.encodeValue(ofObjCType: self.objCType, at: self.value) } private var _size : Int { return self._typeInfo.size } private var value : UnsafeMutableRawPointer { return self._storage } private func _isEqualToValue(_ other: NSConcreteValue) -> Bool { if self === other { return true } if self._size != other._size { return false } let bytes1 = self.value let bytes2 = other.value if bytes1 == bytes2 { return true } return memcmp(bytes1, bytes2, self._size) == 0 } override func isEqual(_ value: Any?) -> Bool { guard let other = value as? NSConcreteValue else { return false } return self._typeInfo == other._typeInfo && self._isEqualToValue(other) } override var hash: Int { return self._typeInfo.name.hashValue &+ Int(bitPattern: CFHashBytes(self.value.assumingMemoryBound(to: UInt8.self), self._size)) } } internal func ==(x : NSConcreteValue.TypeInfo, y : NSConcreteValue.TypeInfo) -> Bool { return x.name == y.name && x.size == y.size }
apache-2.0
c883997080c51702664fe78074029aec
32.445055
124
0.577953
5.207015
false
false
false
false
evgenyneu/moa
Moa/Simulator/MoaSimulator.swift
1
5953
import Foundation /** Simulates image download in unit tests instead of sending real network requests. Example: override func tearDown() { super.tearDown() MoaSimulator.clear() } func testDownload() { // Create simulator to catch downloads of the given image let simulator = MoaSimulator.simulate("35px.jpg") // Download the image let imageView = UIImageView() imageView.moa.url = "http://site.com/35px.jpg" // Check the image download has been requested XCTAssertEqual(1, simulator.downloaders.count) XCTAssertEqual("http://site.com/35px.jpg", simulator.downloaders[0].url) // Simulate server response with the given image let bundle = NSBundle(forClass: self.dynamicType) let image = UIImage(named: "35px.jpg", inBundle: bundle, compatibleWithTraitCollection: nil)! simulator.respondWithImage(image) // Check the image has arrived XCTAssertEqual(35, imageView.image!.size.width) } */ public final class MoaSimulator { /// Array of currently registered simulators. static var simulators = [MoaSimulator]() /** Returns a simulator that will be used to catch image requests that have matching URLs. This method is usually called at the beginning of the unit test. - parameter urlPart: Image download request that include the supplied urlPart will be simulated. All other requests will continue to real network. - returns: Simulator object. It is usually used in unit test to verify which request have been sent and simulating server response by calling its respondWithImage and respondWithError methods. */ @discardableResult public static func simulate(_ urlPart: String) -> MoaSimulator { let simulator = MoaSimulator(urlPart: urlPart) simulators.append(simulator) return simulator } /** Respond to all future download requests that have matching URLs. Call `clear` method to stop auto responding. - parameter urlPart: Image download request that include the supplied urlPart will automatically and immediately succeed with the supplied image. All other requests will continue to real network. - parameter image: Image that is be passed to success handler of future requests. - returns: Simulator object. It is usually used in unit test to verify which request have been sent. One does not need to call its `respondWithImage` method because it will be called automatically for all matching requests. */ @discardableResult public static func autorespondWithImage(_ urlPart: String, image: MoaImage) -> MoaSimulator { let simulator = simulate(urlPart) simulator.autorespondWithImage = image return simulator } /** Fail all future download requests that have matching URLs. Call `clear` method to stop auto responding. - parameter urlPart: Image download request that include the supplied urlPart will automatically and immediately fail. All other requests will continue to real network. - parameter error: Optional error that is passed to the error handler of failed requests. - parameter response: Optional response that is passed to the error handler of failed requests. - returns: Simulator object. It is usually used in unit test to verify which request have been sent. One does not need to call its `respondWithError` method because it will be called automatically for all matching requests. */ @discardableResult public static func autorespondWithError(_ urlPart: String, error: Error? = nil, response: HTTPURLResponse? = nil) -> MoaSimulator { let simulator = simulate(urlPart) simulator.autorespondWithError = (error, response) return simulator } /// Stop using simulators and use real network instead. public static func clear() { simulators = [] } static func simulatorsMatchingUrl(_ url: String) -> [MoaSimulator] { return simulators.filter { simulator in MoaString.contains(url, substring: simulator.urlPart) } } static func createDownloader(_ url: String) -> MoaSimulatedImageDownloader? { let matchingSimulators = simulatorsMatchingUrl(url) if !matchingSimulators.isEmpty { let downloader = MoaSimulatedImageDownloader(url: url) for simulator in matchingSimulators { simulator.downloaders.append(downloader) if let autorespondWithImage = simulator.autorespondWithImage { downloader.autorespondWithImage = autorespondWithImage } if let autorespondWithError = simulator.autorespondWithError { downloader.autorespondWithError = autorespondWithError } } return downloader } return nil } // MARK: - Instance var urlPart: String /// The image that will be used to respond to all future download requests var autorespondWithImage: MoaImage? var autorespondWithError: (error: Error?, response: HTTPURLResponse?)? /// Array of registered image downloaders. public var downloaders = [MoaSimulatedImageDownloader]() init(urlPart: String) { self.urlPart = urlPart } /** Simulate a successful server response with the supplied image. - parameter image: Image that is be passed to success handler of all ongoing requests. */ public func respondWithImage(_ image: MoaImage) { for downloader in downloaders { downloader.respondWithImage(image) } } /** Simulate an error response from server. - parameter error: Optional error that is passed to the error handler of all ongoing requests. - parameter response: Optional response that is passed to the error handler of all ongoing requests. */ public func respondWithError(_ error: Error? = nil, response: HTTPURLResponse? = nil) { for downloader in downloaders { downloader.respondWithError(error, response: response) } } }
mit
a045e64bf45b78765f47b5c201ce2400
32.823864
226
0.718125
4.859592
false
true
false
false
nixzhu/coolie-cli
Sources/Arguments.swift
1
3655
// // Coolie.swift // Coolie // // Created by NIX on 16/5/14. // Copyright © 2016年 nixWork. All rights reserved. // final public class Arguments { public enum Option: CustomStringConvertible { case Short(key: String) case Long(key: String) case Mixed(shortKey: String, longKey: String) public var description: String { switch self { case .Short(let key): return "-" + key case .Long(let key): return "--" + key case .Mixed(let shortKey, let longKey): return "-" + shortKey + ", " + "--" + longKey } } } enum Value { case None case Exist(String) var value: String? { switch self { case .None: return nil case .Exist(let string): return string } } } let keyValues: [String: Value] public init(_ arguments: [String]) { guard arguments.count > 1 else { self.keyValues = [:] return } var keyValues = [String: Value]() var i = 1 while true { let _a = arguments[arguments_safe: i] let _b = arguments[arguments_safe: i + 1] guard let a = _a else { break } if a.arguments_isKey { if let b = _b, !b.arguments_isKey { keyValues[a] = Value.Exist(b) } else { keyValues[a] = Value.None } } else { print("Invalid argument: \(a)") break } if let b = _b { if b.arguments_isKey { i += 1 } else { i += 2 } } else { break } } self.keyValues = keyValues } public func containsOption(_ option: Option) -> Bool { switch option { case .Short(let key): return keyValues["-" + key] != nil case .Long(let key): return keyValues["--" + key] != nil case .Mixed(let shortKey, let longKey): return (keyValues["-" + shortKey] != nil) || (keyValues["--" + longKey] != nil) } } public func containsOptions(_ options: [Option]) -> Bool { return options.reduce(true, { $0 && containsOption($1) }) } public func valueOfOption(_ option: Option) -> String? { switch option { case .Short(let key): return keyValues["-" + key]?.value case .Long(let key): return keyValues["--" + key]?.value case .Mixed(let shortKey, let longKey): let shortKeyValue = keyValues["-" + shortKey]?.value let longKeyValue = keyValues["--" + longKey]?.value if let shortKeyValue = shortKeyValue, let longKeyValue = longKeyValue { guard shortKeyValue == longKeyValue else { fatalError("Duplicate value for option: \(option)") } } return shortKeyValue ?? longKeyValue } } } private extension String { var arguments_isLongKey: Bool { return hasPrefix("--") } var arguments_isShortKey: Bool { return !arguments_isLongKey && hasPrefix("-") } var arguments_isKey: Bool { return arguments_isLongKey || arguments_isShortKey } } private extension Array { subscript (arguments_safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } }
mit
6696fbc8e24fd4b1fd6aad565f2a88f1
26.458647
91
0.484666
4.755208
false
false
false
false
joerocca/GitHawk
Pods/Apollo/Sources/Apollo/GraphQLResultAccumulator.swift
3
6318
public protocol GraphQLResultAccumulator: class { associatedtype PartialResult associatedtype FieldEntry associatedtype ObjectResult associatedtype FinalResult func accept(scalar: JSONValue, info: GraphQLResolveInfo) throws -> PartialResult func acceptNullValue(info: GraphQLResolveInfo) throws -> PartialResult func accept(list: [PartialResult], info: GraphQLResolveInfo) throws -> PartialResult func accept(fieldEntry: PartialResult, info: GraphQLResolveInfo) throws -> FieldEntry func accept(fieldEntries: [FieldEntry], info: GraphQLResolveInfo) throws -> ObjectResult func finish(rootValue: ObjectResult, info: GraphQLResolveInfo) throws -> FinalResult } public func zip<Accumulator1: GraphQLResultAccumulator, Accumulator2: GraphQLResultAccumulator>(_ accumulator1: Accumulator1, _ accumulator2: Accumulator2) -> Zip2Accumulator<Accumulator1, Accumulator2> { return Zip2Accumulator(accumulator1, accumulator2) } public func zip<Accumulator1: GraphQLResultAccumulator, Accumulator2: GraphQLResultAccumulator, Accumulator3: GraphQLResultAccumulator>(_ accumulator1: Accumulator1, _ accumulator2: Accumulator2, _ accumulator3: Accumulator3) -> Zip3Accumulator<Accumulator1, Accumulator2, Accumulator3> { return Zip3Accumulator(accumulator1, accumulator2, accumulator3) } public final class Zip2Accumulator<Accumulator1: GraphQLResultAccumulator, Accumulator2: GraphQLResultAccumulator>: GraphQLResultAccumulator { public typealias PartialResult = (Accumulator1.PartialResult, Accumulator2.PartialResult) public typealias FieldEntry = (Accumulator1.FieldEntry, Accumulator2.FieldEntry) public typealias ObjectResult = (Accumulator1.ObjectResult, Accumulator2.ObjectResult) public typealias FinalResult = (Accumulator1.FinalResult, Accumulator2.FinalResult) private let accumulator1: Accumulator1 private let accumulator2: Accumulator2 fileprivate init(_ accumulator1: Accumulator1, _ accumulator2: Accumulator2) { self.accumulator1 = accumulator1 self.accumulator2 = accumulator2 } public func accept(scalar: JSONValue, info: GraphQLResolveInfo) throws -> PartialResult { return (try accumulator1.accept(scalar: scalar, info: info), try accumulator2.accept(scalar: scalar, info: info)) } public func acceptNullValue(info: GraphQLResolveInfo) throws -> PartialResult { return (try accumulator1.acceptNullValue(info: info), try accumulator2.acceptNullValue(info: info)) } public func accept(list: [PartialResult], info: GraphQLResolveInfo) throws -> PartialResult { let (list1, list2) = unzip(list) return (try accumulator1.accept(list: list1, info: info), try accumulator2.accept(list: list2, info: info)) } public func accept(fieldEntry: PartialResult, info: GraphQLResolveInfo) throws -> FieldEntry { return (try accumulator1.accept(fieldEntry: fieldEntry.0, info: info), try accumulator2.accept(fieldEntry: fieldEntry.1, info: info)) } public func accept(fieldEntries: [FieldEntry], info: GraphQLResolveInfo) throws -> ObjectResult { let (fieldEntries1, fieldEntries2) = unzip(fieldEntries) return (try accumulator1.accept(fieldEntries: fieldEntries1, info: info), try accumulator2.accept(fieldEntries: fieldEntries2, info: info)) } public func finish(rootValue: ObjectResult, info: GraphQLResolveInfo) throws -> FinalResult { return (try accumulator1.finish(rootValue: rootValue.0, info: info), try accumulator2.finish(rootValue: rootValue.1, info: info)) } } public final class Zip3Accumulator<Accumulator1: GraphQLResultAccumulator, Accumulator2: GraphQLResultAccumulator, Accumulator3: GraphQLResultAccumulator>: GraphQLResultAccumulator { public typealias PartialResult = (Accumulator1.PartialResult, Accumulator2.PartialResult, Accumulator3.PartialResult) public typealias FieldEntry = (Accumulator1.FieldEntry, Accumulator2.FieldEntry, Accumulator3.FieldEntry) public typealias ObjectResult = (Accumulator1.ObjectResult, Accumulator2.ObjectResult, Accumulator3.ObjectResult) public typealias FinalResult = (Accumulator1.FinalResult, Accumulator2.FinalResult, Accumulator3.FinalResult) private let accumulator1: Accumulator1 private let accumulator2: Accumulator2 private let accumulator3: Accumulator3 fileprivate init(_ accumulator1: Accumulator1, _ accumulator2: Accumulator2, _ accumulator3: Accumulator3) { self.accumulator1 = accumulator1 self.accumulator2 = accumulator2 self.accumulator3 = accumulator3 } public func accept(scalar: JSONValue, info: GraphQLResolveInfo) throws -> PartialResult { return (try accumulator1.accept(scalar: scalar, info: info), try accumulator2.accept(scalar: scalar, info: info), try accumulator3.accept(scalar: scalar, info: info)) } public func acceptNullValue(info: GraphQLResolveInfo) throws -> PartialResult { return (try accumulator1.acceptNullValue(info: info), try accumulator2.acceptNullValue(info: info), try accumulator3.acceptNullValue(info: info)) } public func accept(list: [PartialResult], info: GraphQLResolveInfo) throws -> PartialResult { let (list1, list2, list3) = unzip(list) return (try accumulator1.accept(list: list1, info: info), try accumulator2.accept(list: list2, info: info), try accumulator3.accept(list: list3, info: info)) } public func accept(fieldEntry: PartialResult, info: GraphQLResolveInfo) throws -> FieldEntry { return (try accumulator1.accept(fieldEntry: fieldEntry.0, info: info), try accumulator2.accept(fieldEntry: fieldEntry.1, info: info), try accumulator3.accept(fieldEntry: fieldEntry.2, info: info)) } public func accept(fieldEntries: [FieldEntry], info: GraphQLResolveInfo) throws -> ObjectResult { let (fieldEntries1, fieldEntries2, fieldEntries3) = unzip(fieldEntries) return (try accumulator1.accept(fieldEntries: fieldEntries1, info: info), try accumulator2.accept(fieldEntries: fieldEntries2, info: info), try accumulator3.accept(fieldEntries: fieldEntries3, info: info)) } public func finish(rootValue: ObjectResult, info: GraphQLResolveInfo) throws -> FinalResult { return (try accumulator1.finish(rootValue: rootValue.0, info: info), try accumulator2.finish(rootValue: rootValue.1, info: info), try accumulator3.finish(rootValue: rootValue.2, info: info)) } }
mit
03cadaae5db05e8c4be0dca0ec1c4938
57.5
288
0.7849
4.471338
false
false
false
false
rplankenhorn/BrightFreddy
Pod/Classes/HTTPResponse.swift
1
1114
// // HTTPResponse.swift // BrightFreddy // // Created by Robbie Plankenhorn on 3/10/16. // // import Foundation import Freddy let emptyBody:NSData = "".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! public class HTTPResponse { public let statusCode: Int public let body: NSData public let headers: Dictionary<String, AnyObject> private var bodyText: String? init(statusCode: Int, body: NSData, headers: Dictionary<String, AnyObject>) { self.statusCode = statusCode self.body = body self.headers = headers } public var bodyAsText: String { if let bodyT = self.bodyText { return bodyT } else { self.bodyText = NSString(data: body, encoding: NSUTF8StringEncoding)! as String return self.bodyText! } } } extension HTTPResponse { public func bodyJSON() throws -> JSON { return try self.body.jsonObject() } } extension NSData { func jsonObject() throws -> JSON { return try JSON(data: self) } }
mit
008f7792236659671aa1ece1b49fe574
20.037736
96
0.621185
4.385827
false
false
false
false
yonasstephen/swift-of-airbnb
airbnb-datepicker/airbnb-datepicker/AirbnbDatePickerViewController.swift
1
26504
// // AirbnbDatePickerViewController.swift // airbnb-datepicker // // Created by Yonas Stephen on 22/2/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import UIKit import Foundation public protocol AirbnbDatePickerDelegate { func datePickerController(_ datePickerController: AirbnbDatePickerViewController, didSaveStartDate startDate: Date?, endDate: Date?) } public class AirbnbDatePickerViewController: UICollectionViewController { let monthHeaderID = "monthHeaderID" let cellID = "cellID" let dateFormatter = DateFormatter() var delegate: AirbnbDatePickerDelegate? var selectedStartDate: Date? { didSet { headerView.selectedStartDate = selectedStartDate footerView.isSaveEnabled = (selectedStartDate == nil || selectedEndDate != nil) } } var startDateIndexPath: IndexPath? var selectedEndDate: Date? { didSet { headerView.selectedEndDate = selectedEndDate footerView.isSaveEnabled = (selectedStartDate == nil || selectedEndDate != nil) } } var endDateIndexPath: IndexPath? var today: Date! var calendar: Calendar { return Utility.calendar } var isLoadingMore = false var initialNumberOfMonths = 24 var subsequentMonthsLoadCount = 12 var lastNthMonthBeforeLoadMore = 12 var months: [Date]! var days: [(days: Int, prepend: Int, append: Int)]! var itemWidth: CGFloat { return floor(view.frame.size.width / 7) } var collectionViewWidthConstraint: NSLayoutConstraint? // MARK: - Initialization convenience init(dateFrom: Date?, dateTo: Date?) { self.init(collectionViewLayout: UICollectionViewFlowLayout()) today = Date() initDates() // put in closure to trigger didSet ({ selectedStartDate = dateFrom })() ({ selectedEndDate = dateTo })() if selectedStartDate != nil && startDateIndexPath == nil { startDateIndexPath = findIndexPath(forDate: selectedStartDate!) if let indexPath = startDateIndexPath { collectionView?.selectItem(at: indexPath, animated: false, scrollPosition: .left) } } if selectedEndDate != nil && endDateIndexPath == nil { endDateIndexPath = findIndexPath(forDate: selectedEndDate!) if let indexPath = endDateIndexPath { collectionView?.selectItem(at: indexPath, animated: false, scrollPosition: .left) } } NotificationCenter.default.addObserver(self, selector: #selector(AirbnbDatePickerViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } func initDates() { let month = calendar.component(.month, from: today) let year = calendar.component(.year, from: today) let dateComp = DateComponents(year: year, month: month, day: 1) var curMonth = calendar.date(from: dateComp) months = [Date]() days = [(days: Int, prepend: Int, append: Int)]() for _ in 0..<initialNumberOfMonths { months.append(curMonth!) let numOfDays = calendar.range(of: .day, in: .month, for: curMonth!)!.count let firstWeekDay = calendar.component(.weekday, from: curMonth!.startOfMonth()) let lastWeekDay = calendar.component(.weekday, from: curMonth!.endOfMonth()) days.append((days: numOfDays, prepend: firstWeekDay - 1, append: 7 - lastWeekDay)) curMonth = calendar.date(byAdding: .month, value: 1, to: curMonth!) } } // MARK: - View Components lazy var dismissButton: UIBarButtonItem = { let btn = UIButton(type: UIButtonType.custom) btn.setImage(UIImage(named: "Delete"), for: .normal) btn.frame = CGRect(x: 0, y: 0, width: 20, height: 20) btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left btn.addTarget(self, action: #selector(AirbnbDatePickerViewController.handleDismiss), for: .touchUpInside) let barBtn = UIBarButtonItem(customView: btn) return barBtn }() lazy var clearButton: UIBarButtonItem = { let btn = UIButton(type: UIButtonType.custom) btn.setTitle("Clear", for: .normal) btn.frame = CGRect(x: 0, y: 0, width: 100, height: 20) btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right btn.titleLabel?.font = UIFont.systemFont(ofSize: 15) btn.addTarget(self, action: #selector(AirbnbDatePickerViewController.handleClearInput), for: .touchUpInside) let barBtn = UIBarButtonItem(customView: btn) return barBtn }() var headerView: AirbnbDatePickerHeader = { let view = AirbnbDatePickerHeader() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.PRIMARY_COLOR return view }() var headerSeparator: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.SECONDARY_COLOR return view }() lazy var footerView: AirbnbDatePickerFooter = { let view = AirbnbDatePickerFooter() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.PRIMARY_COLOR view.delegate = self return view }() var footerSeparator: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.SECONDARY_COLOR return view }() // MARK: - View Setups override public func viewDidLoad() { super.viewDidLoad() } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if #available(iOS 11, *) { } else { self.automaticallyAdjustsScrollViewInsets = false } self.view.backgroundColor = Theme.PRIMARY_COLOR setupNavigationBar() setupViews() setupLayout() } @objc func rotated() { collectionView?.collectionViewLayout.invalidateLayout() } func setupNavigationBar() { self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.view.backgroundColor = UIColor.clear self.navigationItem.setLeftBarButton(dismissButton, animated: true) self.navigationItem.setRightBarButton(clearButton, animated: true) } func setupViews() { setupHeaderView() setupFooterView() setupCollectionView() } func setupHeaderView() { view.addSubview(headerView) headerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true headerView.topAnchor.constraint(equalTo: view.topAnchor, constant: self.navigationController != nil ? self.navigationController!.navigationBar.frame.size.height : 0).isActive = true headerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true headerView.heightAnchor.constraint(equalToConstant: 150).isActive = true view.addSubview(headerSeparator) headerSeparator.topAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true headerSeparator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true headerSeparator.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true headerSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true } func setupCollectionView() { collectionView?.translatesAutoresizingMaskIntoConstraints = false collectionView?.alwaysBounceVertical = true collectionView?.backgroundColor = Theme.PRIMARY_COLOR collectionView?.showsVerticalScrollIndicator = false collectionView?.allowsMultipleSelection = true collectionView?.register(AirbnbDatePickerCell.self, forCellWithReuseIdentifier: cellID) collectionView?.register(AirbnbDatePickerMonthHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: monthHeaderID) collectionView?.topAnchor.constraint(equalTo: headerSeparator.bottomAnchor).isActive = true collectionView?.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true collectionView?.bottomAnchor.constraint(equalTo: footerSeparator.topAnchor).isActive = true let gap = view.frame.size.width - (itemWidth * 7) collectionViewWidthConstraint = collectionView?.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -gap) collectionViewWidthConstraint?.isActive = true } func setupLayout() { if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout { layout.scrollDirection = .vertical layout.minimumLineSpacing = 5 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets() layout.itemSize = CGSize(width: itemWidth, height: itemWidth) } } func setupFooterView() { view.addSubview(footerView) footerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true footerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true footerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true footerView.heightAnchor.constraint(equalToConstant: 60).isActive = true view.addSubview(footerSeparator) footerSeparator.bottomAnchor.constraint(equalTo: footerView.topAnchor).isActive = true footerSeparator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true footerSeparator.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true footerSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true } // MARK: - Collection View Delegates override public func numberOfSections(in collectionView: UICollectionView) -> Int { return months.count } override public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return days[section].prepend + days[section].days + days[section].append } override public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { // Load more months on reaching last (n)th month if indexPath.section == (months.count - lastNthMonthBeforeLoadMore) && !isLoadingMore { let originalCount = months.count isLoadingMore = true DispatchQueue.global(qos: .background).async { self.loadMoreMonths(completion: { () in DispatchQueue.main.async { collectionView.performBatchUpdates({ () in let range = originalCount..<originalCount.advanced(by: self.subsequentMonthsLoadCount) let indexSet = IndexSet(integersIn: range) collectionView.insertSections(indexSet) }, completion: { (res) in self.isLoadingMore = false }) } }) } } } override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! AirbnbDatePickerCell configure(cell: cell, withIndexPath: indexPath) return cell } override public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: monthHeaderID, for: indexPath) as! AirbnbDatePickerMonthHeader let monthData = months[indexPath.section] let curYear = calendar.component(.year, from: today) let year = calendar.component(.year, from: monthData) let month = calendar.component(.month, from: monthData) if (curYear == year) { header.monthLabel.text = dateFormatter.monthSymbols[month - 1] } else { header.monthLabel.text = "\(dateFormatter.shortMonthSymbols[month - 1]) \(year)" } return header } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: self.view.frame.width, height: 50) } override public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell cell.type.insert(.Selected) let selectedMonth = months[indexPath.section] let year = calendar.component(.year, from: selectedMonth) let month = calendar.component(.month, from: selectedMonth) let dateComp = DateComponents(year: year, month: month, day: Int(cell.dateLabel.text!)) let selectedDate = calendar.date(from: dateComp)! if selectedStartDate == nil || (selectedEndDate == nil && selectedDate < selectedStartDate!) { if startDateIndexPath != nil, let prevStartCell = collectionView.cellForItem(at: startDateIndexPath!) as? AirbnbDatePickerCell { prevStartCell.type.remove(.Selected) prevStartCell.configureCell() collectionView.deselectItem(at: startDateIndexPath!, animated: false) } selectedStartDate = selectedDate startDateIndexPath = indexPath } else if selectedEndDate == nil { selectedEndDate = selectedDate endDateIndexPath = indexPath // select start date to trigger cell UI change if let startCell = collectionView.cellForItem(at: startDateIndexPath!) as? AirbnbDatePickerCell { startCell.type.insert(.SelectedStartDate) startCell.configureCell() } // select end date to trigger cell UI change if let endCell = collectionView.cellForItem(at: endDateIndexPath!) as? AirbnbDatePickerCell { endCell.type.insert(.SelectedEndDate) endCell.configureCell() } // loop through cells in between selected dates and select them selectInBetweenCells() } else { // deselect previously selected cells deselectSelectedCells() selectedStartDate = selectedDate selectedEndDate = nil startDateIndexPath = indexPath endDateIndexPath = nil if let newStartCell = collectionView.cellForItem(at: startDateIndexPath!) as? AirbnbDatePickerCell { newStartCell.type.insert(.Selected) newStartCell.configureCell() } } cell.configureCell() } override public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell return cell.type.contains(.Date) } override public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell if isInBetween(indexPath: indexPath) { deselectSelectedCells() let selectedMonth = months[indexPath.section] let year = calendar.component(.year, from: selectedMonth) let month = calendar.component(.month, from: selectedMonth) let dateComp = DateComponents(year: year, month: month, day: Int(cell.dateLabel.text!)) let selectedDate = calendar.date(from: dateComp)! selectedStartDate = selectedDate selectedEndDate = nil startDateIndexPath = indexPath endDateIndexPath = nil if let newStartCell = collectionView.cellForItem(at: startDateIndexPath!) as? AirbnbDatePickerCell { newStartCell.type.insert(.Selected) newStartCell.configureCell() collectionView.selectItem(at: startDateIndexPath!, animated: false, scrollPosition: .left) } } } override public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool { if selectedEndDate == nil && startDateIndexPath == indexPath { return false } return true } override public func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell cell.type.insert(.Highlighted) cell.configureCell() } override public func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell return cell.type.contains(.Date) } override public func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell cell.type.remove(.Highlighted) cell.configureCell() } func configure(cell: AirbnbDatePickerCell, withIndexPath indexPath: IndexPath) { let dateData = days[indexPath.section] let month = calendar.component(.month, from: months[indexPath.section]) let year = calendar.component(.year, from: months[indexPath.section]) if indexPath.item < dateData.prepend || indexPath.item >= (dateData.prepend + dateData.days) { cell.dateLabel.text = "" cell.type = [.Empty] } else { let todayYear = calendar.component(.year, from: today) let todayMonth = calendar.component(.month, from: today) let todayDay = calendar.component(.day, from: today) let curDay = indexPath.item - dateData.prepend + 1 let isPastDate = year == todayYear && month == todayMonth && curDay < todayDay cell.dateLabel.text = String(curDay) cell.dateLabel.textColor = isPastDate ? Theme.SECONDARY_COLOR : UIColor.white cell.type = isPastDate ? [.PastDate] : [.Date] if todayDay == curDay, todayMonth == month, todayYear == year { cell.type.insert(.Today) } } if startDateIndexPath != nil && indexPath == startDateIndexPath { if endDateIndexPath == nil { cell.type.insert(.Selected) } else { cell.type.insert(.SelectedStartDate) } } if endDateIndexPath != nil { if indexPath == endDateIndexPath { cell.type.insert(.SelectedEndDate) } else if isInBetween(indexPath: indexPath) { cell.type.insert(.InBetweenDate) } } cell.configureCell() } func isInBetween(indexPath: IndexPath) -> Bool { if let start = startDateIndexPath, let end = endDateIndexPath { return (indexPath.section > start.section || (indexPath.section == start.section && indexPath.item > start.item)) && (indexPath.section < end.section || (indexPath.section == end.section && indexPath.item < end.item)) } return false } func selectInBetweenCells() { var section = startDateIndexPath!.section var item = startDateIndexPath!.item var indexPathArr = [IndexPath]() while section < months.count, section <= endDateIndexPath!.section { let curIndexPath = IndexPath(item: item, section: section) if let cell = collectionView?.cellForItem(at: curIndexPath) as? AirbnbDatePickerCell { if curIndexPath != startDateIndexPath && curIndexPath != endDateIndexPath { cell.type.insert(.InBetweenDate) cell.configureCell() } indexPathArr.append(curIndexPath) } if section == endDateIndexPath!.section && item >= endDateIndexPath!.item { // stop iterating beyond end date break } else if item >= (collectionView!.numberOfItems(inSection: section) - 1) { // more than num of days in the month section += 1 item = 0 } else { item += 1 } } collectionView?.performBatchUpdates({ self.collectionView?.reloadItems(at: indexPathArr) }, completion: nil) } func deselectSelectedCells() { if let start = startDateIndexPath { var section = start.section var item = start.item + 1 if let cell = collectionView?.cellForItem(at: start) as? AirbnbDatePickerCell { cell.type.remove([.InBetweenDate, .SelectedStartDate, .SelectedEndDate, .Selected]) cell.configureCell() collectionView?.deselectItem(at: start, animated: false) } if let end = endDateIndexPath { let indexPathArr = [IndexPath]() while section < months.count, section <= end.section { let curIndexPath = IndexPath(item: item, section: section) if let cell = collectionView?.cellForItem(at: curIndexPath) as? AirbnbDatePickerCell { cell.type.remove([.InBetweenDate, .SelectedStartDate, .SelectedEndDate, .Selected]) cell.configureCell() collectionView?.deselectItem(at: curIndexPath, animated: false) } if section == end.section && item >= end.item { // stop iterating beyond end date break } else if item >= (collectionView!.numberOfItems(inSection: section) - 1) { // more than num of days in the month section += 1 item = 0 } else { item += 1 } } collectionView?.performBatchUpdates({ self.collectionView?.reloadItems(at: indexPathArr) }, completion: nil) } } } // MARK: - Event Handlers @objc func handleDismiss() { self.navigationController?.dismiss(animated: true, completion: nil) } @objc func handleClearInput() { deselectSelectedCells() selectedStartDate = nil selectedEndDate = nil startDateIndexPath = nil endDateIndexPath = nil } func loadMoreMonths(completion: (() -> Void)?) { let lastDate = months.last! let month = calendar.component(.month, from: lastDate) let year = calendar.component(.year, from: lastDate) let dateComp = DateComponents(year: year, month: month + 1, day: 1) var curMonth = calendar.date(from: dateComp) for _ in 0..<subsequentMonthsLoadCount { months.append(curMonth!) let numOfDays = calendar.range(of: .day, in: .month, for: curMonth!)!.count let firstWeekDay = calendar.component(.weekday, from: curMonth!.startOfMonth()) let lastWeekDay = calendar.component(.weekday, from: curMonth!.endOfMonth()) days.append((days: numOfDays, prepend: firstWeekDay - 1, append: 7 - lastWeekDay)) curMonth = calendar.date(byAdding: .month, value: 1, to: curMonth!) } if let handler = completion { handler() } } // MARK: - Functions func findIndexPath(forDate date: Date) -> IndexPath? { var indexPath: IndexPath? = nil if let section = months.index(where: { calendar.component(.year, from: $0) == calendar.component(.year, from: date) && calendar.component(.month, from: $0) == calendar.component(.month, from: date)}) { let item = days[section].prepend + calendar.component(.day, from: date) - 1 indexPath = IndexPath(item: item, section: section) } return indexPath } } // MARK: - AirbnbDatePickerFooterDelegate extension AirbnbDatePickerViewController: AirbnbDatePickerFooterDelegate { func didSave() { if let del = delegate { del.datePickerController(self, didSaveStartDate: selectedStartDate, endDate: selectedEndDate) self.navigationController?.dismiss(animated: true, completion: nil) } } }
mit
b3a76fac5f13601414d7843d40198189
40.671384
198
0.622118
5.789209
false
false
false
false
mikina/SwiftNews
SwiftNews/SwiftNews/Modules/LatestNews/TabCoordinator/LatestNewsTabCoordinator.swift
1
841
// // LatestNewsTabCoordinator.swift // SwiftNews // // Created by Mike Mikina on 12/5/16. // Copyright © 2016 SwiftCookies.com. All rights reserved. // import UIKit class LatestNewsTabCoordinator: TabCoordinator { var rootController: CustomNavigationController var customTabBarItem = TabBarItem(builder: TabBarItemBuilder { builder in builder.icon = "latest_news" builder.type = .normal builder.backgroundColor = UIColor.white builder.iconColor = UIColor(Constants.TabBar.DefaultButtonColor) builder.selectedIconColor = UIColor(Constants.TabBar.DefaultSelectedButtonColor) }) init() { let homeVC = ViewController() homeVC.title = "Latest news" self.rootController = CustomNavigationController(rootViewController: homeVC) self.rootController.customTabBarItem = self.customTabBarItem } }
mit
e9c9d1c8a6dde3a5f68ab4760122d5e1
30.111111
84
0.759524
4.516129
false
true
false
false
Raizlabs/ios-template
{{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Coordinators/AuthCoordinator.swift
1
3766
// // AuthCoordinator.swift // {{ cookiecutter.project_name | replace(' ', '') }} // // Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}. // Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved. // import UIKit import Services private enum State { case authenticated case onboarded case needsOnboarding } class AuthCoordinator: Coordinator { var childCoordinator: Coordinator? let baseController: UIViewController weak var delegate: Delegate? private let client = APIClient.shared private var state: State { if client.oauthClient.isAuthenticated { return .authenticated } else if UserDefaults.hasOnboarded { return .onboarded } else { return .needsOnboarding } } init(_ baseController: UIViewController) { self.baseController = baseController } func start(animated: Bool, completion: VoidClosure?) { switch state { case .authenticated: notify(.didSignIn) case .onboarded: let signInCoordinator = SignInCoordinator(baseController) signInCoordinator.delegate = self signInCoordinator.start(animated: animated, completion: completion) childCoordinator = signInCoordinator case .needsOnboarding: let onboardCoordinator = OnboardingCoordinator(baseController) onboardCoordinator.delegate = self onboardCoordinator.start(animated: animated, completion: completion) childCoordinator = onboardCoordinator } } func cleanup(animated: Bool, completion: VoidClosure?) { childCoordinator?.cleanup(animated: animated, completion: completion) } } extension AuthCoordinator: Actionable { enum Action { case didSignIn case didSkipAuth } } extension AuthCoordinator: SignInCoordinatorDelegate { func signInCoordinator(_ coordinator: SignInCoordinator, didNotify action: SignInCoordinator.Action) { switch action { case .didSignIn: notify(.didSignIn) } } } extension AuthCoordinator: OnboardingCoordinatorDelegate { func onboardingCoordinator(_ coordinator: OnboardingCoordinator, didNotify action: OnboardingCoordinator.Action) { switch action { case .didSkipAuth: notify(.didSkipAuth) case .didRequestJoin: guard let onboardCoordinator = childCoordinator as? OnboardingCoordinator else { preconditionFailure("Upon signing in, AppCoordinator should have an AuthCoordinator as a child.") } childCoordinator = nil onboardCoordinator.cleanup(animated: true) { let signInCoordinator = SignInCoordinator(self.baseController) signInCoordinator.delegate = self self.childCoordinator = signInCoordinator // TODO - signInCoordinator move from signIn to register here signInCoordinator.start(animated: true, completion: nil) } case .didRequestSignIn: guard let onboardCoordinator = childCoordinator as? OnboardingCoordinator else { preconditionFailure("Upon signing in, AppCoordinator should have an AuthCoordinator as a child.") } childCoordinator = nil onboardCoordinator.cleanup(animated: true) { let signInCoordinator = SignInCoordinator(self.baseController) signInCoordinator.delegate = self self.childCoordinator = signInCoordinator signInCoordinator.start(animated: true, completion: nil) } } } }
mit
04108d6cffa2a2d34d9a19e78d45fad4
31.456897
118
0.647809
5.393983
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Site Creation/Wizard/WizardNavigation.swift
1
2934
import UIKit // MARK: - WizardNavigation final class WizardNavigation: UINavigationController { private let steps: [WizardStep] private let pointer: WizardNavigationPointer private lazy var firstContentViewController: UIViewController? = { guard let firstStep = self.steps.first else { return nil } return firstStep.content }() init(steps: [WizardStep]) { self.steps = steps self.pointer = WizardNavigationPointer(capacity: steps.count) guard let firstStep = self.steps.first else { fatalError("Navigation Controller was initialized with no steps.") } let root = firstStep.content super.init(rootViewController: root) delegate = self.pointer configureSteps() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Navigation Overrides override var shouldAutorotate: Bool { return WPDeviceIdentification.isiPad() ? true : false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return WPDeviceIdentification.isiPad() ? .all : .portrait } override var preferredStatusBarStyle: UIStatusBarStyle { return .default } private func configureSteps() { for var step in steps { step.delegate = self } } } extension WizardNavigation: WizardDelegate { func nextStep() { guard let nextStepIndex = pointer.nextIndex else { // If we find this statement in Fabric, it suggests 11388 might not have been resolved DDLogInfo("We've exceeded the max index of our wizard navigation steps (i.e., \(pointer.currentIndex)") return } let nextStep = steps[nextStepIndex] let nextViewController = nextStep.content // If we find this statement in Fabric, it's likely that we haven't resolved 11388 if viewControllers.contains(nextViewController) { DDLogInfo("Attempting to push \(String(describing: nextViewController.title)) when it's already on the navigation stack!") } pushViewController(nextViewController, animated: true) } } final class WizardNavigationPointer: NSObject, UINavigationControllerDelegate { private let maxIndex: Int private(set) var currentIndex = 0 init(capacity: Int = 1) { self.maxIndex = max(capacity - 1, 0) } var nextIndex: Int? { guard currentIndex < maxIndex else { return nil } return (currentIndex + 1) } func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { guard let index = navigationController.viewControllers.firstIndex(of: viewController) else { return } currentIndex = index } }
gpl-2.0
d164a573864f9850b37fa4cdd3c35db5
29.5625
137
0.659509
5.305606
false
false
false
false
aquarchitect/MyKit
Sources/Shared/Utilities/Matrix.swift
1
2953
// // Matrix.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2015 Hai Nguyen. // /// Simple _Matrix_ to work with LCS algorithm (debugging purposes only). /// /// - warning: reference [Surge](https://github.com/mattt/Surge) for optimized matrix computation. public struct Matrix<Element> { // MARK: Property fileprivate var elements: [Element] public let rows: Int public let columns: Int public var count: Int { return elements.count } // MARK: Initialization public init(repeating value: Element, rows: Int, columns: Int) { self.rows = rows self.columns = columns self.elements = Array(repeating: value, count: rows * columns) } } // MARK: - Support Methods private extension Matrix { func isValid(row: Int, column: Int) -> Bool { return (0..<rows).contains(row) && (0..<columns).contains(column) } } // MARK: - Supscription public extension Matrix { subscript(row: Int, column: Int) -> Element { get { assert(isValid(row: row, column: column), "Index out of bounds.") return elements[row * columns + column] } set { assert(isValid(row: row, column: column), "Index out of bounds") elements[row * columns + column] = newValue } } subscript(row row: Int) -> ArraySlice<Element> { get { assert(row < rows, "Row out of bounds.") let startIndex = row * columns let endIndex = startIndex + columns return elements[startIndex..<endIndex] } set { assert(row < rows, "Row out of bounds.") assert(newValue.count == columns, "Column out of bounds") let startIndex = row * columns let endIndex = startIndex + columns elements.replaceSubrange(startIndex..<endIndex, with: newValue) } } subscript(column column: Int) -> ArraySlice<Element> { get { assert(column < columns, "Column out of bounds") let base = (0..<rows) .makeIterator() .lazy .map({ self.elements[$0 * self.columns + column] }) return ArraySlice(base) } set { assert(column < columns, "Column out of bounds") assert(newValue.count == rows, "Row out of bounds") for index in 0..<rows { elements[index * columns + column] = newValue[index] } } } } // MARK: - Custom String extension Matrix: CustomDebugStringConvertible { public var debugDescription: String { let displayRow: (Int) -> String = { row in (0..<self.columns) .map { column in "\(self[row, column])" } .joined(separator: " ") } return (0..<rows) .map(displayRow) .joined(separator: "\n") } }
mit
81a0c8f00e81b00e7ed7b0afd885eb59
25.366071
98
0.553336
4.361891
false
false
false
false
v-adhithyan/cricket-score-applet
Cricket Score Applet/ScoreViewController.swift
1
3078
// // ScoreViewController.swift // Cricket Score Applet // // Created by Adhithyan Vijayakumar on 19/03/16. // Copyright © 2016 Adhithyan Vijayakumar. All rights reserved. // import Cocoa class ScoreViewController: NSViewController, XMLParserDelegate { @IBOutlet var scoreCard: NSTextField! var parser = XMLParser() var posts = NSMutableArray() var content = NSMutableString() var currentItem = "" var itemCount = 0 var appendCount = 0 var currentScoreIndex: Int = 0{ didSet{ updateScore() } } //let scores = Score.all //viewdidload is available only on 10.10 and later override func viewDidLoad() { if #available(OSX 10.10, *) { super.viewDidLoad() } else { // Fallback on earlier versions } self.beginParsing() updateScore() } func beginParsing(){ posts = [] parser = XMLParser(contentsOf: URL(string:"http://live-feeds.cricbuzz.com/CricbuzzFeed?format=xml")!)! parser.delegate = self parser.parse() } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { if(elementName == "item"){ itemCount = itemCount + 1; content = NSMutableString() } switch(elementName){ case "title": currentItem = "title" break case "description": currentItem = "description" break case "link": currentItem = "link" break default: break } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if(elementName == "item"){ itemCount = itemCount - 1; currentItem = "" appendCount = 0 posts.add(content) } } @nonobjc func parser(parser: XMLParser, foundCharacters string: String) { if(itemCount == 1){ if(currentItem == "title" || currentItem == "description"){ if(appendCount < 3){ content.append(string) } appendCount = appendCount + 1; } } } func updateScore(){ scoreCard.stringValue = String(describing: posts[currentScoreIndex]) } func removeHtml(string: String){ } } extension ScoreViewController{ @IBAction func goLeft(sender: NSButton){ currentScoreIndex = (currentScoreIndex - 1 + posts.count) % (posts.count) } @IBAction func goRight(sender: NSButton){ currentScoreIndex = (currentScoreIndex + 1) % (posts.count) } @IBAction func refresh(sender: NSButton){ beginParsing() updateScore() } }
mit
4ea5871206906fcc2d0890432750d0f8
24.857143
173
0.546636
4.9232
false
false
false
false
apple/swift-nio
Sources/NIOWebSocket/WebSocketFrame.swift
1
13475
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore private extension UInt8 { func isAnyBitSetInMask(_ mask: UInt8) -> Bool { return self & mask != 0 } mutating func changingBitsInMask(_ mask: UInt8, to: Bool) { if to { self |= mask } else { self &= ~mask } } } /// A single 4-byte websocket masking key. /// /// WebSockets uses a masking key to prevent malicious users from injecting /// predictable binary sequences into websocket data streams. This structure provides /// a more convenient method of interacting with a masking key than simply by passing /// around a four-tuple. public struct WebSocketMaskingKey: Sendable { @usableFromInline internal let _key: (UInt8, UInt8, UInt8, UInt8) public init?<T: Collection>(_ buffer: T) where T.Element == UInt8 { guard buffer.count == 4 else { return nil } self._key = (buffer[buffer.startIndex], buffer[buffer.index(buffer.startIndex, offsetBy: 1)], buffer[buffer.index(buffer.startIndex, offsetBy: 2)], buffer[buffer.index(buffer.startIndex, offsetBy: 3)]) } /// Creates a websocket masking key from the network-encoded /// representation. /// /// - parameters: /// - integer: The encoded network representation of the /// masking key. @usableFromInline internal init(networkRepresentation integer: UInt32) { self._key = (UInt8((integer & 0xFF000000) >> 24), UInt8((integer & 0x00FF0000) >> 16), UInt8((integer & 0x0000FF00) >> 8), UInt8(integer & 0x000000FF)) } } extension WebSocketMaskingKey: ExpressibleByArrayLiteral { public typealias ArrayLiteralElement = UInt8 public init(arrayLiteral elements: UInt8...) { precondition(elements.count == 4, "WebSocketMaskingKeys must be exactly 4 bytes long") self.init(elements)! // length precondition above } } extension WebSocketMaskingKey { /// Returns a random masking key, using the given generator as a source for randomness. /// - Parameter generator: The random number generator to use when creating the /// new random masking key. /// - Returns: A random masking key @inlinable public static func random<Generator>( using generator: inout Generator ) -> WebSocketMaskingKey where Generator: RandomNumberGenerator { return WebSocketMaskingKey(networkRepresentation: .random(in: UInt32.min...UInt32.max, using: &generator)) } /// Returns a random masking key, using the `SystemRandomNumberGenerator` as a source for randomness. /// - Returns: A random masking key @inlinable public static func random() -> WebSocketMaskingKey { var generator = SystemRandomNumberGenerator() return .random(using: &generator) } } extension WebSocketMaskingKey: Equatable { public static func ==(lhs: WebSocketMaskingKey, rhs: WebSocketMaskingKey) -> Bool { return lhs._key == rhs._key } } extension WebSocketMaskingKey: Collection { public typealias Element = UInt8 public typealias Index = Int public var startIndex: Int { return 0 } public var endIndex: Int { return 4 } public func index(after: Int) -> Int { return after + 1 } public subscript(index: Int) -> UInt8 { switch index { case 0: return self._key.0 case 1: return self._key.1 case 2: return self._key.2 case 3: return self._key.3 default: fatalError("Invalid index on WebSocketMaskingKey: \(index)") } } @inlinable public func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<UInt8>) throws -> R) rethrows -> R? { return try withUnsafeBytes(of: self._key) { ptr in // this is boilerplate necessary to convert from UnsafeRawBufferPointer to UnsafeBufferPointer<UInt8> // we know ptr is bound since we defined self._key as let let typedPointer = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self) let typedBufferPointer = UnsafeBufferPointer(start: typedPointer, count: ptr.count) return try body(typedBufferPointer) } } } /// A structured representation of a single WebSocket frame. public struct WebSocketFrame { private var _storage: WebSocketFrame._Storage /// The masking key, if any. /// /// A masking key is used to prevent specific byte sequences from appearing in the network /// stream. This is primarily used by entities like browsers, but should be used any time it /// is possible for a malicious user to control the data that appears in a websocket stream. /// /// If this value is `nil`, and this frame was *received from* the network, the data in `data` /// is not masked. If this value is `nil`, and this frame is being *sent to* the network, the /// data in `data` will not be masked. public var maskKey: WebSocketMaskingKey? = nil /// Rather than unpack all the fields from the first byte, and thus take up loads /// of storage in the structure, we keep them in their packed form in this byte and /// use computed properties to unpack them. internal var firstByte: UInt8 = 0 /// The value of the `fin` bit. If set, this is the last frame in a fragmented frame. If not /// set, this frame is one of the intermediate frames in a fragmented frame. Must be set if /// a frame is not fragmented at all. public var fin: Bool { get { return self.firstByte.isAnyBitSetInMask(0x80) } set { self.firstByte.changingBitsInMask(0x80, to: newValue) } } /// The value of the first reserved bit. Must be `false` unless using an extension that defines its use. public var rsv1: Bool { get { return self.firstByte.isAnyBitSetInMask(0x40) } set { self.firstByte.changingBitsInMask(0x40, to: newValue) } } /// The value of the second reserved bit. Must be `false` unless using an extension that defines its use. public var rsv2: Bool { get { return self.firstByte.isAnyBitSetInMask(0x20) } set { self.firstByte.changingBitsInMask(0x20, to: newValue) } } /// The value of the third reserved bit. Must be `false` unless using an extension that defines its use. public var rsv3: Bool { get { return self.firstByte.isAnyBitSetInMask(0x10) } set { self.firstByte.changingBitsInMask(0x10, to: newValue) } } /// The opcode for this frame. public var opcode: WebSocketOpcode { get { // this is a public initialiser which only fails if the opcode is invalid. But all opcodes in 0...0xF // space are valid so this can never fail. return WebSocketOpcode(encodedWebSocketOpcode: firstByte & 0x0F)! } set { self.firstByte = (self.firstByte & 0xF0) + UInt8(webSocketOpcode: newValue) } } /// The total length of the data in the frame. public var length: Int { return data.readableBytes + (extensionData?.readableBytes ?? 0) } /// The application data. /// /// On frames received from the network, this data is not necessarily unmasked. This is to provide as much /// information as possible. If unmasked data is desired, either use the computed `unmaskedData` property to /// obtain it, or transform this data directly by calling `data.unmask(maskKey)`. public var data: ByteBuffer { get { return self._storage.data } set { if !isKnownUniquelyReferenced(&self._storage) { self._storage = _Storage(copying: self._storage) } self._storage.data = newValue } } /// The extension data, if any. /// /// On frames received from the network, this data is not necessarily unmasked. This is to provide as much /// information as possible. If unmasked data is desired, either use the computed `unmaskedExtensionData` property to /// obtain it, or transform this data directly by calling `extensionData.unmask(maskKey)`. public var extensionData: ByteBuffer? { get { return self._storage.extensionData } set { if !isKnownUniquelyReferenced(&self._storage) { self._storage = _Storage(copying: self._storage) } self._storage.extensionData = newValue } } /// The unmasked application data. /// /// If a masking key is present on the frame, this property will automatically unmask the underlying data /// and return the unmasked data to the user. This is a convenience method that should only be used when /// persisting the underlying masked data is worthwhile: otherwise, performance will often be better to /// manually unmask the data with `data.unmask(maskKey)`. public var unmaskedData: ByteBuffer { get { guard let maskKey = self.maskKey else { return self.data } var data = self.data data.webSocketUnmask(maskKey, indexOffset: (self.extensionData?.readableBytes ?? 0) % 4) return data } } /// The unmasked extension data. /// /// If a masking key is present on the frame, this property will automatically unmask the underlying data /// and return the unmasked data to the user. This is a convenience method that should only be used when /// persisting the underlying masked data is worthwhile: otherwise, performance will often be better to /// manually unmask the data with `data.unmask(maskKey)`. public var unmaskedExtensionData: ByteBuffer? { get { guard let maskKey = self.maskKey else { return self.extensionData } var extensionData = self.extensionData extensionData?.webSocketUnmask(maskKey) return extensionData } } /// Creates an empty `WebSocketFrame`. /// /// - parameters: /// - allocator: The `ByteBufferAllocator` to use when editing the empty buffers. public init(allocator: ByteBufferAllocator) { self._storage = .init(data: allocator.buffer(capacity: 0), extensionData: nil) } /// Create a `WebSocketFrame` with the given properties. /// /// - parameters: /// - fin: The value of the `fin` bit. Defaults to `false`. /// - rsv1: The value of the first reserved bit. Defaults to `false`. /// - rsv2: The value of the second reserved bit. Defaults to `false`. /// - rsv3: The value of the third reserved bit. Defaults to `false`. /// - opcode: The opcode for the frame. Defaults to `.continuation`. /// - maskKey: The masking key for the frame, if any. Defaults to `nil`. /// - data: The application data for the frame. /// - extensionData: The extension data for the frame. public init(fin: Bool = false, rsv1: Bool = false, rsv2: Bool = false, rsv3: Bool = false, opcode: WebSocketOpcode = .continuation, maskKey: WebSocketMaskingKey? = nil, data: ByteBuffer, extensionData: ByteBuffer? = nil) { self._storage = .init(data: data, extensionData: extensionData) self.fin = fin self.rsv1 = rsv1 self.rsv2 = rsv2 self.rsv3 = rsv3 self.opcode = opcode self.maskKey = maskKey } /// Create a `WebSocketFrame` from the underlying data representation. internal init(firstByte: UInt8, maskKey: WebSocketMaskingKey?, applicationData: ByteBuffer) { self._storage = .init(data: applicationData, extensionData: nil) self.firstByte = firstByte self.maskKey = maskKey } } extension WebSocketFrame: @unchecked Sendable {} extension WebSocketFrame: Equatable {} extension WebSocketFrame { fileprivate class _Storage { var data: ByteBuffer var extensionData: Optional<ByteBuffer> fileprivate init(data: ByteBuffer, extensionData: ByteBuffer?) { self.data = data self.extensionData = extensionData } fileprivate init(copying original: WebSocketFrame._Storage) { self.data = original.data self.extensionData = original.extensionData } } } #if swift(>=5.6) @available(*, unavailable) extension WebSocketFrame._Storage: Sendable {} #endif extension WebSocketFrame._Storage: Equatable { static func ==(lhs: WebSocketFrame._Storage, rhs: WebSocketFrame._Storage) -> Bool { return lhs.data == rhs.data && lhs.extensionData == rhs.extensionData } }
apache-2.0
1375ea6f9610dcdde8172c4eec00716a
36.851124
121
0.629536
4.583333
false
false
false
false
apple/swift-experimental-string-processing
Sources/_StringProcessing/Utility/Misc.swift
1
2087
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2022 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 // //===----------------------------------------------------------------------===// extension Array { /// Coalesce adjacent elements using a given accumulator. The accumulator is /// transformed into elements of the array by `finish`. The `accumulate` /// function should return `true` if the accumulator has coalesced the /// element, `false` otherwise. func coalescing<T>( with initialAccumulator: T, into finish: (T) -> Self, accumulate: (inout T, Element) -> Bool ) -> Self { var didAccumulate = false var accumulator = initialAccumulator var result = Self() for elt in self { if accumulate(&accumulator, elt) { // The element has been coalesced into accumulator, there is nothing // else to do. didAccumulate = true continue } if didAccumulate { // We have a leftover accumulator, which needs to be finished before we // can append the next element. result += finish(accumulator) accumulator = initialAccumulator didAccumulate = false } result.append(elt) } // Handle a leftover accumulation. if didAccumulate { result += finish(accumulator) } return result } /// Coalesce adjacent elements using a given accumulator. The accumulator is /// transformed into an element of the array by `finish`. The `accumulate` /// function should return `true` if the accumulator has coalesced the /// element, `false` otherwise. func coalescing<T>( with initialAccumulator: T, into finish: (T) -> Element, accumulate: (inout T, Element) -> Bool ) -> Self { coalescing( with: initialAccumulator, into: { [finish($0) ]}, accumulate: accumulate) } }
apache-2.0
b54020d9d67a9bec61b274a1d1b13dd1
34.372881
80
0.6138
4.864802
false
false
false
false
jinseokpark6/u-team
Code/Controllers/CVCalendarDayView.swift
1
17386
// // CVCalendarDayView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit class CVCalendarDayView: UIView { // MARK: - Public properties let weekdayIndex: Int! weak var weekView: CVCalendarWeekView! var date: CVDate! var dayLabel: UILabel! var circleView: CVAuxiliaryView? var topMarker: CALayer? var dotMarker: CVAuxiliaryView? var isOut = false var isCurrentDay = false weak var monthView: CVCalendarMonthView! { get { var monthView: MonthView! if let weekView = weekView, let activeMonthView = weekView.monthView { monthView = activeMonthView } return monthView } } weak var calendarView: CVCalendarView! { get { var calendarView: CVCalendarView! if let weekView = weekView, let activeCalendarView = weekView.calendarView { calendarView = activeCalendarView } return calendarView } } override var frame: CGRect { didSet { if oldValue != frame { circleView?.setNeedsDisplay() topMarkerSetup() } } } override var hidden: Bool { didSet { userInteractionEnabled = hidden ? false : true } } // MARK: - Initialization init(weekView: CVCalendarWeekView, frame: CGRect, weekdayIndex: Int) { self.weekView = weekView self.weekdayIndex = weekdayIndex super.init(frame: frame) date = dateWithWeekView(weekView, andWeekIndex: weekdayIndex) labelSetup() setupDotMarker() topMarkerSetup() if !calendarView.shouldShowWeekdaysOut && isOut { hidden = true } } func dateWithWeekView(weekView: CVCalendarWeekView, andWeekIndex index: Int) -> CVDate { func hasDayAtWeekdayIndex(weekdayIndex: Int, weekdaysDictionary: [Int : [Int]]) -> Bool { for key in weekdaysDictionary.keys { if key == weekdayIndex { return true } } return false } var day: Int! let weekdaysIn = weekView.weekdaysIn if let weekdaysOut = weekView.weekdaysOut { if hasDayAtWeekdayIndex(weekdayIndex, weekdaysDictionary: weekdaysOut) { isOut = true day = weekdaysOut[weekdayIndex]![0] } else if hasDayAtWeekdayIndex(weekdayIndex, weekdaysDictionary: weekdaysIn!) { day = weekdaysIn![weekdayIndex]![0] } } else { day = weekdaysIn![weekdayIndex]![0] } if day == monthView.currentDay && !isOut { let dateRange = Manager.dateRange(monthView.date) let currentDateRange = Manager.dateRange(NSDate()) if dateRange.month == currentDateRange.month && dateRange.year == currentDateRange.year { isCurrentDay = true } } let dateRange = Manager.dateRange(monthView.date) let year = dateRange.year let week = weekView.index + 1 var month = dateRange.month if isOut { day > 20 ? month-- : month++ } return CVDate(day: day, month: month, week: week, year: year) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Subviews setup extension CVCalendarDayView { func labelSetup() { let appearance = calendarView.appearance dayLabel = UILabel() dayLabel!.text = String(date.day) dayLabel!.textAlignment = NSTextAlignment.Center dayLabel!.frame = bounds var font = appearance.dayLabelWeekdayFont var color: UIColor? if isOut { color = appearance.dayLabelWeekdayOutTextColor } else if isCurrentDay { let coordinator = calendarView.coordinator if coordinator.selectedDayView == nil { let touchController = calendarView.touchController touchController.receiveTouchOnDayView(self) calendarView.didSelectDayView(self) } else { color = appearance.dayLabelPresentWeekdayTextColor if appearance.dayLabelPresentWeekdayInitallyBold! { font = appearance.dayLabelPresentWeekdayBoldFont } else { font = appearance.dayLabelPresentWeekdayFont } } } else { color = appearance.dayLabelWeekdayInTextColor } if color != nil && font != nil { dayLabel!.textColor = color! dayLabel!.font = font } addSubview(dayLabel!) } // TODO: Make this widget customizable func topMarkerSetup() { safeExecuteBlock({ func createMarker() { let height = CGFloat(0.5) let layer = CALayer() layer.borderColor = UIColor.grayColor().CGColor layer.borderWidth = height layer.frame = CGRectMake(0, 1, CGRectGetWidth(self.frame), height) self.topMarker = layer self.layer.addSublayer(self.topMarker!) } if let delegate = self.calendarView.delegate { if self.topMarker != nil { self.topMarker?.removeFromSuperlayer() self.topMarker = nil } if let shouldDisplay = delegate.topMarker?(shouldDisplayOnDayView: self) where shouldDisplay { createMarker() } } else { if self.topMarker == nil { createMarker() } else { self.topMarker?.removeFromSuperlayer() self.topMarker = nil createMarker() } } }, collapsingOnNil: false, withObjects: weekView, weekView.monthView, weekView.monthView) } func setupDotMarker() { if let dotMarker = dotMarker { self.dotMarker!.removeFromSuperview() self.dotMarker = nil } if let delegate = calendarView.delegate { if let shouldShow = delegate.dotMarker?(shouldShowOnDayView: self) where shouldShow { let color = isOut ? .grayColor() : delegate.dotMarker?(colorOnDayView: self) let width: CGFloat = 13 let height: CGFloat = 13 var yOffset = bounds.height / 5 if let y = delegate.dotMarker?(moveOffsetOnDayView: self) { yOffset = y } let x = frame.width / 2 let y = CGRectGetMidY(frame) + yOffset let markerFrame = CGRectMake(0, 0, width, height) dotMarker = CVAuxiliaryView(dayView: self, rect: markerFrame, shape: .Circle) dotMarker!.fillColor = color dotMarker!.center = CGPointMake(x, y) insertSubview(dotMarker!, atIndex: 0) let coordinator = calendarView.coordinator if self == coordinator.selectedDayView { moveDotMarkerBack(false, coloring: false) } dotMarker!.setNeedsDisplay() } } } } // MARK: - Dot marker movement extension CVCalendarDayView { func moveDotMarkerBack(unwinded: Bool, var coloring: Bool) { if let calendarView = calendarView, let dotMarker = dotMarker { var shouldMove = true if let delegate = calendarView.delegate, let move = delegate.dotMarker?(shouldMoveOnHighlightingOnDayView: self) where !move { shouldMove = move } func colorMarker() { if let delegate = calendarView.delegate { let appearance = calendarView.appearance let frame = dotMarker.frame var color: UIColor? if unwinded { if let myColor = delegate.dotMarker?(colorOnDayView: self) { color = (isOut) ? appearance.dayLabelWeekdayOutTextColor : myColor } } else { color = appearance.dotMarkerColor } dotMarker.fillColor = color dotMarker.setNeedsDisplay() } } func moveMarker() { var transform: CGAffineTransform! if let circleView = circleView { let point = pointAtAngle(CGFloat(-90).toRadians(), withinCircleView: circleView) let spaceBetweenDotAndCircle = CGFloat(0.5) let offset = point.y - dotMarker.frame.origin.y - dotMarker.bounds.height/2 + spaceBetweenDotAndCircle transform = unwinded ? CGAffineTransformIdentity : CGAffineTransformMakeTranslation(0, offset) if dotMarker.center.y + offset > CGRectGetMaxY(frame) { coloring = true } } else { transform = CGAffineTransformIdentity } if !coloring { UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { dotMarker.transform = transform }, completion: { _ in }) } else { moveDotMarkerBack(unwinded, coloring: coloring) } } if shouldMove && !coloring { moveMarker() } else { colorMarker() } } } } // MARK: - Circle geometry extension CGFloat { func toRadians() -> CGFloat { return CGFloat(self) * CGFloat(M_PI / 180) } func toDegrees() -> CGFloat { return CGFloat(180/M_PI) * self } } extension CVCalendarDayView { func pointAtAngle(angle: CGFloat, withinCircleView circleView: UIView) -> CGPoint { let radius = circleView.bounds.width / 2 let xDistance = radius * cos(angle) let yDistance = radius * sin(angle) let center = circleView.center let x = floor(cos(angle)) < 0 ? center.x - xDistance : center.x + xDistance let y = center.y - yDistance let result = CGPointMake(x, y) return result } func moveView(view: UIView, onCircleView circleView: UIView, fromAngle angle: CGFloat, toAngle endAngle: CGFloat, straight: Bool) { let condition = angle > endAngle ? angle > endAngle : angle < endAngle if straight && angle < endAngle || !straight && angle > endAngle { UIView.animateWithDuration(pow(10, -1000), delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseIn, animations: { let angle = angle.toRadians() view.center = self.pointAtAngle(angle, withinCircleView: circleView) }) { _ in let speed = CGFloat(750).toRadians() let newAngle = straight ? angle + speed : angle - speed self.moveView(view, onCircleView: circleView, fromAngle: newAngle, toAngle: endAngle, straight: straight) } } } } // MARK: - Day label state management extension CVCalendarDayView { func setDayLabelHighlighted() { let appearance = calendarView.appearance var backgroundColor: UIColor! var backgroundAlpha: CGFloat! if isCurrentDay { dayLabel?.textColor = appearance.dayLabelPresentWeekdayHighlightedTextColor! dayLabel?.font = appearance.dayLabelPresentWeekdayHighlightedFont backgroundColor = appearance.dayLabelPresentWeekdayHighlightedBackgroundColor backgroundAlpha = appearance.dayLabelPresentWeekdayHighlightedBackgroundAlpha } else { dayLabel?.textColor = appearance.dayLabelWeekdayHighlightedTextColor dayLabel?.font = appearance.dayLabelWeekdayHighlightedFont backgroundColor = appearance.dayLabelWeekdayHighlightedBackgroundColor backgroundAlpha = appearance.dayLabelWeekdayHighlightedBackgroundAlpha } if let circleView = circleView { circleView.fillColor = backgroundColor circleView.alpha = backgroundAlpha circleView.setNeedsDisplay() } else { circleView = CVAuxiliaryView(dayView: self, rect: dayLabel.bounds, shape: .Rect) circleView!.fillColor = circleView!.defaultFillColor circleView!.alpha = backgroundAlpha insertSubview(circleView!, atIndex: 0) } moveDotMarkerBack(false, coloring: false) } func setDayLabelUnhighlightedDismissingState(removeViews: Bool) { let appearance = calendarView.appearance var color: UIColor? if isOut { color = appearance.dayLabelWeekdayOutTextColor } else if isCurrentDay { color = appearance.dayLabelPresentWeekdayTextColor } else { color = appearance.dayLabelWeekdayInTextColor } var font: UIFont? if self.isCurrentDay { if appearance.dayLabelPresentWeekdayInitallyBold! { font = appearance.dayLabelPresentWeekdayBoldFont } else { font = appearance.dayLabelWeekdayFont } } else { font = appearance.dayLabelWeekdayFont } dayLabel?.textColor = color dayLabel?.font = font moveDotMarkerBack(true, coloring: false) if removeViews { circleView?.removeFromSuperview() circleView = nil } } func setDayLabelSelected() { let appearance = calendarView.appearance var backgroundColor: UIColor! var backgroundAlpha: CGFloat! if isCurrentDay { dayLabel?.textColor = appearance.dayLabelPresentWeekdaySelectedTextColor! dayLabel?.font = appearance.dayLabelPresentWeekdaySelectedFont backgroundColor = appearance.dayLabelPresentWeekdaySelectedBackgroundColor backgroundAlpha = appearance.dayLabelPresentWeekdaySelectedBackgroundAlpha } else { dayLabel?.textColor = appearance.dayLabelWeekdaySelectedTextColor dayLabel?.font = appearance.dayLabelWeekdaySelectedFont backgroundColor = appearance.dayLabelWeekdaySelectedBackgroundColor backgroundAlpha = appearance.dayLabelWeekdaySelectedBackgroundAlpha } if let circleView = circleView { circleView.fillColor = backgroundColor circleView.alpha = backgroundAlpha circleView.setNeedsDisplay() } else { circleView = CVAuxiliaryView(dayView: self, rect: dayLabel.bounds, shape: .Circle) circleView!.fillColor = backgroundColor circleView!.alpha = backgroundAlpha circleView?.setNeedsDisplay() insertSubview(circleView!, atIndex: 0) } moveDotMarkerBack(false, coloring: false) } func setDayLabelDeselectedDismissingState(removeViews: Bool) { setDayLabelUnhighlightedDismissingState(removeViews) } } // MARK: - Content reload extension CVCalendarDayView { func reloadContent() { setupDotMarker() dayLabel?.frame = bounds let shouldShowDaysOut = calendarView.shouldShowWeekdaysOut! if !shouldShowDaysOut { if isOut { hidden = true } } else { if isOut { hidden = false } } if circleView != nil { setDayLabelDeselectedDismissingState(true) setDayLabelSelected() } } } // MARK: - Safe execution extension CVCalendarDayView { func safeExecuteBlock(block: Void -> Void, collapsingOnNil collapsing: Bool, withObjects objects: AnyObject?...) { for object in objects { if object == nil { if collapsing { fatalError("Object { \(object) } must not be nil!") } else { return } } } block() } }
apache-2.0
cb5be40fa02608d7359fb3d44354c5c4
33.291913
179
0.555562
5.741744
false
false
false
false
stephentyrone/swift
test/IRGen/objc_class_export.swift
3
6060
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop // CHECK-DAG: %swift.refcounted = type // CHECK-DAG: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }> // CHECK-DAG: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }> // CHECK-DAG: [[INT:%TSi]] = type <{ i64 }> // CHECK-DAG: [[DOUBLE:%TSd]] = type <{ double }> // CHECK-DAG: [[NSRECT:%TSo6NSRectV]] = type <{ %TSo7NSPointV, %TSo6NSSizeV }> // CHECK-DAG: [[NSPOINT:%TSo7NSPointV]] = type <{ %TSd, %TSd }> // CHECK-DAG: [[NSSIZE:%TSo6NSSizeV]] = type <{ %TSd, %TSd }> // CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class { // CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64) // CHECK-SAME: } // CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00" // CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK-SAME: i32 129, // CHECK-SAME: i32 40, // CHECK-SAME: i32 40, // CHECK-SAME: i32 0, // CHECK-SAME: i8* null, // CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK-SAME: @_CLASS_METHODS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null // CHECK-SAME: }, section "__DATA, __objc_const", align 8 // CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK-SAME: i32 128, // CHECK-SAME: i32 16, // CHECK-SAME: i32 24, // CHECK-SAME: i32 0, // CHECK-SAME: i8* null, // CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK-SAME: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: @_IVARS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: _PROPERTIES__TtC17objc_class_export3Foo // CHECK-SAME: }, section "__DATA, __objc_const", align 8 // CHECK: @"$s17objc_class_export3FooCMf" = internal global <{{.*}} }> <{ // CHECK-SAME: void ([[FOO]]*)* @"$s17objc_class_export3FooCfD", // CHECK-SAME: i8** @"$sBOWV", // CHECK-SAME: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64), // CHECK-SAME: %objc_class* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 {{1|2}}), // CHECK-SAME: [[FOO]]* (%swift.type*)* @"$s17objc_class_export3FooC6createACyFZ", // CHECK-SAME: void (double, double, double, double, [[FOO]]*)* @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF" // CHECK-SAME: }>, section "__DATA,__objc_data, regular" // -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of // Foo. // CHECK: @"$s17objc_class_export3FooCN" = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @"$s17objc_class_export3FooCMf", i32 0, i32 2) to %swift.type*) // CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @"$s17objc_class_export3FooCN" import gizmo class Hoozit {} struct BigStructWithNativeObjects { var x, y, w : Double var h : Hoozit } @objc class Foo { @objc var x = 0 @objc class func create() -> Foo { return Foo() } @objc func drawInRect(dirty dirty: NSRect) { } // CHECK: define internal void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]* %0, i8* %1, [[NSRECT]]* byval align 8 %2) {{[#0-9]*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]* // CHECK: call swiftcc void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) // CHECK: } @objc func bounds() -> NSRect { return NSRect(origin: NSPoint(x: 0, y: 0), size: NSSize(width: 0, height: 0)) } // CHECK: define internal void @"$s17objc_class_export3FooC6boundsSo6NSRectVyFTo"([[NSRECT]]* noalias nocapture sret %0, [[OPAQUE4:%.*]]* %1, i8* %2) {{[#0-9]*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC6boundsSo6NSRectVyF"([[FOO]]* swiftself [[CAST]]) @objc func convertRectToBacking(r r: NSRect) -> NSRect { return r } // CHECK: define internal void @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret %0, [[OPAQUE5:%.*]]* %1, i8* %2, [[NSRECT]]* byval align 8 %3) {{[#0-9]*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) func doStuffToSwiftSlice(f f: [Int]) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @"$s17objc_class_export3FooC19doStuffToSwiftSlice1fySaySiG_tcAAFTo" func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStruct1ffS_FTV17objc_class_export27BigStructWithNativeObjects_T_ @objc init() { } }
apache-2.0
4bc1041ee879ba9d3148db3faa44f3b3
51.241379
219
0.637954
3.05136
false
false
false
false
txstate-etc/mobile-tracs-ios
mobile-tracs-ios/Utils/Secrets.swift
1
1098
// // Secrets.swift // mobile-tracs-ios // // Created by Nick Wing on 4/13/17. // Copyright © 2017 Texas State University. All rights reserved. // import Foundation class Secrets { static let shared = Secrets() var analyticsid:String? var integrationbaseurl:String? var jwtservicebaseurl:String? var tracsbaseurl:String? var surveyurl:String? var contacturl:String? var loginbaseurl:String? init() { if let path = Bundle.main.path(forResource: "Config", ofType: "plist") { if let dict = NSDictionary(contentsOfFile: path) as? [String:AnyObject] { analyticsid = dict["analyticsid"] as? String integrationbaseurl = dict["integrationbaseurl"] as? String jwtservicebaseurl = dict["jwtservicebaseurl"] as? String tracsbaseurl = dict["tracsbaseurl"] as? String surveyurl = dict["surveyurl"] as? String contacturl = dict["contacturl"] as? String loginbaseurl = dict["loginbaseurl"] as? String } } } }
mit
dc819945e631b8190fbd88dc9ae2dd32
31.264706
85
0.615314
4.062963
false
false
false
false
sixoverground/ImagePickerController
Classes/CameraViewController.swift
1
9464
// // CameraViewController.swift // ImagePickerController // // Created by Craig Phares on 4/19/16. // Copyright © 2016 Six Overground. All rights reserved. // import UIKit import AVFoundation import Photos protocol CameraViewDelegate: class { func setFlashButtonHidden(hidden: Bool) } class CameraViewController: UIViewController { lazy var capturedImageView: UIView = { [unowned self] in let view = UIView() view.backgroundColor = UIColor.blackColor() view.alpha = 0 return view }() let captureSession = AVCaptureSession() var devices = AVCaptureDevice.devices() var captureDevice: AVCaptureDevice? { didSet { if let myDevice = captureDevice { print("HAS FLASH: \(myDevice.hasFlash)") delegate?.setFlashButtonHidden(!myDevice.hasFlash) } else { delegate?.setFlashButtonHidden(false) } } } var capturedDevices: NSMutableArray? var previewLayer: AVCaptureVideoPreviewLayer? var stillImageOutput: AVCaptureStillImageOutput? weak var delegate: CameraViewDelegate? override func viewDidLoad() { super.viewDidLoad() initializeCamera() view.backgroundColor = UIColor.blackColor() previewLayer?.backgroundColor = UIColor.blackColor().CGColor view.addSubview(capturedImageView) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(deviceOrientationDidChange(_:)), name: UIDeviceOrientationDidChangeNotification, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) fixOrientation() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() previewLayer?.position = CGPoint(x: CGRectGetMidX(view.layer.bounds), y: CGRectGetMidY(view.layer.bounds)) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) // previewLayer?.frame.size = size // let totalSize: CGSize = UIScreen.mainScreen().bounds.size // // previewLayer.frame = view.layer.frame // previewLayer?.frame = CGRect(x: 0, y: -(totalSize.height - view.frame.size.height)/2, width: totalSize.width, height: totalSize.height) // print("preview layer frame: \(previewLayer?.frame)") fixOrientation() } // MARK: - Initialization func initializeCamera() { print("init camera") capturedDevices = NSMutableArray() let authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) if devices.isEmpty { devices = AVCaptureDevice.devices() } for device in devices { if let device = device as? AVCaptureDevice where device.hasMediaType(AVMediaTypeVideo) { if authorizationStatus == .Authorized { captureDevice = device capturedDevices?.addObject(device) } else if authorizationStatus == .NotDetermined { AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted) in self.handlePermission(granted, device: device) }) } else { // show no camera } } } captureDevice = capturedDevices?.firstObject as? AVCaptureDevice print("capture device: \(captureDevice)") if captureDevice != nil { beginSession() } } func configureDevice() { if let device = captureDevice { do { try device.lockForConfiguration() } catch { print("Could not lock configuration") } device.unlockForConfiguration() } } func beginSession() { configureDevice() guard captureSession.inputs.count == 0 else { return } // captureSession.sessionPreset = AVCaptureSessionPresetPhoto let captureDeviceInput: AVCaptureDeviceInput? do { try captureDeviceInput = AVCaptureDeviceInput(device: captureDevice) captureSession.addInput(captureDeviceInput) } catch { print("Failed to capture device") } guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else { return } print("load previewLayer: \(previewLayer)") self.previewLayer = previewLayer previewLayer.autoreverses = true previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill view.layer.addSublayer(previewLayer) // let totalBounds = UIScreen.mainScreen().bounds // let bounds = view.bounds previewLayer.frame = view.layer.frame // previewLayer.frame = totalBounds // previewLayer.frame = CGRect(x: 0, y: -(totalSize.height - view.frame.size.height)/2, width: totalSize.width, height: totalSize.height) // print("preview layer frame: \(previewLayer.frame)") // let offset = -(totalBounds.size.height - bounds.size.height) / 2 // previewLayer.position = CGPoint(x: CGRectGetMidX(bounds), y: offset) // view.layer.position = CGPoint(x: CGRectGetMidX(bounds), y: offset) previewLayer.position = CGPoint(x: CGRectGetMidX(view.layer.bounds), y: CGRectGetMidY(view.layer.bounds)) view.clipsToBounds = true captureSession.startRunning() stillImageOutput = AVCaptureStillImageOutput() stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] captureSession.addOutput(stillImageOutput) } // MARK: - Permissions func handlePermission(granted: Bool, device: AVCaptureDevice) { if granted { captureDevice = device capturedDevices?.addObject(device) print("granted: \(captureDevice)") } dispatch_async(dispatch_get_main_queue()) { // show no camera - granted } } // MARK: - Actions func flipCamera() { guard let captureDevice = captureDevice, currentDeviceInput = captureSession.inputs.first as? AVCaptureDeviceInput, deviceIndex = capturedDevices?.indexOfObject(captureDevice) else { return } var newDeviceIndex = 0 if let index = capturedDevices?.count where deviceIndex != index - 1 && deviceIndex < capturedDevices?.count { newDeviceIndex = deviceIndex + 1 } self.captureDevice = capturedDevices?.objectAtIndex(newDeviceIndex) as? AVCaptureDevice configureDevice() guard let _ = self.captureDevice else { return } self.captureSession.beginConfiguration() self.captureSession.removeInput(currentDeviceInput) do { try self.captureSession.addInput(AVCaptureDeviceInput(device: self.captureDevice)) } catch { print("There was an error capturing your device.") } self.captureSession.commitConfiguration() } func changeFlash(title: String) { guard let _ = captureDevice?.hasFlash else { return } do { try captureDevice?.lockForConfiguration() } catch _ { print("could not lock device") } var flashMode = AVCaptureFlashMode.Auto switch title { case "ON": flashMode = .On case "OFF": flashMode = .Off default: flashMode = .Auto } if let device = captureDevice { if device.isFlashModeSupported(flashMode) { captureDevice?.flashMode = flashMode } } } func takePicture(completion: () -> ()) { capturedImageView.frame = view.bounds UIView.animateWithDuration(0.1, animations: { self.capturedImageView.alpha = 1 }) { (finished) in UIView.animateWithDuration(0.1, animations: { self.capturedImageView.alpha = 0 }) } let queue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL) guard let stillImageOutput = self.stillImageOutput else { return } dispatch_async(queue) { stillImageOutput.captureStillImageAsynchronouslyFromConnection(stillImageOutput.connectionWithMediaType(AVMediaTypeVideo), completionHandler: { (buffer, error) in let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) guard let imageFromData = UIImage(data: imageData) else { return } PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let request = PHAssetChangeRequest.creationRequestForAssetFromImage(imageFromData) request.creationDate = NSDate() }, completionHandler: { (success, error) in dispatch_async(dispatch_get_main_queue(), { completion() }) }) }) } } // MARK: - Helpers func deviceOrientationDidChange(notification: NSNotification) { print("device orientation did change") fixOrientation() } func fixOrientation() { guard let stillImageOutput = self.stillImageOutput, connection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) else { return } switch UIDevice.currentDevice().orientation { case .Portrait: print("change orientation to portrait") connection.videoOrientation = .Portrait case .LandscapeLeft: print("change orientation to landscape right") connection.videoOrientation = .LandscapeRight case .LandscapeRight: print("change orientation to landscape left") connection.videoOrientation = .LandscapeLeft case .PortraitUpsideDown: print("change orientation to upside down") connection.videoOrientation = .PortraitUpsideDown default: break } } }
mit
a155fde119dc86096bb05693abc0a853
30.648829
195
0.684878
5.228177
false
false
false
false
hughbe/swift
test/decl/protocol/special/coding/struct_codable_failure_diagnostics.swift
3
4186
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s 2>&1 | %FileCheck %s // Codable struct with non-Codable property. struct S1 : Codable { struct Nested {} var a: String = "" var b: Int = 0 var c: Nested = Nested() // CHECK: error: type 'S1' does not conform to protocol 'Decodable' // CHECK: note: cannot automatically synthesize 'Decodable' because 'S1.Nested' does not conform to 'Decodable' // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: error: type 'S1' does not conform to protocol 'Encodable' // CHECK: note: cannot automatically synthesize 'Encodable' because 'S1.Nested' does not conform to 'Encodable' // CHECK: note: protocol requires function 'encode(to:)' with type 'Encodable' } // Codable struct with non-enum CodingKeys. struct S2 : Codable { var a: String = "" var b: Int = 0 var c: Double? struct CodingKeys : CodingKey { var stringValue: String = "" var intValue: Int? = nil init?(stringValue: String) {} init?(intValue: Int) {} } // CHECK: error: type 'S2' does not conform to protocol 'Decodable' // CHECK: note: cannot automatically synthesize 'Decodable' because 'CodingKeys' is not an enum // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: error: type 'S2' does not conform to protocol 'Encodable' // CHECK: note: cannot automatically synthesize 'Encodable' because 'CodingKeys' is not an enum // CHECK: note: protocol requires function 'encode(to:)' with type 'Encodable' } // Codable struct with CodingKeys not conforming to CodingKey. struct S3 : Codable { var a: String = "" var b: Int = 0 var c: Double? enum CodingKeys : String { case a case b case c } // CHECK: error: type 'S3' does not conform to protocol 'Decodable' // CHECK: note: cannot automatically synthesize 'Decodable' because 'CodingKeys' does not conform to CodingKey // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: error: type 'S3' does not conform to protocol 'Encodable' // CHECK: note: cannot automatically synthesize 'Encodable' because 'CodingKeys' does not conform to CodingKey // CHECK: note: protocol requires function 'encode(to:)' with type 'Encodable' } // Codable struct with extraneous CodingKeys struct S4 : Codable { var a: String = "" var b: Int = 0 var c: Double? enum CodingKeys : String, CodingKey { case a case a2 case b case b2 case c case c2 } // CHECK: error: type 'S4' does not conform to protocol 'Decodable' // CHECK: note: CodingKey case 'a2' does not match any stored properties // CHECK: note: CodingKey case 'b2' does not match any stored properties // CHECK: note: CodingKey case 'c2' does not match any stored properties // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: error: type 'S4' does not conform to protocol 'Encodable' // CHECK: note: CodingKey case 'a2' does not match any stored properties // CHECK: note: CodingKey case 'b2' does not match any stored properties // CHECK: note: CodingKey case 'c2' does not match any stored properties // CHECK: note: protocol requires function 'encode(to:)' with type 'Encodable' } // Codable struct with non-decoded property (which has no default value). struct S5 : Codable { var a: String = "" var b: Int var c: Double? enum CodingKeys : String, CodingKey { case a case c } // CHECK: error: type 'S5' does not conform to protocol 'Decodable' // CHECK: note: cannot automatically synthesize 'Decodable' because 'b' does not have a matching CodingKey and does not have a default value // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' } // Structs cannot yet synthesize Encodable or Decodable in extensions. struct S6 {} extension S6 : Codable {} // CHECK: error: implementation of 'Decodable' cannot be automatically synthesized in an extension yet // CHECK: error: implementation of 'Encodable' cannot be automatically synthesized in an extension yet
apache-2.0
917b5571371d913dc652e303943e0cbb
37.054545
142
0.704252
4.052275
false
false
false
false
TangentMicroServices/HoursService.iOSClient
HoursService.iOSClient/HoursService.iOSClient/LoginViewController.swift
1
3424
// // LoginViewController.swift // HoursService.iOSClient // // Created by Ian Roberts on 2/10/15. // Copyright (c) 2015 Ian Roberts. All rights reserved. // import UIKit import AlamoFire public class LoginViewController: UIViewController { var api: ServiceApi = ServiceApi() var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() func displayAlert(title:String, message:String){ var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in self.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } public override func viewDidLoad(){ super.viewDidLoad() self.view.userInteractionEnabled = true println("Here arrived") } func startLoader(){ activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50)) activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray view.addSubview(activityIndicator) activityIndicator.startAnimating() UIApplication.sharedApplication().beginIgnoringInteractionEvents() } func stopLoader(){ activityIndicator.stopAnimating() UIApplication.sharedApplication().endIgnoringInteractionEvents() } public override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true) } @IBOutlet weak var txtUserName: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBAction func btnLoginTouch(sender: AnyObject) { var username = txtUserName.text var password = txtPassword.text var error = "" if (username == "" || password == "") { error = "Please enter in a username and password" } if error != "" { displayAlert("Error in Form", message: error) } else{ //Start loader startLoader() //Attempt to login api.authenticateUser(username, password: password, callback: { (success:String?, error:String?) -> () in //Stop the loader self.stopLoader() if ((error) != nil) { self.displayAlert("Login Error", message: error!) } else { //Save the token to memory NSUserDefaults.standardUserDefaults().setObject(success!, forKey: "token") NSUserDefaults.standardUserDefaults().synchronize() //Move the user along //self.performSegueWithIdentifier("gotoTabVC", sender: self) var tabBarVC = self.storyboard?.instantiateViewControllerWithIdentifier("TabVC") as UITabBarController self.navigationController?.pushViewController(tabBarVC, animated: true) } }) } } }
mit
dfb1acfc8dcfe09070d4099b2726a57d
31.923077
122
0.587909
6.017575
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGeometry/Shape/ShapeWinding.swift
1
11830
// // ShapeWinding.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // extension Shape { public enum RenderOperation { case triangle(Point, Point, Point) case quadratic(Point, Point, Point) case cubic(Point, Point, Point, Vector, Vector, Vector) } } @inlinable @inline(__always) public func * (lhs: Shape.RenderOperation, rhs: SDTransform) -> Shape.RenderOperation { switch lhs { case let .triangle(p0, p1, p2): return .triangle(p0 * rhs, p1 * rhs, p2 * rhs) case let .quadratic(p0, p1, p2): return .quadratic(p0 * rhs, p1 * rhs, p2 * rhs) case let .cubic(p0, p1, p2, v0, v1, v2): return .cubic(p0 * rhs, p1 * rhs, p2 * rhs, v0, v1, v2) } } @inlinable @inline(__always) public func *= (lhs: inout Shape.RenderOperation, rhs: SDTransform) { lhs = lhs * rhs } @inline(__always) private func _cubic(_ p0: Point, _ p1: Point, _ p2: Point, _ p3: Point, operation: (Shape.RenderOperation) throws -> Void) rethrows { let (q1, q2, q3) = CubicBezier(p0, p1, p2, p3)._polynomial let d1 = -cross(q3, q2) let d2 = cross(q3, q1) let d3 = -cross(q2, q1) let discr = 3 * d2 * d2 - 4 * d1 * d3 let area = CubicBezier(p0, p1, p2, p3).area + LineSegment(p3, p0).area @inline(__always) func draw(_ k0: Vector, _ k1: Vector, _ k2: Vector, _ k3: Vector, operation: (Shape.RenderOperation) throws -> Void) rethrows { var v0 = k0 var v1 = k0 + k1 / 3 var v2 = k0 + (2 * k1 + k2) / 3 var v3 = k0 + k1 + k2 + k3 if area.sign == .minus { v0.x = -v0.x v1.x = -v1.x v2.x = -v2.x v3.x = -v3.x v0.y = -v0.y v1.y = -v1.y v2.y = -v2.y v3.y = -v3.y } try operation(.cubic(p0, p1, p2, v0, v1, v2)) try operation(.cubic(p0, p2, p3, v0, v2, v3)) } if d1.almostZero() { if d2.almostZero() { if !d3.almostZero(), let intersect = LineSegment(p0, p1).intersect(LineSegment(p2, p3)) { try operation(.quadratic(p0, intersect, p3)) } } else { // cusp with cusp at infinity let tl = d3 let sl = 3 * d2 let tl2 = tl * tl let sl2 = sl * sl let k0 = Vector(x: tl, y: tl2 * tl, z: 1) let k1 = Vector(x: -sl, y: -3 * sl * tl2, z: 0) let k2 = Vector(x: 0, y: 3 * sl2 * tl, z: 0) let k3 = Vector(x: 0, y: -sl2 * sl, z: 0) try draw(k0, k1, k2, k3, operation: operation) } } else { if discr.almostZero() || discr > 0 { // serpentine let delta = sqrt(Swift.max(0, discr)) / sqrt(3) let tl = d2 + delta let sl = 2 * d1 let tm = d2 - delta let sm = 2 * d1 let tl2 = tl * tl let sl2 = sl * sl let tm2 = tm * tm let sm2 = sm * sm var k0 = Vector(x: tl * tm, y: tl2 * tl, z: tm2 * tm) var k1 = Vector(x: -sm * tl - sl * tm, y: -3 * sl * tl2, z: -3 * sm * tm2) var k2 = Vector(x: sl * sm, y: 3 * sl2 * tl, z: 3 * sm2 * tm) var k3 = Vector(x: 0, y: -sl2 * sl, z: -sm2 * sm) if d1.sign == .minus { k0.x = -k0.x k1.x = -k1.x k2.x = -k2.x k3.x = -k3.x k0.y = -k0.y k1.y = -k1.y k2.y = -k2.y k3.y = -k3.y } try draw(k0, k1, k2, k3, operation: operation) } else { // loop let delta = sqrt(-discr) let td = d2 + delta let sd = 2 * d1 let te = d2 - delta let se = 2 * d1 let td2 = td * td let sd2 = sd * sd let te2 = te * te let se2 = se * se var k0 = Vector(x: td * te, y: td2 * te, z: td * te2) var k1 = Vector(x: -se * td - sd * te, y: -se * td2 - 2 * sd * te * td, z: -sd * te2 - 2 * se * td * te) var k2 = Vector(x: sd * se, y: te * sd2 + 2 * se * td * sd, z: td * se2 + 2 * sd * te * se) var k3 = Vector(x: 0, y: -sd2 * se, z: -sd * se2) let v1x = k0.x + k1.x / 3 if d1.sign != v1x.sign { k0.x = -k0.x k1.x = -k1.x k2.x = -k2.x k3.x = -k3.x k0.y = -k0.y k1.y = -k1.y k2.y = -k2.y k3.y = -k3.y } try draw(k0, k1, k2, k3, operation: operation) } } } extension Shape.Component { public func render(_ operation: (Shape.RenderOperation) throws -> Void) rethrows { @inline(__always) func drawCubic(_ p0: Point, _ p1: Point, _ p2: Point, _ p3: Point, operation: (Shape.RenderOperation) throws -> Void) rethrows { let bezier = CubicBezier(p0, p1, p2, p3) if let (t1, t2) = bezier.selfIntersect() { let split_t = [t1, t2].filter { !$0.almostZero() && !$0.almostEqual(1) && 0...1 ~= $0 } if split_t.isEmpty { try _cubic(p0, p1, p2, p3, operation: operation) } else { let beziers = bezier.split(split_t) try operation(.triangle(p0, beziers.last!.p0, beziers.last!.p3)) try beziers.forEach { try _cubic($0.p0, $0.p1, $0.p2, $0.p3, operation: operation) } } } else { let inflection = bezier.inflection.filter { !$0.almostZero() && !$0.almostEqual(1) && 0...1 ~= $0 } if inflection.isEmpty { try _cubic(p0, p1, p2, p3, operation: operation) } else { var last: Point? for b in bezier.split(inflection) { if let last = last { try operation(.triangle(p0, last, b.p3)) } try _cubic(b.p0, b.p1, b.p2, b.p3, operation: operation) last = b.p3 } } } } let start = self.start try self.segments.withUnsafeBufferPointer { segments in if let first = segments.first { var last = start switch first { case let .line(q1): last = q1 case let .quad(q1, q2): try operation(.quadratic(last, q1, q2)) last = q2 case let .cubic(q1, q2, q3): try drawCubic(last, q1, q2, q3, operation: operation) last = q3 } for segment in segments.dropFirst() { switch segment { case let .line(q1): try operation(.triangle(start, last, q1)) last = q1 case let .quad(q1, q2): try operation(.triangle(start, last, q2)) try operation(.quadratic(last, q1, q2)) last = q2 case let .cubic(q1, q2, q3): try operation(.triangle(start, last, q3)) try drawCubic(last, q1, q2, q3, operation: operation) last = q3 } } } } } } extension Shape { @inlinable public func render(_ operation: (Shape.RenderOperation) throws -> Void) rethrows { try self.components.withUnsafeBufferPointer { try $0.forEach { try $0.render(operation) } } } } extension Shape { public enum WindingRule: CaseIterable { case nonZero case evenOdd } @inlinable public func contains(_ p: Point, winding: WindingRule) -> Bool { switch winding { case .nonZero: return self.winding(p) != 0 case .evenOdd: return self.winding(p) & 1 == 1 } } } extension Shape.RenderOperation { @inlinable public func winding(_ position: Point) -> Int { switch self { case let .triangle(p0, p1, p2): guard inTriangle(p0, p1, p2, position) else { return 0 } let d = cross(p1 - p0, p2 - p0) return d.sign == .plus ? 1 : -1 case let .quadratic(p0, p1, p2): guard inTriangle(p0, p1, p2, position), let p = Barycentric(p0, p1, p2, position) else { return 0 } let s = 0.5 * p.y + p.z guard s * s < p.z else { return 0 } let d = cross(p1 - p0, p2 - p0) return d.sign == .plus ? 1 : -1 case let .cubic(p0, p1, p2, v0, v1, v2): guard inTriangle(p0, p1, p2, position), let p = Barycentric(p0, p1, p2, position) else { return 0 } let u0 = p.x * v0 let u1 = p.y * v1 let u2 = p.z * v2 let v = u0 + u1 + u2 guard v.x * v.x * v.x < v.y * v.z else { return 0 } let d = cross(p1 - p0, p2 - p0) return d.sign == .plus ? 1 : -1 } } } extension Shape.Component { @inlinable public func winding(_ position: Point) -> Int { var counter = 0 self.render { counter += $0.winding(position) } return counter } } extension Shape { @inlinable public func winding(_ position: Point) -> Int { guard transform.invertible else { return 0 } let position = position * transform.inverse var counter = 0 self.render { counter += $0.winding(position) } return counter } }
mit
b6cd08c25568c11ca7dd70a90798c9ae
31.410959
136
0.449873
3.686507
false
false
false
false
coaoac/GridView
CustomGridView/GridViewLayout.swift
1
6687
// Created by Amine Chaouki on 10/05/15. // Copyright (c) 2015 chaouki. All rights reserved. import UIKit //Section = row, item = column public class GridViewLayout: UICollectionViewLayout { var itemAttributes = [[UICollectionViewLayoutAttributes]]() var contentSize : CGSize! var dataSource: GridViewLayoutDataSource! let sizeCache = NSCache() public func reset() { sizeCache.removeAllObjects() } override public func prepareLayout() { if self.collectionView?.numberOfSections() == 0 { return } if (self.itemAttributes.count > 0){ for row in 0..<self.collectionView!.numberOfSections() { let numberOfColumns : Int = self.collectionView!.numberOfItemsInSection(row) for column in 0..<numberOfColumns { if row >= dataSource.numberOfColumnTitles() && column >= dataSource.numberOfRowTitles() { continue } let attributes : UICollectionViewLayoutAttributes = self.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: column, inSection: row))! if row < dataSource.numberOfColumnTitles() { var frame = attributes.frame frame.origin.y = self.collectionView!.contentOffset.y + CGFloat(row) * dataSource.heightOfColumnTitles() attributes.frame = frame } if column < dataSource.numberOfRowTitles() { var frame = attributes.frame frame.origin.x = self.collectionView!.contentOffset.x + CGFloat(column) * dataSource.widthOfRowTitles() attributes.frame = frame } } } return } var column = 0 var xOffset : CGFloat = 0 var yOffset : CGFloat = 0 var contentWidth : CGFloat = 0 var contentHeight : CGFloat = 0 for section in 0..<self.collectionView!.numberOfSections() { var sectionAttributes = [UICollectionViewLayoutAttributes]() let numberOfItems : Int = self.collectionView!.numberOfItemsInSection(section) for index in 0..<numberOfItems { let itemSize = self.sizeOfItemAtIndexPath(NSIndexPath(forRow: index, inSection: section)) let indexPath = NSIndexPath(forItem: index, inSection: section) let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) attributes.frame = CGRectIntegral(CGRectMake(xOffset, yOffset, itemSize.width, itemSize.height)) if section < dataSource.numberOfColumnTitles() && index < dataSource.numberOfRowTitles() { attributes.zIndex = 1024; } else if section < dataSource.numberOfColumnTitles() || index < dataSource.numberOfRowTitles() { attributes.zIndex = 1023 } if section < dataSource.numberOfColumnTitles() { var frame = attributes.frame frame.origin.y = self.collectionView!.contentOffset.y + CGFloat(section) * dataSource.heightOfColumnTitles() attributes.frame = frame } if index < dataSource.numberOfRowTitles() { var frame = attributes.frame frame.origin.x = self.collectionView!.contentOffset.x + CGFloat(index) * dataSource.widthOfRowTitles() attributes.frame = frame } sectionAttributes.append(attributes) xOffset += itemSize.width column++ if column == numberOfItems { if xOffset > contentWidth { contentWidth = xOffset } column = 0 xOffset = 0 yOffset += itemSize.height } } self.itemAttributes.append(sectionAttributes) } let attributes : UICollectionViewLayoutAttributes = self.itemAttributes.last!.last! contentHeight = attributes.frame.origin.y + attributes.frame.size.height self.contentSize = CGSizeMake(contentWidth, contentHeight) } override public func collectionViewContentSize() -> CGSize { return self.contentSize } override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return self.itemAttributes[indexPath.section][indexPath.row] } override public func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes = [UICollectionViewLayoutAttributes]() //let attributes : NSMutableArray = NSMutableArray() for section in self.itemAttributes { attributes += section.filter({(attributes: UICollectionViewLayoutAttributes) -> Bool in return CGRectIntersectsRect(rect, attributes.frame) }) } return attributes } override public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } func sizeOfItemAtIndexPath(indexPath: NSIndexPath) -> CGSize { if let size = sizeCache.objectForKey(indexPath)?.CGSizeValue() { return size } let size: CGSize let column = indexPath.item let row = indexPath.section switch (row, column) { case (0..<dataSource.numberOfColumnTitles(), 0..<dataSource.numberOfRowTitles()): size = CGSize(width: dataSource.widthOfRowTitles(), height: dataSource.heightOfColumnTitles()) case (_, 0..<dataSource.numberOfRowTitles()): size = CGSize(width: dataSource.widthOfRowTitles(), height: dataSource.heightForContentRowIndex(row - dataSource.numberOfColumnTitles())) case (0..<dataSource.numberOfColumnTitles(), _): size = CGSize(width: dataSource.widthForContentColumnIndex(column - dataSource.numberOfRowTitles()), height: dataSource.heightOfColumnTitles()) default: size = CGSize(width: dataSource.widthForContentColumnIndex(column - dataSource.numberOfRowTitles()), height: dataSource.heightForContentRowIndex(row - dataSource.numberOfColumnTitles())) } sizeCache.setObject(NSValue(CGSize: size), forKey: indexPath, cost: 1) return size } }
mit
a6ad72dec682b3a0b96a376944a09228
39.533333
198
0.602064
5.981216
false
false
false
false
porkbuns/shmile-ios
Pods/SwiftHTTP/HTTPTask.swift
6
23484
////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPTask.swift // // Created by Dalton Cherry on 6/3/14. // Copyright (c) 2014 Vluxe. All rights reserved. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation /// HTTP Verbs. /// /// - GET: For GET requests. /// - POST: For POST requests. /// - PUT: For PUT requests. /// - HEAD: For HEAD requests. /// - DELETE: For DELETE requests. /// - PATCH: For PATCH requests. public enum HTTPMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case HEAD = "HEAD" case DELETE = "DELETE" case PATCH = "PATCH" } /// Object representation of a HTTP Response. public class HTTPResponse { /// The header values in HTTP response. public var headers: Dictionary<String,String>? /// The mime type of the HTTP response. public var mimeType: String? /// The suggested filename for a downloaded file. public var suggestedFilename: String? /// The body or response data of the HTTP response. public var responseObject: AnyObject? /// The status code of the HTTP response. public var statusCode: Int? /// The URL of the HTTP response. public var URL: NSURL? /// The Error of the HTTP response (if there was one). public var error: NSError? ///Returns the response as a string public var text: String? { if let d = self.responseObject as? NSData { return NSString(data: d, encoding: NSUTF8StringEncoding) as? String } else if let val: AnyObject = self.responseObject { return "\(val)" } return nil } //get the description of the response public var description: String { var buffer = "" if let u = self.URL { buffer += "URL:\n\(u)\n\n" } if let code = self.statusCode { buffer += "Status Code:\n\(code)\n\n" } if let heads = self.headers { buffer += "Headers:\n" for (key, value) in heads { buffer += "\(key): \(value)\n" } buffer += "\n" } if let s = self.text { buffer += "Payload:\n\(s)\n" } return buffer } } /// Holds the blocks of the background task. class BackgroundBlocks { // these 2 only get used for background download/upload since they have to be delegate methods var completionHandler:((HTTPResponse) -> Void)? var progress:((Double) -> Void)? /** Initializes a new Background Block :param: completionHandler The closure that is run when a HTTP Request finished. :param: progress The closure that is run on the progress of a HTTP Upload or Download. */ init(_ completionHandler: ((HTTPResponse) -> Void)?,_ progress: ((Double) -> Void)?) { self.completionHandler = completionHandler self.progress = progress } } /// Subclass of NSOperation for handling and scheduling HTTPTask on a NSOperationQueue. public class HTTPOperation : NSOperation { private var task: NSURLSessionDataTask! private var running = false /// Controls if the task is finished or not. private var done = false //MARK: Subclassed NSOperation Methods /// Returns if the task is asynchronous or not. NSURLSessionTask requests are asynchronous. override public var asynchronous: Bool { return true } /// Returns if the task is current running. override public var executing: Bool { return running } /// Returns if the task is finished. override public var finished: Bool { return done } /// Starts the task. override public func start() { if cancelled { self.willChangeValueForKey("isFinished") done = true self.didChangeValueForKey("isFinished") return } self.willChangeValueForKey("isExecuting") self.willChangeValueForKey("isFinished") running = true done = false self.didChangeValueForKey("isExecuting") self.didChangeValueForKey("isFinished") task.resume() } /// Cancels the running task. override public func cancel() { super.cancel() task.cancel() } /// Sets the task to finished. public func finish() { self.willChangeValueForKey("isExecuting") self.willChangeValueForKey("isFinished") running = false done = true self.didChangeValueForKey("isExecuting") self.didChangeValueForKey("isFinished") } } /// Configures NSURLSession Request for HTTPOperation. Also provides convenience methods for easily running HTTP Request. public class HTTPTask : NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate { var backgroundTaskMap = Dictionary<String,BackgroundBlocks>() //var sess: NSURLSession? public var baseURL: String? public var requestSerializer = HTTPRequestSerializer() public var responseSerializer: HTTPResponseSerializer? //This gets called on auth challenges. If nil, default handling is use. //Returning nil from this method will cause the request to be rejected and cancelled public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)? //This is for doing SSL pinning public var security: HTTPSecurity? //MARK: Public Methods /// A newly minted HTTPTask for your enjoyment. public override init() { super.init() } /** Creates a HTTPOperation that can be scheduled on a NSOperationQueue. Called by convenience HTTP verb methods below. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :param: completionHandler The closure that is run when a HTTP Request finished. :returns: A freshly constructed HTTPOperation to add to your NSOperationQueue. */ public func create(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!, completionHandler:((HTTPResponse) -> Void)!) -> HTTPOperation? { var serialResponse = HTTPResponse() let serialReq = createRequest(url, method: method, parameters: parameters) if let err = serialReq.error { if let handler = completionHandler { serialResponse.error = err handler(serialResponse) } return nil } let opt = HTTPOperation() let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) let task = session.dataTaskWithRequest(serialReq.request, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in if let handler = completionHandler { if let hresponse = response as? NSHTTPURLResponse { serialResponse.headers = hresponse.allHeaderFields as? Dictionary<String,String> serialResponse.mimeType = hresponse.MIMEType serialResponse.suggestedFilename = hresponse.suggestedFilename serialResponse.statusCode = hresponse.statusCode serialResponse.URL = hresponse.URL } serialResponse.error = error if let d = data { serialResponse.responseObject = d if let resSerializer = self.responseSerializer { let resObj = resSerializer.responseObjectFromResponse(response, data: d) serialResponse.responseObject = resObj.object serialResponse.error = resObj.error } if let code = serialResponse.statusCode where serialResponse.statusCode > 299 { serialResponse.error = self.createError(code) } } handler(serialResponse) } opt.finish() }) opt.task = task return opt } /** Creates a HTTPOperation as a HTTP GET request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: completionHandler The closure that is run when a HTTP Request finished. */ public func GET(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) { if let opt = self.create(url, method:.GET, parameters: parameters,completionHandler: completionHandler) { opt.start() } } /** Creates a HTTPOperation as a HTTP POST request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: completionHandler The closure that is run when a HTTP Request finished. */ public func POST(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) { if let opt = self.create(url, method:.POST, parameters: parameters,completionHandler: completionHandler) { opt.start() } } /** Creates a HTTPOperation as a HTTP PATCH request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: completionHandler The closure that is run when a HTTP Request finished. */ public func PATCH(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) { if let opt = self.create(url, method:.PATCH, parameters: parameters,completionHandler: completionHandler) { opt.start() } } /** Creates a HTTPOperation as a HTTP PUT request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: completionHandler The closure that is run when a HTTP Request finished. */ public func PUT(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) { if let opt = self.create(url, method:.PUT, parameters: parameters,completionHandler: completionHandler) { opt.start() } } /** Creates a HTTPOperation as a HTTP DELETE request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: completionHandler The closure that is run when a HTTP Request finished. */ public func DELETE(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) { if let opt = self.create(url, method:.DELETE, parameters: parameters,completionHandler: completionHandler) { opt.start() } } /** Creates a HTTPOperation as a HTTP HEAD request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: completionHandler The closure that is run when a HTTP Request finished. */ public func HEAD(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) { if let opt = self.create(url, method:.HEAD, parameters: parameters,completionHandler: completionHandler) { opt.start() } } /** Creates and starts a HTTPOperation to download a file in the background. :param: url The url you would like to make a request to. :param: method The HTTP method you want to use. Default is GET. :param: parameters The parameters are HTTP parameters you would like to send. :param: progress The progress returned in the progress closure is between 0 and 1. :param: completionHandler The closure that is run when the HTTP Request finishes. The HTTPResponse responseObject object will be a fileURL. You MUST copy the fileURL return in HTTPResponse.responseObject to a new location before using it (e.g. your documents directory). */ public func download(url: String, method: HTTPMethod = .GET, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, completionHandler:((HTTPResponse) -> Void)!) -> NSURLSessionDownloadTask? { let serialReq = createRequest(url,method: method, parameters: parameters) if let err = serialReq.error { if let handler = completionHandler { var res = HTTPResponse() res.error = err handler(res) } return nil } let ident = createBackgroundIdent() let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident) let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) let task = session.downloadTaskWithRequest(serialReq.request) backgroundTaskMap[ident] = BackgroundBlocks(completionHandler,progress) //this does not have to be queueable as Apple's background dameon *should* handle that. task.resume() return task } /** Creates and starts a HTTPOperation to upload a file in the background. :param: url The url you would like to make a request to. :param: method The HTTP method you want to use. Default is POST. :param: parameters The parameters are HTTP parameters you would like to send. :param: progress The progress returned in the progress closure is between 0 and 1. :param: completionHandler The closure that is run when a HTTP Request finished. */ public func upload(url: String, method: HTTPMethod = .POST, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, completionHandler:((HTTPResponse) -> Void)!) -> NSURLSessionTask? { let serialReq = createRequest(url,method: method, parameters: parameters) if let err = serialReq.error { if let handler = completionHandler { var res = HTTPResponse() res.error = err handler(res) } return nil } let ident = createBackgroundIdent() let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident) let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) let task = session.uploadTaskWithStreamedRequest(serialReq.request) backgroundTaskMap[ident] = BackgroundBlocks(completionHandler,progress) task.resume() return task } //MARK: Private Helper Methods /** Creates and starts a HTTPOperation to download a file in the background. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :returns: A NSURLRequest from configured requestSerializer. */ private func createRequest(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!) -> (request: NSURLRequest, error: NSError?) { var urlVal = url //probably should change the 'http' to something more generic if !url.hasPrefix("http") && self.baseURL != nil { var split = url.hasPrefix("/") ? "" : "/" urlVal = "\(self.baseURL!)\(split)\(url)" } if let u = NSURL(string: urlVal) { return self.requestSerializer.createRequest(u, method: method, parameters: parameters) } return (NSURLRequest(),createError(-1001)) } /** Creates a random string to use for the identifier of the background download/upload requests. :returns: Identifier String. */ private func createBackgroundIdent() -> String { let letters = "abcdefghijklmnopqurstuvwxyz" var str = "" for var i = 0; i < 14; i++ { let start = Int(arc4random() % 14) str.append(letters[advance(letters.startIndex,start)]) } return "com.vluxe.swifthttp.request.\(str)" } /** Creates a random string to use for the identifier of the background download/upload requests. :param: code Code for error. :returns: An NSError. */ private func createError(code: Int) -> NSError { var text = "An error occured" if code == 404 { text = "Page not found" } else if code == 401 { text = "Access denied" } else if code == -1001 { text = "Invalid URL" } return NSError(domain: "HTTPTask", code: code, userInfo: [NSLocalizedDescriptionKey: text]) } /** Creates a random string to use for the identifier of the background download/upload requests. :param: identifier The identifier string. :returns: An NSError. */ private func cleanupBackground(identifier: String) { backgroundTaskMap.removeValueForKey(identifier) } //MARK: NSURLSession Delegate Methods /// Method for authentication challenge. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { if let sec = security where challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let space = challenge.protectionSpace if let trust = space.serverTrust { if sec.isValid(trust, domain: space.host) { completionHandler(.UseCredential, NSURLCredential(trust: trust)) return } } completionHandler(.CancelAuthenticationChallenge, nil) return } else if let a = auth { let cred = a(challenge) if let c = cred { completionHandler(.UseCredential, c) return } completionHandler(.RejectProtectionSpace, nil) return } completionHandler(.PerformDefaultHandling, nil) } //MARK: Methods for background download/upload ///update the download/upload progress closure func handleProgress(session: NSURLSession, totalBytesExpected: Int64, currentBytes: Int64) { if session.configuration.valueForKey("identifier") != nil { //temp workaround for radar: 21097168 let increment = 100.0/Double(totalBytesExpected) var current = (increment*Double(currentBytes))*0.01 if current > 1 { current = 1; } if let blocks = backgroundTaskMap[session.configuration.identifier] { if blocks.progress != nil { blocks.progress!(current) } } } } //call the completionHandler closure for upload/download requests func handleFinish(session: NSURLSession, task: NSURLSessionTask, response: AnyObject) { if session.configuration.valueForKey("identifier") != nil { //temp workaround for radar: 21097168 if let blocks = backgroundTaskMap[session.configuration.identifier] { if let handler = blocks.completionHandler { var resp = HTTPResponse() if let hresponse = task.response as? NSHTTPURLResponse { resp.headers = hresponse.allHeaderFields as? Dictionary<String,String> resp.mimeType = hresponse.MIMEType resp.suggestedFilename = hresponse.suggestedFilename resp.statusCode = hresponse.statusCode resp.URL = hresponse.URL } resp.responseObject = response if let code = resp.statusCode where resp.statusCode > 299 { resp.error = self.createError(code) } handler(resp) } } cleanupBackground(session.configuration.identifier) } } /// Called when the background task failed. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let err = error { if session.configuration.valueForKey("identifier") != nil { //temp workaround for radar: 21097168 if let blocks = backgroundTaskMap[session.configuration.identifier] { if let handler = blocks.completionHandler { var res = HTTPResponse() res.error = err handler(res) } } cleanupBackground(session.configuration.identifier) } } } /// The background download finished and reports the url the data was saved to. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL!) { handleFinish(session, task: downloadTask, response: location) } /// Will report progress of background download func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { handleProgress(session, totalBytesExpected: totalBytesExpectedToWrite, currentBytes:totalBytesWritten) } /// The background download finished, don't have to really do anything. public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { } /// The background upload finished and reports the response. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData!) { handleFinish(session, task: dataTask, response: data) } ///Will report progress of background upload public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { handleProgress(session, totalBytesExpected: totalBytesExpectedToSend, currentBytes:totalBytesSent) } //implement if we want to support partial file upload/download func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { } }
mit
d06f4bbbbbf19d968ee54e6da7de78bd
41.389892
278
0.626171
5.36042
false
false
false
false
scsonic/cosremote
ios/CosRemote/InmoovType.swift
1
638
// // InmoovType.swift // CosRemote // // Created by 郭 又鋼 on 2016/4/11. // Copyright © 2016年 郭 又鋼. All rights reserved. // import Foundation public enum InmoovType: Int { case arm = 0 case index = 1 case middle = 2 case ring = 3 case little = 4 case thumb = 5 case delay = 100 } /* public enum CVScrollDirection { case None case Right case Left var description: String { get { switch self { case .Left: return "Left" case .Right: return "Right" case .None: return "None" } } } } */
mit
c3b5c40bea6818e9553b0f8038f4b50c
15
48
0.529695
3.601156
false
false
false
false
AChildFromBUAA/PracticePlace
TestPractice/SettingsViewController.swift
1
1083
// // SettingsViewController.swift // TestPractice // // Created by kyz on 15/10/14. // Copyright © 2015年 BUAA.Software. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var psdLabel: UILabel! @IBOutlet weak var batteryLabel: UILabel! @IBOutlet weak var soundLabel: UILabel! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.getPreference() } func getPreference() { let defaults = NSUserDefaults.standardUserDefaults() self.nameLabel.text = defaults.stringForKey("name_preference") self.psdLabel.text = defaults.stringForKey("password_preference") self.batteryLabel.text = String(stringInterpolationSegment: defaults.integerForKey("batteryLimit_preference")) if defaults.boolForKey("soundEnable_preference") { self.soundLabel.text = "Yes" } else { self.soundLabel.text = "No" } } }
mit
5346a10633b212a08ebe846ad634fbf1
26.692308
118
0.660185
4.615385
false
false
false
false
devyu/Stroe
JYStore/ViewController.swift
1
2167
// // ViewController.swift // JYStore // // Created by mac on 12/4/15. // Copyright © 2015 JY. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var productsButton: NSPopUpButton! private var overviewViewController: OverviewController! private var detailViewController: DetailViewController! private var products = [Product]() var selectProduct: Product! override func viewDidLoad() { super.viewDidLoad() if let filePath = NSBundle.mainBundle().pathForResource("Products", ofType: "plist") { products = Product.productsList(filePath) } productsButton.removeAllItems() for product in products { productsButton.addItemWithTitle(product.title) } selectProduct = products[0] productsButton.selectItemAtIndex(0) } @IBAction func valueChanged(sender: NSPopUpButton) { if let bookTitle = sender.selectedItem?.title, let index = products.indexOf({$0.title == bookTitle}) { selectProduct = products[index] overviewViewController.selectedProduct = selectProduct detailViewController.selectedProduct = selectProduct } } override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) { // 1. get the refrence to the TabViewController let tableViewController = segue.destinationController as! NSTabViewController // 2. Iterates over all its child view controllers for controller in tableViewController.childViewControllers { // 3. Check if the current child view controller is an instance of OverviewController, and if it is, sets its selectedProduct property. if controller is OverviewController { overviewViewController = controller as! OverviewController overviewViewController.selectedProduct = selectProduct } else { detailViewController = controller as! DetailViewController detailViewController.selectedProduct = selectProduct } } } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } }
mit
4f05015bf625eca607537a905b05de74
27.88
143
0.700831
5.348148
false
false
false
false
stripysock/SwiftGen
UnitTests/TestsHelper.swift
1
1646
// // SwiftGen // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Foundation import XCTest func diff(lhs: String, _ rhs: String) -> String { var firstDiff : Int? = nil let nl = NSCharacterSet.newlineCharacterSet() let lhsLines = lhs.componentsSeparatedByCharactersInSet(nl) let rhsLines = rhs.componentsSeparatedByCharactersInSet(nl) for (idx, pair) in zip(lhsLines, rhsLines).enumerate() { if pair.0 != pair.1 { firstDiff = idx break; } } if let idx = firstDiff { let numLines = { (num: Int, line: String) -> String in "\(num)".stringByPaddingToLength(3, withString: " ", startingAtIndex: 0) + "|" + line } let lhsNum = lhsLines.enumerate().map(numLines).joinWithSeparator("\n") let rhsNum = rhsLines.enumerate().map(numLines).joinWithSeparator("\n") return "Mismatch at line \(idx)>\n>>>>>> lhs\n\(lhsNum)\n======\n\(rhsNum)\n<<<<<< rhs" } return "" } func XCTDiffStrings(lhs: String, _ rhs: String) { XCTAssertEqual(lhs, rhs, diff(lhs, rhs)) } extension XCTestCase { var fixturesDir : String { return NSBundle(forClass: self.dynamicType).resourcePath! } func fixturePath(name: String) -> String { guard let path = NSBundle(forClass: self.dynamicType).pathForResource(name, ofType: "") else { fatalError("Unable to find fixture \"\(name)\"") } return path } func fixtureString(name: String, encoding: UInt = NSUTF8StringEncoding) -> String { do { return try NSString(contentsOfFile: fixturePath(name), encoding: encoding) as String } catch let e { fatalError("Unable to load fixture content: \(e)") } } }
mit
12d40042aa06de75a5d741a520f52344
29.5
146
0.662211
3.947242
false
false
false
false
marty-suzuki/QiitaWithFluxSample
Carthage/Checkouts/RxSwift/scripts/package-spm.swift
1
12373
#!/usr/bin/swift // // package-spm.swift // scripts // // Created by Krunoslav Zaher on 12/26/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** This script packages normal Rx* structure into `Sources` directory. * creates and updates links to normal project structure * builds unit tests `main.swift` Unfortunately, Swift support for Linux, libdispatch and package manager are still quite unstable, so certain class of unit tests is excluded for now. */ // It is kind of ironic that we need to additionally package for package manager :/ let fileManager = FileManager.default let allowedExtensions = [ ".swift", ".h", ".m", ] // Those tests are dependent on conditional compilation logic and it's hard to handle them automatically // They usually test some internal state, so it should be ok to exclude them for now. let excludedTests: [String] = [ "testConcat_TailRecursionCollection", "testConcat_TailRecursionSequence", "testMapCompose_OptimizationIsPerformed", "testMapCompose_OptimizationIsNotPerformed", "testObserveOn_EnsureCorrectImplementationIsChosen", "testObserveOnDispatchQueue_EnsureCorrectImplementationIsChosen", "testResourceLeaksDetectionIsTurnedOn", "testAnonymousObservable_disposeReferenceDoesntRetainObservable", "testObserveOnDispatchQueue_DispatchQueueSchedulerIsSerial", "ReleasesResourcesOn", "testShareReplayLatestWhileConnectedDisposableDoesntRetainAnything", "testSingle_DecrementCountsFirst", "testSinglePredicate_DecrementCountsFirst", "testLockUnlockCountsResources" ] func excludeTest(_ name: String) -> Bool { for exclusion in excludedTests { if name.contains(exclusion) { return true } } return false } let excludedTestClasses: [String] = [ /*"ObservableConcurrentSchedulerConcurrencyTest", "SubjectConcurrencyTest", "VirtualSchedulerTest", "HistoricalSchedulerTest"*/ "BagTest" ] let throwingWordsInTests: [String] = [ /*"error", "fail", "throw", "retrycount", "retrywhen",*/ ] func isExtensionAllowed(_ path: String) -> Bool { return (allowedExtensions.map { path.hasSuffix($0) }).reduce(false) { $0 || $1 } } func checkExtension(_ path: String) throws { if !isExtensionAllowed(path) { throw NSError(domain: "Security", code: -1, userInfo: ["path" : path]) } } func packageRelativePath(_ paths: [String], targetDirName: String, excluded: [String] = []) throws { let targetPath = "Sources/\(targetDirName)" print("Checking " + targetPath) for file in try fileManager.contentsOfDirectory(atPath: targetPath).sorted { $0 < $1 } { if file != "include" && file != ".DS_Store" { print("Checking extension \(file)") try checkExtension(file) print("Cleaning \(file)") try fileManager.removeItem(atPath: "\(targetPath)/\(file)") } } for sourcePath in paths { var isDirectory: ObjCBool = false fileManager.fileExists(atPath: sourcePath, isDirectory: &isDirectory) let files: [String] = isDirectory.boolValue ? fileManager.subpaths(atPath: sourcePath)! : [sourcePath] for file in files { if !isExtensionAllowed(file) { print("Skipping \(file)") continue } if excluded.contains(file) { print("Skipping \(file)") continue } let fileRelativePath = isDirectory.boolValue ? "\(sourcePath)/\(file)" : file let destinationURL = NSURL(string: "../../\(fileRelativePath)")! let fileName = (file as NSString).lastPathComponent let atURL = NSURL(string: "file:///\(fileManager.currentDirectoryPath)/\(targetPath)/\(fileName)")! if fileName.hasSuffix(".h") { let sourcePath = NSURL(string: "file:///" + fileManager.currentDirectoryPath + "/" + sourcePath + "/" + file)! //throw NSError(domain: sourcePath.description, code: -1, userInfo: nil) try fileManager.copyItem(at: sourcePath as URL, to: atURL as URL) } else { print("Linking \(fileName) [\(atURL)] -> \(destinationURL)") try fileManager.createSymbolicLink(at: atURL as URL, withDestinationURL: destinationURL as URL) } } } } func buildAllTestsTarget(_ testsPath: String) throws { let splitClasses = "(?:class|extension)\\s+(\\w+)" let testMethods = "\\s+func\\s+(test\\w+)" let splitClassesRegularExpression = try! NSRegularExpression(pattern: splitClasses, options:[]) let testMethodsExpression = try! NSRegularExpression(pattern: testMethods, options: []) var reducedMethods: [String: [String]] = [:] for file in try fileManager.contentsOfDirectory(atPath: testsPath).sorted { $0 < $1 } { if !file.hasSuffix(".swift") || file == "main.swift" { continue } let fileRelativePath = "\(testsPath)/\(file)" let testContent = try String(contentsOfFile: fileRelativePath, encoding: String.Encoding.utf8) print(fileRelativePath) let classMatches = splitClassesRegularExpression.matches(in: testContent as String, options: [], range: NSRange(location: 0, length: testContent.characters.count)) let matchIndexes = classMatches .map { $0.range.location } #if swift(>=4.0) let classNames = classMatches.map { (testContent as NSString).substring(with: $0.range(at: 1)) as NSString } #else let classNames = classMatches.map { (testContent as NSString).substring(with: $0.rangeAt(1)) as NSString } #endif let ranges = zip([0] + matchIndexes, matchIndexes + [testContent.characters.count]).map { NSRange(location: $0, length: $1 - $0) } let classRanges = ranges[1 ..< ranges.count] let classes = zip(classNames, classRanges.map { (testContent as NSString).substring(with: $0) as NSString }) for (name, classCode) in classes { if excludedTestClasses.contains(name as String) { print("Skipping \(name)") continue } let methodMatches = testMethodsExpression.matches(in: classCode as String, options: [], range: NSRange(location: 0, length: classCode.length)) #if swift(>=4.0) let methodNameRanges = methodMatches.map { $0.range(at: 1) } #else let methodNameRanges = methodMatches.map { $0.rangeAt(1) } #endif let testMethodNames = methodNameRanges .map { classCode.substring(with: $0) } .filter { !excludeTest($0) } if testMethodNames.count == 0 { continue } let existingMethods = reducedMethods[name as String] ?? [] reducedMethods[name as String] = existingMethods + testMethodNames } } var mainContent = [String]() mainContent.append("// this file is autogenerated using `./scripts/package-swift-manager.swift`") mainContent.append("import XCTest") mainContent.append("import RxSwift") mainContent.append("") mainContent.append("protocol RxTestCase {") mainContent.append("#if os(macOS)") mainContent.append(" init()") mainContent.append(" static var allTests: [(String, (Self) -> () -> ())] { get }") mainContent.append("#endif") mainContent.append(" func setUp()") mainContent.append(" func tearDown()") mainContent.append("}") mainContent.append("") for (name, methods) in reducedMethods { mainContent.append("") mainContent.append("final class \(name)_ : \(name), RxTestCase {") mainContent.append(" #if os(macOS)") mainContent.append(" required override init() {") mainContent.append(" super.init()") mainContent.append(" }") mainContent.append(" #endif") mainContent.append("") mainContent.append(" static var allTests: [(String, (\(name)_) -> () -> ())] { return [") for method in methods { // throwing error on Linux, you will crash let isTestCaseHandlingError = throwingWordsInTests.map { (method as String).lowercased().contains($0) }.reduce(false) { $0 || $1 } mainContent.append(" \(isTestCaseHandlingError ? "//" : "")(\"\(method)\", \(name).\(method)),") } mainContent.append(" ] }") mainContent.append("}") } mainContent.append("#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)") mainContent.append("") mainContent.append("func testCase<T: RxTestCase>(_ tests: [(String, (T) -> () -> ())]) -> () -> () {") mainContent.append(" return {") mainContent.append(" for testCase in tests {") mainContent.append(" print(\"Test \\(testCase)\")") mainContent.append(" for test in T.allTests {") mainContent.append(" let testInstance = T()") mainContent.append(" testInstance.setUp()") mainContent.append(" print(\" testing \\(test.0)\")") mainContent.append(" test.1(testInstance)()") mainContent.append(" testInstance.tearDown()") mainContent.append(" }") mainContent.append(" }") mainContent.append(" }") mainContent.append("}") mainContent.append("") mainContent.append("func XCTMain(_ tests: [() -> ()]) {") mainContent.append(" for testCase in tests {") mainContent.append(" testCase()") mainContent.append(" }") mainContent.append("}") mainContent.append("") mainContent.append("#endif") mainContent.append("") mainContent.append(" XCTMain([") for testCase in reducedMethods.keys { mainContent.append(" testCase(\(testCase)_.allTests),") } mainContent.append(" ])") mainContent.append("//}") mainContent.append("") let serializedMainContent = mainContent.joined(separator: "\n") try serializedMainContent.write(toFile: "\(testsPath)/main.swift", atomically: true, encoding: String.Encoding.utf8) } try packageRelativePath(["RxSwift"], targetDirName: "RxSwift") //try packageRelativePath(["RxCocoa/Common", "RxCocoa/macOS", "RxCocoa/RxCocoa.h"], targetDirName: "RxCocoa") try packageRelativePath([ "RxCocoa/RxCocoa.swift", "RxCocoa/Deprecated.swift", "RxCocoa/Traits", "RxCocoa/Common", "RxCocoa/Foundation", "RxCocoa/iOS", "RxCocoa/macOS", "RxCocoa/Platform", ], targetDirName: "RxCocoa") try packageRelativePath([ "RxCocoa/Runtime/include", ], targetDirName: "RxCocoaRuntime/include") try packageRelativePath([ "RxCocoa/Runtime/_RX.m", "RxCocoa/Runtime/_RXDelegateProxy.m", "RxCocoa/Runtime/_RXKVOObserver.m", "RxCocoa/Runtime/_RXObjCRuntime.m", ], targetDirName: "RxCocoaRuntime") try packageRelativePath(["RxBlocking"], targetDirName: "RxBlocking") try packageRelativePath(["RxTest"], targetDirName: "RxTest") // It doesn't work under `Tests` subpath ¯\_(ツ)_/¯ try packageRelativePath([ "Tests/RxSwiftTests", "Tests/RxBlockingTests", "RxSwift/RxMutableBox.swift", "Tests/RxTest.swift", "Tests/Recorded+Timeless.swift", "Tests/TestErrors.swift", "Tests/XCTest+AllTests.swift", "Platform", "Tests/RxCocoaTests/Driver+Test.swift", "Tests/RxCocoaTests/Signal+Test.swift", "Tests/RxCocoaTests/SharedSequence+Extensions.swift", "Tests/RxCocoaTests/SharedSequence+Test.swift", "Tests/RxCocoaTests/SharedSequence+OperatorTest.swift", "Tests/RxCocoaTests/NotificationCenterTests.swift", ], targetDirName: "AllTestz", excluded: [ "Tests/VirtualSchedulerTest.swift", "Tests/HistoricalSchedulerTest.swift", // @testable import doesn't work well in Linux :/ "QueueTests.swift", // @testable import doesn't work well in Linux :/ "SubjectConcurrencyTest.swift", // @testable import doesn't work well in Linux :/ "BagTest.swift" ]) try buildAllTestsTarget("Sources/AllTestz")
mit
c4e8ea59d1fbc572c35d12120bb2e570
36.478788
171
0.628962
4.542049
false
true
false
false
17thDimension/AudioKit
Tests/Tests/AKTrackedFrequency.swift
2
1407
// // main.swift // AudioKit // // Created by Aurelius Prochazka on 1/4/15. // Copyright (c) 2015 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: Float = 10 class Instrument : AKInstrument { override init() { super.init() let frequencyLine = AKLine( firstPoint: 110.ak, secondPoint: 880.ak, durationBetweenPoints: testDuration.ak ) let frequencyLineDeviation = AKOscillator() frequencyLineDeviation.frequency = 1.ak frequencyLineDeviation.amplitude = 30.ak let toneGenerator = AKOscillator() toneGenerator.frequency = frequencyLine.plus(frequencyLineDeviation) setAudioOutput(toneGenerator) let tracker = AKTrackedFrequency( audioSource: toneGenerator, sampleSize: 512.ak ) enableParameterLog( "Actual frequency = ", parameter: toneGenerator.frequency, timeInterval: 0.1 ) enableParameterLog( "Tracked frequency = ", parameter: tracker, timeInterval: 0.1 ) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() AKOrchestra.addInstrument(instrument) instrument.play() let manager = AKManager.sharedManager() while(manager.isRunning) {} //do nothing println("Test complete!")
lgpl-3.0
fbdaab0996736aa36be40b8b97a3b589
22.45
76
0.633973
4.954225
false
true
false
false
avinassh/ClickCounter
Click Counter/ViewController.swift
1
2493
// // ViewController.swift // Click Counter // // Created by avi on 10/03/15. // Copyright (c) 2015 avi. All rights reserved. // import UIKit class ViewController: UIViewController { // model var count = 0 var label: UILabel! func incrementCount() { count++ label.text = "\(count)" } func decrementCount() { count-- label.text = "\(count)" } func toggleBackground() { if view.backgroundColor == UIColor(red: 1, green: 1, blue: 1, alpha: 1) { view.backgroundColor = UIColor.grayColor() } else { view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // adds a label var label = UILabel() label.frame = CGRectMake(150, 150, 60, 60) label.text = "0" view.addSubview(label) self.label = label // adds a increment button var incButton = UIButton() incButton.frame = CGRectMake(150, 250, 120, 60) incButton.setTitle("Increment", forState: .Normal) incButton.setTitleColor(UIColor.blueColor(), forState: .Normal) view.addSubview(incButton) incButton.addTarget(self, action: "incrementCount", forControlEvents: .TouchUpInside) // adds a decrement button var decButton = UIButton() decButton.frame = CGRectMake(150, 350, 120, 60) decButton.setTitle("Decrement", forState: .Normal) decButton.setTitleColor(UIColor.blueColor(), forState: .Normal) view.addSubview(decButton) decButton.addTarget(self, action: "decrementCount", forControlEvents: .TouchUpInside) // adds a button which toggles the background var toggleBgButton = UIButton() toggleBgButton.frame = CGRectMake(150, 450, 180, 60) toggleBgButton.setTitle("Toggle Background", forState: .Normal) toggleBgButton.setTitleColor(UIColor.blueColor(), forState: .Normal) view.addSubview(toggleBgButton) toggleBgButton.addTarget(self, action: "toggleBackground", forControlEvents: .TouchUpInside) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
a78db3bd7e688488c0bf8146179fc1fa
29.036145
100
0.610509
4.59116
false
false
false
false
coach-plus/ios
Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift
6
5081
// // BehaviorSubject.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Represents a value that changes over time. /// /// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. public final class BehaviorSubject<Element> : Observable<Element> , SubjectType , ObserverType , SynchronizedUnsubscribeType , Cancelable { public typealias SubjectObserverType = BehaviorSubject<Element> typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType /// Indicates whether the subject has any observers public var hasObservers: Bool { self._lock.lock() let value = self._observers.count > 0 self._lock.unlock() return value } let _lock = RecursiveLock() // state private var _isDisposed = false private var _element: Element private var _observers = Observers() private var _stoppedEvent: Event<Element>? #if DEBUG private let _synchronizationTracker = SynchronizationTracker() #endif /// Indicates whether the subject has been disposed. public var isDisposed: Bool { return self._isDisposed } /// Initializes a new instance of the subject that caches its last value and starts with the specified value. /// /// - parameter value: Initial value sent to observers when no other value has been received by the subject yet. public init(value: Element) { self._element = value #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } /// Gets the current value or throws an error. /// /// - returns: Latest value. public func value() throws -> Element { self._lock.lock(); defer { self._lock.unlock() } // { if self._isDisposed { throw RxError.disposed(object: self) } if let error = self._stoppedEvent?.error { // intentionally throw exception throw error } else { return self._element } //} } /// Notifies all subscribed observers about next event. /// /// - parameter event: Event to send to the observers. public func on(_ event: Event<Element>) { #if DEBUG self._synchronizationTracker.register(synchronizationErrorMessage: .default) defer { self._synchronizationTracker.unregister() } #endif dispatch(self._synchronized_on(event), event) } func _synchronized_on(_ event: Event<Element>) -> Observers { self._lock.lock(); defer { self._lock.unlock() } if self._stoppedEvent != nil || self._isDisposed { return Observers() } switch event { case .next(let element): self._element = element case .error, .completed: self._stoppedEvent = event } return self._observers } /// Subscribes an observer to the subject. /// /// - parameter observer: Observer to subscribe to the subject. /// - returns: Disposable object that can be used to unsubscribe the observer from the subject. public override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { self._lock.lock() let subscription = self._synchronized_subscribe(observer) self._lock.unlock() return subscription } func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { if self._isDisposed { observer.on(.error(RxError.disposed(object: self))) return Disposables.create() } if let stoppedEvent = self._stoppedEvent { observer.on(stoppedEvent) return Disposables.create() } let key = self._observers.insert(observer.on) observer.on(.next(self._element)) return SubscriptionDisposable(owner: self, key: key) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { self._lock.lock() self._synchronized_unsubscribe(disposeKey) self._lock.unlock() } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { if self._isDisposed { return } _ = self._observers.removeKey(disposeKey) } /// Returns observer interface for subject. public func asObserver() -> BehaviorSubject<Element> { return self } /// Unsubscribe all observers and release resources. public func dispose() { self._lock.lock() self._isDisposed = true self._observers.removeAll() self._stoppedEvent = nil self._lock.unlock() } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif }
mit
5a4b3f1fdb7179f36f00f3f5c0ef96ba
29.60241
130
0.60689
5.110664
false
false
false
false
kylef/Requests
Tests/SendResponseSpec.swift
1
634
import Spectre import Inquiline @testable import Requests func describeSendRequest() { describe("Sending a request") { var outSocket: Socket! var inSocket: Socket! $0.before { let pipe = try! Socket.pipe() inSocket = pipe[0] outSocket = pipe[1] } $0.it("sends the HTTP request to the server") { let request = Request(method: "GET", path: "/path", headers: [], content: "Hello World") sendRequest(outSocket, request: request) let message = String.fromCString((try inSocket.read(512)) + [0]) try expect(message) == "GET /path HTTP/1.1\r\n\r\nHello World" } } }
bsd-2-clause
56160c013d1c7655601fd6e94f293db5
24.36
94
0.629338
3.581921
false
false
false
false
silence0201/Swift-Study
Learn/10.属性和下标/结构体和枚举中的计算属性.playground/section-1.swift
1
510
struct Department { let no: Int = 0 var name: String = "SALES" var fullName: String { return "Swift." + name + ".D" } } var dept = Department() print(dept.fullName) enum WeekDays: String { case Monday = "Mon." case Tuesday = "Tue." case Wednesday = "Wed." case Thursday = "Thu." case Friday = "Fri." var message: String { return "Today is " + self.rawValue } } var day = WeekDays.Monday print(day.message)
mit
6790776d85c2ebe08e7d07e107d678f3
17.214286
42
0.539216
3.517241
false
false
false
false
vzool/ios-nanodegree-earth-diary
OpenWeatherMap.swift
1
2691
// // OpenWeatherMap.swift // Map Forecast Diary // // Created by Abdelaziz Elrashed on 8/18/15. // Copyright (c) 2015 Abdelaziz Elrashed. All rights reserved. // import Foundation extension String { func toDouble() -> Double? { return NSNumberFormatter().numberFromString(self)?.doubleValue } } class OpenWeatherMap{ struct Key{ static let API_KEY = "d1bdb0aa0a27c34ffc59f7da125de3a8" static let BASE_URL = "http://api.openweathermap.org/data/2.5/weather" } static internal func GetTodayForecast(lat:String, lon:String, completion: ((data: NSDictionary) -> Void)? ){ let param = [ "lat": lat, "lon": lon, "APPID": Key.API_KEY, "units": "metric" ] let session = NSURLSession.sharedSession() let urlString = OpenWeatherMap.Key.BASE_URL + escapedParameters(param) let url = NSURL(string: urlString)! let request = NSURLRequest(URL: url) let task = session.dataTaskWithRequest(request) {data, response, downloadError in if let error = downloadError { println("Could not complete the request \(error)") if let completion = completion{ var resultError = NSDictionary(objects: [error], forKeys: ["error"]) completion(data: resultError) } } else { var parsingError: NSError? = nil let parsedResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) as! NSDictionary if let completion = completion{ completion(data: parsedResult) } } } task.resume() } /* Helper function: Given a dictionary of parameters, convert to a string for a url */ static func escapedParameters(parameters: [String : AnyObject]) -> String { var urlVars = [String]() for (key, value) in parameters { /* Make sure that it is a string value */ let stringValue = "\(value)" /* Escape it */ let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) /* Append it */ urlVars += [key + "=" + "\(escapedValue!)"] } return (!urlVars.isEmpty ? "?" : "") + join("&", urlVars) } }
mit
ba6fc92007b66e91da0f10b794cc3fa1
31.421687
164
0.543292
5.266145
false
false
false
false
PixelTown/PixelLife
PixelLife/PixelLife/ShoppingScene.swift
1
3062
// // ShoppingScene.swift // PixelLife // // Created by Yifang Zhang on 8/11/15. // Copyright (c) 2015 Yifang. All rights reserved. // import Foundation import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class ShoppingScene: SKScene { //script references override func didMoveToView(view: SKView) { /* Setup your scene here */ let myLabel = SKLabelNode(fontNamed:"Chalkduster") myLabel.text = "Welcome to the shopping page"; myLabel.fontSize = 40; myLabel.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center; myLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center; myLabel.position = CGPoint(x:CGRectGetMaxX(self.frame)/2, y:CGRectGetMaxY(self.frame)/4); myLabel.name = "Welcome" myLabel.fontColor = SKColor.blueColor() self.addChild(myLabel) //set the label to previous page: let previous = SKLabelNode(fontNamed: "Chalkduster") previous.text = "previous page" previous.fontSize = 24; previous.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center previous.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center previous.position = CGPoint(x:CGRectGetMaxX(self.frame)/2, y:CGRectGetMaxY(self.frame)*3/4) previous.name = "previous" previous.fontColor = SKColor.whiteColor() self.addChild(previous) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { /* Called when a touch begins */ for touch in (touches as! Set<UITouch>) { let location = touch.locationInNode(self) let nodesInTouch = self.nodesAtPoint(location) for node in nodesInTouch { if(node.name == "previous"){ let transition = SKTransition.revealWithDirection(SKTransitionDirection.Right, duration: 1.0) let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene scene!.scaleMode = .AspectFill self.scene!.view!.presentScene(scene, transition: transition) } } } } override func update(currentTime: NSTimeInterval) { // do something here } }
mit
df9e4463d12d27427f4f8a49a098acd2
33.41573
113
0.612018
5.270224
false
false
false
false
janukobytsch/cardiola
cardiola/cardiola/Patient.swift
1
877
// // Patient.swift // cardiola // // Created by Janusch Jacoby on 30/01/16. // Copyright © 2016 BPPolze. All rights reserved. // import Foundation import RealmSwift class Patient: Object, PersistentModel { dynamic var id: String = NSUUID().UUIDString override static func primaryKey() -> String? { return "id" } dynamic var hasChestPain: Bool = false dynamic var hasAngina: Bool = false dynamic var name: String? dynamic var serverId: String? let plans = List<MeasurementPlan>() let bloodSugar = RealmOptional<Int>() let ecg = RealmOptional<Int>() convenience init(name: String) { self.init() self.name = name } static func createDemoPatient() -> Patient { let demoPatient = Patient(name: "Pep") demoPatient.serverId = "1" return demoPatient } }
mit
8f9e54e3e8a8f3b577278b24924f0446
22.702703
50
0.631279
4.036866
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/STZPopupView/STZPopupViewConfig.swift
1
2542
// // STZPopupViewConfig.swift // STZPopupView // // Created by Kenji Abe on 2015/02/22. // Copyright (c) 2015年 Kenji Abe. All rights reserved. // import UIKit /** Show Animation type */ public enum STZPopupShowAnimation { case none case fadeIn case slideInFromTop case slideInFromBottom case slideInFromLeft case slideInFromRight case custom // Need implements 'showCustomAnimation' } /** Dismiss Animation */ public enum STZPopupDismissAnimation { case none case fadeOut case slideOutToTop case slideOutToBottom case slideOutToLeft case slideOutToRight case custom // Need implements 'dismissCustomAnimation' } /** * Popup Config */ open class STZPopupViewConfig { /// Dismiss touch the Background if ture. open var dismissTouchBackground = true /// Popup corner radius value. open var cornerRadius: CGFloat = 0 /// Background overlay color. open var overlayColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) /// Show animation type. open var showAnimation = STZPopupShowAnimation.fadeIn /// Dismiss animation type. open var dismissAnimation = STZPopupDismissAnimation.fadeOut /// Clouser show animation is completed. /// Pass the popup view to argument. open var showCompletion: ((UIView) -> Void)? = nil /// Clouser disimss animation is completed. /// Pass the popup view to argument. open var dismissCompletion: ((UIView) -> Void)? = nil /// Show custom animation of closure. /// /// Set STZPopupShowAnimation.Custom to 'showAnimation' property to use custom animation. /// /// Argument: /// /// - containerView: Enclosing a popup view. Added to the view of UIViewController. /// - popupView: A popup view is displayed. /// - completion: Be sure to call after animation completion. open var showCustomAnimation: (UIView, UIView, @escaping (Void) -> Void) -> Void = { containerView, popupView, completion in } /// Dismiss custom animation of closure. /// /// Set STZPopupShowAnimation.Custom to 'dismissAnimation' property to use custom animation. /// /// Argument: /// /// - containerView: Enclosing a popup view. Added to the view of UIViewController. /// - popupView: A popup view is displayed. /// - completion: Be sure to call after animation completion. open var dismissCustomAnimation: (UIView, UIView, @escaping (Void) -> Void) -> Void = { containerView, popupView, completion in } public init() {} }
mit
0df67c25ca560f5c6bea00ef149a9c80
27.863636
133
0.683858
4.356775
false
false
false
false
yannickl/DynamicButton
Sources/DynamicButtonStyles/DynamicButtonStyleArrowLeft.swift
1
2073
/* * DynamicButton * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit /// Leftwards arrow style: ← struct DynamicButtonStyleArrowLeft: DynamicButtonBuildableStyle { let pathVector: DynamicButtonPathVector init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) { let rightPoint = CGPoint(x: offset.x + size - lineWidth / 2, y: center.y) let headPoint = CGPoint(x: offset.x + lineWidth, y: center.y) let topPoint = CGPoint(x: offset.x + size / 3.2, y: center.y + size / 3.2) let bottomPoint = CGPoint(x: offset.x + size / 3.2, y: center.y - size / 3.2) let p1 = PathHelper.line(from: rightPoint, to: headPoint) let p2 = PathHelper.line(from: headPoint, to: topPoint) let p3 = PathHelper.line(from: headPoint, to: bottomPoint) pathVector = DynamicButtonPathVector(p1: p1, p2: p2, p3: p3, p4: p1) } /// "Arrow Left" style. static var styleName: String { return "Arrow Left" } }
mit
e90d69bd3861c1fd8f778f0c8f2f34e3
40.42
81
0.722839
3.959847
false
false
false
false
MorganCabral/swiftrekt-ios-app-dev-challenge-2015
app-dev-challenge/app-dev-challenge/IntroCountdownSprite.swift
1
1222
// // IntroCountdownSprite.swift // app-dev-challenge // // Created by Morgan Cabral on 2/8/15. // Copyright (c) 2015 Team SwiftRekt. All rights reserved. // import Foundation import SpriteKit public class IntroCountdownSprite : SKLabelNode { public override init() { self._countdownFinishedTime = 0 super.init() self.fontName = "Palatino" self.text = "5" self.fontColor = UIColor.blackColor() self.fontSize = 144 } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func initializeCountdown ( currentTime : CFTimeInterval ) { _countdownFinishedTime = currentTime + 5 } func updateIntroAnimationStartupTimer( currentTime : CFTimeInterval ) { var remainingTime = Int(_countdownFinishedTime - currentTime) if remainingTime <= 0 { self.text = "GO!" var waitAction = SKAction.waitForDuration(NSTimeInterval(1.0)) var slideOutAnimation = SKAction.moveToY(3000.0, duration: 1.0) self.runAction(SKAction.sequence([waitAction, slideOutAnimation])) } else { self.text = "\(remainingTime)" } } private var _countdownFinishedTime : CFTimeInterval }
mit
c696bcb346c6422a9d8448110577adcf
25.586957
73
0.689034
4.272727
false
false
false
false
Fiskie/jsrl
jsrl/Chat.swift
1
3404
// // Chat.swift // jsrl // import Foundation enum ChatFetchError: Error { case xmlParserInitFailed } class Chat : Resource { var recvEndpoint = "/chat/messages.xml" var sendEndpoint = "/chat/save.php" /** Fetch the latest chat messages in messages.xml. - properties: - callback: Callback returning an Error (nil if OK) and an array of ChatMessage responses. */ func fetch(_ callback: @escaping (_ err: Error?, _ body: [ChatMessage])->()) { let url = URL(string: context.root + recvEndpoint) DispatchQueue.main.async { let parser = XMLParser(contentsOf: url!) if let parser = parser { let chatParser = ChatParser() parser.delegate = chatParser parser.parse() callback(nil, chatParser.messages) } else { callback(ChatFetchError.xmlParserInitFailed, []) } } } /** Post a message to the chat. - properties: - message: A ChatMessage. - callback: Callback returning an Error (nil if OK) and an URLResponse. */ func send(_ message: ChatMessage, _ callback: @escaping (_ err: Error?, _ response: URLResponse?)->()) { let url = URL(string: context.root + sendEndpoint) // Create our form string. There's probably a better way to do this let form: [String: String] = [ "chatmessage": message.text, "chatpassword": message.password ? "true" : "false", "username": message.username ] let formData = form.map({"\($0)=\($1.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)"}).joined(separator: "&") var request = URLRequest(url: url!) request.httpMethod = "POST" request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData request.httpBody = formData.data(using: String.Encoding.utf8) let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in guard let _ = data, let _:URLResponse = response , error == nil else { callback(error, response) return } callback(nil, response) } task.resume() } } /** An entity representing a single message digest. */ class ChatMessage: CustomStringConvertible { /** Message text. */ var text: String = "" /** Usernames. May contain HTML */ var username: String = "" /** is a 40-character hash, e.g. 250e7dd82f8dbba1e0463134ea4f7e3dcdb313e3 It is unknown if this field is decryptable or not: - it's too long to be an md5 hash - doesn't seem to decode as hex or base64 - is not referenced in the site's obfuscated javascript source */ var ip: String = "" /** Not sure how this field works yet. */ var password: Bool = false init() { } init(username: String, text: String, ip: String) { self.username = username self.text = text self.ip = ip } var description: String { return "[ChatMessage] \(username): \(text)" } }
gpl-3.0
6b237e48dc35bde9fb8aa09b52808784
26.901639
135
0.552879
4.643929
false
false
false
false
cdtschange/SwiftMKit
SwiftMKit/UI/Schema/BaseKitTableViewModel.swift
1
4785
// // BaseKitTableViewModel.swift // SwiftMKitDemo // // Created by Mao on 5/13/16. // Copyright © 2016 cdts. All rights reserved. // import UIKit import CocoaLumberjack import Alamofire import MJRefresh open class BaseKitTableViewModel: NSObject { open weak var viewController: BaseKitTableViewController! open var hud: HudProtocol { get { return self.viewController.hud } } open var taskIndicator: Indicator { get { return self.viewController.taskIndicator } } open var view: UIView { get { return self.viewController.view } } open func fetchData() { } deinit { DDLogError("Deinit: \(NSStringFromClass(type(of: self)))") } fileprivate struct InnerConstant { static let StringNoMoreDataTip = "数据已全部加载完毕" } open var listViewController: BaseKitTableViewController! { get { return viewController as BaseKitTableViewController } } var dataArray:[AnyObject] { get { if dataSource.first == nil { dataSource.append([AnyObject]()) } return dataSource.first! } set { dataSource = [newValue] } } var dataSource:[[AnyObject]] = [[AnyObject]]() { didSet { if self.viewController == nil { return } if self.listViewController.listViewType == .refreshOnly || self.listViewController.listViewType == .none { return } var noMoreDataTip = InnerConstant.StringNoMoreDataTip let count: UInt = UInt(dataSource.count) if count == 0 { self.viewController.showEmptyView() self.listViewController.listView.mj_footer.endRefreshingWithNoMoreData() noMoreDataTip = "" return } if oldValue.count == 0 { self.viewController.hideEmptyView() self.listViewController.listView.mj_footer.resetNoMoreData() } if count < listLoadNumber { self.listViewController.listView.mj_footer.endRefreshingWithNoMoreData() noMoreDataTip = "" }else if count % listLoadNumber > 0 || count >= listMaxNumber { self.listViewController.listView.mj_footer.endRefreshingWithNoMoreData() } if let footer = self.listViewController.listView.mj_footer as? MJRefreshAutoStateFooter { footer.setTitle(noMoreDataTip, for: .noMoreData) } } } var dataIndex: UInt = 0 let listLoadNumber: UInt = 20 let listMaxNumber: UInt = UInt.max open func updateDataArray(_ newData: [AnyObject]?) { if let data = newData { if dataIndex == 0 { dataArray = data } else { dataArray += data } } else { if dataIndex == 0 { dataArray = [] } } if let table = self.listViewController.listView as? UITableView { table.reloadData() } else if let collect = self.listViewController.listView as? UICollectionView { collect.reloadData() } } open func updateDataSource(_ newData: [[AnyObject]]?) { dataSource = newData ?? [[AnyObject]]() if let table = self.listViewController.listView as? UITableView { table.reloadData() } else if let collect = self.listViewController.listView as? UICollectionView { collect.reloadData() } } } //HUD extension BaseKitTableViewModel { public func showTip(_ tip: String, completion : @escaping () -> Void = {}) { showTip(tip, view: self.view, completion: completion) } public func showTip(_ tip: String, image: UIImage?, completion : @escaping () -> Void = {}) { MBHud.shared.showTip(inView: view, text: tip, image: image, animated: true, completion: completion) } public func showTip(_ tip: String, view: UIView, offset: CGPoint = CGPoint.zero, completion : @escaping () -> Void = {}) { MBHud.shared.showTip(inView: view, text: tip, offset: offset, animated: true, completion: completion) } public func showLoading(_ text: String = "") { viewController.showIndicator(inView: viewController.view, text: text) } public func showLoading(_ text: String, view: UIView) { viewController.showIndicator(inView: view, text: text) } public func hideLoading() { viewController.hideLoading() } public func hideLoading(_ view: UIView) { viewController.hideLoading(view) } }
mit
5d34ec17467c3ca54a678b12ef419b3e
32.097222
126
0.586446
4.964583
false
false
false
false
pfvernon2/swiftlets
iOSX/CoalescingTimer.swift
1
4999
// // CoalescingTimer.swift // swiftlets // // Created by Frank Vernon on 9/15/15. // Copyright © 2015 Frank Vernon. All rights reserved. // import Foundation /** A Timer wrapper with simple coalescing and reuse semantics. This timer class is particularly useful when using a delayed operation pattern where an operation is to be performed in a batched or coalesced fashion, for example when the device becomes idle. - Note: The wrapper ensures all operations occur on main queue. ```` var delayedOperationTimer:CoalescingTimer? = nil override func awakeFromNib() { //Create a timer to save current state 1 second after the user completes // their touch operation. delayedOperationTimer = CoalescingTimer(duration:1.0) { (CoalescingTimer) in //Save state } } override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { //User ends operation so start the timer. delayedOperationTimer?.prime() } override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { //User begins new operation so restart the timer. delayedOperationTimer?.restart() } override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) { //User still moving so restart the timer. delayedOperationTimer?.restart() } ```` */ open class CoalescingTimer { fileprivate var timer:Timer? fileprivate var duration:TimeInterval { didSet { if running { restart() } } } fileprivate var repeats:Bool = false fileprivate var tolerance:Float = 0.1 fileprivate var closure: (_ timer:CoalescingTimer) -> () = { (CoalescingTimer) in } fileprivate weak var queue:DispatchQueue? = DispatchQueue.main open var running:Bool { get { guard let timer = timer else { return false } return timer.isValid } } deinit { self._stop() } /** Create a timer with closure. - Parameter duration: The duration in seconds between start and when the closure is invoked. - Parameter repeats: Indicate if timer should repeat. Defaults to false - Parameter tolerance: The percentage of time after the scheduled fire date that the timer may fire. Defaults to 0.1. Range 0.0...1.0. Using a non-zero tolerance value when timing accuracy is not crucial allows the OS to better optimize for power and CPU usage. - Parameter queue: The DispatchQueue to invoke the closure on. - Parameter closure: The closure to be invoked when the timer fires. */ public init(duration: TimeInterval, repeats: Bool = false, tolerance:Float = 0.1, queue:DispatchQueue = DispatchQueue.main, closure: @escaping (CoalescingTimer)->()) { self.closure = closure self.duration = duration self.repeats = repeats self.queue = queue } /** Start the timer if not running. */ open func prime() { DispatchQueue.main.async { () -> Void in if self.timer == nil { self.start() } else if let timer = self.timer, !timer.isValid { self.start() } } } /** Start the timer. Currently running timers are stoped without firing. */ open func start() { DispatchQueue.main.async { () -> Void in self._stop() self.timer = Timer.scheduledTimer(withTimeInterval: self.duration, repeats: self.repeats) { (timer) in self.queue?.async { self.closure(self) } } self.timer?.tolerance = self.duration * TimeInterval(self.tolerance) } } /** Restart a previously running timer or no-op if not running */ open func restart() { DispatchQueue.main.async { () -> Void in guard let timer = self.timer else { return } if timer.isValid { timer.fireDate = Date(timeIntervalSinceNow: self.duration) } else { self.start() } } } /** Stop the timer without firing. */ open func stop() { DispatchQueue.main.async { () -> Void in self._stop() } } /** Forces timer to fire immediately without interrupting regular fire scheduling. If the timer is non-repeating it is invalidated after fiing. */ open func fire() { DispatchQueue.main.async {() -> Void in guard let timer = self.timer, timer.isValid else { return } timer.fire() } } //MARK: - Internal Implementation fileprivate func _stop() { guard let timer = self.timer else { return } timer.invalidate() self.timer = nil } }
apache-2.0
5bbaf70a0e9cd5ea5b092747e755d90b
28.573964
266
0.591637
4.866602
false
false
false
false
TeamProxima/predictive-fault-tracker
mobile/SieHack/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift
52
2037
// // ChartLimitLine.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// The limit line is an additional feature for all Line, Bar and ScatterCharts. /// It allows the displaying of an additional line in the chart that marks a certain maximum / limit on the specified axis (x- or y-axis). open class ChartLimitLine: ComponentBase { @objc(ChartLimitLabelPosition) public enum LabelPosition: Int { case leftTop case leftBottom case rightTop case rightBottom } /// limit / maximum (the y-value or xIndex) open var limit = Double(0.0) fileprivate var _lineWidth = CGFloat(2.0) open var lineColor = NSUIColor(red: 237.0/255.0, green: 91.0/255.0, blue: 91.0/255.0, alpha: 1.0) open var lineDashPhase = CGFloat(0.0) open var lineDashLengths: [CGFloat]? open var valueTextColor = NSUIColor.black open var valueFont = NSUIFont.systemFont(ofSize: 13.0) open var drawLabelEnabled = true open var label = "" open var labelPosition = LabelPosition.rightTop public override init() { super.init() } public init(limit: Double) { super.init() self.limit = limit } public init(limit: Double, label: String) { super.init() self.limit = limit self.label = label } /// set the line width of the chart (min = 0.2, max = 12); default 2 open var lineWidth: CGFloat { get { return _lineWidth } set { if newValue < 0.2 { _lineWidth = 0.2 } else if newValue > 12.0 { _lineWidth = 12.0 } else { _lineWidth = newValue } } } }
mit
b92e6d749e57e3205174f96d49b4e290
22.964706
138
0.567992
4.343284
false
false
false
false
tomkowz/Swifternalization
Swifternalization/SharedExpressionsProcessor.swift
1
4609
// // ExpressionsProcessor.swift // Swifternalization // // Created by Tomasz Szulc on 26/07/15. // Copyright (c) 2015 Tomasz Szulc. All rights reserved. // import Foundation /** Swifternalization contains some built-in country-related shared expressions. Developer can create its own expressions in expressions.json file for base and preferred languages. The class is responsible for proper loading the built-in shared ones and those loaded from project's files. It handles overriding of built-in and loads those from Base and preferred language version. It always load base expressions, then looking for language specific. If in Base are some expressions that overrides built-ins, that's fine. The class adds developer's custom expressions and adds only those of built-in that are not contained in the Base. The same is for preferred languages but also here what is important is that at first preferred language file expressions are loaded, then if something different is defined in Base it will be also loaded and then the built-in expression that differs. */ class SharedExpressionsProcessor { /** Method takes expression for both Base and preferred language localizations and also internally loads built-in expressions, combine them and returns expressions for Base and prefered language. :param: preferedLanguage A user device's language. :param: preferedLanguageExpressions Expressions from expressions.json :param: baseLanguageExpressions Expressions from base section of expression.json. :returns: array of shared expressions for Base and preferred language. */ class func processSharedExpression(_ preferedLanguage: CountryCode, preferedLanguageExpressions: [SharedExpression], baseLanguageExpressions: [SharedExpression]) -> [SharedExpression] { /* Get unique base expressions that are not presented in prefered language expressions. Those from base will be used in a case when programmer will ask for string localization and when there is no such expression in prefered language section defined. It means two things: 1. Programmer make this expression shared through prefered language and this is good as base expression. 2. He forgot to define such expression for prefered language. */ let uniqueBaseExpressions = baseLanguageExpressions <! preferedLanguageExpressions // Expressions from json files. let loadedExpressions = uniqueBaseExpressions + preferedLanguageExpressions // Load prefered language nad base built-in expressions. Get unique. let prefBuiltInExpressions = loadBuiltInExpressions(preferedLanguage) let baseBuiltInExpressions = SharedBaseExpression.allExpressions() let uniqueBaseBuiltInExpressions = baseBuiltInExpressions <! prefBuiltInExpressions // Unique built-in expressions made of base + prefered language. let builtInExpressions = uniqueBaseBuiltInExpressions + prefBuiltInExpressions /* To get it done we must get only unique built-in expressions that are not in loaded expressions. */ return loadedExpressions + (builtInExpressions <! loadedExpressions) } /** Method loads built-in framework's built-in expressions for specific language. :param: language A preferred user's language. :returns: Shared expressions for specific language. If there is no expression for passed language empty array is returned. */ private class func loadBuiltInExpressions(_ language: CountryCode) -> [SharedExpression] { switch language { case "pl": return SharedPolishExpression.allExpressions() default: return [] } } } precedencegroup SetPrecedence { higherThan: DefaultPrecedence } infix operator <! : SetPrecedence /** "Get Unique" operator. It helps in getting unique shared expressions from two arrays. Content of `lhs` array will be checked in terms on uniqueness. The operator does check is there is any shared expression in `lhs` that is presented in `rhs`. If element from `lhs` is not in `rhs` then this element is correct and is returned in new array which is a result of this operation. */ func <! (lhs: [SharedExpression], rhs: [SharedExpression]) -> [SharedExpression] { var result = lhs if rhs.count > 0 { result = lhs.filter({ let tmp = $0 return rhs.filter({$0.identifier == tmp.identifier}).count == 0 }) } return result }
mit
2c0811abe98b75c97b816603147b1113
40.522523
189
0.727056
5.098451
false
false
false
false
catloafsoft/AudioKit
AudioKit/Common/Nodes/Effects/Reverb/Apple Reverb/AKReverb2.swift
1
8313
// // AKReverb2.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// AudioKit version of Apple's Reverb2 Audio Unit /// /// - parameter input: Input node to process /// - parameter dryWetMix: Dry Wet Mix (CrossFade) ranges from 0 to (Default: 0.5) /// - parameter gain: Gain (Decibels) ranges from -20 to 20 (Default: 0) /// - parameter minDelayTime: Min Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.008) /// - parameter maxDelayTime: Max Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.050) /// - parameter decayTimeAt0Hz: Decay Time At0 Hz (Secs) ranges from 0.001 to 20.0 (Default: 1.0) /// - parameter decayTimeAtNyquist: Decay Time At Nyquist (Secs) ranges from 0.001 to 20.0 (Default: 0.5) /// - parameter randomizeReflections: Randomize Reflections (Integer) ranges from 1 to 1000 (Default: 1) /// public class AKReverb2: AKNode, AKToggleable { private let cd = AudioComponentDescription( componentType: kAudioUnitType_Effect, componentSubType: kAudioUnitSubType_Reverb2, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) internal var internalEffect = AVAudioUnitEffect() internal var internalAU = AudioUnit() private var lastKnownMix: Double = 50 /// Dry Wet Mix (CrossFade) ranges from 0 to 1 (Default: 0.5) public var dryWetMix: Double = 0.5 { didSet { if dryWetMix < 0 { dryWetMix = 0 } if dryWetMix > 1 { dryWetMix = 1 } AudioUnitSetParameter( internalAU, kReverb2Param_DryWetMix, kAudioUnitScope_Global, 0, Float(dryWetMix * 100.0), 0) } } /// Gain (Decibels) ranges from -20 to 20 (Default: 0) public var gain: Double = 0 { didSet { if gain < -20 { gain = -20 } if gain > 20 { gain = 20 } AudioUnitSetParameter( internalAU, kReverb2Param_Gain, kAudioUnitScope_Global, 0, Float(gain), 0) } } /// Min Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.008) public var minDelayTime: Double = 0.008 { didSet { if minDelayTime < 0.0001 { minDelayTime = 0.0001 } if minDelayTime > 1.0 { minDelayTime = 1.0 } AudioUnitSetParameter( internalAU, kReverb2Param_MinDelayTime, kAudioUnitScope_Global, 0, Float(minDelayTime), 0) } } /// Max Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.050) public var maxDelayTime: Double = 0.050 { didSet { if maxDelayTime < 0.0001 { maxDelayTime = 0.0001 } if maxDelayTime > 1.0 { maxDelayTime = 1.0 } AudioUnitSetParameter( internalAU, kReverb2Param_MaxDelayTime, kAudioUnitScope_Global, 0, Float(maxDelayTime), 0) } } /// Decay Time At0 Hz (Secs) ranges from 0.001 to 20.0 (Default: 1.0) public var decayTimeAt0Hz: Double = 1.0 { didSet { if decayTimeAt0Hz < 0.001 { decayTimeAt0Hz = 0.001 } if decayTimeAt0Hz > 20.0 { decayTimeAt0Hz = 20.0 } AudioUnitSetParameter( internalAU, kReverb2Param_DecayTimeAt0Hz, kAudioUnitScope_Global, 0, Float(decayTimeAt0Hz), 0) } } /// Decay Time At Nyquist (Secs) ranges from 0.001 to 20.0 (Default: 0.5) public var decayTimeAtNyquist: Double = 0.5 { didSet { if decayTimeAtNyquist < 0.001 { decayTimeAtNyquist = 0.001 } if decayTimeAtNyquist > 20.0 { decayTimeAtNyquist = 20.0 } AudioUnitSetParameter( internalAU, kReverb2Param_DecayTimeAtNyquist, kAudioUnitScope_Global, 0, Float(decayTimeAtNyquist), 0) } } /// Randomize Reflections (Integer) ranges from 1 to 1000 (Default: 1) public var randomizeReflections: Double = 1 { didSet { if randomizeReflections < 1 { randomizeReflections = 1 } if randomizeReflections > 1000 { randomizeReflections = 1000 } AudioUnitSetParameter( internalAU, kReverb2Param_RandomizeReflections, kAudioUnitScope_Global, 0, Float(randomizeReflections), 0) } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted = true /// Initialize the reverb2 node /// /// - parameter input: Input node to process /// - parameter dryWetMix: Dry Wet Mix (CrossFade) ranges from 0 to 1 (Default: 0.5) /// - parameter gain: Gain (Decibels) ranges from -20 to 20 (Default: 0) /// - parameter minDelayTime: Min Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.008) /// - parameter maxDelayTime: Max Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.050) /// - parameter decayTimeAt0Hz: Decay Time At0 Hz (Secs) ranges from 0.001 to 20.0 (Default: 1.0) /// - parameter decayTimeAtNyquist: Decay Time At Nyquist (Secs) ranges from 0.001 to 20.0 (Default: 0.5) /// - parameter randomizeReflections: Randomize Reflections (Integer) ranges from 1 to 1000 (Default: 1) /// public init( _ input: AKNode, dryWetMix: Double = 0.5, gain: Double = 0, minDelayTime: Double = 0.008, maxDelayTime: Double = 0.050, decayTimeAt0Hz: Double = 1.0, decayTimeAtNyquist: Double = 0.5, randomizeReflections: Double = 1) { self.dryWetMix = dryWetMix self.gain = gain self.minDelayTime = minDelayTime self.maxDelayTime = maxDelayTime self.decayTimeAt0Hz = decayTimeAt0Hz self.decayTimeAtNyquist = decayTimeAtNyquist self.randomizeReflections = randomizeReflections internalEffect = AVAudioUnitEffect(audioComponentDescription: cd) super.init() self.avAudioNode = internalEffect AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) internalAU = internalEffect.audioUnit AudioUnitSetParameter(internalAU, kReverb2Param_DryWetMix, kAudioUnitScope_Global, 0, Float(dryWetMix * 100.0), 0) AudioUnitSetParameter(internalAU, kReverb2Param_Gain, kAudioUnitScope_Global, 0, Float(gain), 0) AudioUnitSetParameter(internalAU, kReverb2Param_MinDelayTime, kAudioUnitScope_Global, 0, Float(minDelayTime), 0) AudioUnitSetParameter(internalAU, kReverb2Param_MaxDelayTime, kAudioUnitScope_Global, 0, Float(maxDelayTime), 0) AudioUnitSetParameter(internalAU, kReverb2Param_DecayTimeAt0Hz, kAudioUnitScope_Global, 0, Float(decayTimeAt0Hz), 0) AudioUnitSetParameter(internalAU, kReverb2Param_DecayTimeAtNyquist, kAudioUnitScope_Global, 0, Float(decayTimeAtNyquist), 0) AudioUnitSetParameter(internalAU, kReverb2Param_RandomizeReflections, kAudioUnitScope_Global, 0, Float(randomizeReflections), 0) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { if isStopped { dryWetMix = lastKnownMix isStarted = true } } /// Function to stop or bypass the node, both are equivalent public func stop() { if isPlaying { lastKnownMix = dryWetMix dryWetMix = 0 isStarted = false } } }
mit
1e305531f6d6b009933c31af07eef724
36.445946
140
0.580055
4.474166
false
false
false
false
airbnb/lottie-ios
Sources/Private/CoreAnimation/Layers/InfiniteOpaqueAnimationLayer.swift
2
1739
// Created by Cal Stephens on 10/10/22. // Copyright © 2022 Airbnb Inc. All rights reserved. import QuartzCore // MARK: - ExpandedAnimationLayer /// A `BaseAnimationLayer` subclass that renders its background color /// as if the layer is infinitely large, without affecting its bounds /// or the bounds of its sublayers final class InfiniteOpaqueAnimationLayer: BaseAnimationLayer { // MARK: Lifecycle override init() { super.init() addSublayer(additionalPaddingLayer) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Called by CoreAnimation to create a shadow copy of this layer /// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init override init(layer: Any) { super.init(layer: layer) } // MARK: Internal override func layoutSublayers() { super.layoutSublayers() masksToBounds = false additionalPaddingLayer.backgroundColor = backgroundColor // Scale `additionalPaddingLayer` to be larger than this layer // by `additionalPadding` at each size, and centered at the center // of this layer. Since `additionalPadding` is very large, this has // the affect of making `additionalPaddingLayer` appear infinite. let scaleRatioX = (bounds.width + (CALayer.veryLargeLayerPadding * 2)) / bounds.width let scaleRatioY = (bounds.height + (CALayer.veryLargeLayerPadding * 2)) / bounds.height additionalPaddingLayer.transform = CATransform3DScale( CATransform3DMakeTranslation(-CALayer.veryLargeLayerPadding, -CALayer.veryLargeLayerPadding, 0), scaleRatioX, scaleRatioY, 1) } // MARK: Private private let additionalPaddingLayer = CALayer() }
apache-2.0
a9647de802c2a26dff5484ca0f7f7aaa
30.035714
102
0.729574
4.445013
false
false
false
false
RailwayStations/Bahnhofsfotos
Modules/Data/Sources/Network/API.swift
1
5998
// // API.swift // Bahnhofsfotos // // Created by Miguel Dönicke on 15.01.17. // Copyright © 2017 MrHaitec. All rights reserved. // import Alamofire import Domain import Foundation import Shared import SwiftyUserDefaults public class API { public enum Error: Swift.Error { case message(String) } static var baseUrl: String { return Constants.baseUrl } // Get all countries public static func getCountries(completionHandler: @escaping ([CountryDTO]) -> Void) { AF.request(API.baseUrl + "/countries.json") .responseJSON { response in guard let data = response.data else { return completionHandler([]) } let countries = try? JSONDecoder().decode([CountryDTO].self, from: data) completionHandler(countries ?? []) } } // Get all stations (or with/out photo) public static func getStations(withPhoto hasPhoto: Bool?, completionHandler: @escaping ([StationDTO]) -> Void) { var parameters = Parameters() if Defaults.country.count > 0 { parameters["country"] = Defaults.country.lowercased() } if let hasPhoto = hasPhoto { parameters["hasPhoto"] = hasPhoto.description } AF.request(API.baseUrl + "/stations", parameters: parameters, encoding: URLEncoding.default, headers: nil) .responseJSON { response in guard let data = response.data else { return completionHandler([]) } do { let stations = try JSONDecoder().decode([StationDTO].self, from: data) completionHandler(stations) } catch { debugPrint(error.localizedDescription) completionHandler([]) } } } // Get all photographers of given country public static func getPhotographers(completionHandler: @escaping ([String: Int]) -> Void) { var parameters = Parameters() if Defaults.country.count > 0 { parameters["country"] = Defaults.country.lowercased() } AF.request(API.baseUrl + "/photographers", parameters: parameters, encoding: URLEncoding.default, headers: nil) .responseJSON { response in guard let data = response.data else { return completionHandler([:]) } do { let photographers = try JSONDecoder().decode([String: Int].self, from: data) completionHandler(photographers) } catch { debugPrint(error.localizedDescription) completionHandler([:]) } } } // Register user public static func register(completionHandler: @escaping (Bool) -> Void) { let parameters: Parameters = [ "nickname": Defaults.accountNickname ?? "", "email": Defaults.accountEmail ?? "", "license": "CC0", "photoOwner": Defaults.photoOwner, "linking": Defaults.accountType.rawValue, "link": Defaults.accountName ?? "" ] AF.request(API.baseUrl + "/registration", method: .post, parameters: parameters, encoding: JSONEncoding.default).response { dataResponse in // 202 = registration accepted completionHandler(dataResponse.response?.statusCode == 202) } } // Upload photo public static func uploadPhoto(imageData: Data, ofStation station: Station, inCountry country: Country, progressHandler: ((Double) -> Void)? = nil, completionHandler: @escaping (() throws -> Void) -> Void) { // 202 - upload successful // 400 - wrong request // 401 - wrong token // 409 - photo already exists // 413 - image too large (maximum 20 MB) guard let token = Defaults.uploadToken, let nickname = Defaults.accountNickname, let email = Defaults.accountEmail else { completionHandler { throw Error.message("Fehlerhafte Daten in Einstellungen überprüfen") } return } let headers: HTTPHeaders = [ "Upload-Token": token, "Nickname": nickname, "Email": email, "Station-Id": "\(station.id)", "Country": country.code, // country code "Content-Type": "image/jpeg" // "image/png" or "image/jpeg" ] let request = AF.upload(imageData, to: API.baseUrl + "/photoUpload", method: .post, headers: headers) if let progressHandler = progressHandler { request.uploadProgress { progress in progressHandler(progress.fractionCompleted) } } request.response { dataResponse in guard let response = dataResponse.response else { completionHandler { throw Error.message("Fehler beim Upload, bitte später erneut versuchen") } return } switch response.statusCode { case 400, 402: completionHandler { throw Error.message("Upload nicht möglich") } case 401: completionHandler { throw Error.message("Token ungültig") } case 409: completionHandler { throw Error.message("Foto bereits vorhanden") } case 413: completionHandler { throw Error.message("Foto ist zu groß (max. 20 MB)") } default: completionHandler { return } } } } }
apache-2.0
234eebecd779c65b632d445e01010cab
35.52439
116
0.538063
5.314996
false
false
false
false
zoeyzhong520/InformationTechnology
InformationTechnology/InformationTechnology/Classes/Recommend推荐/Science科技/View/AdDetailCell.swift
1
5394
// // AdDetailCell.swift // InformationTechnology // // Created by qianfeng on 16/11/4. // Copyright © 2016年 zzj. All rights reserved. // import UIKit class AdDetailCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var descLabel: UILabel! @IBOutlet weak var pageLabel: UILabel! @IBOutlet weak var pageControl: UIPageControl! //缩放比例 var scale:CGFloat = 1.0 //显示数据 var slideArray:Array<AdDetailBodySlides>? { didSet { showData() } } //显示数据 func showData() { //遍历添加图片 let cnt = slideArray?.count if slideArray?.count > 0 { //滚动视图加约束 //1.创建一个容器视图,作为滚动视图的子视图 let containerView = UIView.createView() scrollView.delegate = self scrollView.addSubview(containerView) containerView.snp_makeConstraints(closure: { (make) in make.edges.equalTo(scrollView) //一定要设置高度 make.height.equalTo(scrollView) }) //2.循环设置子视图的约束,子视图是添加到容器视图里面 var lastView: UIView? = nil for i in 0..<cnt! { let model = slideArray![i] //创建图片 let tmpImageView = UIImageView() if model.image != nil { let url = NSURL(string: model.image!) tmpImageView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } containerView.addSubview(tmpImageView) //图片的约束 tmpImageView.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(scrollView) if lastView == nil { make.left.equalTo(containerView) }else{ make.left.equalTo((lastView?.snp_right)!) } }) lastView = tmpImageView //添加pinch缩放手势 tmpImageView.userInteractionEnabled = true let pinch = UIPinchGestureRecognizer(target: self, action: #selector(bigOrSmall(_:))) tmpImageView.addGestureRecognizer(pinch) //显示标题 if model.title != nil { titleLabel.text = slideArray![pageControl.currentPage].title } //显示描述内容 if model.description1 != nil { descLabel.text = slideArray![pageControl.currentPage].description1 } //显示图片页数 pageLabel.text = "\(pageControl.currentPage+1)∕\(slideArray!.count)" } //3.修改container的宽度 containerView.snp_makeConstraints(closure: { (make) in make.right.equalTo(lastView!) }) //分页控件 pageControl.numberOfPages = cnt! } } func bigOrSmall(pinch:UIPinchGestureRecognizer) { pinch.view?.transform = CGAffineTransformMakeScale(pinch.scale*scale, pinch.scale*scale) if pinch.state == .Ended { //记录每次手势结束后,缩放的比例 scale *= pinch.scale } } //创建cell的方法 class func createAdSlidesForCell(tableView:UITableView, atIndexPath:NSIndexPath, slideArray:Array<AdDetailBodySlides>?) -> AdDetailCell { let cellId = "adDetailCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? AdDetailCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("AdDetailCell", owner: nil, options: nil).last as? AdDetailCell } cell?.slideArray = slideArray return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } //MARK: UIScrollView代理方法 extension AdDetailCell:UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = scrollView.contentOffset.x/scrollView.bounds.size.width pageControl!.currentPage = Int(index) //显示标题 titleLabel.text = slideArray![pageControl.currentPage].title //显示描述内容 descLabel.text = slideArray![pageControl.currentPage].description1 //显示图片页数 pageLabel.text = "\(pageControl.currentPage+1)∕\(slideArray!.count)" } }
mit
719b1230b0864b09bb4228d917d27c20
28.189655
170
0.53357
5.437901
false
false
false
false
dongdongSwift/guoke
gouke/果壳/SliderView.swift
1
2168
// // SliderView.swift // 果壳 // // Created by qianfeng on 2016/10/21. // Copyright © 2016年 张冬. All rights reserved. // import UIKit class SliderView: UIViewController { var tableview:UITableView? var changeClosure:((NSIndexPath)->())? var groupArray=["首页","消息","收藏页","设置"] var groupIcon=["home","mail","favourite","setup"] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor=UIColor.redColor() configUI() } func configUI(){ tableview=UITableView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)) view.addSubview(tableview!) tableview?.userInteractionEnabled=true tableview?.delegate=self tableview?.dataSource=self tableview?.bounces=false tableview?.separatorStyle = .SingleLine tableview?.tableHeaderView=NSBundle.mainBundle().loadNibNamed("headView", owner: nil, options: nil).last as? headView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK:uitablevbiew代理 extension SliderView:UITableViewDelegate,UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 40 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell=tableview?.dequeueReusableCellWithIdentifier("cell") if cell==nil{ cell=UITableViewCell(style: .Default, reuseIdentifier: "cell") } cell?.imageView?.frame=CGRectMake(0, 0, 60, 60) cell?.imageView?.image=UIImage(named: groupIcon[indexPath.row]) cell?.textLabel?.text=groupArray[indexPath.row] return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { changeClosure!(indexPath) } }
mit
e34136bb17fb752ade503f90ec09b98b
31.363636
125
0.662295
4.930716
false
false
false
false
AppleWatchHipster/AvanceDB
src/avancedb/test/scripts/SwiftHarnessForAvanceDB/SwiftHarnessForAvanceDB/HTTP.swift
2
4353
import Foundation /** * HTTP */ public class HTTP { public typealias Response = (Result) -> Void public typealias Headers = [String: String] public enum Method: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case HEAD = "HEAD" case DELETE = "DELETE" } public enum Result { case Success(AnyObject, NSHTTPURLResponse) case Error(NSError) } private var request: NSMutableURLRequest /** * Init */ public init(method: Method, url: String) { self.request = NSMutableURLRequest(URL: NSURL(string: url)!) self.request.HTTPMethod = method.rawValue } public init(method: Method, url: String, headers: Headers?) { self.request = NSMutableURLRequest(URL: NSURL(string: url)!) self.request.HTTPMethod = method.rawValue if let headers = headers { self.request.allHTTPHeaderFields = headers } } /** * Class funcs */ // GET public class func get(url: String) -> HTTP { return HTTP(method: .GET, url: url) } public class func get(url: String, headers: Headers?) -> HTTP { return HTTP(method: .GET, url: url, headers: headers) } public class func get(url: String, done: Response) -> HTTP { return HTTP.get(url).end(done) } public class func get(url: String, headers: Headers?, done: Response) -> HTTP { return HTTP(method: .GET, url: url, headers: headers).end(done) } // POST public class func post(url: String) -> HTTP { return HTTP(method: .POST, url: url) } public class func post(url: String, headers: Headers?) -> HTTP { return HTTP(method: .POST, url: url, headers: headers) } public class func post(url: String, done: Response) -> HTTP { return HTTP.post(url).end(done) } public class func post(url: String, data: AnyObject, done: Response) -> HTTP { return HTTP.post(url).send(data).end(done) } public class func post(url: String, headers: Headers?, data: AnyObject, done: Response) -> HTTP { return HTTP.post(url, headers: headers).send(data).end(done) } // PUT public class func put(url: String) -> HTTP { return HTTP(method: .PUT, url: url) } public class func put(url: String, done: Response) -> HTTP { return HTTP.put(url).end(done) } public class func put(url: String, data: AnyObject, done: Response) -> HTTP { return HTTP.put(url).send(data).end(done) } // DELETE public class func delete(url: String) -> HTTP { return HTTP(method: .DELETE, url: url) } public class func delete(url: String, done: Response) -> HTTP { return HTTP.delete(url).end(done) } /** * Methods */ public func send(data: AnyObject) -> HTTP { do { self.request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(data, options: []) } catch { self.request.HTTPBody = nil } self.request.addValue("application/json", forHTTPHeaderField: "Accept") self.request.addValue("application/json", forHTTPHeaderField: "Content-Type") return self } public func end(done: Response) -> HTTP { let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(self.request) { data, response, error in // we have an error -> maybe connection lost if let error = error { done(Result.Error(error)) return } // request was success var json: AnyObject! if let data = data { do { json = try NSJSONSerialization.JSONObjectWithData(data, options: []) } catch let error as NSError { done(Result.Error(error)) return } } // looking good let res = response as! NSHTTPURLResponse done(Result.Success(json, res)) } task.resume() return self } }
agpl-3.0
b2eae51b3201577b7bce69ac40a3dd6d
26.556962
101
0.549506
4.478395
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Style/TrailingClosureRule.swift
1
5800
import Foundation import SourceKittenFramework struct TrailingClosureRule: OptInRule, ConfigurationProviderRule { var configuration = TrailingClosureConfiguration() init() {} static let description = RuleDescription( identifier: "trailing_closure", name: "Trailing Closure", description: "Trailing closure syntax should be used whenever possible.", kind: .style, nonTriggeringExamples: [ Example("foo.map { $0 + 1 }\n"), Example("foo.bar()\n"), Example("foo.reduce(0) { $0 + 1 }\n"), Example("if let foo = bar.map({ $0 + 1 }) { }\n"), Example("foo.something(param1: { $0 }, param2: { $0 + 1 })\n"), Example("offsets.sorted { $0.offset < $1.offset }\n"), Example("foo.something({ return 1 }())"), Example("foo.something({ return $0 }(1))"), Example("foo.something(0, { return 1 }())") ], triggeringExamples: [ Example("↓foo.map({ $0 + 1 })\n"), Example("↓foo.reduce(0, combine: { $0 + 1 })\n"), Example("↓offsets.sorted(by: { $0.offset < $1.offset })\n"), Example("↓foo.something(0, { $0 + 1 })\n") ] ) func validate(file: SwiftLintFile) -> [StyleViolation] { let dict = file.structureDictionary return violationOffsets(for: dict, file: file).map { StyleViolation(ruleDescription: Self.description, severity: configuration.severityConfiguration.severity, location: Location(file: file, byteOffset: $0)) } } private func violationOffsets(for dictionary: SourceKittenDictionary, file: SwiftLintFile) -> [ByteCount] { var results = [ByteCount]() if dictionary.expressionKind == .call, shouldBeTrailingClosure(dictionary: dictionary, file: file), let offset = dictionary.offset { results = [offset] } if let kind = dictionary.statementKind, kind != .brace { // trailing closures are not allowed in `if`, `guard`, etc results += dictionary.substructure.flatMap { subDict -> [ByteCount] in guard subDict.statementKind == .brace else { return [] } return violationOffsets(for: subDict, file: file) } } else { results += dictionary.substructure.flatMap { subDict in violationOffsets(for: subDict, file: file) } } return results } private func shouldBeTrailingClosure(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool { func shouldTrigger() -> Bool { return !isAlreadyTrailingClosure(dictionary: dictionary, file: file) && !isAnonymousClosureCall(dictionary: dictionary, file: file) } let arguments = dictionary.enclosedArguments // check if last parameter should be trailing closure if !configuration.onlySingleMutedParameter, arguments.isNotEmpty, case let closureArguments = filterClosureArguments(arguments, file: file), closureArguments.count == 1, closureArguments.last?.offset == arguments.last?.offset { return shouldTrigger() } let argumentsCountIsExpected: Bool = { if SwiftVersion.current >= .fiveDotSix, arguments.count == 1, arguments[0].expressionKind == .argument { return true } return arguments.isEmpty }() // check if there's only one unnamed parameter that is a closure if argumentsCountIsExpected, let offset = dictionary.offset, let totalLength = dictionary.length, let nameOffset = dictionary.nameOffset, let nameLength = dictionary.nameLength, case let start = nameOffset + nameLength, case let length = totalLength + offset - start, case let byteRange = ByteRange(location: start, length: length), let range = file.stringView.byteRangeToNSRange(byteRange), let match = regex("\\s*\\(\\s*\\{").firstMatch(in: file.contents, options: [], range: range)?.range, match.location == range.location { return shouldTrigger() } return false } private func filterClosureArguments(_ arguments: [SourceKittenDictionary], file: SwiftLintFile) -> [SourceKittenDictionary] { return arguments.filter { argument in guard let bodyByteRange = argument.bodyByteRange, let range = file.stringView.byteRangeToNSRange(bodyByteRange), let match = regex("\\s*\\{").firstMatch(in: file.contents, options: [], range: range)?.range, match.location == range.location else { return false } return true } } private func isAlreadyTrailingClosure(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool { guard let byteRange = dictionary.byteRange, let text = file.stringView.substringWithByteRange(byteRange) else { return false } return !text.hasSuffix(")") } private func isAnonymousClosureCall(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool { guard let byteRange = dictionary.byteRange, let range = file.stringView.byteRangeToNSRange(byteRange) else { return false } let pattern = regex("\\)\\s*\\)\\z") return pattern.numberOfMatches(in: file.contents, range: range) > 0 } }
mit
4523c8bc260aa3ddca25e74b24615b98
38.671233
112
0.5827
5.062937
false
false
false
false
Samiabo/Weibo
Weibo/Weibo/Classes/Profile/ProfileViewController.swift
1
2976
// // ProfileViewController.swift // Weibo // // Created by han xuelong on 2016/12/27. // Copyright © 2016年 han xuelong. All rights reserved. // import UIKit class ProfileViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() visitorView.setupVisitorViewInfo(iconName: "visitordiscover_image_profile", title: "登录后,别人评论你的微博,给你发消息,都会在这里收到通知") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. 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 to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source 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 to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
0560af0b1f5615cb463947685a66d275
31.054945
136
0.666781
5.144621
false
false
false
false
jacobwhite/firefox-ios
Shared/Prefs.swift
1
6707
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation public struct PrefsKeys { public static let KeyLastRemoteTabSyncTime = "lastRemoteTabSyncTime" public static let KeyLastSyncFinishTime = "lastSyncFinishTime" public static let KeyDefaultHomePageURL = "KeyDefaultHomePageURL" public static let KeyNoImageModeStatus = "NoImageModeStatus" public static let KeyNightModeButtonIsInMenu = "NightModeButtonIsInMenuPrefKey" public static let KeyNightModeStatus = "NightModeStatus" public static let KeyMailToOption = "MailToOption" public static let HasFocusInstalled = "HasFocusInstalled" public static let HasPocketInstalled = "HasPocketInstalled" public static let IntroSeen = "IntroViewControllerSeen" //Activity Stream public static let KeyTopSitesCacheIsValid = "topSitesCacheIsValid" public static let KeyTopSitesCacheSize = "topSitesCacheSize" public static let KeyNewTab = "NewTabPrefKey" public static let ASPocketStoriesVisible = "ASPocketStoriesVisible" public static let ASRecentHighlightsVisible = "ASRecentHighlightsVisible" public static let ASBookmarkHighlightsVisible = "ASBookmarkHighlightsVisible" public static let ASLastInvalidation = "ASLastInvalidation" public static let KeyUseCustomSyncService = "useCustomSyncService" public static let KeyCustomSyncToken = "customSyncTokenServer" public static let KeyCustomSyncProfile = "customSyncProfileServer" public static let KeyCustomSyncOauth = "customSyncOauthServer" public static let KeyCustomSyncAuth = "customSyncAuthServer" public static let KeyCustomSyncWeb = "customSyncWebServer" public static let UseStageServer = "useStageSyncService" } public struct PrefsDefaults { public static let ChineseHomePageURL = "http://mobile.firefoxchina.cn/" public static let ChineseNewTabDefault = "HomePage" } public protocol Prefs { func getBranchPrefix() -> String func branch(_ branch: String) -> Prefs func setTimestamp(_ value: Timestamp, forKey defaultName: String) func setLong(_ value: UInt64, forKey defaultName: String) func setLong(_ value: Int64, forKey defaultName: String) func setInt(_ value: Int32, forKey defaultName: String) func setString(_ value: String, forKey defaultName: String) func setBool(_ value: Bool, forKey defaultName: String) func setObject(_ value: Any?, forKey defaultName: String) func stringForKey(_ defaultName: String) -> String? func objectForKey<T: Any>(_ defaultName: String) -> T? func boolForKey(_ defaultName: String) -> Bool? func intForKey(_ defaultName: String) -> Int32? func timestampForKey(_ defaultName: String) -> Timestamp? func longForKey(_ defaultName: String) -> Int64? func unsignedLongForKey(_ defaultName: String) -> UInt64? func stringArrayForKey(_ defaultName: String) -> [String]? func arrayForKey(_ defaultName: String) -> [Any]? func dictionaryForKey(_ defaultName: String) -> [String: Any]? func removeObjectForKey(_ defaultName: String) func clearAll() } open class MockProfilePrefs: Prefs { let prefix: String open func getBranchPrefix() -> String { return self.prefix } // Public for testing. open var things: NSMutableDictionary = NSMutableDictionary() public init(things: NSMutableDictionary, prefix: String) { self.things = things self.prefix = prefix } public init() { self.prefix = "" } open func branch(_ branch: String) -> Prefs { return MockProfilePrefs(things: self.things, prefix: self.prefix + branch + ".") } private func name(_ name: String) -> String { return self.prefix + name } open func setTimestamp(_ value: Timestamp, forKey defaultName: String) { self.setLong(value, forKey: defaultName) } open func setLong(_ value: UInt64, forKey defaultName: String) { setObject(NSNumber(value: value as UInt64), forKey: defaultName) } open func setLong(_ value: Int64, forKey defaultName: String) { setObject(NSNumber(value: value as Int64), forKey: defaultName) } open func setInt(_ value: Int32, forKey defaultName: String) { things[name(defaultName)] = NSNumber(value: value as Int32) } open func setString(_ value: String, forKey defaultName: String) { things[name(defaultName)] = value } open func setBool(_ value: Bool, forKey defaultName: String) { things[name(defaultName)] = value } open func setObject(_ value: Any?, forKey defaultName: String) { things[name(defaultName)] = value } open func stringForKey(_ defaultName: String) -> String? { return things[name(defaultName)] as? String } open func boolForKey(_ defaultName: String) -> Bool? { return things[name(defaultName)] as? Bool } open func objectForKey<T: Any>(_ defaultName: String) -> T? { return things[name(defaultName)] as? T } open func timestampForKey(_ defaultName: String) -> Timestamp? { return unsignedLongForKey(defaultName) } open func unsignedLongForKey(_ defaultName: String) -> UInt64? { return things[name(defaultName)] as? UInt64 } open func longForKey(_ defaultName: String) -> Int64? { return things[name(defaultName)] as? Int64 } open func intForKey(_ defaultName: String) -> Int32? { return things[name(defaultName)] as? Int32 } open func stringArrayForKey(_ defaultName: String) -> [String]? { if let arr = self.arrayForKey(defaultName) { if let arr = arr as? [String] { return arr } } return nil } open func arrayForKey(_ defaultName: String) -> [Any]? { let r: Any? = things.object(forKey: name(defaultName)) as Any? if r == nil { return nil } if let arr = r as? [Any] { return arr } return nil } open func dictionaryForKey(_ defaultName: String) -> [String: Any]? { return things.object(forKey: name(defaultName)) as? [String: Any] } open func removeObjectForKey(_ defaultName: String) { self.things.removeObject(forKey: name(defaultName)) } open func clearAll() { let dictionary = things as! [String: Any] let keysToDelete: [String] = dictionary.keys.filter { $0.hasPrefix(self.prefix) } things.removeObjects(forKeys: keysToDelete) } }
mpl-2.0
f5bf7b1cb0fdf5a73ba1f54051328e5e
35.650273
89
0.68272
4.562585
false
false
false
false
hardikdevios/HKKit
Pod/Classes/HKSubclass/HKTableView.swift
1
1345
//// //// HKTableView.swift //// HKKit //// //// Created by Hardik Shah on 24/05/17. //// Copyright © 2017 Hardik. All rights reserved. //// // //import UIKit //import DZNEmptyDataSet // //open class HKTableView: UITableView { // // public var onLoadMore:(()->())? // // override init(frame: CGRect, style: UITableView.Style) { // super.init(frame: frame, style: style) // setUp() // } // // required public init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // setUp() // // } // // public func setUp(){ // // self.keyboardDismissMode = .onDrag // self.rowHeight = UITableView.automaticDimension // self.estimatedRowHeight = 50 // setEmptyData() // // } // public func scrollViewDidScroll(_ scrollView: UIScrollView) { // // let offset = Int(scrollView.contentOffset.y) // let maxOffset = Int(scrollView.contentSize.height - scrollView.frame.size.height) // // if (maxOffset - offset) < 0 { // self.onLoadMore?() // } // } // // // //} // // //extension HKTableView: DZNEmptyDataSetSource,DZNEmptyDataSetDelegate { // // public func setEmptyData(){ // self.emptyDataSetSource = self // self.emptyDataSetDelegate = self // } // //}
mit
9bc1186344c119426f2661ebdbda8124
22.578947
91
0.563244
3.785915
false
false
false
false
firebase/quickstart-ios
swiftui/PasswordlessSwiftUI/PasswordlessSwiftUI/ContentView.swift
1
5501
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import SwiftUI import FirebaseAuth /// Main view where user can login in using Email Link Authentication. struct ContentView: View { @State private var email: String = "" @State private var isPresentingSheet = false /// This property will cause an alert view to display when it has a non-null value. @State private var alertItem: AlertItem? = nil var body: some View { NavigationView { VStack(alignment: .leading) { Text("Authenticate users with only their email, no password required!") .padding(.bottom, 60) CustomStyledTextField( text: $email, placeholder: "Email", symbolName: "person.circle.fill" ) CustomStyledButton(title: "Send Sign In Link", action: sendSignInLink) .disabled(email.isEmpty) Spacer() } .padding() .navigationBarTitle("Passwordless Login") } .onOpenURL { url in let link = url.absoluteString if Auth.auth().isSignIn(withEmailLink: link) { passwordlessSignIn(email: email, link: link) { result in switch result { case let .success(user): isPresentingSheet = user?.isEmailVerified ?? false case let .failure(error): isPresentingSheet = false alertItem = AlertItem( title: "An authentication error occurred.", message: error.localizedDescription ) } } } } .sheet(isPresented: $isPresentingSheet) { SuccessView(email: email) } .alert(item: $alertItem) { alert -> Alert in Alert( title: Text(alert.title), message: Text(alert.message) ) } } // MARK: - Firebase 🔥 private func sendSignInLink() { let actionCodeSettings = ActionCodeSettings() actionCodeSettings.url = URL(string: "https://passwordlessswiftui.page.link/demo_login") actionCodeSettings.handleCodeInApp = true actionCodeSettings.setIOSBundleID(Bundle.main.bundleIdentifier!) Auth.auth().sendSignInLink(toEmail: email, actionCodeSettings: actionCodeSettings) { error in if let error = error { alertItem = AlertItem( title: "The sign in link could not be sent.", message: error.localizedDescription ) } } } private func passwordlessSignIn(email: String, link: String, completion: @escaping (Result<User?, Error>) -> Void) { Auth.auth().signIn(withEmail: email, link: link) { result, error in if let error = error { print("ⓧ Authentication error: \(error.localizedDescription).") completion(.failure(error)) } else { print("✔ Authentication was successful.") completion(.success(result?.user)) } } } } /// Model object for an `Alert` view. struct AlertItem: Identifiable { var id = UUID() var title: String var message: String } /// A custom styled TextField with an SF symbol icon. struct CustomStyledTextField: View { @Binding var text: String let placeholder: String let symbolName: String var body: some View { HStack { Image(systemName: symbolName) .imageScale(.large) .padding(.leading) TextField(placeholder, text: $text) .padding(.vertical) .accentColor(.orange) .autocapitalization(.none) } .background( RoundedRectangle(cornerRadius: 16.0, style: .circular) .foregroundColor(Color(.secondarySystemFill)) ) } } /// A custom styled button with a custom title and action. struct CustomStyledButton: View { let title: String let action: () -> Void var body: some View { Button(action: action) { /// Embed in an HStack to display a wide button with centered text. HStack { Spacer() Text(title) .padding() .accentColor(.white) Spacer() } } .background(Color.orange) .cornerRadius(16.0) } } /// Displayed when a user successfuly logs in. struct SuccessView: View { let email: String var body: some View { /// The first view in this `ZStack` is a `Color` view that expands /// to set the background color of the `SucessView`. ZStack { Color.orange .edgesIgnoringSafeArea(.all) VStack(alignment: .leading) { Group { Text("Welcome") .font(.largeTitle) .fontWeight(.semibold) Text(email.lowercased()) .font(.title3) .fontWeight(.bold) .multilineTextAlignment(.leading) } .padding(.leading) Image(systemName: "checkmark.circle") .resizable() .aspectRatio(contentMode: .fit) .scaleEffect(0.5) } .foregroundColor(.white) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
apache-2.0
8b2fc8125a9bad3fa2fb06cc6950c556
27.319588
97
0.628322
4.434221
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/expression/equality_operators/three.swift
2
930
// three.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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- import fooey private var counter = 0 func == (lhs : Fooey, rhs : Fooey) -> Bool { Fooey.BumpCounter(3) return lhs.m_var == rhs.m_var + 1 } extension Fooey { class func CompareEm3(_ lhs : Fooey, _ rhs : Fooey) -> Bool { return lhs == rhs } } var lhs = Fooey() var rhs = Fooey() let result1 = Fooey.CompareEm1(lhs, rhs) Fooey.ResetCounter() let result2 = Fooey.CompareEm2(lhs, rhs) Fooey.ResetCounter() let result3 = Fooey.CompareEm3(lhs, rhs)
apache-2.0
626010771023d9eb5fc51b47a1083077
24.135135
80
0.624731
3.604651
false
false
false
false
mozilla-mobile/firefox-ios
Client/Application/AppLaunchUtil.swift
2
11551
// 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 Account import Glean // A convinient mapping, `Profile.swift` can't depend // on `PlacesMigrationConfiguration` directly since // the FML is only usable from `Client` at the moment extension PlacesMigrationConfiguration { func into() -> HistoryMigrationConfiguration { switch self { case .disabled: return .disabled case .dryRun: return .dryRun case .real: return .real } } } extension PlacesApiConfiguration { func into() -> HistoryAPIConfiguration { switch self { case .old: return .old case .new: return .new } } } class AppLaunchUtil { private var log: RollingFileLogger private var adjustHelper: AdjustHelper private var profile: Profile init(log: RollingFileLogger = Logger.browserLogger, profile: Profile) { self.log = log self.profile = profile self.adjustHelper = AdjustHelper(profile: profile) } func setUpPreLaunchDependencies() { // If the 'Save logs to Files app on next launch' toggle // is turned on in the Settings app, copy over old logs. if DebugSettingsBundleOptions.saveLogsToDocuments { Logger.copyPreviousLogsToDocuments() } // Now roll logs. DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { Logger.syncLogger.deleteOldLogsDownToSizeLimit() Logger.browserLogger.deleteOldLogsDownToSizeLimit() } TelemetryWrapper.shared.setup(profile: profile) // Need to get "settings.sendUsageData" this way so that Sentry can be initialized // before getting the Profile. let sendUsageData = NSUserDefaultsPrefs(prefix: "profile").boolForKey(AppConstants.PrefSendUsageData) ?? true SentryIntegration.shared.setup(sendUsageData: sendUsageData) setUserAgent() KeyboardHelper.defaultHelper.startObserving() DynamicFontHelper.defaultHelper.startObserving() MenuHelper.defaultHelper.setItems() let logDate = Date() // Create a new sync log file on cold app launch. Note that this doesn't roll old logs. Logger.syncLogger.newLogWithDate(logDate) Logger.browserLogger.newLogWithDate(logDate) // Initialize the feature flag subsystem. // Among other things, it toggles on and off Nimbus, Contile, Adjust. // i.e. this must be run before initializing those systems. FeatureFlagsManager.shared.initializeDeveloperFeatures(with: profile) FeatureFlagUserPrefsMigrationUtility(with: profile).attemptMigration() // Migrate wallpaper folder LegacyWallpaperMigrationUtility(with: profile).attemptMigration() WallpaperManager().migrateLegacyAssets() // Start initializing the Nimbus SDK. This should be done after Glean // has been started. initializeExperiments() NotificationCenter.default.addObserver(forName: .FSReadingListAddReadingListItem, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, let url = userInfo["URL"] as? URL { let title = (userInfo["Title"] as? String) ?? "" self.profile.readingList.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.current.name) } } SystemUtils.onFirstRun() RustFirefoxAccounts.startup(prefs: profile.prefs).uponQueue(.main) { _ in print("RustFirefoxAccounts started") } } func setUpPostLaunchDependencies() { let persistedCurrentVersion = InstallType.persistedCurrentVersion() let introScreen = profile.prefs.intForKey(PrefsKeys.IntroSeen) // upgrade install - Intro screen shown & persisted current version does not match if introScreen != nil && persistedCurrentVersion != AppInfo.appVersion { InstallType.set(type: .upgrade) InstallType.updateCurrentVersion(version: AppInfo.appVersion) } // We need to check if the app is a clean install to use for // preventing the What's New URL from appearing. if introScreen == nil { // fresh install - Intro screen not yet shown InstallType.set(type: .fresh) InstallType.updateCurrentVersion(version: AppInfo.appVersion) // Profile setup profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } else if profile.prefs.boolForKey(PrefsKeys.KeySecondRun) == nil { profile.prefs.setBool(true, forKey: PrefsKeys.KeySecondRun) } updateSessionCount() adjustHelper.setupAdjust() } private func setUserAgent() { let firefoxUA = UserAgent.getUserAgent() // Record the user agent for use by search suggestion clients. SearchViewController.userAgent = firefoxUA // Some sites will only serve HTML that points to .ico files. // The FaviconFetcher is explicitly for getting high-res icons, so use the desktop user agent. FaviconFetcher.userAgent = UserAgent.desktopUserAgent() } private func initializeExperiments() { // We initialize the generated FxNimbus singleton very early on with a lazily // constructed singleton. FxNimbus.shared.initialize(with: { Experiments.shared }) // We also make sure that any cache invalidation happens after each applyPendingExperiments(). NotificationCenter.default.addObserver(forName: .nimbusExperimentsApplied, object: nil, queue: nil) { _ in FxNimbus.shared.invalidateCachedValues() self.runEarlyExperimentDependencies() } let defaults = UserDefaults.standard let nimbusFirstRun = "NimbusFirstRun" let isFirstRun = defaults.object(forKey: nimbusFirstRun) == nil defaults.set(false, forKey: nimbusFirstRun) Experiments.customTargetingAttributes = ["isFirstRun": "\(isFirstRun)"] let initialExperiments = Bundle.main.url(forResource: "initial_experiments", withExtension: "json") let serverURL = Experiments.remoteSettingsURL let savedOptions = Experiments.getLocalExperimentData() let options: Experiments.InitializationOptions switch (savedOptions, isFirstRun, initialExperiments, serverURL) { // QA testing case: experiments come from the Experiments setting screen. case (let payload, _, _, _) where payload != nil: log.info("Nimbus: Loading from experiments provided by settings screen") options = Experiments.InitializationOptions.testing(localPayload: payload!) // First startup case: case (nil, true, let file, _) where file != nil: log.info("Nimbus: Loading from experiments from bundle, at first startup") options = Experiments.InitializationOptions.preload(fileUrl: file!) // Local development case: load from the bundled initial_experiments.json case (_, _, let file, let url) where file != nil && url == nil: log.info("Nimbus: Loading from experiments from bundle, with no URL") options = Experiments.InitializationOptions.preload(fileUrl: file!) case (_, _, _, let url) where url != nil: log.info("Nimbus: server exists") options = Experiments.InitializationOptions.normal default: log.info("Nimbus: server does not exist") options = Experiments.InitializationOptions.normal } Experiments.intialize(options) } private func updateSessionCount() { var sessionCount: Int32 = 0 // Get the session count from preferences if let currentSessionCount = profile.prefs.intForKey(PrefsKeys.SessionCount) { sessionCount = currentSessionCount } // increase session count value profile.prefs.setInt(sessionCount + 1, forKey: PrefsKeys.SessionCount) } private func runEarlyExperimentDependencies() { runAppServicesHistoryMigration() } // MARK: - Application Services History Migration private func runAppServicesHistoryMigration() { let placesHistory = FxNimbus.shared.features.placesHistory.value() FxNimbus.shared.features.placesHistory.recordExposure() guard placesHistory.migration != .disabled else { log.info("Migration disabled, won't run migration") return } let browserProfile = self.profile as? BrowserProfile let migrationRanKey = "PlacesHistoryMigrationRan" + placesHistory.migration.rawValue let migrationRan = UserDefaults.standard.bool(forKey: migrationRanKey) UserDefaults.standard.setValue(true, forKey: migrationRanKey) if !migrationRan { if placesHistory.api == .new { browserProfile?.historyApiConfiguration = .new // We set a user default so users with new configuration never go back UserDefaults.standard.setValue(true, forKey: PrefsKeys.NewPlacesAPIDefaultKey) } log.info("Migrating Application services history") let id = GleanMetrics.PlacesHistoryMigration.duration.start() // We mark that the migration started // this will help us identify how often the migration starts, but never ends // additionally, we have a seperate metric for error rates GleanMetrics.PlacesHistoryMigration.migrationEndedRate.addToNumerator(1) GleanMetrics.PlacesHistoryMigration.migrationErrorRate.addToNumerator(1) browserProfile?.migrateHistoryToPlaces( migrationConfig: placesHistory.migration.into(), callback: { result in self.log.info("Successful Migration took \(result.totalDuration / 1000) seconds") // We record various success metrics here GleanMetrics.PlacesHistoryMigration.duration.stopAndAccumulate(id) GleanMetrics.PlacesHistoryMigration.numMigrated.set(Int64(result.numSucceeded)) self.log.info("Migrated \(result.numSucceeded) entries") GleanMetrics.PlacesHistoryMigration.numToMigrate.set(Int64(result.numTotal)) GleanMetrics.PlacesHistoryMigration.migrationEndedRate.addToDenominator(1) }, errCallback: { err in let errDescription = err?.localizedDescription ?? "Unknown error during History migration" self.log.error(errDescription) GleanMetrics.PlacesHistoryMigration.duration.cancel(id) GleanMetrics.PlacesHistoryMigration.migrationEndedRate.addToDenominator(1) GleanMetrics.PlacesHistoryMigration.migrationErrorRate.addToDenominator(1) // We also send the error to sentry SentryIntegration.shared.sendWithStacktrace(message: "Error executing application services history migration", tag: SentryTag.rustPlaces, severity: .error, description: errDescription) }) } else { log.info("History Migration skipped, already migrated") } } }
mpl-2.0
8490aedb20c25de4d6097f576a019aaf
43.256705
200
0.671284
5.131497
false
false
false
false
Sergtsaeb/Tinqer
Tinqer/Controller/CategoryView.swift
1
5363
// // CategoryView.swift // Tinqer // // Created by JD Leonard on 7/31/17. // Copyright © 2017 Sergtsaeb. All rights reserved. // import UIKit class CategoryView: UIView, UITableViewDelegate { //, UITableViewDataSource { @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var categoryList: UITableView! var composeVC:ComposeViewController! var keyboardShowing:Bool! // PRAGMA MARK: ANIMATED VARIABLES var animator:UIDynamicAnimator! var container:UICollisionBehavior! var snap:UISnapBehavior? var dynamicItem:UIDynamicItemBehavior! var gravity:UIGravityBehavior! var panGestureRecognizer:UIPanGestureRecognizer! // PRAGMA MARK: SETUP func setup () { panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(CategoryView.handlePan(_:))) panGestureRecognizer.cancelsTouchesInView = false self.addGestureRecognizer(panGestureRecognizer) animator = UIDynamicAnimator(referenceView: self.superview!) dynamicItem = UIDynamicItemBehavior(items: [self]) dynamicItem.allowsRotation = false dynamicItem.elasticity = 0 gravity = UIGravityBehavior(items: [self]) gravity.gravityDirection = CGVector(dx: 0, dy: -1) container = UICollisionBehavior(items: [self]) configureContainer() animator.addBehavior(gravity) animator.addBehavior(dynamicItem) animator.addBehavior(container) // animations added. now load on tableview and label viewLoaded() } func viewLoaded() { self.backgroundColor = UIColor.red self.categoryLabel.text = "CATEGORY" labelSetUp(for: self.categoryLabel, color: UIColor.blue) keyboardShowing = true categoryList.delegate = self // categoryList.dataSource = self } func labelSetUp(for label:UILabel, color:UIColor) { label.backgroundColor = color } func configureContainer (){ let boundaryWidth = UIScreen.main.bounds.size.width let boundaryHeight = UIScreen.main.bounds.size.height container.addBoundary(withIdentifier: "upper" as NSCopying, from: CGPoint(x: 0, y: -boundaryHeight * 11/12), to: CGPoint(x: boundaryWidth, y: -boundaryHeight * 11/12)) container.addBoundary(withIdentifier: "lower" as NSCopying, from: CGPoint(x: 0, y: boundaryHeight), to: CGPoint(x: boundaryWidth, y: boundaryHeight)) } // PRAGMA MARK: TABLEVIEW /* func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("asking for numbers") } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return 1 } */ // PRAGMA MARK: HANDLING func handlePan (_ pan:UIPanGestureRecognizer){ let velocity = pan.velocity(in: self.superview).y var movement = self.frame movement.origin.x = 0 movement.origin.y = movement.origin.y + (velocity * 0.05) if pan.state == .ended { panGestureEnded() }else if pan.state == .began { snapToBottom() }else{ if var snap = snap { animator.removeBehavior(snap) snap = UISnapBehavior(item: self, snapTo: CGPoint(x: movement.midX, y: movement.midY)) animator.addBehavior(snap) } } } func panGestureEnded () { let velocity = dynamicItem.linearVelocity(for: self) if fabsf(Float(velocity.y)) > 250 { if velocity.y < 0 { snapToTop() }else{ snapToBottom() } }else{ if let superViewHeigt = self.superview?.bounds.size.height { if self.frame.origin.y > superViewHeigt / 2 { snapToBottom() }else{ snapToTop() } } } // not sure if this is helping or not guard let snap = snap else { return } animator.removeBehavior(snap) } // maybe using BOOL, make into just one notifcation center function called with parameter of notif func snapToBottom() { gravity.gravityDirection = CGVector(dx: 0, dy: 2.5) if keyboardShowing == true { let myNotificationKey = "byeByeKeyboard" NotificationCenter.default.post( name: Notification.Name( rawValue: myNotificationKey), object: self) keyboardShowing = false } } func snapToTop(){ gravity.gravityDirection = CGVector(dx: 0, dy: -2.5) if keyboardShowing == false { let myNotificationKey = "helloKeyboard" NotificationCenter.default.post( name: Notification.Name( rawValue: myNotificationKey), object: self) keyboardShowing = true } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! // self.tintColor = UIColor.clear } }
mit
cf46f54b90024655b1fe46a2d97ae67f
29.123596
175
0.588959
5.053723
false
false
false
false
pmtao/SwiftUtilityFramework
SwiftUtilityFramework/Foundation/Dispatch/DispatchObject+Extension.swift
1
2626
// // DispatchObject+Extension.swift // SwiftUtilityFramework // // Created by 阿涛 on 18-6-28. // Copyright © 2019年 SinkingSoul. All rights reserved. // import Foundation extension DispatchObject { /// 延迟执行闭包 /// /// - Parameters: /// - time: 几秒后执行 /// - block: 待执行的闭包 public static func dispatch_later(_ time: TimeInterval, block: @escaping ()->()) { let t = DispatchTime.now() + time DispatchQueue.main.asyncAfter(deadline: t, execute: block) } /// 可以对原任务进行替换的闭包,并支持指定新延迟时间。 /// (新的延迟时间与原有延迟时间都从相同的时间起点计算) /// /// - Parameters: /// - newDelayTime: 新任务执行时的延迟时间 /// - anotherTask: 待替换的新任务 public typealias ExchangableTask = ( _ newDelayTime: TimeInterval?, _ anotherTask:@escaping (() -> ()) ) -> Void /// 延迟执行一个任务,并支持在实际执行前替换为新的任务,并设定新的延迟时间。 /// /// - Parameters: /// - time: 延迟时间 /// - yourTask: 要执行的任务 /// - Returns: 可替换原任务的闭包 public static func delay(_ time: TimeInterval, yourTask: @escaping ()->()) -> ExchangableTask { var exchangingTask: (() -> ())? // 备用替代任务 var newDelayTime: TimeInterval? // 新的延迟时间 let finalClosure = { () -> Void in if exchangingTask == nil { DispatchQueue.main.async(execute: yourTask) } else { if newDelayTime == nil { DispatchQueue.main.async { print("任务已更改,现在是:\(Date().timeIntervalSince1970 * 1000) 毫秒") exchangingTask!() } } print("原任务取消了,现在是:\(Date().timeIntervalSince1970 * 1000) 毫秒") } } dispatch_later(time) { finalClosure() } let exchangableTask: ExchangableTask = { delayTime, anotherTask in exchangingTask = anotherTask newDelayTime = delayTime if delayTime != nil { self.dispatch_later(delayTime!) { anotherTask() print("任务已更改,现在是:\(Date().timeIntervalSince1970 * 1000) 毫秒") } } } return exchangableTask } }
mit
298ee942c264b44cb82c9559ef7dc7ba
28.077922
99
0.518982
4.138632
false
false
false
false
caicai0/ios_demo
load/Carthage/Checkouts/Alamofire/Tests/ParameterEncodingTests.swift
18
27850
// // ParameterEncodingTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation import XCTest class ParameterEncodingTestCase: BaseTestCase { let urlRequest = URLRequest(url: URL(string: "https://example.com/")!) } // MARK: - class URLParameterEncodingTestCase: ParameterEncodingTestCase { // MARK: Properties let encoding = URLEncoding.default // MARK: Tests - Parameter Types func testURLParameterEncodeNilParameters() { do { // Given, When let urlRequest = try encoding.encode(self.urlRequest, with: nil) // Then XCTAssertNil(urlRequest.url?.query) } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeEmptyDictionaryParameter() { do { // Given let parameters: [String: Any] = [:] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertNil(urlRequest.url?.query) } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeOneStringKeyStringValueParameter() { do { // Given let parameters = ["foo": "bar"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo=bar") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeOneStringKeyStringValueParameterAppendedToQuery() { do { // Given var mutableURLRequest = self.urlRequest var urlComponents = URLComponents(url: mutableURLRequest.url!, resolvingAgainstBaseURL: false)! urlComponents.query = "baz=qux" mutableURLRequest.url = urlComponents.url let parameters = ["foo": "bar"] // When let urlRequest = try encoding.encode(mutableURLRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "baz=qux&foo=bar") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeTwoStringKeyStringValueParameters() { do { // Given let parameters = ["foo": "bar", "baz": "qux"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "baz=qux&foo=bar") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyNSNumberIntegerValueParameter() { do { // Given let parameters = ["foo": NSNumber(value: 25)] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo=25") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyNSNumberBoolValueParameter() { do { // Given let parameters = ["foo": NSNumber(value: false)] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo=0") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyIntegerValueParameter() { do { // Given let parameters = ["foo": 1] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo=1") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyDoubleValueParameter() { do { // Given let parameters = ["foo": 1.1] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo=1.1") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyBoolValueParameter() { do { // Given let parameters = ["foo": true] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo=1") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyArrayValueParameter() { do { // Given let parameters = ["foo": ["a", 1, true]] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo%5B%5D=a&foo%5B%5D=1&foo%5B%5D=1") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyDictionaryValueParameter() { do { // Given let parameters = ["foo": ["bar": 1]] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo%5Bbar%5D=1") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyNestedDictionaryValueParameter() { do { // Given let parameters = ["foo": ["bar": ["baz": 1]]] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo%5Bbar%5D%5Bbaz%5D=1") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyNestedDictionaryArrayValueParameter() { do { // Given let parameters = ["foo": ["bar": ["baz": ["a", 1, true]]]] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then let expectedQuery = "foo%5Bbar%5D%5Bbaz%5D%5B%5D=a&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1" XCTAssertEqual(urlRequest.url?.query, expectedQuery) } catch { XCTFail("Test encountered unexpected error: \(error)") } } // MARK: Tests - All Reserved / Unreserved / Illegal Characters According to RFC 3986 func testThatReservedCharactersArePercentEscapedMinusQuestionMarkAndForwardSlash() { do { // Given let generalDelimiters = ":#[]@" let subDelimiters = "!$&'()*+,;=" let parameters = ["reserved": "\(generalDelimiters)\(subDelimiters)"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then let expectedQuery = "reserved=%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D" XCTAssertEqual(urlRequest.url?.query, expectedQuery) } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testThatReservedCharactersQuestionMarkAndForwardSlashAreNotPercentEscaped() { do { // Given let parameters = ["reserved": "?/"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "reserved=?/") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testThatUnreservedNumericCharactersAreNotPercentEscaped() { do { // Given let parameters = ["numbers": "0123456789"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "numbers=0123456789") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testThatUnreservedLowercaseCharactersAreNotPercentEscaped() { do { // Given let parameters = ["lowercase": "abcdefghijklmnopqrstuvwxyz"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "lowercase=abcdefghijklmnopqrstuvwxyz") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testThatUnreservedUppercaseCharactersAreNotPercentEscaped() { do { // Given let parameters = ["uppercase": "ABCDEFGHIJKLMNOPQRSTUVWXYZ"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "uppercase=ABCDEFGHIJKLMNOPQRSTUVWXYZ") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testThatIllegalASCIICharactersArePercentEscaped() { do { // Given let parameters = ["illegal": " \"#%<>[]\\^`{}|"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then let expectedQuery = "illegal=%20%22%23%25%3C%3E%5B%5D%5C%5E%60%7B%7D%7C" XCTAssertEqual(urlRequest.url?.query, expectedQuery) } catch { XCTFail("Test encountered unexpected error: \(error)") } } // MARK: Tests - Special Character Queries func testURLParameterEncodeStringWithAmpersandKeyStringWithAmpersandValueParameter() { do { // Given let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo%26bar=baz%26qux&foobar=bazqux") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringWithQuestionMarkKeyStringWithQuestionMarkValueParameter() { do { // Given let parameters = ["?foo?": "?bar?"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "?foo?=?bar?") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringWithSlashKeyStringWithQuestionMarkValueParameter() { do { // Given let parameters = ["foo": "/bar/baz/qux"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo=/bar/baz/qux") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringWithSpaceKeyStringWithSpaceValueParameter() { do { // Given let parameters = [" foo ": " bar "] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "%20foo%20=%20bar%20") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringWithPlusKeyStringWithPlusValueParameter() { do { // Given let parameters = ["+foo+": "+bar+"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "%2Bfoo%2B=%2Bbar%2B") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyPercentEncodedStringValueParameter() { do { // Given let parameters = ["percent": "%25"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "percent=%2525") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringKeyNonLatinStringValueParameter() { do { // Given let parameters = [ "french": "français", "japanese": "日本語", "arabic": "العربية", "emoji": "😃" ] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then let expectedParameterValues = [ "arabic=%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9", "emoji=%F0%9F%98%83", "french=fran%C3%A7ais", "japanese=%E6%97%A5%E6%9C%AC%E8%AA%9E" ] let expectedQuery = expectedParameterValues.joined(separator: "&") XCTAssertEqual(urlRequest.url?.query, expectedQuery) } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringForRequestWithPrecomposedQuery() { do { // Given let url = URL(string: "https://example.com/movies?hd=[1]")! let parameters = ["page": "0"] // When let urlRequest = try encoding.encode(URLRequest(url: url), with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "hd=%5B1%5D&page=0") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringWithPlusKeyStringWithPlusValueParameterForRequestWithPrecomposedQuery() { do { // Given let url = URL(string: "https://example.com/movie?hd=[1]")! let parameters = ["+foo+": "+bar+"] // When let urlRequest = try encoding.encode(URLRequest(url: url), with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "hd=%5B1%5D&%2Bfoo%2B=%2Bbar%2B") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testURLParameterEncodeStringWithThousandsOfChineseCharacters() { do { // Given let repeatedCount = 2_000 let url = URL(string: "https://example.com/movies")! let parameters = ["chinese": String(repeating: "一二三四五六七八九十", count: repeatedCount)] // When let urlRequest = try encoding.encode(URLRequest(url: url), with: parameters) // Then var expected = "chinese=" for _ in 0..<repeatedCount { expected += "%E4%B8%80%E4%BA%8C%E4%B8%89%E5%9B%9B%E4%BA%94%E5%85%AD%E4%B8%83%E5%85%AB%E4%B9%9D%E5%8D%81" } XCTAssertEqual(urlRequest.url?.query, expected) } catch { XCTFail("Test encountered unexpected error: \(error)") } } // MARK: Tests - Varying HTTP Methods func testThatURLParameterEncodingEncodesGETParametersInURL() { do { // Given var mutableURLRequest = self.urlRequest mutableURLRequest.httpMethod = HTTPMethod.get.rawValue let parameters = ["foo": 1, "bar": 2] // When let urlRequest = try encoding.encode(mutableURLRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "bar=2&foo=1") XCTAssertNil(urlRequest.value(forHTTPHeaderField: "Content-Type"), "Content-Type should be nil") XCTAssertNil(urlRequest.httpBody, "HTTPBody should be nil") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testThatURLParameterEncodingEncodesPOSTParametersInHTTPBody() { do { // Given var mutableURLRequest = self.urlRequest mutableURLRequest.httpMethod = HTTPMethod.post.rawValue let parameters = ["foo": 1, "bar": 2] // When let urlRequest = try encoding.encode(mutableURLRequest, with: parameters) // Then XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/x-www-form-urlencoded; charset=utf-8") XCTAssertNotNil(urlRequest.httpBody, "HTTPBody should not be nil") if let httpBody = urlRequest.httpBody, let decodedHTTPBody = String(data: httpBody, encoding: .utf8) { XCTAssertEqual(decodedHTTPBody, "bar=2&foo=1") } else { XCTFail("decoded http body should not be nil") } } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testThatURLEncodedInURLParameterEncodingEncodesPOSTParametersInURL() { do { // Given var mutableURLRequest = self.urlRequest mutableURLRequest.httpMethod = HTTPMethod.post.rawValue let parameters = ["foo": 1, "bar": 2] // When let urlRequest = try URLEncoding.queryString.encode(mutableURLRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "bar=2&foo=1") XCTAssertNil(urlRequest.value(forHTTPHeaderField: "Content-Type")) XCTAssertNil(urlRequest.httpBody, "HTTPBody should be nil") } catch { XCTFail("Test encountered unexpected error: \(error)") } } } // MARK: - class JSONParameterEncodingTestCase: ParameterEncodingTestCase { // MARK: Properties let encoding = JSONEncoding.default // MARK: Tests func testJSONParameterEncodeNilParameters() { do { // Given, When let URLRequest = try encoding.encode(self.urlRequest, with: nil) // Then XCTAssertNil(URLRequest.url?.query, "query should be nil") XCTAssertNil(URLRequest.value(forHTTPHeaderField: "Content-Type")) XCTAssertNil(URLRequest.httpBody, "HTTPBody should be nil") } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testJSONParameterEncodeComplexParameters() { do { // Given let parameters: [String: Any] = [ "foo": "bar", "baz": ["a", 1, true], "qux": [ "a": 1, "b": [2, 2], "c": [3, 3, 3] ] ] // When let URLRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertNil(URLRequest.url?.query) XCTAssertNotNil(URLRequest.value(forHTTPHeaderField: "Content-Type")) XCTAssertEqual(URLRequest.value(forHTTPHeaderField: "Content-Type"), "application/json") XCTAssertNotNil(URLRequest.httpBody) if let httpBody = URLRequest.httpBody { do { let json = try JSONSerialization.jsonObject(with: httpBody, options: .allowFragments) if let json = json as? NSObject { XCTAssertEqual(json, parameters as NSObject) } else { XCTFail("json should be an NSObject") } } catch { XCTFail("json should not be nil") } } } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testJSONParameterEncodeArray() { do { // Given let array: [String] = ["foo", "bar", "baz"] // When let URLRequest = try encoding.encode(self.urlRequest, withJSONObject: array) // Then XCTAssertNil(URLRequest.url?.query) XCTAssertNotNil(URLRequest.value(forHTTPHeaderField: "Content-Type")) XCTAssertEqual(URLRequest.value(forHTTPHeaderField: "Content-Type"), "application/json") XCTAssertNotNil(URLRequest.httpBody) if let httpBody = URLRequest.httpBody { do { let json = try JSONSerialization.jsonObject(with: httpBody, options: .allowFragments) if let json = json as? NSObject { XCTAssertEqual(json, array as NSObject) } else { XCTFail("json should be an NSObject") } } catch { XCTFail("json should not be nil") } } } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testJSONParameterEncodeParametersRetainsCustomContentType() { do { // Given var mutableURLRequest = URLRequest(url: URL(string: "https://example.com/")!) mutableURLRequest.setValue("application/custom-json-type+json", forHTTPHeaderField: "Content-Type") let parameters = ["foo": "bar"] // When let urlRequest = try encoding.encode(mutableURLRequest, with: parameters) // Then XCTAssertNil(urlRequest.url?.query) XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/custom-json-type+json") } catch { XCTFail("Test encountered unexpected error: \(error)") } } } // MARK: - class PropertyListParameterEncodingTestCase: ParameterEncodingTestCase { // MARK: Properties let encoding = PropertyListEncoding.default // MARK: Tests func testPropertyListParameterEncodeNilParameters() { do { // Given, When let urlRequest = try encoding.encode(self.urlRequest, with: nil) // Then XCTAssertNil(urlRequest.url?.query) XCTAssertNil(urlRequest.value(forHTTPHeaderField: "Content-Type")) XCTAssertNil(urlRequest.httpBody) } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testPropertyListParameterEncodeComplexParameters() { do { // Given let parameters: [String: Any] = [ "foo": "bar", "baz": ["a", 1, true], "qux": [ "a": 1, "b": [2, 2], "c": [3, 3, 3] ] ] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertNil(urlRequest.url?.query) XCTAssertNotNil(urlRequest.value(forHTTPHeaderField: "Content-Type")) XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/x-plist") XCTAssertNotNil(urlRequest.httpBody) if let httpBody = urlRequest.httpBody { do { let plist = try PropertyListSerialization.propertyList(from: httpBody, options: [], format: nil) if let plist = plist as? NSObject { XCTAssertEqual(plist, parameters as NSObject) } else { XCTFail("plist should be an NSObject") } } catch { XCTFail("plist should not be nil") } } } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testPropertyListParameterEncodeDateAndDataParameters() { do { // Given let date: Date = Date() let data: Data = "data".data(using: .utf8, allowLossyConversion: false)! let parameters: [String: Any] = [ "date": date, "data": data ] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertNil(urlRequest.url?.query) XCTAssertNotNil(urlRequest.value(forHTTPHeaderField: "Content-Type")) XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/x-plist") XCTAssertNotNil(urlRequest.httpBody) if let httpBody = urlRequest.httpBody { do { let plist = try PropertyListSerialization.propertyList(from: httpBody, options: [], format: nil) as AnyObject XCTAssertTrue(plist.value(forKey: "date") is Date) XCTAssertTrue(plist.value(forKey: "data") is Data) } catch { XCTFail("plist should not be nil") } } else { XCTFail("HTTPBody should not be nil") } } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testPropertyListParameterEncodeParametersRetainsCustomContentType() { do { // Given var mutableURLRequest = URLRequest(url: URL(string: "https://example.com/")!) mutableURLRequest.setValue("application/custom-plist-type+plist", forHTTPHeaderField: "Content-Type") let parameters = ["foo": "bar"] // When let urlRequest = try encoding.encode(mutableURLRequest, with: parameters) // Then XCTAssertNil(urlRequest.url?.query) XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/custom-plist-type+plist") } catch { XCTFail("Test encountered unexpected error: \(error)") } } }
mit
5d2a5aefbab08798e48d957c7b334394
32.671913
132
0.564736
5.021303
false
true
false
false
jdkelley/Udacity-VirtualTourist
VirtualTourist/VirtualTourist/MKMapView+Helpers.swift
1
1333
// // MKMapView+Helpers.swift // VirtualTourist // // Created by Joshua Kelley on 10/25/16. // Copyright © 2016 Joshua Kelley. All rights reserved. // import Foundation import MapKit extension MKMapView { func setZoomFor(annotation: MKPointAnnotation, widthInMeters: CLLocationDistance = 4500.0, heightInMeters: CLLocationDistance = 1500.0) { let viewRegion = MKCoordinateRegionMakeWithDistance(annotation.coordinate, heightInMeters, widthInMeters) let adjustedRegion = self.regionThatFits(viewRegion) self.setRegion(adjustedRegion, animated: true) } func setSavedZoomFor(latitude: CLLocationDegrees, longitude: CLLocationDegrees, widthInMeters: CLLocationDistance, heightInMeters: CLLocationDistance) { let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let viewRegion = MKCoordinateRegionMake(coordinate, MKCoordinateSpan(latitudeDelta: heightInMeters, longitudeDelta: widthInMeters)) self.setRegion(viewRegion, animated: true) } func getZoomLevel() -> (lonWidth: CLLocationDistance, latHeight: CLLocationDistance) { let heightInMeters = self.region.span.latitudeDelta let widthInMeters = self.region.span.longitudeDelta return (widthInMeters, heightInMeters) } }
mit
d8164f7aa98685a2b9587a6f643412aa
39.363636
156
0.74024
4.988764
false
false
false
false
wanliming11/MurlocAlgorithms
Last/LeetCode/String/14._Longest_Common_Prefix/14. Longest Common Prefix/main.swift
1
1486
// // main.swift // 14. Longest Common Prefix // // Created by FlyingPuPu on 17/02/2017. // Copyright (c) 2017 FPP. All rights reserved. // /* Write a function to find the longest common prefix string amongst an array of strings. 思想:拿第一个 str 作为标准,后面的字符串依次做比对。 复杂度:时间复杂度 O(nm), 空间复杂度 O(m), m 是第一个字符串的长度。 这题的关键在于,不断缩减比对的长度,例如下一个比对的长度小于当前,则最小长度就变成了下一个的长度, 如果同下一个比对的过程中出现不匹配,则最小长度又变成了不匹配长度位置的上一位。 */ import Foundation func longestCommonPrefix(_ strs: [String]) -> String { guard strs.count > 0 else { return "" } var compareArray = [Character](strs[0].characters) for s in strs { let currentArray = [Character](s.characters) //因为始终共有长度是最小长度,所以每次都用最小长度去作为下一次比较的基础 if compareArray.count > currentArray.count { compareArray = Array(compareArray[0 ..< currentArray.count]) } for i in 0..<compareArray.count { if currentArray[i] != compareArray[i] { compareArray = Array(compareArray[0 ..< i]) break } } } return String(compareArray) } print(longestCommonPrefix(["abc", "ab", "ab", "abc"]))
mit
650f9ddb009b246692e37cc54a9f0258
24.977273
86
0.635727
3.163435
false
false
false
false
doronkatz/firefox-ios
Shared/SentryIntegration.swift
1
2290
/* 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 Sentry public class SentryIntegration { public static let shared = SentryIntegration() public var crashedLastLaunch: Bool { return Client.shared?.crashedLastLaunch() ?? false } private let SentryDSNKey = "SentryDSN" private var enabled = false public func setup(sendUsageData: Bool) { assert(!enabled, "SentryIntegration.setup() should only be called once") if !sendUsageData { Logger.browserLogger.error("Not enabling Sentry; Not enabled by user choice") return } guard let dsn = Bundle.main.object(forInfoDictionaryKey: SentryDSNKey) as? String, !dsn.isEmpty else { Logger.browserLogger.error("Not enabling Sentry; Not configured in Info.plist") return } Logger.browserLogger.error("Enabling Sentry crash handler") do { Client.shared = try Client(dsn: dsn) try Client.shared?.startCrashHandler() enabled = true } catch let error { Logger.browserLogger.error("Failed to initialize Sentry: \(error)") } } public func crash() { Client.shared?.crash() } public func send(message: String, tag: String = "general", severity: SentrySeverity = .info, completion: SentryRequestFinished? = nil) { if !enabled { if completion != nil { completion!(nil) } return } let event = Event(level: severity) event.message = message event.tags = ["event": tag] Client.shared?.send(event: event, completion: completion) } public func sendSync(message: String, tag: String = "general", severity: SentrySeverity = .info) { if !enabled { return } let dispatchGroup = DispatchGroup() dispatchGroup.enter() send(message: message, tag: tag, severity: severity, completion: { (error) in dispatchGroup.leave() }) dispatchGroup.wait() } }
mpl-2.0
3189a04dfd66baebb69b06daad132145
28.74026
140
0.606114
4.770833
false
false
false
false
piscoTech/Workout
Workout Core/Model/Health.swift
1
1532
// // Health.swift // Workout // // Created by Marco Boschi on 08/06/2019. // Copyright © 2019 Marco Boschi. All rights reserved. // import HealthKit public class Health { let store = HKHealthStore() public init() {} /// List of health data to require access to. private let readData: Set<HKObjectType> = { var types: Set<HKObjectType> = [ HKObjectType.workoutType(), HKObjectType.quantityType(forIdentifier: .heartRate)!, HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!, HKObjectType.quantityType(forIdentifier: .basalEnergyBurned)!, HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!, HKObjectType.quantityType(forIdentifier: .stepCount)!, HKObjectType.quantityType(forIdentifier: .distanceSwimming)!, HKObjectType.quantityType(forIdentifier: .swimmingStrokeCount)!, HKObjectType.quantityType(forIdentifier: .distanceCycling)! ] if #available(iOS 11.0, *) { types.insert(HKSeriesType.workoutRoute()) } return types }() public func authorizeHealthKitAccess(_ callback: @escaping () -> Void) { let req = { self.store.requestAuthorization(toShare: nil, read: self.readData) { _, _ in DispatchQueue.main.async { callback() } } } if #available(iOS 12.0, *) { store.getRequestStatusForAuthorization(toShare: [], read: readData) { status, _ in if status != .unnecessary { req() } } } else { req() } } public var isHealthDataAvailable: Bool { HKHealthStore.isHealthDataAvailable() } }
mit
12ccfca28f90418d3bcd78c5ee2f8dff
22.19697
85
0.700849
3.761671
false
false
false
false
Witcast/witcast-ios
WiTcast/ViewController/Player/PlayerDetailViewController.swift
1
2526
// // PlayerDetailViewController.swift // WiTcast // // Created by Tanakorn Phoochaliaw on 3/29/2560 BE. // Copyright © 2560 Tanakorn Phoochaliaw. All rights reserved. // import UIKit import RealmSwift class PlayerDetailViewController: UIViewController, UIWebViewDelegate { internal var titleTab: String = "" @IBOutlet weak var webview: UIWebView! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var nextButton: UIButton! let realm = try! Realm() var isPlay = false; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. webview.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) var index = 1; var episodeNow = 1; var episodeShow = 1; if (UserDefaults.standard.object(forKey: "episodeNow") as? Int) != nil { episodeNow = UserDefaults.standard.object(forKey: "episodeNow") as! Int; } if (UserDefaults.standard.object(forKey: "episodeShow") as? Int) != nil { episodeShow = UserDefaults.standard.object(forKey: "episodeShow") as! Int; } if (episodeNow == episodeShow) { self.isPlay = true } if (self.isPlay == true) { index = episodeNow; } else { index = episodeShow; } let data = realm.objects(NormalEpisode.self).filter("episodeId = \(index)") let url = NSURL (string: data[0].detail); let requestObj = NSURLRequest(url: url! as URL); webview.loadRequest(requestObj as URLRequest); backButton.isEnabled = false nextButton.isEnabled = false } func webViewDidFinishLoad(_ webView: UIWebView) { backButton.isEnabled = webview.canGoBack nextButton.isEnabled = webview.canGoForward } func initView(titleTab: String) { self.titleTab = titleTab preparePageTabBarItem() } @IBAction func backButtonAction(_ sender: Any) { webview.goBack() } @IBAction func nextButtonAction(_ sender: Any) { webview.goForward() } } /// PageTabBar. extension PlayerDetailViewController { internal func preparePageTabBarItem() { tabItem.title = self.titleTab tabItem.titleColor = .black tabItem.titleLabel?.font = UIFont(name: font_header_regular, size: 20); } }
apache-2.0
3fc4821b38c48a439f3d1f568c9954b5
26.445652
86
0.612673
4.557762
false
false
false
false
chrisroedig/swiftAndVision
cameratest/cameratest/ViewController.swift
1
3624
// // ViewController.swift // cameratest // // Created by Christoph Roedig on 1/1/15. // Copyright (c) 2015 Offroed. All rights reserved. // import Cocoa import AVFoundation import AVKit import QuartzCore class ViewController: NSViewController { var avCaptureSession : AVCaptureSession? var avCaptureDevices: [AVCaptureDevice]! var avCurrentCaptureDevice: AVCaptureDevice? var avCaptureInput: AVCaptureDeviceInput? var avOutput: AVCaptureVideoDataOutput? @IBOutlet weak var cameraPicker: NSPopUpButton! @IBOutlet weak var camView: NSView! // MARK: - NSViewController Overrides override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.configureCapture() self.enumerateCameras() self.startCaptureOnFirstCamera() } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } // MARK: - Camera Operations func configureCapture(){ self.avCaptureSession = AVCaptureSession() self.avCaptureSession?.sessionPreset = AVCaptureSessionPreset640x480 self.avCaptureSession?.beginConfiguration() self.avCaptureSession?.commitConfiguration() self.avOutput = AVCaptureVideoDataOutput() self.avOutput?.videoSettings = [kCVPixelBufferPixelFormatTypeKey as NSString:kCVPixelFormatType_32BGRA] self.avOutput?.alwaysDiscardsLateVideoFrames = true if (self.avCaptureSession?.canAddOutput(self.avOutput) != nil) { self.avCaptureSession?.addOutput(self.avOutput) } var captureLayer = AVCaptureVideoPreviewLayer( session: self.avCaptureSession) self.camView.wantsLayer = true self.camView.layer = AVCaptureVideoPreviewLayer( session: self.avCaptureSession) } func enumerateCameras(){ self.avCaptureDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as [AVCaptureDevice] self.cameraPicker.removeAllItems() for device in self.avCaptureDevices{ self.cameraPicker.addItemWithTitle(device.localizedName) } } func selectCameraByIndex(cam_index : Int ){ let device = self.avCaptureDevices[cam_index]; var err: NSError? if( !device.hasMediaType(AVMediaTypeVideo) ){ return; } self.avCurrentCaptureDevice = device self.avCaptureSession?.removeInput(self.avCaptureInput) self.avCaptureInput = AVCaptureDeviceInput.deviceInputWithDevice( device as AVCaptureDevice, error: &err) as? AVCaptureDeviceInput self.avCaptureSession?.addInput(self.avCaptureInput) } func startCapture(){ self.avCaptureSession?.startRunning() } func endCapture(){ self.avCaptureSession?.stopRunning() } func startCaptureOnFirstCamera(){ if(self.avCaptureDevices.count<1){ return; } self.selectCameraByIndex(0) self.startCapture() } // MARK: - IBActions @IBAction func refreshBtnClicked(sender: AnyObject) { self.endCapture() self.enumerateCameras() } @IBAction func cameraSelected(sender: NSPopUpButton) { endCapture() self.selectCameraByIndex(sender.indexOfSelectedItem) startCapture() } }
gpl-3.0
7fd0064b89c463eff90c392435f8400f
26.876923
76
0.637417
5.321586
false
false
false
false
evan-liu/FormationLayout
Scripts/anchors.swift
1
3682
/** * FormationLayout * * Copyright (c) 2016 Evan Liu. Licensed under the MIT license, as follows: * * 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 extension String { func search(regExp pattern: String, options: NSRegularExpression.Options = []) -> [String]? { let ns = self as NSString return (try? NSRegularExpression(pattern: pattern, options: options)) .flatMap { $0.firstMatch(in: self, options: [], range: NSRange(location: 0, length: utf16.count)) } .flatMap { match in return (0..<match.numberOfRanges).map { ns.substring(with: match.rangeAt($0)) } } } } @available (OSX 10.11, *) func main() { let fileManager = FileManager.default let pwdURL = URL(fileURLWithPath: fileManager.currentDirectoryPath) let scriptURL = URL(fileURLWithPath: #file, relativeTo: pwdURL) let sourcesURL = scriptURL.appendingPathComponent("../../Sources") let codeFileURL = sourcesURL.appendingPathComponent("ConstraintMaker+Anchors.swift") let code = try! String(contentsOf: codeFileURL) guard let match = code.search(regExp: "(.*?)(extension ConstraintMaker \\{.*?^\\})", options: [.dotMatchesLineSeparators, .anchorsMatchLines]) else { print("Wrong code format") return } let header = match[1] let seedCode = match[2] guard let seedAnchor = seedCode.search(regExp: "func (.*?)\\(")?.last else { print("Wrong code format") return } let anchors = [ "left", "right", "top", "bottom", "leading", "trailing", "width", "height", "centerX", "centerY", "lastBaseline", "firstBaseline", "centerXWithinMargins", "centerYWithinMargins", ] var equals = anchors .map { seedCode.replacingOccurrences(of: seedAnchor, with: $0) } let equalsString = equals.joined(separator: "\n\n") let relations = ["greaterThanOrEqual", "lessThanOrEqual"] .map { equalsString.replacingOccurrences(of: "equalTo", with: "\($0)To").replacingOccurrences(of: ".equal", with: ".\($0)") } equals.insert("//== ↓ Generated by `swift Scripts/anchors.swift` ↓ ==", at: 1) let finalCode = header + (equals + relations).joined(separator: "\n\n") do { try finalCode.write(to: codeFileURL, atomically: true, encoding: .utf8) print("Done") } catch { print(error) } } if #available(OSX 10.11, *) { main() } else { print("Only available on OS X 10.11 or newer") exit(1) }
mit
b74647fb4e2852474c1b86dec670d794
35.78
153
0.648178
4.242215
false
false
false
false
sergdort/CleanArchitectureRxSwift
RealmPlatform/Entities/RMComment.swift
1
1468
// // RMComment.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import QueryKit import Domain import RealmSwift import Realm final class RMComment: Object { @objc dynamic var body: String = "" @objc dynamic var email: String = "" @objc dynamic var name: String = "" @objc dynamic var postId: String = "" @objc dynamic var uid: String = "" override class func primaryKey() -> String? { return "uid" } } extension RMComment { static var body: Attribute<String> { return Attribute("body")} static var email: Attribute<String> { return Attribute("email")} static var name: Attribute<String> { return Attribute("name")} static var postId: Attribute<String> { return Attribute("postId")} static var uid: Attribute<String> { return Attribute("uid")} } extension RMComment: DomainConvertibleType { func asDomain() -> Comment { return Comment(body: body, email: email, name: name, postId: postId, uid: uid) } } extension Comment: RealmRepresentable { func asRealm() -> RMComment { return RMComment.build { object in object.body = body object.email = email object.name = name object.uid = uid object.postId = postId } } }
mit
3147bd2c2a640696b63beb809257e1e6
25.196429
70
0.5985
4.445455
false
false
false
false
matheusmonte/IOSProjects
TaskManager/TaskManager/AppDelegate.swift
1
6115
// // AppDelegate.swift // TaskManager // // Created by Clark on 9/14/15. // Copyright (c) 2015 Clark. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "indt.TaskManager" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("TaskManager", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TaskManager.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
gpl-2.0
3b96f03c362e7323fe5159ed6411fd7a
54.09009
290
0.715454
5.785241
false
false
false
false
auth0/Auth0.swift
Auth0/UserInfo.swift
1
5924
// swiftlint:disable function_body_length import Foundation /// OIDC Standard Claims user information. /// /// ## See Also /// /// - [Claims](https://auth0.com/docs/secure/tokens/json-web-tokens/json-web-token-claims) public struct UserInfo: JSONObjectPayload { /// The list of public claims. public static let publicClaims = [ "sub", "name", "given_name", "family_name", "middle_name", "nickname", "preferred_username", "profile", "picture", "website", "email", "email_verified", "gender", "birthdate", "zoneinfo", "locale", "phone_number", "phone_number_verified", "address", "updated_at" ] // MARK: - Claims /// The Auth0 user identifier. public let sub: String /// The name of the user. /// /// - Requires: The `profile` scope. public let name: String? /// The first name of the user. /// /// - Requires: The `profile` scope. public let givenName: String? /// The last name of the user. /// /// - Requires: The `profile` scope. public let familyName: String? /// The middle name of the user. /// /// - Requires: The `profile` scope. public let middleName: String? /// The nickname of the user. /// /// - Requires: The `profile` scope. public let nickname: String? /// The preferred username of the user. /// /// - Requires: The `profile` scope. public let preferredUsername: String? /// The URL of the user's profile page. /// /// - Requires: The `profile` scope. public let profile: URL? /// The URL of the user's picture. /// /// - Requires: The `profile` scope. public let picture: URL? /// The URL of the user's website. /// /// - Requires: The `profile` scope. public let website: URL? /// The email of the user. /// /// - Requires: The `email` scope. public let email: String? /// If the user's email is verified. /// /// - Requires: The `email` scope. public let emailVerified: Bool? /// The gender of the user. /// /// - Requires: The `profile` scope. public let gender: String? /// The birthdate of the user. /// /// - Requires: The `profile` scope. public let birthdate: String? /// The time zone of the user. /// /// - Requires: The `profile` scope. public let zoneinfo: TimeZone? /// The locale of the user. /// /// - Requires: The `profile` scope. public let locale: Locale? /// The phone number of the user. /// /// - Requires: The `phone_number` scope. public let phoneNumber: String? /// If the user's phone number is verified. /// /// - Requires: The `phone_number` scope. public let phoneNumberVerified: Bool? /// The address of the user. /// /// - Requires: The `address` scope. public let address: [String: String]? /// The date and time the user's information was last updated. /// /// - Requires: The `profile` scope. public let updatedAt: Date? /// Any custom claims. public let customClaims: [String: Any]? } // MARK: - Initializer public extension UserInfo { /// Creates a new `UserInfo` from a JSON dictionary. init?(json: [String: Any]) { guard let sub = json["sub"] as? String else { return nil } let name = json["name"] as? String let givenName = json["given_name"] as? String let familyName = json["family_name"] as? String let middleName = json["middle_name"] as? String let nickname = json["nickname"] as? String let preferredUsername = json["preferred_username"] as? String var profile: URL? if let profileURL = json["profile"] as? String { profile = URL(string: profileURL) } var picture: URL? if let pictureURL = json["picture"] as? String { picture = URL(string: pictureURL) } var website: URL? if let websiteURL = json["website"] as? String { website = URL(string: websiteURL) } let email = json["email"] as? String let emailVerified = json["email_verified"] as? Bool let gender = json["gender"] as? String let birthdate = json["birthdate"] as? String var zoneinfo: TimeZone? if let timeZone = json["zoneinfo"] as? String { zoneinfo = TimeZone(identifier: timeZone) } var locale: Locale? if let localeInfo = json["locale"] as? String { locale = Locale(identifier: localeInfo) } let phoneNumber = json["phone_number"] as? String let phoneNumberVerified = json["phone_number_verified"] as? Bool let address = json["address"] as? [String: String] var updatedAt: Date? if let dateString = json["updated_at"] as? String { updatedAt = date(from: dateString) } var customClaims = json UserInfo.publicClaims.forEach { customClaims.removeValue(forKey: $0) } self.init(sub: sub, name: name, givenName: givenName, familyName: familyName, middleName: middleName, nickname: nickname, preferredUsername: preferredUsername, profile: profile, picture: picture, website: website, email: email, emailVerified: emailVerified, gender: gender, birthdate: birthdate, zoneinfo: zoneinfo, locale: locale, phoneNumber: phoneNumber, phoneNumberVerified: phoneNumberVerified, address: address, updatedAt: updatedAt, customClaims: customClaims) } }
mit
9b1b1b3d98233f1c448623f48f8c6c61
26.943396
99
0.565327
4.430815
false
false
false
false
natestedman/TreeSourceView
TreeSourceView/TreeSourceViewHelper.swift
1
12877
// TreeSourceView // Written in 2015 by Nate Stedman <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and // related and neighboring rights to this software to the public domain worldwide. // This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with // this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. import UIKit /// An internal helper class, hiding the backing `UITableView` of `TreeSourceView` by implementing the data source and /// delegate protocols outside of that class. internal class TreeSourceViewHelper: NSObject { /// The associated tree source view. weak var treeSourceView: TreeSourceView? } extension TreeSourceViewHelper: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { // the sections are: // 0: upward navigation // 1: root sections or current navigation - selected section cell is reused // 2: downward navigation return treeSourceView?.dataSource != nil ? 3 : 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let treeSourceView = self.treeSourceView, dataSource = treeSourceView.dataSource { let selectedIndexPath = treeSourceView.selectedIndexPath switch section { case 0: return selectedIndexPath.length ?? 0 case 1: if selectedIndexPath.length == 0 { return dataSource.treeSourceView(treeSourceView, numberOfChildrenAtIndexPath: NSIndexPath()) } else { return 1 } case 2: if selectedIndexPath.length > 0 { return dataSource.treeSourceView(treeSourceView, numberOfChildrenAtIndexPath: selectedIndexPath) } else { return 0 } default: fatalError("Invalid tree source view section") } } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let treeSourceView = self.treeSourceView, dataSource = treeSourceView.dataSource { let reuse = "\(treeSourceView.cellType)" let cell = treeSourceView.tableView.dequeueReusableCellWithIdentifier(reuse) ?? treeSourceView.cellType.init(style: .Default, reuseIdentifier: reuse) let selectedIndexPath = treeSourceView.selectedIndexPath switch indexPath.section { case 0: let count = tableView.numberOfRowsInSection(indexPath.section) var path = selectedIndexPath for _ in 0..<(count - indexPath.row) { path = path.indexPathByRemovingLastIndex() } dataSource.treeSourceView( treeSourceView, updateCell: cell, forIndexPath: path, withCellStyle: .Upward ) case 1: let isRoot = selectedIndexPath.length == 0 let item = isRoot ? indexPath.item : selectedIndexPath.indexAtPosition(0) dataSource.treeSourceView( treeSourceView, updateCell: cell, forIndexPath: NSIndexPath(index: item), withCellStyle: isRoot ? .Root : .Current ) case 2: dataSource.treeSourceView( treeSourceView, updateCell: cell, forIndexPath: selectedIndexPath.indexPathByAddingIndex(indexPath.row), withCellStyle: .Downward ) default: fatalError("Invalid tree source view section") } return cell } else { fatalError("Requested a cell, but no data source") } } } extension TreeSourceViewHelper: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard let treeSourceView = self.treeSourceView else { fatalError("Received delegate callback, but no TreeSourceView") } let previousSelectedPath = treeSourceView.selectedIndexPath tableView.deselectRowAtIndexPath(indexPath, animated: false) switch indexPath.section { case 0: let count = tableView.numberOfRowsInSection(indexPath.section) treeSourceView._selectedIndexPath = previousSelectedPath.indexPathByRemovingIndices(count - indexPath.item) tableView.beginUpdates() // remove the upwards navigation rows let upwardsPaths = (treeSourceView.selectedIndexPath.length..<previousSelectedPath.length).map({ row in NSIndexPath(forRow: row, inSection: 0) }) tableView.deleteRowsAtIndexPaths(upwardsPaths, withRowAnimation: .Bottom) // remove rows for downwards navigation let previousChildren = treeSourceView.dataSource?.treeSourceView( treeSourceView, numberOfChildrenAtIndexPath: previousSelectedPath ) ?? 0 let previousDownwardPaths = (0..<previousChildren).map({ row in NSIndexPath(forRow: row, inSection: 2) }) tableView.deleteRowsAtIndexPaths(previousDownwardPaths, withRowAnimation: .Bottom) if treeSourceView.selectedIndexPath.length == 0 { // insert the new root rows let currentSelectedRoot = previousSelectedPath.indexAtPosition(0) let beforePaths = (0..<currentSelectedRoot).map({ row in NSIndexPath(forRow: row, inSection: 1) }) let totalRootRows = treeSourceView.dataSource?.treeSourceView(treeSourceView, numberOfChildrenAtIndexPath: NSIndexPath()) ?? 0 let afterPaths = ((currentSelectedRoot + 1)..<totalRootRows).map({ row in NSIndexPath(forRow: row, inSection: 1) }) tableView.insertRowsAtIndexPaths(beforePaths, withRowAnimation: .Top) tableView.insertRowsAtIndexPaths(afterPaths, withRowAnimation: .Fade) } else { // add the rows for the new upwards navigation let children = treeSourceView.dataSource?.treeSourceView(treeSourceView, numberOfChildrenAtIndexPath: treeSourceView.selectedIndexPath) ?? 0 let downwardPaths = (0..<children).map({ row in NSIndexPath(forRow: row, inSection: 2) }) tableView.insertRowsAtIndexPaths(downwardPaths, withRowAnimation: .Fade) } tableView.endUpdates() let toRoot = treeSourceView.selectedIndexPath.length == 0 let treePath = toRoot ? NSIndexPath(index: previousSelectedPath.indexAtPosition(0)) : treeSourceView.selectedIndexPath let tablePath = NSIndexPath(forRow: toRoot ? treePath.indexAtPosition(0) : 0, inSection: 1) if let cell = tableView.cellForRowAtIndexPath(tablePath) { UIView.animateWithDuration(0.33, animations: { treeSourceView.dataSource?.treeSourceView( treeSourceView, updateCell: cell, forIndexPath: treePath, withCellStyle: toRoot ? .Root : .Current ) }) } case 1: if treeSourceView.selectedIndexPath.length == 0 { treeSourceView._selectedIndexPath = treeSourceView.selectedIndexPath.indexPathByAddingIndex(indexPath.row) tableView.beginUpdates() // remove the non-selected root rows let beforePaths = (0..<(indexPath.row)).map({ row in NSIndexPath(forRow: row, inSection: 1) }) let afterPaths = ((indexPath.row + 1)..<(tableView.numberOfRowsInSection(1))).map({ row in NSIndexPath(forRow: row, inSection: 1) }) tableView.deleteRowsAtIndexPaths(beforePaths, withRowAnimation: .Top) tableView.deleteRowsAtIndexPaths(afterPaths, withRowAnimation: .Fade) // add the root upwards navigation row tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Bottom) // add the rows for the current downwards navigation let children = treeSourceView.dataSource?.treeSourceView(treeSourceView, numberOfChildrenAtIndexPath: treeSourceView.selectedIndexPath) ?? 0 let downwardPaths = (0..<children).map({ row in NSIndexPath(forRow: row, inSection: 2) }) tableView.insertRowsAtIndexPaths(downwardPaths, withRowAnimation: .Fade) tableView.endUpdates() // update the navigation cell for the new category if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1)) { UIView.animateWithDuration(0.33, animations: { treeSourceView.dataSource?.treeSourceView( treeSourceView, updateCell: cell, forIndexPath: treeSourceView.selectedIndexPath, withCellStyle: .Current ) }) } } else { treeSourceView.delegate?.treeSourceViewTappedSelectedItem(treeSourceView) } case 2: treeSourceView._selectedIndexPath = previousSelectedPath.indexPathByAddingIndex(indexPath.row) tableView.beginUpdates() // insert a new upwards navigation path let upwardsPaths = [NSIndexPath(forRow: treeSourceView.selectedIndexPath.length - 1, inSection: 0)] tableView.insertRowsAtIndexPaths(upwardsPaths, withRowAnimation: .Bottom) // remove rows for downwards navigation let previousChildren = treeSourceView.dataSource?.treeSourceView(treeSourceView, numberOfChildrenAtIndexPath: previousSelectedPath) ?? 0 let previousDownwardPaths = (0..<previousChildren).map({ row in NSIndexPath(forRow: row, inSection: 2) }) tableView.deleteRowsAtIndexPaths(previousDownwardPaths, withRowAnimation: .Fade) // add the rows for the current downwards navigation let children = treeSourceView.dataSource?.treeSourceView(treeSourceView, numberOfChildrenAtIndexPath: treeSourceView.selectedIndexPath) ?? 0 let downwardPaths = (0..<children).map({ row in NSIndexPath(forRow: row, inSection: 2) }) tableView.insertRowsAtIndexPaths(downwardPaths, withRowAnimation: .Fade) tableView.endUpdates() // update the navigation cell for the new category if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1)) { UIView.animateWithDuration(0.33, animations: { treeSourceView.dataSource?.treeSourceView( treeSourceView, updateCell: cell, forIndexPath: treeSourceView.selectedIndexPath, withCellStyle: .Current ) }) } default: fatalError("Invalid tree source view section") } } }
cc0-1.0
ffc1c4f8c7838ebdc411b40118564fb9
40.944625
156
0.558438
6.346476
false
false
false
false
1457792186/JWSwift
SwiftLearn/SwiftDemo/Pods/MonkeyKing/Sources/Extensions.swift
1
6929
import Foundation extension Set { subscript(platform: MonkeyKing.SupportedPlatform) -> MonkeyKing.Account? { let accountSet = MonkeyKing.shared.accountSet switch platform { case .weChat: for account in accountSet { if case .weChat = account { return account } } case .qq: for account in accountSet { if case .qq = account { return account } } case .weibo: for account in accountSet { if case .weibo = account { return account } } case .pocket: for account in accountSet { if case .pocket = account { return account } } case .alipay: for account in accountSet { if case .alipay = account { return account } } case .twitter: for account in accountSet { if case .twitter = account { return account } } } return nil } subscript(platform: MonkeyKing.Message) -> MonkeyKing.Account? { let accountSet = MonkeyKing.shared.accountSet switch platform { case .weChat: for account in accountSet { if case .weChat = account { return account } } case .qq: for account in accountSet { if case .qq = account { return account } } case .weibo: for account in accountSet { if case .weibo = account { return account } } case .alipay: for account in accountSet { if case .alipay = account { return account } } case .twitter: for account in accountSet { if case .twitter = account { return account } } } return nil } } extension Bundle { var monkeyking_displayName: String? { func getNameByInfo(_ info: [String : Any]) -> String? { guard let displayName = info["CFBundleDisplayName"] as? String else { return info["CFBundleName"] as? String } return displayName } var info = infoDictionary if let localizedInfo = localizedInfoDictionary, !localizedInfo.isEmpty { for (key, value) in localizedInfo { info?[key] = value } } guard let unwrappedInfo = info else { return nil } return getNameByInfo(unwrappedInfo) } var monkeyking_bundleID: String? { return object(forInfoDictionaryKey: "CFBundleIdentifier") as? String } } extension String { var monkeyking_base64EncodedString: String? { return data(using: .utf8)?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) } var monkeyking_urlEncodedString: String? { return addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed) } var monkeyking_base64AndURLEncodedString: String? { return monkeyking_base64EncodedString?.monkeyking_urlEncodedString } var monkeyking_urlDecodedString: String? { return replacingOccurrences(of: "+", with: " ").removingPercentEncoding } var monkeyking_qqCallbackName: String { var hexString = String(format: "%02llx", (self as NSString).longLongValue) while hexString.count < 8 { hexString = "0" + hexString } return "QQ" + hexString } } extension Data { var monkeyking_json: [String: Any]? { do { return try JSONSerialization.jsonObject(with: self, options: .allowFragments) as? [String: Any] } catch { return nil } } } extension URL { var monkeyking_queryDictionary: [String: Any] { let components = URLComponents(url: self, resolvingAgainstBaseURL: false) guard let items = components?.queryItems else { return [:] } var infos = [String: Any]() items.forEach { if let value = $0.value { infos[$0.name] = value } } return infos } } extension UIImage { var monkeyking_compressedImageData: Data? { var compressionQuality: CGFloat = 0.7 func compressedDataOfImage(_ image: UIImage) -> Data? { let maxHeight: CGFloat = 240.0 let maxWidth: CGFloat = 240.0 var actualHeight: CGFloat = image.size.height var actualWidth: CGFloat = image.size.width var imgRatio: CGFloat = actualWidth/actualHeight let maxRatio: CGFloat = maxWidth/maxHeight if actualHeight > maxHeight || actualWidth > maxWidth { if imgRatio < maxRatio { // adjust width according to maxHeight imgRatio = maxHeight / actualHeight actualWidth = imgRatio * actualWidth actualHeight = maxHeight } else if imgRatio > maxRatio { // adjust height according to maxWidth imgRatio = maxWidth / actualWidth actualHeight = imgRatio * actualHeight actualWidth = maxWidth } else { actualHeight = maxHeight actualWidth = maxWidth } } let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight) UIGraphicsBeginImageContext(rect.size) defer { UIGraphicsEndImageContext() } image.draw(in: rect) let imageData = UIGraphicsGetImageFromCurrentImageContext().flatMap({ UIImageJPEGRepresentation($0, compressionQuality) }) return imageData } let fullImageData = UIImageJPEGRepresentation(self, compressionQuality) guard var imageData = fullImageData else { return nil } let minCompressionQuality: CGFloat = 0.01 let dataLengthCeiling: Int = 31500 while imageData.count > dataLengthCeiling && compressionQuality > minCompressionQuality { compressionQuality -= 0.1 guard let image = UIImage(data: imageData) else { break } if let compressedImageData = compressedDataOfImage(image) { imageData = compressedImageData } else { break } } return imageData } }
apache-2.0
cf39de44fb527778247c95c79b7eaf72
30.639269
107
0.529369
5.615073
false
false
false
false
AndreMuis/TISensorTag
TISensorTag/Library/TSTAngularVelocityAnimationEngine.swift
1
659
// // TSTAngularVelocityAnimationEngine.swift // TISensorTag // // Created by Andre Muis on 5/22/16. // Copyright © 2016 Andre Muis. All rights reserved. // import SceneKit class TSTAngularVelocityAnimationEngine : TSTAnimationEngine { var scene : SCNScene var sensorTagNode : SCNNode init() { self.scene = SCNScene() self.sensorTagNode = SCNNode() } func addCamera(position position : SCNVector3) { let cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.position = position self.scene.rootNode.addChildNode(cameraNode) } }
mit
735173bd837b14df2081e15414e41109
13.954545
60
0.632219
4.569444
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/ScoreViewController.swift
1
7075
// // ScoreViewController.swift // DNM_iOS // // Created by James Bean on 11/26/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit import DNMModel public class ScoreViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - UI @IBOutlet weak var previousPageButton: UIButton! @IBOutlet weak var nextPageButton: UIButton! @IBOutlet weak var menuButton: UIButton! @IBOutlet weak var viewSelectorTableView: UITableView! // MARK: - Score Views /// All ScoreViews organized by ID private var scoreViewsByID = OrderedDictionary<PerformerID, ScoreView>() /// All ScoreViewIDs (populates ScoreViewTableView) // performerIDs + "omni" private var scoreViewIDs: [PerformerID] = [] // Identifiers for each PerformerView in the ensemble private var performerIDs: [PerformerID] = [] /// ScoreView currently displayed private var currentScoreView: ScoreView? /// Model of an entire musical work public var scoreModel: DNMScoreModel! public override func viewDidLoad() { super.viewDidLoad() } public func showScoreWithScoreModel(scoreModel: DNMScoreModel) { self.scoreModel = scoreModel // maybe don't make this an ivar? setPerformerIDsWithScoreModel(scoreModel) setScoreViewIDsWithScoreModel(scoreModel) manageColorMode() build() } private func build() { setupScoreViewTableView() createScoreViews() showScoreViewWithID("omni") goToFirstPage() } // MARK: ScoreView Management /** Show the ScoreView with a PerformerID - parameter id: PerformerID */ public func showScoreViewWithID(id: PerformerID) { if let scoreView = scoreViewsByID[id] { removeCurrentScoreView() showScoreView(scoreView) } } private func createScoreViews() { for viewerID in scoreViewIDs { let peerIDs = performerIDs.filter { $0 != viewerID } let scoreView = ScoreView( scoreModel: scoreModel, viewerID: viewerID, peerIDs: peerIDs ) scoreViewsByID[viewerID] = scoreView } } private func showScoreView(scoreView: ScoreView) { view.insertSubview(scoreView, atIndex: 0) currentScoreView = scoreView } private func removeCurrentScoreView() { if let currentScoreView = currentScoreView { currentScoreView.removeFromSuperview() } } private func setPerformerIDsWithScoreModel(scoreModel: DNMScoreModel) { performerIDs = scoreModel.instrumentIDsAndInstrumentTypesByPerformerID.keys } private func setScoreViewIDsWithScoreModel(scoreModel: DNMScoreModel) { scoreViewIDs = performerIDs + ["omni"] } // MARK: - UI Setup private func setupScoreViewTableView() { viewSelectorTableView.delegate = self viewSelectorTableView.dataSource = self viewSelectorTableView.autoresizingMask = UIViewAutoresizing.FlexibleHeight viewSelectorTableView.translatesAutoresizingMaskIntoConstraints = true positionViewSelectorTableView() } private func manageColorMode() { view.backgroundColor = DNMColorManager.backgroundColor setViewSelectorTableViewBackground() } private func setViewSelectorTableViewBackground() { let bgView = UIView() bgView.backgroundColor = DNMColorManager.backgroundColor viewSelectorTableView.backgroundView = bgView } // MARK: - PageLayer Navigation /** Go to the first page of the currently displayed ScoreView */ public func goToFirstPage() { currentScoreView?.goToFirstPage() } /** Go to the last page of the currently displayed ScoreView */ public func goToLastPage() { currentScoreView?.goToLastPage() } /** Go to the next page of the currently displayed ScoreView */ public func goToNextPage() { currentScoreView?.goToNextPage() } /** Go to the previous page of the currently displayed ScoreView */ public func goToPreviousPage() { currentScoreView?.goToPreviousPage() } @IBAction func didPressPreviousButton(sender: UIButton) { goToPreviousPage() } @IBAction func didPressNextButton(sender: UIButton) { goToNextPage() } private func resizeViewSelectorTableView() { let contentsHeight = viewSelectorTableView.contentSize.height let frameHeight = viewSelectorTableView.frame.height if contentsHeight <= frameHeight { var frame = viewSelectorTableView.frame frame.size.height = contentsHeight viewSelectorTableView.frame = frame } } private func positionViewSelectorTableView() { let pad: CGFloat = 20 let right = view.bounds.width let centerX = right - 0.5 * viewSelectorTableView.frame.width - pad viewSelectorTableView.layer.position.x = centerX } // MARK: - View Selector UITableViewDelegate public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath ) { if let identifier = (tableView.cellForRowAtIndexPath(indexPath) as? ScoreSelectorTableViewCell)?.identifier { showScoreViewWithID(identifier) } } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return scoreViewIDs.count } // extend beyond title public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("scoreSelectorCell", forIndexPath: indexPath ) as! ScoreSelectorTableViewCell let viewerID = scoreViewIDs[indexPath.row] // do all this in ScoreSelectorTableViewCell implementation cell.identifier = viewerID cell.textLabel?.text = viewerID setVisualAttributesOfTableViewCell(cell) resizeViewSelectorTableView() return cell } // do this in ScoreSelectorTableViewCell private func setVisualAttributesOfTableViewCell(cell: UITableViewCell) { cell.textLabel?.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground) cell.backgroundColor = UIColor.grayscaleColorWithDepthOfField(DepthOfField.Background) let selBGView = UIView() selBGView.backgroundColor = UIColor.grayscaleColorWithDepthOfField(.Middleground) cell.selectedBackgroundView = selBGView } public override func prefersStatusBarHidden() -> Bool { return true } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
babf3c6255dddcda6aefb242c69786d2
30.026316
96
0.668222
5.228381
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEchartsTest_iOS/RingGraphicSpec.swift
1
5215
// // RingGraphicSpec.swift // SwiftyEcharts // // Created by Pluto Y on 06/08/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class RingGraphicSpec: QuickSpec { override func spec() { let cxShapeValue: Float = 85.3747 let cyShapeValue: Float = 0.48347 let rShapeValue: Float = 7675834 let r0ShapeValue: Float = 94757.83732 let shape = RingGraphic.Shape() shape.cx = cxShapeValue shape.cy = cyShapeValue shape.r = rShapeValue shape.r0 = r0ShapeValue describe("For RingGraphic.Shape") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "cx": cxShapeValue, "cy": cyShapeValue, "r": rShapeValue, "r0": r0ShapeValue ] expect(shape.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let shapeByEnums = RingGraphic.Shape( .cx(cxShapeValue), .cy(cyShapeValue), .r(rShapeValue), .r0(r0ShapeValue) ) expect(shapeByEnums.jsonString).to(equal(shape.jsonString)) } } describe("For RingGraphic") { let typeValue = GraphicType.ring let idValue = "ringGraphicIdValue" let actionValue = GraphicAction.merge let leftValue = Position.insideRight let rightValue = Position.insideLeft let topValue = Position.insideBottom let bottomValue = Position.insideTop let boundingValue = GraphicBounding.raw let zValue: Float = 474.237 let zlevelValue: Float = 95.347 let silentValue = false let invisibleValue = true let cursorValue = "ringGraphicCursorValue" let draggableValue = false let progressiveValue = true let shapeValue = shape let styleValue = CommonGraphicStyle( .shadowBlur(99.2836), .stroke(Color.array([Color.red, Color.transparent])) ) let ringGraphic = RingGraphic() ringGraphic.id = idValue ringGraphic.action = actionValue ringGraphic.left = leftValue ringGraphic.right = rightValue ringGraphic.top = topValue ringGraphic.bottom = bottomValue ringGraphic.bounding = boundingValue ringGraphic.z = zValue ringGraphic.zlevel = zlevelValue ringGraphic.silent = silentValue ringGraphic.invisible = invisibleValue ringGraphic.cursor = cursorValue ringGraphic.draggable = draggableValue ringGraphic.progressive = progressiveValue ringGraphic.shape = shapeValue ringGraphic.style = styleValue it("needs to check the typeValue") { expect(ringGraphic.type.jsonString).to(equal(typeValue.jsonString)) } it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "type": typeValue, "id": idValue, "$action": actionValue, "left": leftValue, "right": rightValue, "top": topValue, "bottom": bottomValue, "bounding": boundingValue, "z": zValue, "zlevel": zlevelValue, "silent": silentValue, "invisible": invisibleValue, "cursor": cursorValue, "draggable": draggableValue, "progressive": progressiveValue, "shape": shapeValue, "style": styleValue ] expect(ringGraphic.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let ringGraphicByEnums = RingGraphic( .id(idValue), .action(actionValue), .left(leftValue), .right(rightValue), .top(topValue), .bottom(bottomValue), .bounding(boundingValue), .z(zValue), .zlevel(zlevelValue), .silent(silentValue), .invisible(invisibleValue), .cursor(cursorValue), .draggable(draggableValue), .progressive(progressiveValue), .shape(shapeValue), .style(styleValue) ) expect(ringGraphicByEnums.jsonString).to(equal(ringGraphic.jsonString)) } } } }
mit
da6a4ad974f57b247770d83dd3dd9854
35.71831
87
0.49674
5.505808
false
false
false
false
AsyncNinja/AsyncNinja
Sources/AsyncNinja/EventSource_Transform.swift
1
17868
// // Copyright (c) 2016-2017 Anton Mironov // // 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 Dispatch public extension EventSource { /// Adds indexes to update values of the channel /// /// - Parameters: /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: channel with tuple (index, update) as update value func enumerated(cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<(Int, Update), Success> { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) var index: OSAtomic_int64_aligned64_t = -1 return self.map(executor: .immediate, cancellationToken: cancellationToken, bufferSize: bufferSize) { let localIndex = Int(OSAtomicIncrement64(&index)) return (localIndex, $0) } #else let locking = makeLocking() var index = 0 return self.map(executor: .immediate, cancellationToken: cancellationToken, bufferSize: bufferSize) { locking.lock() defer { locking.unlock() } let localIndex = index index += 1 return (localIndex, $0) } #endif } /// Makes channel of pairs of update values /// /// - Parameters: /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: channel with tuple (update, update) as update value func bufferedPairs(cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<(Update, Update), Success> { let locking = makeLocking() var previousUpdate: Update? return makeProducer( executor: .immediate, pure: true, cancellationToken: cancellationToken, bufferSize: bufferSize, traceID: traceID?.appending("∙bufferedPairs") ) { (value, producer, originalExecutor) in switch value { case let .update(update): locking.lock() let _previousUpdate = previousUpdate previousUpdate = update locking.unlock() if let previousUpdate = _previousUpdate { let change = (previousUpdate, update) producer.value?.traceID?._asyncNinja_log("update \(update)") producer.value?.update(change, from: originalExecutor) } case let .completion(completion): producer.value?.traceID?._asyncNinja_log("complete \(completion)") producer.value?.complete(completion, from: originalExecutor) } } } /// Makes channel of arrays of update values /// /// - Parameters: /// - capacity: number of update values of original channel used /// as update value of derived channel /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: channel with [update] as update value func buffered(capacity: Int, cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<[Update], Success> { var buffer = [Update]() buffer.reserveCapacity(capacity) let locking = makeLocking() return makeProducer( executor: .immediate, pure: true, cancellationToken: cancellationToken, bufferSize: bufferSize, traceID: traceID?.appending("∙buffered") ) { (value, producer, originalExecutor) in locking.lock() switch value { case let .update(update): buffer.append(update) if capacity == buffer.count { let localBuffer = buffer buffer.removeAll(keepingCapacity: true) locking.unlock() producer.value?.traceID?._asyncNinja_log("update \(localBuffer)") producer.value?.update(localBuffer, from: originalExecutor) } else { locking.unlock() } case let .completion(completion): let localBuffer = buffer buffer.removeAll(keepingCapacity: false) locking.unlock() if !localBuffer.isEmpty { producer.value?.traceID?._asyncNinja_log("update \(localBuffer)") producer.value?.update(localBuffer, from: originalExecutor) } producer.value?.traceID?._asyncNinja_log("complete \(completion)") producer.value?.complete(completion, from: originalExecutor) } } } /// Makes channel that delays each value produced by originial channel /// /// - Parameters: /// - timeout: in seconds to delay original channel by /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: delayed channel func delayedUpdate(timeout: Double, delayingExecutor: Executor = .primary, cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<Update, Success> { return makeProducer( executor: .immediate, pure: true, cancellationToken: cancellationToken, bufferSize: bufferSize, traceID: traceID?.appending("∙buffered") ) { (event: Event, producer, originalExecutor: Executor) -> Void in delayingExecutor.execute(after: timeout) { (originalExecutor) in producer.value?.traceID?._asyncNinja_log("event \(event)") producer.value?.post(event, from: originalExecutor) } } } } // MARK: - Distinct extension EventSource { /// Returns channel of distinct update values of original channel. /// Requires dedicated equality checking closure /// /// - Parameters: /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - isEqual: closure that tells if specified values are equal /// - Returns: channel with distinct update values public func distinct( cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default, isEqual: @escaping (Update, Update) -> Bool ) -> Channel<Update, Success> { let locking = makeLocking() var previousUpdate: Update? return makeProducer( executor: .immediate, pure: true, cancellationToken: cancellationToken, bufferSize: bufferSize, traceID: traceID?.appending("∙buffered") ) { (value, producer, originalExecutor) in switch value { case let .update(update): locking.lock() let _previousUpdate = previousUpdate previousUpdate = update locking.unlock() if let previousUpdate = _previousUpdate { if !isEqual(previousUpdate, update) { producer.value?.traceID?._asyncNinja_log("update \(update)") producer.value?.update(update, from: originalExecutor) } } else { producer.value?.traceID?._asyncNinja_log("update \(update)") producer.value?.update(update, from: originalExecutor) } case let .completion(completion): producer.value?.traceID?._asyncNinja_log("complete \(completion)") producer.value?.complete(completion, from: originalExecutor) } } } } extension EventSource where Update: Equatable { /// Returns channel of distinct update values of original channel. /// Works only for equatable update values /// [0, 0, 1, 2, 3, 3, 4, 3] => [0, 1, 2, 3, 4, 3] /// /// - Parameters: /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: channel with distinct update values public func distinct( cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<Update, Success> { // Test: EventSource_TransformTests.testDistinctInts return distinct(cancellationToken: cancellationToken, bufferSize: bufferSize, isEqual: ==) } } // MARK: - skip public extension EventSource { /// Makes a channel that skips updates /// /// - Parameters: /// - first: number of first updates to skip /// - last: number of last updates to skip /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: channel that skips updates func skip( first: Int, last: Int, cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<Update, Success> { // Test: EventSource_TransformTests.testSkip let locking = makeLocking(isFair: true) var updatesQueue = Queue<Update>() var numberOfFirstToSkip = first let numberOfLastToSkip = last func onEvent( event: ChannelEvent<Update, Success>, producerBox: WeakBox<BaseProducer<Update, Success>>, originalExecutor: Executor) { switch event { case let .update(update): let updateToPost: Update? = locking.locker { if numberOfFirstToSkip > 0 { numberOfFirstToSkip -= 1 return nil } else if numberOfLastToSkip > 0 { updatesQueue.push(update) while updatesQueue.count > numberOfLastToSkip { return updatesQueue.pop() } return nil } else { return update } } if let updateToPost = updateToPost { producerBox.value?.traceID?._asyncNinja_log("update \(updateToPost)") producerBox.value?.update(updateToPost, from: originalExecutor) } case let .completion(completion): producerBox.value?.traceID?._asyncNinja_log("complete \(completion)") producerBox.value?.complete(completion, from: originalExecutor) } } return makeProducer(executor: .immediate, pure: true, cancellationToken: cancellationToken, bufferSize: bufferSize, traceID: traceID?.appending("∙skip"), onEvent) } } // MARK: take public extension EventSource { /// Makes a channel that takes updates specific number of update /// /// - Parameters: /// - first: number of first updates to take /// - completion: completion to use after specified ammount of updates /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: channel that takes specified amount of updates func take( _ first: Int, completion: Success, cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<Update, Success> { let locking = makeLocking(isFair: true) let updatesQueue = Queue<Update>() var numberOfFirstToTake = first func onEvent( event: ChannelEvent<Update, Success>, producerBox: WeakBox<BaseProducer<Update, Success>>, originalExecutor: Executor) { switch event { case let .update(update): let updateToPost: Update? = locking.locker { if numberOfFirstToTake > 0 { numberOfFirstToTake -= 1 return update } else { return nil } } if let updateToPost = updateToPost { producerBox.value?.traceID?._asyncNinja_log("update \(updateToPost)") producerBox.value?.update(updateToPost, from: originalExecutor) } if numberOfFirstToTake == 0 { producerBox.value?.traceID?._asyncNinja_log("complete \(completion)") producerBox.value?.succeed(completion) } case let .completion(completion): if let producer = producerBox.value { let queue = locking.locker { updatesQueue } producer.traceID?._asyncNinja_log("update \(queue)") producer.update(queue) producer.traceID?._asyncNinja_log("complete \(completion)") producer.complete(completion, from: originalExecutor) } } } return makeProducer(executor: .immediate, pure: true, cancellationToken: cancellationToken, bufferSize: bufferSize, traceID: traceID?.appending("∙take"), onEvent) } /// Makes a channel that takes updates specific number of update /// /// - Parameters: /// - first: number of first updates to take /// - last: number of last updates to take /// - cancellationToken: `CancellationToken` to use. /// Keep default value of the argument unless you need /// an extended cancellation options of returned primitive /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: channel that takes updates func take( first: Int, last: Int, cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<Update, Success> { // Test: EventSource_TransformTests.testTake let locking = makeLocking(isFair: true) var updatesQueue = Queue<Update>() var numberOfFirstToTake = first let numberOfLastToTake = last func onEvent( event: ChannelEvent<Update, Success>, producerBox: WeakBox<BaseProducer<Update, Success>>, originalExecutor: Executor) { switch event { case let .update(update): let updateToPost: Update? = locking.locker { if numberOfFirstToTake > 0 { numberOfFirstToTake -= 1 return update } else if numberOfLastToTake > 0 { updatesQueue.push(update) while updatesQueue.count > numberOfLastToTake { _ = updatesQueue.pop() } return nil } else { return nil } } if let updateToPost = updateToPost { producerBox.value?.update(updateToPost, from: originalExecutor) producerBox.value?.traceID?._asyncNinja_log("update \(updateToPost)") } case let .completion(completion): if let producer = producerBox.value { let queue = locking.locker { updatesQueue } producer.traceID?._asyncNinja_log("update \(queue)") producer.update(queue) producer.traceID?._asyncNinja_log("complete \(completion)") producer.complete(completion, from: originalExecutor) } } } return makeProducer( executor: .immediate, pure: true, cancellationToken: cancellationToken, bufferSize: bufferSize, traceID: traceID?.appending("∙take"), onEvent ) } }
mit
f2f8cdc1df25d5839af058a96a6a480f
36.508403
94
0.649994
4.812399
false
false
false
false
wfleming/pico-block
pblockTests/ModelSpecs/RuleOptionsSpec.swift
1
2242
import Quick import Nimble @testable import pblock class RuleOptionsSpec: QuickSpec { override func spec() { describe("RuleActionType enum") { it("should give correct json string") { expect(RuleActionType.Invalid.jsonValue()).to(beNil()) expect(RuleActionType.Block.jsonValue()).to(equal("block")) expect(RuleActionType.CssDisplayNone.jsonValue()).to(equal("css-display-none")) expect(RuleActionType.CssDisplayNoneStyleSheet.jsonValue()).to(equal("css-display-none-style-sheet")) expect(RuleActionType.IgnorePreviousRules.jsonValue()).to(equal("ignore-previous-rules")) } } describe("RuleResourceTypeOptions") { it("should return appropiate rawValue for combined options") { let opt = RuleResourceTypeOptions.Script.union(RuleResourceTypeOptions.Image) let rawVal = opt.rawValue expect(rawVal & RuleResourceTypeOptions.Script.rawValue).to(equal(RuleResourceTypeOptions.Script.rawValue)) expect(rawVal & RuleResourceTypeOptions.StyleSheet.rawValue).to(equal(0)) } it("should return correct JSON when no values") { let opt = RuleResourceTypeOptions.None expect(opt.jsonValue()).to(beNil()) } it("should return correct JSON when it has values") { let opt = RuleResourceTypeOptions.Script.union(RuleResourceTypeOptions.Image) expect(opt.jsonValue()).to(equal(["script", "image"])) } } describe("RuleLoadTypeOptions") { it("should return appropiate rawValue for combined options") { let opt = RuleLoadTypeOptions.FirstParty let rawVal = opt.rawValue expect(rawVal & RuleLoadTypeOptions.FirstParty.rawValue).to(equal(RuleLoadTypeOptions.FirstParty.rawValue)) expect(rawVal & RuleLoadTypeOptions.ThirdParty.rawValue).to(equal(0)) } it("should return correct JSON when no values") { let opt = RuleLoadTypeOptions.None expect(opt.jsonValue()).to(beNil()) } it("should return correct JSON when it has values") { let opt = RuleLoadTypeOptions.FirstParty.union(RuleLoadTypeOptions.ThirdParty) expect(opt.jsonValue()).to(equal(["first-party", "third-party"])) } } } }
mit
ffd329e9a09eb25e350d30c1d8103876
39.763636
115
0.688225
4.303263
false
false
false
false
luvacu/Twitter-demo-app
Twitter Demo/Source/Services/TwitterRepository/TwitterNetworkProxy.swift
1
6277
// // TwitterNetworkProxy.swift // Twitter Demo // // Created by Luis Valdés on 16/7/17. // Copyright © 2017 Luis Valdés Cuesta. All rights reserved. // import Foundation import RxSwift import TwitterKit struct TwitterNetworkProxy { private struct Requests { static let baseURL = "https://api.twitter.com/1.1/" struct Timeline { static let method = "GET" static let path = "statuses/home_timeline.json" } struct Favourites { static let method = "POST" static let paramID = "id" static let createPath = "favorites/create.json" static let destroyPath = "favorites/destroy.json" } } enum Error: Swift.Error { /// The server returned no data as a response case didNotReceiveData /// The server returned data in a different format than expected case invalidDataFormat } private let client: TWTRAPIClient init(client: TWTRAPIClient) { self.client = client } func retrieveTweets() -> Observable<[TwitterRepository.Tweet]> { return Observable.create { observer -> Disposable in let request: URLRequest do { request = try self.urlRequestForHomeTimeline() } catch { observer.onError(error) return Disposables.create() } let progress = self.client.sendTwitterRequest(request) { (_, data, error) in DispatchQueue.global(qos: .userInitiated).async { guard error == nil else { observer.onError(error!) return } guard let data = data else { observer.onCompleted() return } do { let json = try JSONSerialization.jsonObject(with: data, options: []) guard let jsonArray = json as? [Any], let tweets = TwitterRepository.Tweet.tweets(withJSONArray: jsonArray) as? [TwitterRepository.Tweet] else { observer.onCompleted() return } observer.onNext(tweets) observer.onCompleted() } catch { observer.onError(error) } } } return Disposables.create { progress.cancel() } }.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated)) } func retrieveUser(withID userID: String) -> Single<TwitterRepository.User> { return Single.create { single in self.client.loadUser(withID: userID) { user, error in guard error == nil else { single(.error(error!)) return } guard let user = user else { single(.error(Error.didNotReceiveData)) return } single(.success(user)) } return Disposables.create() } } func markTweet(withID tweetID: String, asFavourite favourite: Bool) -> Single<Bool> { return Single.create { single -> Disposable in let request: URLRequest do { request = try self.urlRequestToMarkTweet(withID: tweetID, asFavourite: favourite) } catch { single(.error(error)) return Disposables.create() } let progress = self.client.sendTwitterRequest(request) { (_, data, error) in DispatchQueue.global(qos: .userInitiated).async { guard error == nil else { single(.error(error!)) return } guard let data = data else { single(.error(Error.didNotReceiveData)) return } do { let json = try JSONSerialization.jsonObject(with: data, options: []) guard let jsonObject = json as? [AnyHashable : Any], let tweet = TwitterRepository.Tweet(jsonDictionary: jsonObject) else { single(.error(Error.didNotReceiveData)) return } single(.success(tweet.isLiked)) } catch { single(.error(error)) } } } return Disposables.create { progress.cancel() } }.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated)) } private func urlRequestForHomeTimeline() throws -> URLRequest { let url = Requests.baseURL + Requests.Timeline.path let method = Requests.Timeline.method let params: [AnyHashable : Any]? = nil return try urlRequest(method: method, url: url, parameters: params) } private func urlRequestToMarkTweet(withID tweetID: String, asFavourite favourite: Bool) throws -> URLRequest { let url = Requests.baseURL + (favourite ? Requests.Favourites.createPath : Requests.Favourites.destroyPath) let method = Requests.Favourites.method let params = [Requests.Favourites.paramID : tweetID] return try urlRequest(method: method, url: url, parameters: params) } private func urlRequest(method: String, url: String, parameters: [AnyHashable : Any]?) throws -> URLRequest { var error: NSError? let request = client.urlRequest(withMethod: method, url: url, parameters: parameters, error: &error) guard error == nil else { throw error! } return request } }
mit
a9694ac605508160de2b72b8b2643095
34.851429
134
0.5
5.803885
false
false
false
false
koneman/Hearth
TableViewController.swift
1
4699
// // TableViewController.swift // Hearth // // Created by Sathvik Koneru on 5/16/16. // Copyright © 2016 Sathvik Koneru. All rights reserved. // import UIKit //this class is used to organize the second view controller //which is a table view of multiple cells to hold all the pins the user adds class TableViewController: UITableViewController { @IBOutlet var doen: UINavigationBar! //this method is similar to a constructor and creates the table view object override func viewDidLoad() { super.viewDidLoad() if allPlaces.count == -1 { allPlaces.removeAtIndex(0) allPlaces.append(["name":"Taj Mahal","lat":"27.175277","lon":"78.042128"]) } } //default memory warning method override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source //this method returns the number of sections the Table View has //our app only needs 1 sectiosn override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } //this method reutrns the total number of entries in the dictionary to create //a cell for each pin and entry override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return allPlaces.count } //this method edits the text of each cell //it is set to the corresponding value in the allPlaces dictionary override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) cell.textLabel?.text = allPlaces[indexPath.row]["name"] return cell } //this method returns the corresponding index of the row override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { activePlace = indexPath.row return indexPath } //this method reloads the data so that each time new pins are added, they will //show up in the Table View override func viewWillAppear(animated: Bool) { tableView.reloadData() } //this method in invoked when the user presses the "+" or "back" button //the view controller //when this happens activePlace is reset override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if ((segue.identifier == "newPlace") || (segue.identifier == "done")){ activePlace = -1 } } //extra methods for TableViewController /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // 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. } */ }
mit
8695d60b9123acabb50e450214ea0e2f
33.043478
158
0.656875
5.34471
false
false
false
false
garethpaul/FabricTwitterBeacons
settee/RESTApi.swift
1
2150
// // TVSearchAPI.swift // settee // // Created by Gareth Jones on 12/14/14. // Copyright (c) 2014 Twitter. All rights reserved. // import Foundation import TwitterKit func Search(handle: String, completion: (result: String) -> Void) { typealias JSON = AnyObject typealias JSONDictionary = Dictionary<String, JSON> typealias JSONArray = Array<JSON> let statusesShowEndpoint = "https://api.twitter.com/1.1/search/tweets.json" let params = ["q": "#NETFLIX OR #BBCONE or #CHANNEL4 or #ITV"] var clientError : NSError? Twitter.initialize() Twitter.sharedInstance().logInWithCompletion{ (session, error) -> Void in if (session != nil) { println("signed in as \(session.userName)"); /// go let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod("GET", URL: statusesShowEndpoint, parameters: params, error:&clientError) if request != nil { println("request is not nil") Twitter.sharedInstance().APIClient.sendTwitterRequest(request) { (response, data, connectionError) -> Void in if (connectionError == nil) { var jsonError : NSError? let json : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) if let statuses = json!["statuses"] as? JSONArray { for tweet in statuses { if let id = tweet["id"] as?Int{ println(String(id)) } } } } else { println("Error: \(connectionError)") } } } else { println("Error: \(clientError)") } } else { println("error: \(error.localizedDescription)"); } } }
apache-2.0
c69575c46d940a00aca2f832012601e5
30.15942
156
0.487442
5.334988
false
false
false
false
SahebRoy92/SRPopView
Example/SRSwiftyPopView/SettingsViewController.swift
1
5645
// // SettingsViewController.swift // SRSwiftyPopView_Example // // Created by Administrator on 29/08/18. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit import SRSwiftyPopView class SettingsViewController: UIViewController { var allsettings = [[String : Any]]() @IBOutlet weak var tblView: UITableView! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { loadSettings() } func loadSettings(){ var blurResult = "" if SRPopview.shared.blurBackground == .none { blurResult = "None" } else if SRPopview.shared.blurBackground == .dark { blurResult = "Dark" } else { blurResult = "Light" } var colorScheme = "" switch SRPopview.shared.currentColorScheme { case .black: colorScheme = "black" case .dark: colorScheme = "dark" case .bright: colorScheme = "bright" case .matte: colorScheme = "matte" case .strangerthings: colorScheme = "strangerthings" case .westworld: colorScheme = "westworld" case .firefly: colorScheme = "firefly" } var logVal = "" if SRPopview.shared.showLog == .off { logVal = "Off" } else { logVal = "On" } allsettings = [ ["title" : "Auto Search", "value" : ["On","Off"], "current" : SRPopview.shared.autoSearch ? "On" : "Off" ], ["title" : "Background Blur", "value" : ["None","Light","Dark"], "current" : blurResult], ["title" : "Color Scheme", "value" : ["dark","bright","black","matte","strangerthings","westworld","firefly"], "current" : colorScheme], ["title" : "Show Log", "value" : ["On","Off"], "current" : logVal ] ] } func redraw(){ let searchCurrent = allsettings[0]["current"] as! String if searchCurrent == "On" { SRPopview.shared.autoSearch = true } else { SRPopview.shared.autoSearch = false } let backgroundBlurCurrent = allsettings[1]["current"] as! String switch backgroundBlurCurrent { case "None" : SRPopview.shared.blurBackground = .none case "Light" : SRPopview.shared.blurBackground = .vibrant case "Dark" : SRPopview.shared.blurBackground = .dark default: print("Nothing-") } let colorSchemeCurrent = allsettings[2]["current"] as! String switch colorSchemeCurrent { case "black" : SRPopview.shared.currentColorScheme = .black case "dark" : SRPopview.shared.currentColorScheme = .dark case "bright" : SRPopview.shared.currentColorScheme = .bright case "matte" : SRPopview.shared.currentColorScheme = .matte case "strangerthings" : SRPopview.shared.currentColorScheme = .strangerthings case "westworld" : SRPopview.shared.currentColorScheme = .westworld case "firefly" : SRPopview.shared.currentColorScheme = .firefly default: print("Nothing - ") } let logResult = allsettings[3]["current"] as! String if logResult == "On" { SRPopview.shared.showLog = .verbose } else { SRPopview.shared.showLog = .off } } } extension SettingsViewController : UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return allsettings.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let dict = allsettings[section] let arr = dict["value"] as! [String] return arr.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let dict = allsettings[section] return dict["title"] as? String } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuse") let dict = allsettings[indexPath.section] let itemArr = dict["value"] as! [String] let item = itemArr[indexPath.row] cell?.textLabel?.text = item let currentVal = dict["current"] as! String if currentVal == item { cell?.accessoryType = .checkmark } else { cell?.accessoryType = .none } return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var dict = allsettings[indexPath.section] let itemArr = dict["value"] as! [String] let item = itemArr[indexPath.row] dict["current"] = item allsettings[indexPath.section] = dict redraw() tableView.reloadData() } }
mit
15e715ad105bd23cb8fba9fcca6adefb
28.092784
108
0.519135
4.88658
false
false
false
false
kperryua/swift
stdlib/public/SDK/IOKit/IOReturn.swift
10
6351
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import IOKit /// General error public var kIOReturnError: IOReturn { return iokit_common_err(0x2bc) } /// Can't allocate memory public var kIOReturnNoMemory: IOReturn { return iokit_common_err(0x2bd) } /// Resource shortage public var kIOReturnNoResources: IOReturn { return iokit_common_err(0x2be) } /// Error during IPC public var kIOReturnIPCError: IOReturn { return iokit_common_err(0x2bf) } /// No such device public var kIOReturnNoDevice: IOReturn { return iokit_common_err(0x2c0) } /// Privilege violation public var kIOReturnNotPrivileged: IOReturn { return iokit_common_err(0x2c1) } /// Invalid argument public var kIOReturnBadArgument: IOReturn { return iokit_common_err(0x2c2) } /// Device read locked public var kIOReturnLockedRead: IOReturn { return iokit_common_err(0x2c3) } /// Device write locked public var kIOReturnLockedWrite: IOReturn { return iokit_common_err(0x2c4) } /// Exclusive access and device already open public var kIOReturnExclusiveAccess: IOReturn { return iokit_common_err(0x2c5) } /// Sent/received messages had different msg_id public var kIOReturnBadMessageID: IOReturn { return iokit_common_err(0x2c6) } /// Unsupported function public var kIOReturnUnsupported: IOReturn { return iokit_common_err(0x2c7) } /// Misc. VM failure public var kIOReturnVMError: IOReturn { return iokit_common_err(0x2c8) } /// Internal error public var kIOReturnInternalError: IOReturn { return iokit_common_err(0x2c9) } /// General I/O error public var kIOReturnIOError: IOReturn { return iokit_common_err(0x2ca) } /// Can't acquire lock public var kIOReturnCannotLock: IOReturn { return iokit_common_err(0x2cc) } /// Device not open public var kIOReturnNotOpen: IOReturn { return iokit_common_err(0x2cd) } /// Read not supported public var kIOReturnNotReadable: IOReturn { return iokit_common_err(0x2ce) } /// Write not supported public var kIOReturnNotWritable: IOReturn { return iokit_common_err(0x2cf) } /// Alignment error public var kIOReturnNotAligned: IOReturn { return iokit_common_err(0x2d0) } /// Media error public var kIOReturnBadMedia: IOReturn { return iokit_common_err(0x2d1) } /// Device(s) still open public var kIOReturnStillOpen: IOReturn { return iokit_common_err(0x2d2) } /// RLD failure public var kIOReturnRLDError: IOReturn { return iokit_common_err(0x2d3) } /// DMA failure public var kIOReturnDMAError: IOReturn { return iokit_common_err(0x2d4) } /// Device busy public var kIOReturnBusy: IOReturn { return iokit_common_err(0x2d5) } /// I/O timeout public var kIOReturnTimeout: IOReturn { return iokit_common_err(0x2d6) } /// Device offline public var kIOReturnOffline: IOReturn { return iokit_common_err(0x2d7) } /// Not ready public var kIOReturnNotReady: IOReturn { return iokit_common_err(0x2d8) } /// Device not attached public var kIOReturnNotAttached: IOReturn { return iokit_common_err(0x2d9) } /// No DMA channels left public var kIOReturnNoChannels: IOReturn { return iokit_common_err(0x2da) } /// No space for data public var kIOReturnNoSpace: IOReturn { return iokit_common_err(0x2db) } /// Port already exists public var kIOReturnPortExists: IOReturn { return iokit_common_err(0x2dd) } /// Can't wire down physical memory public var kIOReturnCannotWire: IOReturn { return iokit_common_err(0x2de) } /// No interrupt attached public var kIOReturnNoInterrupt: IOReturn { return iokit_common_err(0x2df) } /// No DMA frames enqueued public var kIOReturnNoFrames: IOReturn { return iokit_common_err(0x2e0) } /// Oversized msg received on interrupt port public var kIOReturnMessageTooLarge: IOReturn { return iokit_common_err(0x2e1) } /// Not permitted public var kIOReturnNotPermitted: IOReturn { return iokit_common_err(0x2e2) } /// No power to device public var kIOReturnNoPower: IOReturn { return iokit_common_err(0x2e3) } /// Media not present public var kIOReturnNoMedia: IOReturn { return iokit_common_err(0x2e4) } /// media not formatted public var kIOReturnUnformattedMedia: IOReturn { return iokit_common_err(0x2e5) } /// No such mode public var kIOReturnUnsupportedMode: IOReturn { return iokit_common_err(0x2e6) } /// Data underrun public var kIOReturnUnderrun: IOReturn { return iokit_common_err(0x2e7) } /// Data overrun public var kIOReturnOverrun: IOReturn { return iokit_common_err(0x2e8) } /// The device is not working properly public var kIOReturnDeviceError: IOReturn { return iokit_common_err(0x2e9) } /// A completion routine is required public var kIOReturnNoCompletion: IOReturn { return iokit_common_err(0x2ea) } /// Operation aborted public var kIOReturnAborted: IOReturn { return iokit_common_err(0x2eb) } /// Bus bandwidth would be exceeded public var kIOReturnNoBandwidth: IOReturn { return iokit_common_err(0x2ec) } /// Device not responding public var kIOReturnNotResponding: IOReturn { return iokit_common_err(0x2ed) } /// Isochronous I/O request for distant past public var kIOReturnIsoTooOld: IOReturn { return iokit_common_err(0x2ee) } /// Isochronous I/O request for distant future public var kIOReturnIsoTooNew: IOReturn { return iokit_common_err(0x2ef) } /// Data was not found public var kIOReturnNotFound: IOReturn { return iokit_common_err(0x2f0) } /// Should never be seen public var kIOReturnInvalid: IOReturn { return iokit_common_err(0x1) } internal let SYS_IOKIT = UInt32((0x38 & 0x3f) << 26) internal let SUB_IOKIT_COMMON = UInt32((0 & 0xfff) << 14) internal func iokit_common_err(_ value: UInt32) -> IOReturn { return IOReturn(bitPattern: SYS_IOKIT | SUB_IOKIT_COMMON | value) }
apache-2.0
8846da00dd53b32d92f509b7e11104a4
49.808
81
0.709967
3.407189
false
false
false
false
sdaheng/Biceps
BicepsService.swift
1
3411
// // BicepsService.swift // HomeNAS // // Created by SDH on 03/04/2017. // Copyright © 2017 sdaheng. All rights reserved. // import Foundation // MARK: Service Layer public protocol BicepsProvidable { func fetch(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps func send(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps } public extension BicepsProvidable { func fetch(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps { throw BicepsError.UnimplementedMethodError.fetch } func send(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps { throw BicepsError.UnimplementedMethodError.send } } open class BicepsService { open class func fetch<T: BicepsProvidable>(by provider: T, paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?) -> Void) throws { do { let biceps = try provider.fetch(paramater: paramater, resultBlock: resultBlock) try add(biceps, to: BicepsOperationQueue.shared.operationQueue) } catch { throw BicepsError.UnimplementedMethodError.fetch } } open class func send<T: BicepsProvidable>(by provider: T, paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?) -> Void) throws { do { let biceps = try provider.send(paramater: paramater, resultBlock: resultBlock) try add(biceps, to: BicepsOperationQueue.shared.operationQueue) } catch { throw BicepsError.UnimplementedMethodError.send } } class func add(_ biceps: Biceps, to queue: OperationQueue) throws { let operationQueue = queue if let combinedRequests = biceps.combinedRequest { operationQueue.addOperations(combinedRequests.map { (biceps) in return BicepsOperation(biceps) }, waitUntilFinished: false) } else if biceps.hasDependency() { guard let dependency = biceps.dependency, dependency != biceps else { throw BicepsError.DependencyError.cycle } operationQueue.addOperations(resolveDependencyChain(from: biceps), waitUntilFinished: false) } else { operationQueue.addOperation(BicepsOperation(biceps)) } } class func resolveDependencyChain(from head: Biceps) -> [BicepsOperation] { var dependencyChain = head var dependencyOperation = BicepsOperation(head) var dependencyOperations = Set<BicepsOperation>() while dependencyChain.hasDependency() { if let depsDependency = dependencyChain.dependency { let depsDependencyOperation = BicepsOperation(depsDependency) dependencyOperation.addDependency(depsDependencyOperation) dependencyOperations.insert(dependencyOperation) if !depsDependency.hasDependency() { dependencyOperations.insert(depsDependencyOperation) } dependencyOperation = depsDependencyOperation dependencyChain = depsDependency } } return dependencyOperations.map { return $0 } } }
mit
925a44a78c444d64d47174a5d62e8465
39.117647
146
0.633138
4.522546
false
false
false
false
Takanu/Pelican
Sources/Pelican/API/Types/Message Content/Voice.swift
1
1677
// // Voice.swift // Pelican // // Created by Takanu Kyriako on 31/08/2017. // import Foundation /** Represents a Voice type, which will appear as if it was a user-recorded voice message if sent. */ public struct Voice: TelegramType, MessageFile { // STORAGE AND IDENTIFIERS public var contentType: String = "voice" public var method: String = "sendVoice" // FILE SOURCE public var fileID: String? public var url: String? // PARAMETERS /// The duration of the voice note, in seconds. public var duration: Int? /// The mime type of the voice file. public var mimeType: String? /// The file size. public var fileSize: Int? /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case fileID = "file_id" case url case duration case mimeType = "mime_type" case fileSize = "file_size" } public init(fileID: String, duration: Int? = nil, mimeType: String? = nil, fileSize: Int? = nil) { self.fileID = fileID self.duration = duration self.mimeType = mimeType self.fileSize = fileSize } public init?(url: String, duration: Int? = nil, mimeType: String? = nil, fileSize: Int? = nil) { if url.checkURLValidity(acceptedExtensions: ["ogg"]) == false { return nil } self.url = url self.duration = duration self.mimeType = mimeType self.fileSize = fileSize } // SendType conforming methods to send itself to Telegram under the provided method. public func getQuery() -> [String: Codable] { var keys: [String: Codable] = [ "voice": fileID] if duration != 0 { keys["duration"] = duration } return keys } }
mit
74e506077ac2f5bc3a1ba0b19f1a3df0
20.5
94
0.660107
3.523109
false
false
false
false
Sherlouk/IGListKit
Examples/Examples-iOS/IGListKitExamples/SectionControllers/GridSectionController.swift
4
2115
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit class GridItem: NSObject { let color: UIColor let itemCount: Int init(color: UIColor, itemCount: Int) { self.color = color self.itemCount = itemCount } } extension GridItem: IGListDiffable { func diffIdentifier() -> NSObjectProtocol { return self } func isEqual(toDiffableObject object: IGListDiffable?) -> Bool { return self === object ? true : self.isEqual(object) } } final class GridSectionController: IGListSectionController, IGListSectionType { var object: GridItem? override init() { super.init() self.minimumInteritemSpacing = 1 self.minimumLineSpacing = 1 } func numberOfItems() -> Int { return object?.itemCount ?? 0 } func sizeForItem(at index: Int) -> CGSize { let width = collectionContext?.containerSize.width ?? 0 let itemSize = floor(width / 4) return CGSize(width: itemSize, height: itemSize) } func cellForItem(at index: Int) -> UICollectionViewCell { let cell = collectionContext!.dequeueReusableCell(of: CenterLabelCell.self, for: self, at: index) as! CenterLabelCell cell.label.text = "\(index + 1)" cell.backgroundColor = object?.color return cell } func didUpdate(to object: Any) { self.object = object as? GridItem } func didSelectItem(at index: Int) {} }
bsd-3-clause
c00ccdd37c96e25b7005bc1f9fb2ad5d
27.2
125
0.68227
4.752809
false
false
false
false
roambotics/swift
test/Concurrency/objc_async_protocol_irgen.swift
2
1097
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -disable-availability-checking -import-objc-header %S/Inputs/Delegate.h %s -emit-ir -o - | %FileCheck %s -DALIGNMENT=%target-alignment --check-prefix=CHECK-%is-darwin // REQUIRES: concurrency // REQUIRES: objc_interop let anyObject: AnyObject = (MyAsyncProtocol.self as AnyObject) // or something like this // rdar://76192003 // Make sure we don't emit 2 copies of methods, due to a completion-handler // version and another due to an async based version. // CHECK-isNotDarwin-LABEL: @_PROTOCOL_INSTANCE_METHODS_MyAsyncProtocol = weak hidden constant // CHECK-isNotDarwin-SAME: selector_data(myAsyncMethod:) // CHECK-isNotDarwin-NOT: selector_data(myAsyncMethod:) // CHECK-isNotDarwin-SAME: align [[ALIGNMENT]] // CHECK-isDarwin: @OBJC_METH_VAR_NAME_ = private unnamed_addr constant [15 x i8] c"myAsyncMethod:\00" // CHECK-isDarwin: @"_OBJC_$_PROTOCOL_INSTANCE_METHODS_MyAsyncProtocol" = // CHECK-isDarwin-SAME: [1 x %struct._objc_method] // CHECK-isDarwin-SAME: @OBJC_METH_VAR_NAME_ // CHECK-isDarwin-SAME: align [[ALIGNMENT]]
apache-2.0
2422d32b56522056dd1f057b2e86b974
48.863636
229
0.744758
3.385802
false
false
false
false
zoul/Movies
MovieKit/Movie.swift
1
2480
import Foundation // https://developers.themoviedb.org/3/movies/get-movie-details // // Note that while most (all?) of the fields are marked as optional // in the spec, we treat them as required, since there’s not much to do // with a movie without a title. public struct Movie { public let id: Int public let title: String public let voteAverage: Float public let backdropPath: String public let releaseDate: String public let overview: String // This is a simplistic view of the image support offered by the backend, // see https://developers.themoviedb.org/3/getting-started/images for details. public var backdropURL: URL? { return URL(string: "https://image.tmdb.org/t/p/w500" + backdropPath) } public var iconURL: URL? { return URL(string: "https://image.tmdb.org/t/p/w75" + backdropPath) } } extension Movie : JSONDecodable { public init?(jsonObject: Any) { guard let dict = jsonObject as? NSDictionary, let id = dict["id"] as? Int, let title = dict["title"] as? String, let voteAverage = dict["vote_average"] as? Float, let backdropPath = dict["backdrop_path"] as? String, let overview = dict["overview"] as? String, let releaseDate = dict["release_date"] as? String else { return nil } self.id = id self.title = title self.voteAverage = voteAverage self.backdropPath = backdropPath self.overview = overview self.releaseDate = releaseDate } } extension Movie { public static func withID(_ id: Int) -> Resource<Movie> { return Resource(url: URL(string: "https://api.themoviedb.org/3/movie/\(id)")!) } public static func popular(pageNumber: Int = 1) -> Resource<MovieListPage> { return Resource( url: URL(string: "https://api.themoviedb.org/3/movie/popular")!, urlParams: ["page": String(pageNumber)] ) } } extension Movie { public static let template = Movie(id: 157336, title: "Interstellar", voteAverage: 8.12, backdropPath: "/xu9zaAevzQ5nnrsXN6JcahLnG4i.jpg", releaseDate: "2014-11-05", overview: "Interstellar chronicles the adventures of a group of explorers who " + "make use of a newly discovered wormhole to surpass the limitations on human " + "space travel and conquer the vast distances involved in an interstellar voyage.") }
mit
7538255fb9a91307b5d8fb014623826b
33.901408
94
0.646086
3.990338
false
false
false
false
UniqHu/Youber
Youber/Youber/View/GuidePage.swift
1
2700
// // GuidePage.swift // Youber // // Created by uniqhj on 2017/3/20. // Copyright © 2017年 Hujian 😄. All rights reserved. // import UIKit import AVFoundation class GuidePage: YbBasePage { @IBOutlet weak var bgImgView: UIImageView! @IBOutlet weak var btnLogin: UIButton! @IBOutlet weak var btnRegister: UIButton! @IBOutlet weak var bgView: UIView! var player: AVPlayer! var playerItem: AVPlayerItem! var location: YbLocation! override func viewDidLoad() { super.viewDidLoad() btnLogin.layer.cornerRadius = 8 btnRegister.layer.cornerRadius = 8 setUpAvPlayer() guideAnimation() } func replayVideo(noti:NSNotification){ let item = noti.object as! AVPlayerItem item.seek(to: kCMTimeZero) player.play() } func setUpAvPlayer() { let path = Bundle.main.path(forResource: "welcome_video", ofType: "mp4") let url = NSURL.fileURL(withPath: path!) playerItem = AVPlayerItem(url: url) player = AVPlayer(playerItem: playerItem) let playerLayer = AVPlayerLayer(player: player) playerLayer.frame = bgView.frame playerLayer.videoGravity = AVLayerVideoGravityResizeAspect bgView.layer.insertSublayer(playerLayer, at: 0) bgView.alpha = 0 NotificationCenter.default.addObserver(self, selector:#selector(replayVideo(noti:)), name:NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) } func guideAnimation(){ var imgName:String? var img:UIImage? var imgArr :[UIImage] = [] for index in 1...67 { imgName = "logo-" + (NSString(format: "%03d", index) as String) img = UIImage(named: imgName!) imgArr.append(img!) } bgImgView.animationImages = imgArr bgImgView.animationDuration = 5 bgImgView.animationRepeatCount = 1 bgImgView.startAnimating() UIView.animate(withDuration: 0.7, delay: 5.1, options: .curveEaseInOut, animations: { self.bgView.alpha = 1 self.player.play() }) { (finished) in } } @IBAction func actionLogin(_ sender: UIButton) { location = YbLocation() location.startLocation() } @IBAction func actionRegister(_ sender: UIButton) { let page = CreateAccountPage() let navCon = UINavigationController(rootViewController: page) present(navCon, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
ef6b5379ead5a621576bc6e4809a05e1
28.282609
167
0.62101
4.70979
false
false
false
false
wangyun-hero/sinaweibo-with-swift
sinaweibo/Classes/Tools/Temp/WYTempViewController.swift
1
1572
// // WYTempViewController.swift // sinaweibo // // Created by 王云 on 16/8/30. // Copyright © 2016年 王云. All rights reserved. // import UIKit class WYTempViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //设置控制器的颜色 view.backgroundColor = UIColor.white // //设置左边的item // navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_back_withtext", title: "返回", target: self, action: #selector(back)) //设置右边的item navigationItem.rightBarButtonItem = UIBarButtonItem(title: "PUSH", target: self, action: #selector(push)) } // //点击左边item执行pop // func back () { // _ = navigationController?.popViewController(animated: true) // } //点击右边的item执行push func push (){ let vc = WYTempViewController() self.navigationController?.pushViewController(vc, animated: true) } 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
4d15edb6d43681c0d8a1e1d6f8c36fd2
25.696429
154
0.641472
4.657321
false
false
false
false
mnespor/AzureNotificationHubClient
Pod/Classes/NotificationHub.swift
1
2210
// // NotificationHub.swift // Pods // // Created by Matthew Nespor on 4/9/16. // // import Foundation public class NotificationHub { let endpoint: NSURL let path: String let tokenProvider: TokenProvider let storageManager: LocalStorage let apiVersion = "2013-04" let userAgentTemplate = "NOTIFICATIONHUBS/%@(api-origin=IosSdk; os=%@; os_version=%@;)" public static var version: String { return "v0.1" } public init?(connectionString: String, notificationHubPath: String) { let connectionInfo = HubHelper.parseConnectionString(connectionString) // swiftlint:disable opening_brace guard let endpointPath = connectionInfo["endpoint"], endpoint = NSURL(string: endpointPath) where endpoint.host != nil else { print("Endpoint is missing or is not in URL format in connectionString.") return nil } // swiftlint:enable opening_brace self.path = notificationHubPath self.endpoint = endpoint self.tokenProvider = TokenProvider(connectionDictionary: connectionInfo) self.storageManager = LocalStorage(notificationHubPath: notificationHubPath) } public func registerNative(deviceToken: NSData, tags: Set<String>, completion: ((ErrorType?) -> Void)?) { completion?(nil) } // swiftlint:disable function_parameter_count public func registerTemplate(deviceToken: NSData, name: String, jsonBodyTemplate: String, expiryTemplate: String, tags: Set<String>, completion: ((ErrorType?) -> Void)?) { completion?(nil) } // swiftlint:enable function_parameter_count public func unregisterNative(completion: ((ErrorType?) -> Void)?) { completion?(nil) } public func unregisterTemplate(name: String, completion: ((ErrorType?) -> Void)?) { completion?(nil) } public func unregisterAll(deviceToken: NSData, completion: ((ErrorType?) -> Void)?) { completion?(nil) } }
apache-2.0
e287ff21aee36eacb312b4a541fd6ae2
30.571429
91
0.60543
4.944072
false
false
false
false
KenanAtmaca/Design-Patterns-Swift
Behavioral/Command.swift
1
956
// // Created by Kenan Atmaca // kenanatmaca.com // protocol DoorExecute { func execute() var doorName:String {get set} } class DoorOpen: DoorExecute { var doorName: String init(name:String) { self.doorName = name } func execute() { print("Opened door {\(self.doorName)}") } } class DoorClose: DoorExecute { var doorName: String init(name:String) { self.doorName = name } func execute() { print("Closed door {\(self.doorName)}") } } class Door { private var doorOpen:DoorExecute private var doorClose:DoorExecute init(name:String) { doorOpen = DoorOpen(name: name) doorClose = DoorClose(name: name) } func open() { doorOpen.execute() } func close() { doorClose.execute() } } let door = Door(name: "A Block") door.open() door.close()
gpl-3.0
b9c02e8b6a1c8cfe7bef5661e7dff12a
13.9375
47
0.548117
3.662835
false
false
false
false
HeMet/DLife
MVVMKit/MVVMKit/Utils/DynamicPropertyTyped.swift
1
2775
// // DynamicPropertyTyped.swift // DeclarativeUI // // Created by Евгений Губин on 17.04.15. // Copyright (c) 2015 SimbirSoft. All rights reserved. // import Foundation import ReactiveCocoa // let toMap = { (s: String) -> AnyObject? in return s } // let fromMap = { (o: AnyObject?) -> String in return o as! String } // var textProperty2 = DynamicPropertyTyped<String>(object: self.subviewHook, keyPath: "text", mapTo: toMap, mapFrom: fromMap) @objc public final class DynamicPropertyTyped<T>: RACDynamicPropertySuperclass, MutablePropertyType { public typealias Value = T public typealias MapToClosure = (T) -> AnyObject? public typealias MapFromClosure = (AnyObject?) -> T private weak var object: NSObject? private let keyPath: String private let mapTo: MapToClosure private let mapFrom: MapFromClosure /// The current value of the property, as read and written using Key-Value /// Coding. public var value: T { get { let temp: AnyObject? = object?.valueForKeyPath(keyPath) return mapFrom(temp) } set(newValue) { let temp: AnyObject? = mapTo(newValue) object?.setValue(temp, forKeyPath: keyPath) } } /// A producer that will create a Key-Value Observer for the given object, /// send its initial value then all changes over time, and then complete /// when the observed object has deallocated. /// /// By definition, this only works if the object given to init() is /// KVO-compliant. Most UI controls are not! public var producer: SignalProducer<Value, NoError> { if let object = object { return object.rac_valuesForKeyPath(keyPath, observer: nil).toSignalProducer() |> map(mapFrom) // Errors aren't possible, but the compiler doesn't know that. |> catch { error in assert(false, "Received unexpected error from KVO signal: \(error)") return .empty } } else { return .empty } } /// Initializes a property that will observe and set the given key path of /// the given object. `object` must support weak references! public init(object: NSObject?, keyPath: String, mapTo: MapToClosure, mapFrom: MapFromClosure) { self.object = object self.keyPath = keyPath self.mapTo = mapTo self.mapFrom = mapFrom /// DynamicProperty stay alive as long as object is alive. /// This is made possible by strong reference cycles. super.init() object?.rac_willDeallocSignal()?.toSignalProducer().start(completed: { self }) } }
mit
38f30e666ffc7834fa303d6b7900a6d6
35.84
133
0.625407
4.574503
false
false
false
false
alexiosdev/IBAnimatable
IBAnimatableApp/GradientViewController.swift
1
2812
// // Created by jason akakpo on 27/07/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit import IBAnimatable class GradientViewController: UIViewController { @IBOutlet weak var gView: AnimatableView! let gradientValues = ParamType.init(fromEnum: GradientType.self) let startPointValues = ParamType.init(fromEnum: GradientStartPoint.self) let colorValues = ParamType.init(fromEnum: ColorType.self) var usePredefinedGradient = true lazy var componentValues: [ParamType] = { return self.usePredefinedGradient ? [self.gradientValues, self.startPointValues] : [self.colorValues, self.colorValues, self.startPointValues] }() override func viewDidLoad() { super.viewDidLoad() if usePredefinedGradient { gView.predefinedGradient = GradientType(rawValue: gradientValues.value(at: 0)) gView.startPoint = GradientStartPoint(rawValue: startPointValues.value(at: 0)) ?? .top } else { gView.startColor = ColorType(rawValue: self.colorValues.value(at: 0))?.color gView.endColor = ColorType(rawValue: self.colorValues.value(at: 0))?.color } } } extension GradientViewController : UIPickerViewDelegate, UIPickerViewDataSource { func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return componentValues[component].count() } func numberOfComponents(in pickerView: UIPickerView) -> Int { return componentValues.count } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let label = UILabel() label.textColor = .white label.textAlignment = .center label.minimumScaleFactor = 0.5 label.text = componentValues[component].title(at: row) return label } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { return componentValues[component].title(at: row).colorize(.white) } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if usePredefinedGradient { gView.predefinedGradient = GradientType(rawValue: gradientValues.value(at: pickerView.selectedRow(inComponent: 0))) gView.startPoint = GradientStartPoint(rawValue: startPointValues.value(at: pickerView.selectedRow(inComponent: 1))) ?? .top } else { gView.startColor = ColorType(rawValue: self.colorValues.value(at: pickerView.selectedRow(inComponent: 0)))?.color gView.endColor = ColorType(rawValue: self.colorValues.value(at: pickerView.selectedRow(inComponent: 1)))?.color gView.startPoint = GradientStartPoint(rawValue: startPointValues.value(at: pickerView.selectedRow(inComponent: 2))) ?? .top } gView.configureGradient() } }
mit
24208a46ea2cc7a64edde43b0b01a8e9
42.246154
146
0.743863
4.447785
false
false
false
false
mihaicris/digi-cloud
Digi Cloud/Extensions/Date+DigiCloud.swift
1
3142
// // Date+DigiCloud.swift // Digi Cloud // // Created by Mihai Cristescu on 29/03/2017. // Copyright © 2017 Mihai Cristescu. All rights reserved. // import Foundation extension Date { var timeAgoSyle: String { let minute = 60 let hour = 60 * minute let day = 24 * hour let week = 7 * day let month = 4 * week let year = 12 * month let secondsAgo = Int(Date().timeIntervalSince(self)) var output: String = "" switch secondsAgo { case 0..<2: output = NSLocalizedString("now", comment: "") case 2..<minute: output = "\(secondsAgo) seconds ago" case minute..<hour: let localizedString: String let minutesAgo = secondsAgo / minute if minutesAgo == 1 { localizedString = NSLocalizedString("%d minute ago", comment: "") } else { localizedString = NSLocalizedString("%d minutes ago", comment: "") } output = String(format: localizedString, minutesAgo) case hour..<day: let localizedString: String let hoursAgo = secondsAgo / hour if hoursAgo == 1 { localizedString = NSLocalizedString("%d hour ago", comment: "") } else { localizedString = NSLocalizedString("%d hours ago", comment: "") } output = String(format: localizedString, hoursAgo) case day..<week: let localizedString: String let daysAgo = secondsAgo / day if daysAgo == 1 { localizedString = NSLocalizedString("yesterday", comment: "") } else { localizedString = NSLocalizedString("%d days ago", comment: "") } output = String(format: localizedString, daysAgo) case week..<month: let localizedString: String let weeksAgo = secondsAgo / week if weeksAgo == 1 { localizedString = NSLocalizedString("last week", comment: "") } else { localizedString = NSLocalizedString("%d weeks ago", comment: "") } output = String(format: localizedString, weeksAgo) case month..<year: let localizedString: String let monthsAgo = secondsAgo / month if monthsAgo == 1 { localizedString = NSLocalizedString("last month", comment: "") } else { localizedString = NSLocalizedString("%d months ago", comment: "") } output = String(format: localizedString, monthsAgo) default: let localizedString: String let yearsAgo = secondsAgo / year if yearsAgo == 1 { localizedString = NSLocalizedString("last year", comment: "") } else { localizedString = NSLocalizedString("%d years ago", comment: "") } output = String(format: localizedString, yearsAgo) } return output } }
mit
44e3642221b1fb1b66747e8ef08204be
26.077586
82
0.532315
5.453125
false
false
false
false
arn00s/cariocamenu
Sources/CariocaGestureManager.swift
1
6936
// // CariocaGestureManager.swift // CariocaMenu // // Created by Arnaud Schloune on 21/11/2017. // Copyright © 2017 CariocaMenu. All rights reserved. // import Foundation import UIKit ///Manages all the gestures class CariocaGestureManager { ///The hostview of the menu let hostView: UIView ///The menu's controller let controller: CariocaController ///The edges of the menu let edges: [UIRectEdge] ///The edge gestures let edgePanGestures: [UIScreenEdgePanGestureRecognizer] = [] ///The events delegate weak var delegate: CariocaGestureManagerDelegate? ///The Y position in which the ScreenEdgePan started. var originalScreeenEdgePanY: CGFloat = 0.0 ///The menu's container let container: CariocaMenuContainerView ///Internal selection index, used to check index changes. private var internalSelectedIndex: Int ///Initialises the gesture manager ///- Parameter hostView: The menu's host view ///- Parameter controller: The menu's content controller ///- Parameter edges: The menu's edges ///- Parameter container: The menu's container view ///- Parameter selectedIndex: The menu's default selected index init(hostView: UIView, controller: CariocaController, edges: [UIRectEdge], container: CariocaMenuContainerView, selectedIndex: Int) { //TODO: Check that the edges are only .left or .right, as they are the only supported self.hostView = hostView self.controller = controller self.edges = edges self.container = container self.internalSelectedIndex = selectedIndex makeEdgePanGestures() } ///Create the required gestures depending on the edges func makeEdgePanGestures() { edges.forEach { edge in let panGesture = UIScreenEdgePanGestureRecognizer(target: self, action: .pannedFromScreenEdge) panGesture.edges = edge hostView.addGestureRecognizer(panGesture) } } ///Pan gesture event received ///- Parameter gesture: UIScreenEdgePanGestureRecognizer @objc func panGestureEvent(_ gesture: UIScreenEdgePanGestureRecognizer) { let yLocation = gesture.location(in: gesture.view).y panned(yLocation: yLocation, edge: gesture.edges, state: gesture.state) } ///Manages the panning in the view ///- Parameter yLocation: The gesture's location ///- Parameter edge: The edge where the gesture started ///- Parameter state: The gesture state ///- Parameter state: The gesture state ///- Parameter fromGesture: When called from rotation event, some method calls are optionl. Default: true func panned(yLocation: CGFloat, edge: UIRectEdge, state: UIGestureRecognizerState, fromGesture: Bool = true) { if state == .began { if fromGesture { delegate?.willOpenFromEdge(edge: edge) } delegate?.didUpdateSelectionIndex(internalSelectedIndex, selectionFeedback: fromGesture) originalScreeenEdgePanY = yLocation } if state == .changed { let frameHeight = hostView.frame.height let rangeUpperBound = container.menuHeight > frameHeight ? frameHeight : (frameHeight - container.menuHeight) let yRange: ClosedRange<CGFloat> = 20.0...rangeUpperBound let topY = CariocaGestureManager.topYConstraint(yLocation: yLocation, originalScreeenEdgePanY: originalScreeenEdgePanY, menuHeight: container.menuHeight, heightForRow: controller.heightForRow(), selectedIndex: delegate?.selectedIndex ?? internalSelectedIndex, yRange: yRange, isOffscreenAllowed: controller.isOffscreenAllowed) container.topConstraint.constant = topY let newIndex = CariocaGestureManager.matchingIndex(yLocation: yLocation, menuYPosition: topY, heightForRow: controller.heightForRow(), numberOfMenuItems: controller.menuItems.count) if newIndex != internalSelectedIndex { delegate?.didUpdateSelectionIndex(newIndex, selectionFeedback: fromGesture) } internalSelectedIndex = newIndex } if state == .ended { delegate?.didSelectItem(at: internalSelectedIndex) } if state == .failed { CariocaMenu.log("Failed Gesture") } if state == .possible { CariocaMenu.log("Possible Gesture") } if state == .cancelled { CariocaMenu.log("cancelled Gesture") } } // swiftlint:disable function_parameter_count ///Calculates the y top constraint, to move the menu ///- Parameter yLocation: The gesture's location ///- Parameter originalScreenEdgePanY: The Y location where the gesture started ///- Parameter menuHeight: The total menu height ///- Parameter heightForRow: The height of each menu item ///- Parameter selectedIndex: The menu's previously selected index ///- Parameter yRange: The y range representing the top/bottom Y limits where the menu can go ///- Parameter isOffscreenAllowed: Can the menu go out of the screen ? ///- Returns: CGFloat: The new menu's Y position class func topYConstraint(yLocation: CGFloat, originalScreeenEdgePanY: CGFloat, menuHeight: CGFloat, heightForRow: CGFloat, selectedIndex: Int, yRange: ClosedRange<CGFloat>, isOffscreenAllowed: Bool) -> CGFloat { var yPosition = originalScreeenEdgePanY - (heightForRow * CGFloat(selectedIndex)) - (heightForRow / 2.0) + originalScreeenEdgePanY - yLocation if !isOffscreenAllowed { if yPosition < yRange.lowerBound { yPosition = yRange.lowerBound } else if yPosition > yRange.upperBound { yPosition = yRange.upperBound } } return yPosition } // swiftlint:enable function_parameter_count ///Calculates the menu's matching index based on Y position ///- Parameter yLocation: The gesture's location ///- Parameter menuYPosition: The menu's Y top constraint value ///- Parameter heightForRow: The menu's item height ///- Parameter numberOfMenuItems: The number of items in the menu ///- Returns: Int: The matching index class func matchingIndex(yLocation: CGFloat, menuYPosition: CGFloat, heightForRow: CGFloat, numberOfMenuItems: Int) -> Int { var matchingIndex = Int(floor((yLocation - menuYPosition) / heightForRow)) //check if < 0 or > numberOfMenuItems matchingIndex = (matchingIndex < 0) ? 0 : ((matchingIndex > numberOfMenuItems - 1) ? (numberOfMenuItems - 1) : matchingIndex) return matchingIndex } }
mit
bc165f625b10e5cbb327d4a5b6d3e339
42.074534
111
0.659841
4.904526
false
false
false
false