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
JaySonGD/SwiftDayToDay
iOS9 之后的定位/iOS9 之后的定位/ViewController.swift
1
2128
// // ViewController.swift // iOS9 之后的定位 // // Created by czljcb on 16/3/10. // Copyright © 2016年 czljcb. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController { //前台 //1.0 locationMgr.requestWhenInUseAuthorization() // 后台 /* 1.0 locationMgr.requestWhenInUseAuthorization() if #available(iOS 9.0, *) { locationMgr.allowsBackgroundLocationUpdates = true; // locationMgr.allowsBackgroundLocationUpdates = true; 必须勾选backround model update location }*/ /*2.0 if #available(iOS 8.0, *) { //info key locationMgr.requestAlwaysAuthorization() if #available(iOS 9.0, *) { locationMgr.allowsBackgroundLocationUpdates = true; // locationMgr.allowsBackgroundLocationUpdates = true; 必须勾选backround model update location } } */ lazy var locationMgr: CLLocationManager = { let locationMgr = CLLocationManager() locationMgr.delegate = self if #available(iOS 8.0, *) { //locationMgr.requestWhenInUseAuthorization() //info key locationMgr.requestAlwaysAuthorization() if #available(iOS 9.0, *) { locationMgr.allowsBackgroundLocationUpdates = true; // locationMgr.allowsBackgroundLocationUpdates = true; 必须勾选backround model update location } } return locationMgr }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. locationMgr.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: CLLocationManagerDelegate{ func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("555") } }
mit
d54f1831445c8984d11cdc955667ab70
23.232558
106
0.620259
5.273418
false
false
false
false
drmohundro/Nimble
Nimble/Wrappers/ObjCMatcher.swift
1
3346
import Foundation struct ObjCMatcherWrapper : Matcher { let matcher: NMBMatcher let to: String let toNot: String func matches(actualExpression: Expression<NSObject?>, failureMessage: FailureMessage) -> Bool { failureMessage.to = to let pass = matcher.matches(({ actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location) return pass } func doesNotMatch(actualExpression: Expression<NSObject?>, failureMessage: FailureMessage) -> Bool { failureMessage.to = toNot let pass = matcher.matches(({ actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location) return !pass } } // Equivalent to Expectation, but simplified for ObjC objects only public class NMBExpectation : NSObject { let _actualBlock: () -> NSObject! var _negative: Bool let _file: String let _line: UInt var _timeout: NSTimeInterval = 1.0 public init(actualBlock: () -> NSObject!, negative: Bool, file: String, line: UInt) { self._actualBlock = actualBlock self._negative = negative self._file = file self._line = line } public var withTimeout: (NSTimeInterval) -> NMBExpectation { return ({ timeout in self._timeout = timeout return self }) } public var to: (matcher: NMBMatcher) -> Void { return ({ matcher in expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.to( ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not") ) }) } public var toNot: (matcher: NMBMatcher) -> Void { return ({ matcher in expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toNot( ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not") ) }) } public var notTo: (matcher: NMBMatcher) -> Void { return toNot } public var toEventually: (matcher: NMBMatcher) -> Void { return ({ matcher in expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toEventually( ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"), timeout: self._timeout ) }) } public var toEventuallyNot: (matcher: NMBMatcher) -> Void { return ({ matcher in expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toEventuallyNot( ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"), timeout: self._timeout ) }) } } @objc public class NMBObjCMatcher : NMBMatcher { let _matcher: (actualExpression: () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool init(matcher: (actualExpression: () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool) { self._matcher = matcher } public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { return _matcher( actualExpression: ({ actualBlock() as NSObject? }), failureMessage: failureMessage, location: location) } }
apache-2.0
2c1c7438c0768b8cc1b016d683a52e3a
35.369565
138
0.617454
4.920588
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/TamalesOaxaquenos/Area/Floor/Item/MOptionTamalesOaxaquenosAreaFloorItemGroundHill.swift
1
924
import UIKit class MOptionTamalesOaxaquenosAreaFloorItemGroundHill:MOptionTamalesOaxaquenosAreaFloorItemGroundProtocol { let hillHeight:CGFloat private(set) weak var textureGround:MGameTexture! private(set) weak var textureHill:MGameTexture! private(set) var positionX:CGFloat init( textureGround:MGameTexture, textureHill:MGameTexture, hillHeight:CGFloat, positionX:CGFloat) { self.textureGround = textureGround self.textureHill = textureHill self.hillHeight = hillHeight self.positionX = positionX } func factoryNode(controller:ControllerGame<MOptionTamalesOaxaquenos>) -> ViewGameNode<MOptionTamalesOaxaquenos>? { let node:VOptionTamalesOaxaquenosFloorGroundHill = VOptionTamalesOaxaquenosFloorGroundHill( controller:controller, model:self) return node } }
mit
fe8e0880955693759a9d6c780e84b6db
29.8
116
0.708874
5.220339
false
false
false
false
stowy/ReactiveTwitterSearch
ReactiveTwitterSearch/Service/TwitterSearchService.swift
1
2614
// // TwitterSearchService.swift // ReactiveTwitterSearch // // Created by Colin Eberhardt on 10/05/2015. // Copyright (c) 2015 Colin Eberhardt. All rights reserved. // import Foundation import Accounts import Social import ReactiveCocoa class TwitterSearchService { private let accountStore: ACAccountStore private let twitterAccountType: ACAccountType init() { accountStore = ACAccountStore() twitterAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) } func requestAccessToTwitterSignal() -> SignalProducer<Int, NSError> { return SignalProducer { sink, _ in self.accountStore.requestAccessToAccountsWithType(self.twitterAccountType, options: nil) { (granted, _) in if granted { sendCompleted(sink) } else { sendError(sink, TwitterInstantError.AccessDenied.toError()) } } } } func signalForSearchWithText(text: String) -> SignalProducer<TwitterResponse, NSError> { func requestforSearchText(text: String) -> SLRequest { let url = NSURL(string: "https://api.twitter.com/1.1/search/tweets.json") let params = [ "q" : text, "count": "100", "lang" : "en" ] return SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: url, parameters: params) } return SignalProducer { sink, disposable in let request = requestforSearchText(text) let maybeTwitterAccount = self.getTwitterAccount() if let twitterAccount = maybeTwitterAccount { request.account = twitterAccount println("performing request") request.performRequestWithHandler { (data, response, _) -> Void in println("response received") if response != nil && response.statusCode == 200 { let timelineData = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: nil) as! NSDictionary sendNext(sink, TwitterResponse(tweetsDictionary: timelineData)) sendCompleted(sink) } else { sendError(sink, TwitterInstantError.InvalidResponse.toError()) } } } else { sendError(sink, TwitterInstantError.NoTwitterAccounts.toError()) } } } private func getTwitterAccount() -> ACAccount? { let twitterAccounts = self.accountStore.accountsWithAccountType(self.twitterAccountType) as! [ACAccount] if twitterAccounts.count == 0 { return nil } else { return twitterAccounts[0] } } }
mit
6fd776c59f0c628595cecae0c0fcd238
29.752941
130
0.662586
4.867784
false
false
false
false
colbylwilliams/bugtrap
iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/JIRA/Domain/JiraAvatarUrls.swift
1
1400
// // JiraAvatarUrls.swift // bugTrap // // Created by Colby L Williams on 1/27/15. // Copyright (c) 2015 bugTrap. All rights reserved. // import Foundation class JiraAvatarUrls : JsonSerializable { var size48 = "" var size32 = "" var size24 = "" var size16 = "" var isEmpty: Bool { return !size48.isEmpty || !size32.isEmpty || !size24.isEmpty || !size16.isEmpty } var largestAvailable: String? { return !size48.isEmpty ? size48 : !size32.isEmpty ? size32 : !size24.isEmpty ? size24 : !size16.isEmpty ? size16 : nil } init() { } init(size48: String, size32: String, size24: String, size16: String) { self.size48 = size48 self.size32 = size32 self.size24 = size24 self.size16 = size16 } class func deserialize (json: JSON) -> JiraAvatarUrls? { let size48 = json["48x48"].stringValue let size32 = json["32x32"].stringValue let size24 = json["24x24"].stringValue let size16 = json["16x16"].stringValue return JiraAvatarUrls(size48: size48, size32: size32, size24: size24, size16: size16) } class func deserializeAll(json: JSON) -> [JiraAvatarUrls] { var items = [JiraAvatarUrls]() if let jsonArray = json.array { for item: JSON in jsonArray { if let si = deserialize(item) { items.append(si) } } } return items } func serialize () -> NSMutableDictionary { let dict = NSMutableDictionary() return dict } }
mit
a444943a5a5db5b5472cbdfcd3cab76c
18.732394
120
0.667857
3.023758
false
false
false
false
lorentey/swift
validation-test/Sema/type_checker_perf/fast/rdar19836070.swift
11
321
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -solver-disable-shrink -disable-constraint-solver-performance-hacks -solver-enable-operator-designated-types // REQUIRES: tools-release,no_asan let _: (Character) -> Bool = { c in ("a" <= c && c <= "z") || ("A" <= c && c <= "Z") || c == "_" }
apache-2.0
f6e5b26f8314effaffb1af1b2e064fe0
52.5
183
0.641745
3.116505
false
false
false
false
wrld3d/wrld-example-app
ios/Include/WrldSDK/iphoneos12.0/WrldNavWidget.framework/Headers/WRLDNavWidgetBase.swift
6
2944
import UIKit import WrldUtils import WrldNav @objc public class WRLDNavWidgetBase: UIView, WRLDNavModelObserverProtocol { internal let navModeKeyPath = #keyPath(WRLDNavModel.navMode) internal let navTopViewPanelHeightKeyPath = #keyPath(WRLDNavWidgetBase.topPanelVisibleHeight) internal let navBottomViewPanelHeightKeyPath = #keyPath(WRLDNavWidgetBase.bottomPanelVisibleHeight) @objc public var observer: WRLDNavModelObserver @objc public func setViewVisibility(animate: Bool, hideViews: Bool) {} /** The current navigation mode. */ private var m_topPanelVisibleHeight: CGFloat = 0 @objc(topPanelVisibleHeight) public var topPanelVisibleHeight: CGFloat { set { if m_topPanelVisibleHeight != newValue { willChangeValue(forKey: navTopViewPanelHeightKeyPath) m_topPanelVisibleHeight = newValue didChangeValue(forKey: navTopViewPanelHeightKeyPath) } } get { return m_topPanelVisibleHeight } } /** The current navigation mode. */ private var m_bottomPanelVisibleHeight: CGFloat = 0 @objc(bottomPanelVisibleHeight) public var bottomPanelVisibleHeight: CGFloat { set { if m_bottomPanelVisibleHeight != newValue { willChangeValue(forKey: navBottomViewPanelHeightKeyPath) m_bottomPanelVisibleHeight = newValue didChangeValue(forKey: navBottomViewPanelHeightKeyPath) } } get { return m_bottomPanelVisibleHeight } } open func updateNavMode(animate: Bool) {} public override init(frame: CGRect) { observer = WRLDNavModelObserver() m_topPanelVisibleHeight = 0.0 m_bottomPanelVisibleHeight = 0.0 super.init(frame: frame) observer.delegate = self } public required init?(coder aDecoder: NSCoder) { observer = WRLDNavModelObserver() m_topPanelVisibleHeight = 0.0 m_bottomPanelVisibleHeight = 0.0 super.init(coder: aDecoder) observer.delegate = self } public func eventReceived(key: WRLDNavEvent) { if(key == WRLDNavEvent.widgetAnimateOut) { setViewVisibility(animate: true, hideViews: true) } else if(key == WRLDNavEvent.widgetAnimateIn) { setViewVisibility(animate: true, hideViews: false) } } public func changeReceived(keyPath: String) { if(keyPath == navModeKeyPath) { updateNavMode(animate: true) return; } } override public func layoutSubviews() { if let b = superview?.bounds { frame = b } super.layoutSubviews() updateNavMode(animate: false) } }
bsd-2-clause
928fd77c0fc8736ff1f3c9ad1f0d6905
27.582524
103
0.61447
4.866116
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSOperation.swift
1
16376
// 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 // #if DEPLOYMENT_ENABLE_LIBDISPATCH import Dispatch #if os(Linux) import CoreFoundation private func pthread_main_np() -> Int32 { return _CFIsMainThread() ? 1 : 0 } #endif #endif public class Operation: NSObject { let lock = Lock() internal weak var _queue: OperationQueue? internal var _cancelled = false internal var _executing = false internal var _finished = false internal var _ready = false internal var _dependencies = Set<Operation>() #if DEPLOYMENT_ENABLE_LIBDISPATCH internal var _group = DispatchGroup() internal var _depGroup = DispatchGroup() internal var _groups = [DispatchGroup]() #endif public override init() { super.init() #if DEPLOYMENT_ENABLE_LIBDISPATCH _group.enter() #endif } internal func _leaveGroups() { // assumes lock is taken #if DEPLOYMENT_ENABLE_LIBDISPATCH _groups.forEach() { $0.leave() } _groups.removeAll() _group.leave() #endif } /// - Note: Operations that are asynchronous from the execution of the operation queue itself are not supported since there is no KVO to trigger the finish. public func start() { main() finish() } internal func finish() { lock.lock() _finished = true _leaveGroups() lock.unlock() if let queue = _queue { queue._operationFinished(self) } #if DEPLOYMENT_ENABLE_LIBDISPATCH // The completion block property is a bit cagey and can not be executed locally on the queue due to thread exhaust potentials. // This sets up for some strange behavior of finishing operations since the handler will be executed on a different queue if let completion = completionBlock { DispatchQueue.global(attributes: .qosBackground).async { () -> Void in completion() } } #endif } public func main() { } public var isCancelled: Bool { return _cancelled } public func cancel() { lock.lock() _cancelled = true _leaveGroups() lock.unlock() } public var isExecuting: Bool { return _executing } public var isFinished: Bool { return _finished } // - Note: This property is NEVER used in the objective-c implementation! public var isAsynchronous: Bool { return false } public var isReady: Bool { return _ready } public func addDependency(_ op: Operation) { lock.lock() _dependencies.insert(op) op.lock.lock() #if DEPLOYMENT_ENABLE_LIBDISPATCH _depGroup.enter() op._groups.append(_depGroup) #endif op.lock.unlock() lock.unlock() } public func removeDependency(_ op: Operation) { lock.lock() _dependencies.remove(op) op.lock.lock() #if DEPLOYMENT_ENABLE_LIBDISPATCH let groupIndex = op._groups.index(where: { $0 === self._depGroup }) if let idx = groupIndex { let group = op._groups.remove(at: idx) group.leave() } #endif op.lock.unlock() lock.unlock() } public var dependencies: [Operation] { lock.lock() let ops = _dependencies.map() { $0 } lock.unlock() return ops } public var queuePriority: QueuePriority = .normal public var completionBlock: (() -> Void)? public func waitUntilFinished() { #if DEPLOYMENT_ENABLE_LIBDISPATCH _group.wait() #endif } public var threadPriority: Double = 0.5 /// - Note: Quality of service is not directly supported here since there are not qos class promotions available outside of darwin targets. public var qualityOfService: NSQualityOfService = .default public var name: String? internal func _waitUntilReady() { #if DEPLOYMENT_ENABLE_LIBDISPATCH _depGroup.wait() #endif _ready = true } } extension Operation { public enum QueuePriority : Int { case veryLow case low case normal case high case veryHigh } } public class BlockOperation: Operation { typealias ExecutionBlock = () -> Void internal var _block: () -> Void internal var _executionBlocks = [ExecutionBlock]() public init(block: () -> Void) { _block = block } override public func main() { lock.lock() let block = _block let executionBlocks = _executionBlocks lock.unlock() block() executionBlocks.forEach { $0() } } public func addExecutionBlock(_ block: () -> Void) { lock.lock() _executionBlocks.append(block) lock.unlock() } public var executionBlocks: [() -> Void] { lock.lock() let blocks = _executionBlocks lock.unlock() return blocks } } public let NSOperationQueueDefaultMaxConcurrentOperationCount: Int = Int.max internal struct _OperationList { var veryLow = [Operation]() var low = [Operation]() var normal = [Operation]() var high = [Operation]() var veryHigh = [Operation]() var all = [Operation]() mutating func insert(_ operation: Operation) { all.append(operation) switch operation.queuePriority { case .veryLow: veryLow.append(operation) break case .low: low.append(operation) break case .normal: normal.append(operation) break case .high: high.append(operation) break case .veryHigh: veryHigh.append(operation) break } } mutating func remove(_ operation: Operation) { if let idx = all.index(of: operation) { all.remove(at: idx) } switch operation.queuePriority { case .veryLow: if let idx = veryLow.index(of: operation) { veryLow.remove(at: idx) } break case .low: if let idx = low.index(of: operation) { low.remove(at: idx) } break case .normal: if let idx = normal.index(of: operation) { normal.remove(at: idx) } break case .high: if let idx = high.index(of: operation) { high.remove(at: idx) } break case .veryHigh: if let idx = veryHigh.index(of: operation) { veryHigh.remove(at: idx) } break } } mutating func dequeue() -> Operation? { if veryHigh.count > 0 { return veryHigh.remove(at: 0) } if high.count > 0 { return high.remove(at: 0) } if normal.count > 0 { return normal.remove(at: 0) } if low.count > 0 { return low.remove(at: 0) } if veryLow.count > 0 { return veryLow.remove(at: 0) } return nil } var count: Int { return all.count } func map<T>(_ transform: @noescape (Operation) throws -> T) rethrows -> [T] { return try all.map(transform) } } public class OperationQueue: NSObject { let lock = Lock() #if DEPLOYMENT_ENABLE_LIBDISPATCH var __concurrencyGate: DispatchSemaphore? var __underlyingQueue: DispatchQueue? let queueGroup = DispatchGroup() #endif var _operations = _OperationList() #if DEPLOYMENT_ENABLE_LIBDISPATCH internal var _concurrencyGate: DispatchSemaphore? { get { lock.lock() let val = __concurrencyGate lock.unlock() return val } } // This is NOT the behavior of the objective-c variant; it will never re-use a queue and instead for every operation it will create a new one. // However this is considerably faster and probably more effecient. internal var _underlyingQueue: DispatchQueue { lock.lock() if let queue = __underlyingQueue { lock.unlock() return queue } else { let effectiveName: String if let requestedName = _name { effectiveName = requestedName } else { effectiveName = "NSOperationQueue::\(unsafeAddress(of: self))" } let attr: DispatchQueueAttributes if maxConcurrentOperationCount == 1 { attr = .serial } else { attr = .concurrent if maxConcurrentOperationCount != NSOperationQueueDefaultMaxConcurrentOperationCount { __concurrencyGate = DispatchSemaphore(value:maxConcurrentOperationCount) } } let queue = DispatchQueue(label: effectiveName, attributes: attr) if _suspended { queue.suspend() } __underlyingQueue = queue lock.unlock() return queue } } #endif public override init() { super.init() } #if DEPLOYMENT_ENABLE_LIBDISPATCH internal init(_queue queue: DispatchQueue, maxConcurrentOperations: Int = NSOperationQueueDefaultMaxConcurrentOperationCount) { __underlyingQueue = queue maxConcurrentOperationCount = maxConcurrentOperations super.init() queue.setSpecific(key: OperationQueue.OperationQueueKey, value: Unmanaged.passUnretained(self)) } #endif internal func _dequeueOperation() -> Operation? { lock.lock() let op = _operations.dequeue() lock.unlock() return op } public func addOperation(_ op: Operation) { addOperations([op], waitUntilFinished: false) } internal func _runOperation() { if let op = _dequeueOperation() { if !op.isCancelled { op._waitUntilReady() if !op.isCancelled { op.start() } } } } public func addOperations(_ ops: [Operation], waitUntilFinished wait: Bool) { #if DEPLOYMENT_ENABLE_LIBDISPATCH var waitGroup: DispatchGroup? if wait { waitGroup = DispatchGroup() } #endif /* If QueuePriority was not supported this could be much faster since it would not need to have the extra book-keeping for managing a priority queue. However this implementation attempts to be similar to the specification. As a concequence this means that the dequeue may NOT nessicarly be the same as the enqueued operation in this callout. So once the dispatch_block is created the operation must NOT be touched; since it has nothing to do with the actual execution. The only differential is that the block enqueued to dispatch_async is balanced with the number of Operations enqueued to the NSOperationQueue. */ ops.forEach { (operation: Operation) -> Void in lock.lock() operation._queue = self _operations.insert(operation) lock.unlock() #if DEPLOYMENT_ENABLE_LIBDISPATCH if let group = waitGroup { group.enter() } let block = DispatchWorkItem(group: queueGroup, flags: .enforceQoS) { () -> Void in if let sema = self._concurrencyGate { sema.wait() self._runOperation() sema.signal() } else { self._runOperation() } if let group = waitGroup { group.leave() } } _underlyingQueue.async(execute: block) #endif } #if DEPLOYMENT_ENABLE_LIBDISPATCH if let group = waitGroup { group.wait() } #endif } internal func _operationFinished(_ operation: Operation) { lock.lock() _operations.remove(operation) operation._queue = nil lock.unlock() } public func addOperationWithBlock(_ block: () -> Void) { let op = BlockOperation(block: block) op.qualityOfService = qualityOfService addOperation(op) } // WARNING: the return value of this property can never be used to reliably do anything sensible public var operations: [Operation] { lock.lock() let ops = _operations.map() { $0 } lock.unlock() return ops } // WARNING: the return value of this property can never be used to reliably do anything sensible public var operationCount: Int { lock.lock() let count = _operations.count lock.unlock() return count } public var maxConcurrentOperationCount: Int = NSOperationQueueDefaultMaxConcurrentOperationCount internal var _suspended = false public var suspended: Bool { get { return _suspended } set { lock.lock() if _suspended != newValue { _suspended = newValue #if DEPLOYMENT_ENABLE_LIBDISPATCH if let queue = __underlyingQueue { if newValue { queue.suspend() } else { queue.resume() } } #endif } lock.unlock() } } internal var _name: String? public var name: String? { get { lock.lock() let val = _name lock.unlock() return val } set { lock.lock() _name = newValue #if DEPLOYMENT_ENABLE_LIBDISPATCH __underlyingQueue = nil #endif lock.unlock() } } public var qualityOfService: NSQualityOfService = .default #if DEPLOYMENT_ENABLE_LIBDISPATCH // Note: this will return non nil whereas the objective-c version will only return non nil when it has been set. // it uses a target queue assignment instead of returning the actual underlying queue. public var underlyingQueue: DispatchQueue? { get { lock.lock() let queue = __underlyingQueue lock.unlock() return queue } set { lock.lock() __underlyingQueue = newValue lock.unlock() } } #endif public func cancelAllOperations() { lock.lock() let ops = _operations.map() { $0 } lock.unlock() ops.forEach() { $0.cancel() } } public func waitUntilAllOperationsAreFinished() { #if DEPLOYMENT_ENABLE_LIBDISPATCH queueGroup.wait() #endif } #if DEPLOYMENT_ENABLE_LIBDISPATCH static let OperationQueueKey = DispatchSpecificKey<Unmanaged<OperationQueue>>() #endif public class func currentQueue() -> OperationQueue? { #if DEPLOYMENT_ENABLE_LIBDISPATCH let specific = DispatchQueue.getSpecific(key: OperationQueue.OperationQueueKey) if specific == nil { if pthread_main_np() == 1 { return OperationQueue.mainQueue() } else { return nil } } else { return specific!.takeUnretainedValue() } #else return nil #endif } public class func mainQueue() -> OperationQueue { #if DEPLOYMENT_ENABLE_LIBDISPATCH let specific = DispatchQueue.main.getSpecific(key: OperationQueue.OperationQueueKey) if specific == nil { return OperationQueue(_queue: DispatchQueue.main, maxConcurrentOperations: 1) } else { return specific!.takeUnretainedValue() } #else fatalError("NSOperationQueue requires libdispatch") #endif } }
apache-2.0
cc72842019f2918f5b43eff343c73ec6
27.729825
160
0.57053
4.891278
false
false
false
false
Henawey/TheArabianCenter
TheArabianCenter/SyncModels.swift
1
4785
// // SyncModels.swift // TheArabianCenter // // Created by Ahmed Henawey on 2/25/17. // Copyright (c) 2017 Ahmed Henawey. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit import ObjectMapper import CoreLocation struct Sync { struct Save { /// Save Request, it conform Mappable Protocal to Make ObjectMapper able to serialize the object to JSON and vice versa struct Request : Mappable,Hashable{ var title:String var description:String var imageLocation:String? var lat:Double? var long:Double? init(title:String, description:String, imageLocation:String? = nil, location:CLLocation? = nil) { self.title = title self.description = description self.imageLocation = imageLocation lat = location?.coordinate.latitude long = location?.coordinate.longitude } init?(map: Map) { guard let title = map.JSON["title"] as? String, let description = map.JSON["description"] as? String, let imageLocation = map.JSON["imageLocation"] as? String else{ return nil } self.title = title self.description = description self.imageLocation = imageLocation } mutating func mapping(map: Map) { title <- map["title"] description <- map["description"] imageLocation <- map["imageLocation"] lat <- map["location.lat"] long <- map["location.long"] } var hashValue: Int{ get{ return "\(title),\(description),\(lat),\(long)".hashValue } } public static func ==(lhs: Sync.Save.Request, rhs: Sync.Save.Request) -> Bool{ return lhs.hashValue == rhs.hashValue } } } struct Retrieve { struct Request{ var id :String init(id :String) { self.id = id } } } /// Retrieve Response, it conform Mappable Protocal to Make ObjectMapper able to serialize the object to JSON and vice versa struct Response: Mappable{ var id :String var title:String var description:String var imageLocation:String init(id :String, title:String, description:String, imageLocation:String) { self.id = id self.title = title self.description = description self.imageLocation = imageLocation } init?(map: Map) { guard let id = map.JSON["id"] as? String, let title = map.JSON["title"] as? String, let description = map.JSON["description"] as? String, let imageLocation = map.JSON["imageLocation"] as? String else{ return nil } self.id = id self.title = title self.description = description self.imageLocation = imageLocation } mutating func mapping(map: Map) { id <- map["id"] title <- map["title"] description <- map["description"] imageLocation <- map["imageLocation"] } } struct ViewModel { var id :String var title:String var description:String var imageLocation:String } enum Error:Swift.Error { case unknownError case configurationMissing case invalidData case invalidResponse case failure(error:Swift.Error) var localizedDescription: String{ switch self { case .unknownError: return NSLocalizedString("unknownError", comment: "") case .configurationMissing: return NSLocalizedString("configurationMissing", comment: "") case .invalidData: return NSLocalizedString("InvalidData", comment: "") case .invalidResponse: return NSLocalizedString("invalidResponse", comment: "") case let .failure(error): return error.localizedDescription } } } }
mit
90e25a60d67dc2063012a3810e9ba269
30.9
128
0.511599
5.596491
false
false
false
false
ws2017tmm/weChat
weChat/Pods/KissXML/KissXML/DDXML.swift
7
1314
// // DDXML.swift // KissXML // // Created by David Chiles on 1/29/16. // // import Foundation #if os(iOS) || os(watchOS) || os(tvOS) public typealias XMLNode = DDXMLNode public typealias XMLElement = DDXMLElement public typealias XMLDocument = DDXMLDocument public let XMLInvalidKind = DDXMLInvalidKind public let XMLDocumentKind = DDXMLDocumentKind public let XMLElementKind = DDXMLElementKind public let XMLAttributeKind = DDXMLAttributeKind public let XMLNamespaceKind = DDXMLNamespaceKind public let XMLProcessingInstructionKind = DDXMLProcessingInstructionKind public let XMLCommentKind = DDXMLCommentKind public let XMLTextKind = DDXMLTextKind public let XMLDTDKind = DDXMLDTDKind public let XMLEntityDeclarationKind = DDXMLEntityDeclarationKind public let XMLAttributeDeclarationKind = DDXMLAttributeDeclarationKind public let XMLElementDeclarationKind = DDXMLElementDeclarationKind public let XMLNotationDeclarationKind = DDXMLNotationDeclarationKind public let XMLNodeOptionsNone = DDXMLNodeOptionsNone public let XMLNodeExpandEmptyElement = DDXMLNodeExpandEmptyElement public let XMLNodeCompactEmptyElement = DDXMLNodeCompactEmptyElement public let XMLNodePrettyPrint = DDXMLNodePrettyPrint #endif
apache-2.0
bdc50d7b17725ade867857d500bc6b38
40.0625
77
0.787671
4.692857
false
false
false
false
kejinlu/SwiftyText
SwiftyText/SwiftyLabel/SwiftyTextDetector.swift
1
5917
// // SwiftyTextDataDetector.swift // SwiftyText // // Created by Luke on 12/3/15. // Copyright © 2015 geeklu.com. All rights reserved. // import Foundation internal let SwiftyTextDetectorResultAttributeName: String = "SwiftyTextDetectorResult" public struct SwiftyTextDetectorType: OptionSetType { public let rawValue: UInt public init(rawValue: UInt){ self.rawValue = rawValue} public static let None = SwiftyTextDetectorType(rawValue: 0) public static let PhoneNumber = SwiftyTextDetectorType(rawValue: 1) public static let URL = SwiftyTextDetectorType(rawValue: 1 << 1) public static let Date = SwiftyTextDetectorType(rawValue: 1 << 2) public static let Address = SwiftyTextDetectorType(rawValue: 1 << 3) public static let All = SwiftyTextDetectorType(rawValue: UInt.max) } /** SwiftyTextDetector is a special kind of SwiftyTextParser which parse attributed string with regular expression */ public class SwiftyTextDetector: NSObject, SwiftyTextParser { public var name:String public var regularExpression: NSRegularExpression public var attributes: [String : AnyObject]? public var highlightedAttributes: [String : AnyObject]? public var replacementAttributedText:((checkingResult: NSTextCheckingResult, matchedAttributedText: NSAttributedString, sourceAttributedText: NSAttributedString) -> NSAttributedString?)? /// link attributes public var linkable: Bool = false public var linkGestures: SwiftyTextLinkGesture = [.Tap] public var highlightLayerRadius: CGFloat? public var highlightLayerColor: UIColor? public init(name:String, regularExpression: NSRegularExpression, attributes: [String : AnyObject]?) { self.name = name self.regularExpression = regularExpression self.attributes = attributes super.init() } public func parseText(attributedText: NSMutableAttributedString) { let text = attributedText.string let checkingResults = self.regularExpression.matchesInString(text, options: NSMatchingOptions(), range: NSMakeRange(0, text.characters.count)) for result in checkingResults.reverse() { let checkingRange = result.range var resultRange = checkingRange if checkingRange.location == NSNotFound { continue } let detectorResultAttribute = attributedText.attribute(SwiftyTextDetectorResultAttributeName, atIndex: checkingRange.location, longestEffectiveRange: nil, inRange: checkingRange) if detectorResultAttribute != nil { continue } if let attributes = self.attributes { attributedText.addAttributes(attributes, range: checkingRange) } if let replacementFunc = self.replacementAttributedText { let replacement = replacementFunc(checkingResult: result, matchedAttributedText: attributedText.attributedSubstringFromRange(checkingRange), sourceAttributedText: attributedText) if replacement != nil { attributedText.replaceCharactersInRange(checkingRange, withAttributedString: replacement!) resultRange.length = replacement!.length } } if self.linkable { let link = SwiftyTextLink() link.highlightedAttributes = self.highlightedAttributes if self.highlightLayerRadius != nil { link.highlightLayerRadius = self.highlightLayerRadius } if self.highlightLayerColor != nil { link.highlightLayerColor = self.highlightLayerColor } link.gestures = self.linkGestures if let URL = result.URL { link.URL = URL } if let phoneNumber = result.phoneNumber { link.phoneNumber = phoneNumber } if let date = result.date { link.date = date } if let timeZone = result.timeZone { link.timeZone = timeZone } if let addressComponents = result.addressComponents { link.addressComponents = addressComponents } attributedText.addAttribute(SwiftyTextLinkAttributeName, value: link, range: resultRange) } attributedText.addAttribute(SwiftyTextDetectorResultAttributeName, value: self, range: resultRange) } } public class func detectorWithType(type: SwiftyTextDetectorType) -> SwiftyTextDetector?{ var checkingTypes = NSTextCheckingType() if type.contains(.PhoneNumber) { checkingTypes = checkingTypes.union(.PhoneNumber) } if type.contains(.URL) { checkingTypes = checkingTypes.union(.Link) } if type.contains(.Date) { checkingTypes = checkingTypes.union(.Date) } if type.contains(.Address) { checkingTypes = checkingTypes.union(.Address) } do { let dataDetector = try NSDataDetector(types: checkingTypes.rawValue) let textDetector = SwiftyTextDetector(name: "Link", regularExpression: dataDetector, attributes: [NSForegroundColorAttributeName:UIColor(red: 0, green: 122/255.0, blue: 1.0, alpha: 1.0),NSUnderlineStyleAttributeName:NSUnderlineStyle.StyleSingle.rawValue]) textDetector.linkable = true return textDetector } catch { } return nil; } }
mit
31d1463000c17c650c137063fdd2537b
39.527397
267
0.622887
5.72147
false
false
false
false
farhanpatel/firefox-ios
Client/Frontend/Settings/AppSettingsTableViewController.swift
2
7827
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import Account /// App Settings Screen (triggered by tapping the 'Gear' in the Tab Tray Controller) class AppSettingsTableViewController: SettingsTableViewController { fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier" override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Settings", comment: "Title in the settings view controller title bar") navigationItem.leftBarButtonItem = UIBarButtonItem( title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"), style: UIBarButtonItemStyle.done, target: navigationController, action: #selector((navigationController as! SettingsNavigationController).SELdone)) navigationItem.leftBarButtonItem?.accessibilityIdentifier = "AppSettingsTableViewController.navigationItem.leftBarButtonItem" tableView.accessibilityIdentifier = "AppSettingsTableViewController.tableView" // Refresh the user's FxA profile upon viewing settings. This will update their avatar, // display name, etc. if AppConstants.MOZ_SHOW_FXA_AVATAR { profile.getAccount()?.updateProfile() } } override func generateSettings() -> [SettingSection] { var settings = [SettingSection]() let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title") let accountDebugSettings = [ // Debug settings: RequirePasswordDebugSetting(settings: self), RequireUpgradeDebugSetting(settings: self), ForgetSyncAuthStateDebugSetting(settings: self), StageSyncServiceDebugSetting(settings: self), ] let prefs = profile.prefs var generalSettings: [Setting] = [ SearchSetting(settings: self), NewTabPageSetting(settings: self), HomePageSetting(settings: self), OpenWithSetting(settings: self), BoolSetting(prefs: prefs, prefKey: "blockPopups", defaultValue: true, titleText: NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")), BoolSetting(prefs: prefs, prefKey: "saveLogins", defaultValue: true, titleText: NSLocalizedString("Save Logins", comment: "Setting to enable the built-in password manager")), ] let accountChinaSyncSetting: [Setting] if !profile.isChinaEdition { accountChinaSyncSetting = [] } else { accountChinaSyncSetting = [ // Show China sync service setting: ChinaSyncServiceSetting(settings: self) ] } // There is nothing to show in the Customize section if we don't include the compact tab layout // setting on iPad. When more options are added that work on both device types, this logic can // be changed. generalSettings += [ BoolSetting(prefs: prefs, prefKey: "showClipboardBar", defaultValue: false, titleText: Strings.SettingsOfferClipboardBarTitle, statusText: Strings.SettingsOfferClipboardBarStatus) ] var accountSectionTitle: NSAttributedString? if AppConstants.MOZ_SHOW_FXA_AVATAR { accountSectionTitle = NSAttributedString(string: Strings.FxAFirefoxAccount) } let footerText = !profile.hasAccount() ? NSAttributedString(string: Strings.FxASyncUsageDetails) : nil settings += [ SettingSection(title: accountSectionTitle, footerTitle: footerText, children: [ // Without a Firefox Account: ConnectSetting(settings: self), AdvanceAccountSetting(settings: self), // With a Firefox Account: AccountStatusSetting(settings: self), SyncNowSetting(settings: self) ] + accountChinaSyncSetting + accountDebugSettings)] settings += [ SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings)] var privacySettings = [Setting]() privacySettings.append(LoginsSetting(settings: self, delegate: settingsDelegate)) privacySettings.append(TouchIDPasscodeSetting(settings: self)) privacySettings.append(ClearPrivateDataSetting(settings: self)) privacySettings += [ BoolSetting(prefs: prefs, prefKey: "settings.closePrivateTabs", defaultValue: false, titleText: NSLocalizedString("Close Private Tabs", tableName: "PrivateBrowsing", comment: "Setting for closing private tabs"), statusText: NSLocalizedString("When Leaving Private Browsing", tableName: "PrivateBrowsing", comment: "Will be displayed in Settings under 'Close Private Tabs'")) ] if #available(iOS 11, *) { privacySettings.append(ContentBlockerSetting(settings: self)) } privacySettings += [ PrivacyPolicySetting() ] settings += [ SettingSection(title: NSAttributedString(string: privacyTitle), children: privacySettings), SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [ ShowIntroductionSetting(settings: self), SendFeedbackSetting(), SendAnonymousUsageDataSetting(prefs: prefs, delegate: settingsDelegate), OpenSupportPageSetting(delegate: settingsDelegate), ]), SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [ VersionSetting(settings: self), LicenseAndAcknowledgementsSetting(), YourRightsSetting(), ExportBrowserDataSetting(settings: self), DeleteExportedDataSetting(settings: self), EnableBookmarkMergingSetting(settings: self), ForceCrashSetting(settings: self) ])] if profile.hasAccount() { settings += [SettingSection(title: nil, footerTitle: NSAttributedString(string: ""), children: [DisconnectSetting(settings: self)])] } return settings } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = super.tableView(tableView, viewForHeaderInSection: section) as! SettingsTableSectionHeaderFooterView // Prevent the top border from showing for the General section. if !profile.hasAccount() { switch section { case 1: headerView.showTopBorder = false default: break } } return headerView } } extension AppSettingsTableViewController { func navigateToLoginsList() { let viewController = LoginListViewController(profile: profile) viewController.settingsDelegate = settingsDelegate navigationController?.pushViewController(viewController, animated: true) } } extension AppSettingsTableViewController: PasscodeEntryDelegate { @objc func passcodeValidationDidSucceed() { navigationController?.dismiss(animated: true) { self.navigateToLoginsList() } } }
mpl-2.0
055f3d199fce416b73472d360dac0804
45.041176
178
0.653763
6.216839
false
false
false
false
eflyjason/astro-daily
Astro Daily - APP/Astro Daily/OptionViewController.swift
1
11791
// // OptionViewController.swift // 星座運勢 // // Created by Arefly on 21/1/2015. // Copyright (c) 2015年 Arefly. All rights reserved. // import UIKit import CoreData import Foundation class OptionViewController: UIViewController { //设置视图 var name = [NSManagedObject]() var birthday = [NSManagedObject]() @IBOutlet var welcomeLabel: UILabel! @IBOutlet var datePicker: UITextField! @IBOutlet var user_name: UITextField! @IBOutlet var versionLabel: UILabel! @IBOutlet var made_by_arefly: UILabel! @IBOutlet var noticeTimePicker: UIDatePicker! @IBOutlet var noticeSwitch: UISwitch! @IBOutlet var noticeHiddenTime: UITextField! var localNotification = UILocalNotification() // You just need one var notificationsCounter = 0 @IBAction func onTouchedSave(sender: AnyObject) { if (datePicker.text.isEmpty) || (user_name.text.isEmpty) { let alert = UIAlertView() alert.title = "错误!" alert.message = "请输入姓名或生日!" alert.addButtonWithTitle("确定") alert.show() }else{ var userDefault = NSUserDefaults.standardUserDefaults() var name:String = user_name.text var name_without_spaces = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) userDefault.setObject(name_without_spaces, forKey: "name") //userDefault.del(name, forKey: "name") userDefault.synchronize() var birthday:String = datePicker.text var birthday_without_spaces = birthday.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) userDefault.setObject(birthday_without_spaces, forKey: "birthday") userDefault.synchronize() var noticeTime = noticeHiddenTime.text userDefault.setObject(noticeTime, forKey: "noticeTime") userDefault.synchronize() let alert = UIAlertView() alert.title = "完成!" alert.message = "已储存您的姓名及日期!" alert.addButtonWithTitle("确定") alert.show() /* 清空网页缓存开始 */ NSURLCache.sharedURLCache().removeAllCachedResponses() NSURLCache.sharedURLCache().diskCapacity = 0 NSURLCache.sharedURLCache().memoryCapacity = 0 /* 清空网页缓存结束 */ UIApplication.sharedApplication().cancelAllLocalNotifications() var optionsNoticeTime = userDefault.stringForKey("noticeTime") as String! optionsNoticeTime = optionsNoticeTime + ":00" let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm:ss" var everydayNoticeTime = dateFormatter.dateFromString(optionsNoticeTime) as NSDate! localNotification.fireDate = everydayNoticeTime localNotification.timeZone = NSTimeZone.localTimeZone() localNotification.repeatInterval = .CalendarUnitDay localNotification.alertAction = "查看今日运势" //localNotification.alertBody = today_info_substr localNotification.alertBody = "又是新的一天!快来看看你今天的运势怎么样吧!😆" localNotification.soundName = UILocalNotificationDefaultSoundName localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1 UIApplication.sharedApplication().scheduleLocalNotification(localNotification) let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewControllerWithIdentifier("mainView") as UIViewController // Explicit cast is required here. viewController.modalTransitionStyle = .CoverVertical self.presentViewController(viewController, animated: true, completion: nil) println("Saved Data and Back To Main View"); } } /* 生日键盘设置开始 */ @IBAction func dateTextInputPressed(sender: UITextField) { //Create the view let inputView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 240)) var datePickerView : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 40, 0, 0)) datePickerView.datePickerMode = UIDatePickerMode.Date datePickerView.locale = NSLocale(localeIdentifier: "zh_CN") var dateString = "2000-01-01" var df = NSDateFormatter() df.dateFormat = "yyyy-MM-dd" var date = df.dateFromString(dateString) if let unwrappedDate = date { datePickerView.setDate(unwrappedDate, animated: false) } inputView.addSubview(datePickerView) // add date picker to UIView //let doneButton = UIButton(frame: CGRectMake(110, 0, 100, 50)) let doneButton = UIButton(frame: CGRectMake((self.view.frame.size.width/2) - (100/2), 0, 100, 50)) doneButton.setTitle("完成", forState: UIControlState.Normal) doneButton.setTitle("完成", forState: UIControlState.Highlighted) doneButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) doneButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted) inputView.addSubview(doneButton) // add Button to UIView doneButton.addTarget(self, action: "doneButton:", forControlEvents: UIControlEvents.TouchUpInside) // set button click event sender.inputView = inputView datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged) handleDatePicker(datePickerView) // Set the date on start. } func handleDatePicker(sender: UIDatePicker) { var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" datePicker.text = dateFormatter.stringFromDate(sender.date) } func doneButton(sender:UIButton) { datePicker.resignFirstResponder() // To resign the inputView on clicking done. } /* 生日键盘设置结束 */ func notificationsOptions() { noticeTimePicker.hidden = true; noticeTimePicker.datePickerMode = UIDatePickerMode.Time noticeTimePicker.locale = NSLocale(localeIdentifier: "zh_CN") // you may add arbitrary key-value pairs to this dictionary. // However, the keys and values must be valid property-list types // if any are not, an exception is raised. // localNotification.userInfo = [NSObject : AnyObject]? } func noticeToggleSwitch(){ var userDefault = NSUserDefaults.standardUserDefaults() if noticeSwitch.on{ noticeTimePicker.userInteractionEnabled = true noticeTimePicker.hidden = false userDefault.setObject("ON", forKey: "noticeSwitch") userDefault.synchronize() println("Enable Notification!") } else { UIApplication.sharedApplication().cancelAllLocalNotifications() //localNotification.fireDate = NSDate(timeIntervalSinceNow: 999999999999) // will never be fired noticeTimePicker.userInteractionEnabled = false noticeTimePicker.hidden = true userDefault.setObject("OFF", forKey: "noticeSwitch") userDefault.synchronize() println("Disable Notification!") } } @IBAction func noticeSwitchPressed(sender: AnyObject) { noticeToggleSwitch() } @IBAction func noticeTimeChanged(sender: UIDatePicker) { var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" noticeHiddenTime.text = dateFormatter.stringFromDate(sender.date) } override func viewDidLoad() { super.viewDidLoad() if (self.view.frame.size.height > 600){ var version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as String var build = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as NSString) as String versionLabel.numberOfLines = 0; // Enable \n break line versionLabel.hidden = false; // Disable Hidden versionLabel.text = "V " + version + " (Build " + build + ")" }else{ versionLabel.hidden = true made_by_arefly.hidden = true } if self.restorationIdentifier == "startView" { welcomeLabel.numberOfLines = 0; welcomeLabel.text = "欢迎!\n\n让我们一起来看看我们\n每个人最独特的星座运势吧!" } notificationsOptions() let defaults = NSUserDefaults.standardUserDefaults() var name = defaults.stringForKey("name") as String! var birthday = defaults.stringForKey("birthday") as String! var noticeTime = defaults.stringForKey("noticeTime") as String! var noticeOnOff = defaults.stringForKey("noticeSwitch") as String! if (name == nil) { //DO NOTHING }else{ user_name.text = name } if (birthday == nil) { //DO NOTHING }else{ datePicker.text = birthday } if (noticeTime == nil) { //DO NOTHING }else{ var df = NSDateFormatter() df.dateFormat = "HH:mm" var date = df.dateFromString(noticeTime) if let unwrappedDate = date { noticeTimePicker.setDate(unwrappedDate, animated: false) } } if (noticeOnOff == nil) { //DO NOTHING }else{ if (noticeOnOff == "ON"){ noticeSwitch.on = true noticeToggleSwitch() } } } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } public extension NSDate { func xDays(x:Int) -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: x, toDate: self, options: nil)! } var day: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitDay, fromDate: self).day } var month: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: self).month } var year: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear, fromDate: self).year } var fireDate: NSDate { return NSCalendar.currentCalendar().dateWithEra(1, year: year, month: month, day: day, hour: 7, minute: 0, second: 0, nanosecond: 0)! } }
apache-2.0
4144bd8b0ee4a3731072a68fe1548619
34.58642
165
0.602775
5.514108
false
false
false
false
aiaio/DesignStudioExpress
DesignStudioExpress/Views/Subviews/UIButtonBase.swift
1
1612
// // UIButtonRounded.swift // DesignStudioExpress // // Created by Kristijan Perusko on 11/11/15. // Copyright © 2015 Alexander Interactive. All rights reserved. // import UIKit class UIButtonBase: UIButton { var defaultColor:UIColor { get{ return UIColor.whiteColor() } } var textColor:UIColor { get{ return UIColor.blueColor() } } let borderRadius = CGFloat(3) let titleFont = UIFont(name: "Avenir-Light", size: 13) let kerning: Float = 3.0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // set rounded corners self.layer.cornerRadius = borderRadius self.layer.borderWidth = 1 // colors self.layer.borderColor = defaultColor.CGColor self.backgroundColor = defaultColor self.setTitleColor(textColor, forState: UIControlState.Normal) self.setTitleColor(textColor, forState: UIControlState.Highlighted) // font self.titleLabel?.font = titleFont self.styleTitle(self.titleLabel?.text) } override func setTitle(title: String?, forState state: UIControlState) { super.setTitle(title, forState: state) self.styleTitle(title) } private func styleTitle(title: String?) { // set spacing between title characters to 3.0 if title != nil { let attributedString = NSMutableAttributedString(string: title!) self.titleLabel?.attributedText = NSAttributedString.attributedStringWithSpacing(attributedString, kerning: kerning) } } }
mit
3a748bd52b547d1e5e1d774ab25f0b55
30.607843
128
0.651769
4.823353
false
false
false
false
SuperJerry/Swift
queue.playground/Contents.swift
1
1117
//: Playground - noun: a place where people can play //import UIKit //var str = "Hello, playground" //println("hah") public class Queue{ var items: [Int] = [] public func enqueue(value:Int){ items.append(value) } public func dequeue() ->Int?{ if items.count > 0{ let obj = items.removeAtIndex(0) return obj }else{ return nil } } public func isEmpty() -> Bool{ if items.count > 0 { return false }else{ return true } } var description:String{ var description = "" if isEmpty() == false { let tempItem = self.items while !(self.isEmpty()){ description += "\(self.dequeue()!)" } self.items = tempItem } return description } } var queue = Queue() queue.isEmpty() println(queue.isEmpty()) //println("hah") queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) queue.enqueue(5) queue.enqueue(8) queue.dequeue() queue.description println(queue.description)
mit
4f113c6a83bdd137824cbac541a4bb40
16.730159
52
0.534467
4.106618
false
false
false
false
rymir/ConfidoIOS
ConfidoIOS/KeychainCertificate.swift
1
2961
// // Certificate.swift // // Created by Rudolph van Graan on 23/08/2015. // import Foundation public protocol Certificate { var secCertificate: SecCertificate! { get } var subject: String { get } func trustPoint(policy: TrustPolicy, additionalCertificates: [Certificate]) throws -> TrustPoint } public protocol RootCACertificate : Certificate { } public protocol IntermediateCACertificate: Certificate { } public protocol ClientAuthenticationCertificate: Certificate { } public class KeychainCertificate : KeychainItem, Certificate, KeychainCertificateClassProperties, KeychainFindable, GenerateKeychainFind { public typealias QueryType = TransportCertificate public typealias ResultType = KeychainCertificate public private(set) var secCertificate: SecCertificate! = nil public private(set) var subject: String = "" public class func keychainCertificateFromAttributes(SecItemAttributes attributes: SecItemAttributes) throws -> KeychainCertificate { return try KeychainCertificate(SecItemAttributes: attributes) } public class func certificate(derEncodedCertificateData: NSData) throws -> TransportCertificate { let secCertificate = SecCertificateCreateWithData(nil, derEncodedCertificateData) if secCertificate != nil { return TransportCertificate(secCertificate: secCertificate!) } throw KeychainError.InvalidCertificateData } class func getSecCertificate(SecItemAttributes attributes: NSDictionary) throws -> SecCertificate { if let valueRef: AnyObject = attributes[String(kSecValueRef)] { if CFGetTypeID(valueRef) == SecCertificateGetTypeID() { return (valueRef as! SecCertificate) } } throw KeychainError.NoSecCertificateReference } public init(SecItemAttributes attributes: SecItemAttributes) throws { super.init(securityClass: SecurityClass.Certificate, SecItemAttributes: attributes) self.secCertificate = try KeychainCertificate.getSecCertificate(SecItemAttributes: attributes) self.subject = SecCertificateCopySubjectSummary(self.secCertificate) as String } } /** Container class for an identity in a transportable format */ public class TransportCertificate : KeychainDescriptor, SecItemAddable, Certificate { public private(set) var subject: String public private(set) var secCertificate: SecCertificate! public init(secCertificate: SecCertificate, itemLabel: String? = nil) { self.secCertificate = secCertificate self.subject = SecCertificateCopySubjectSummary(secCertificate) as String super.init(securityClass: SecurityClass.Certificate, itemLabel: itemLabel) attributes[kSecValueRef as String] = secCertificate } public func addToKeychain() throws -> KeychainCertificate { try self.secItemAdd() return try KeychainCertificate.findInKeychain(self)! } }
mit
e1f0121f1cf4bf64bd1371bc78906806
38.48
136
0.749071
5.268683
false
false
false
false
koscida/Kos_AMAD_Spring2015
Spring_16/GRADE_projects/Project_1/Code/Kos_Project_1_Take_2/Kos_Project_1_Take_2/StudentTableViewCell.swift
1
1603
// // StudentTableViewCell.swift // Kos_Project_1_Take_2 // // Created by Brittany Kos on 3/2/16. // Copyright © 2016 Kode Studios. All rights reserved. // import UIKit class StudentTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var numDemeritLabel: UILabel! @IBOutlet weak var numCheckoutLabel: UILabel! var setFirst = false var setLast = false var firstName : String = "" { didSet { if(firstName != oldValue) { setFirst = true setName() } } } var lastName : String = "" { didSet { if(lastName != oldValue) { setLast = true setName() } } } var numDemerit : Int = 0 { didSet { if(numDemerit != oldValue) { numDemeritLabel.text = String(numDemerit) } } } var numCheckout : Int = 0 { didSet { if(numCheckout != oldValue) { numCheckoutLabel.text = String(numCheckout) } } } func setName() { if(setFirst && setLast) { nameLabel.text = firstName + " " + lastName } } 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 } }
gpl-3.0
207e66547824293a04df0c0292bfa5b0
20.078947
63
0.509363
4.643478
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/ScrollExample/ScrollMechanics/Sources/Utils/GeometryUtils.swift
1
1613
import Foundation import CoreGraphics public func getIntersection(segment1: (CGPoint, CGPoint), segment2: (CGPoint, CGPoint)) -> CGPoint? { let p1 = segment1.0 let p2 = segment1.1 let p3 = segment2.0 let p4 = segment2.1 let d = (p2.x - p1.x) * (p4.y - p3.y) - (p2.y - p1.y) * (p4.x - p3.x) if d == 0 { return nil // parallel lines } let u = ((p3.x - p1.x) * (p4.y - p3.y) - (p3.y - p1.y) * (p4.x - p3.x)) / d let v = ((p3.x - p1.x) * (p2.y - p1.y) - (p3.y - p1.y) * (p2.x - p1.x)) / d if u < 0.0 || u > 1.0 { return nil // intersection point is not between p1 and p2 } if v < 0.0 || v > 1.0 { return nil // intersection point is not between p3 and p4 } return CGPoint(x: p1.x + u * (p2.x - p1.x), y: p1.y + u * (p2.y - p1.y)) } public func getIntersection(rect: CGRect, segment: (CGPoint, CGPoint)) -> CGPoint? { let rMinMin = CGPoint(x: rect.minX, y: rect.minY) let rMinMax = CGPoint(x: rect.minX, y: rect.maxY) let rMaxMin = CGPoint(x: rect.maxX, y: rect.minY) let rMaxMax = CGPoint(x: rect.maxX, y: rect.maxY) if let point = getIntersection(segment1: (rMinMin, rMinMax), segment2: segment) { return point } if let point = getIntersection(segment1: (rMinMin, rMaxMin), segment2: segment) { return point } if let point = getIntersection(segment1: (rMinMax, rMaxMax), segment2: segment) { return point } if let point = getIntersection(segment1: (rMaxMin, rMaxMax), segment2: segment) { return point } return nil }
mit
7f313b5570b0cf71ec0da625bba62873
30.627451
101
0.572226
2.810105
false
false
false
false
thedistance/TheDistanceForms
TheDistanceFormsPhotosVideos/Classes/PhotosStack.swift
1
4032
// // PhotosStack.swift // Pods // // Created by Josh Campion on 15/02/2016. // // import UIKit import AdvancedOperationKit import TDStackView import TheDistanceCore open class PhotosStack: ErrorStack, ValueElement, PhotosStackManagerDelegate { public let mediaManager:PhotosStackManager public let mediaCollectionView:UICollectionView public let mediaCollectionViewHeightConstraint:NSLayoutConstraint public let addButton:UIButton private(set) public var addTarget:ObjectTarget<UIButton>? public let textField:UITextField public let contentStack:StackView public var validation:Validation<[PhotosStackAsset]>? public init(collectionView: UICollectionView, manager:PhotosStackManager, addButton: UIButton = UIButton(type: .system), textField:UITextField = UITextField(), errorLabel: UILabel = UILabel(), errorImageView: UIImageView = UIImageView(), iconImageView: UIImageView = UIImageView()) { mediaCollectionView = collectionView mediaCollectionView.backgroundColor = UIColor.clear mediaCollectionViewHeightConstraint = NSLayoutConstraint(item: mediaCollectionView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: 75.0) mediaCollectionView.addConstraint(mediaCollectionViewHeightConstraint) self.addButton = addButton self.textField = textField addButton.setTitle("Add Photo or Video", for: .normal) textField.isHidden = true mediaManager = manager contentStack = CreateStackView([mediaCollectionView, addButton, textField]) contentStack.axis = .vertical contentStack.spacing = 8.0 super.init(centerComponent: contentStack.view, errorLabel: errorLabel, errorImageView: errorImageView, iconImageView: iconImageView) mediaManager.delegate = self addTarget = ObjectTarget<UIButton>(control: addButton, forControlEvents: .touchUpInside, completion: addTapped) } open func addTapped(sender:UIButton) { mediaManager.newAssetFromSource(source: .view(sender)) } open func photosStackManager(stack: PhotosStackManager, selectedAsset: PhotosStackAsset) { updateMediaCollectionViewHeight() } open func photosStackManagerCancelled(stack: PhotosStackManager) { } public func updateMediaCollectionViewHeight() { let contentSize = mediaCollectionView.collectionViewLayout.collectionViewContentSize if contentSize.height != mediaCollectionViewHeightConstraint.constant { mediaCollectionViewHeightConstraint.constant = contentSize.height } } public func getValue() -> Any? { return mediaManager.mediaDataSource } public func setValue<T>(_ value: T?) -> Bool { guard let mediaObjects = value as? [PhotosStackAsset] else { return false } mediaManager.mediaDataSource = mediaObjects mediaManager.collectionView.reloadData() return true } public func validateValue() -> ValidationResult { let value = getValue() as? [PhotosStackAsset] let result = validation?.validate(value) ?? .valid if case .invalid(let message) = result { errorText = message } else { errorText = nil } return result } }
mit
30b81dae6e0757ace11b3b122cc181a0
34.06087
119
0.596974
6.155725
false
false
false
false
huonw/swift
test/SILGen/witness_same_type.swift
1
1471
// RUN: %target-swift-emit-silgen -module-name witness_same_type -enable-sil-ownership %s | %FileCheck %s // RUN: %target-swift-emit-ir -module-name witness_same_type -enable-sil-ownership %s protocol Fooable { associatedtype Bar func foo<T: Fooable>(x x: T) -> Self.Bar where T.Bar == Self.Bar } struct X {} // Ensure that the protocol witness for requirements with same-type constraints // is set correctly. <rdar://problem/16369105> // CHECK-LABEL: sil private [transparent] [thunk] @$S17witness_same_type3FooVAA7FooableA2aDP3foo1x3BarQzqd___tAaDRd__AHQyd__AIRSlFTW : $@convention(witness_method: Fooable) <τ_0_0 where τ_0_0 : Fooable, τ_0_0.Bar == X> (@in_guaranteed τ_0_0, @in_guaranteed Foo) -> @out X struct Foo: Fooable { typealias Bar = X func foo<T: Fooable>(x x: T) -> X where T.Bar == X { return X() } } // rdar://problem/19049566 // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$S17witness_same_type14LazySequenceOfVyxq_Gs0E0AAsAEP12makeIterator0H0QzyFTW : $@convention(witness_method: Sequence) <τ_0_0, τ_0_1 where τ_0_0 : Sequence, τ_0_1 == τ_0_0.Element> (@in_guaranteed LazySequenceOf<τ_0_0, τ_0_1>) -> @out AnyIterator<τ_0_1> public struct LazySequenceOf<SS : Sequence, A> : Sequence where SS.Iterator.Element == A { public func makeIterator() -> AnyIterator<A> { var opt: AnyIterator<A>? return opt! } public subscript(i : Int) -> A { get { var opt: A? return opt! } } }
apache-2.0
d0d03fb7c42b10a425401c8855aff0d0
40.685714
315
0.686086
2.98364
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Controllers/common/issues/GsPullListViewController.swift
1
5262
// // GsRepoPullViewController.swift // GitHubStar // // Created by midoks on 16/3/28. // Copyright © 2016年 midoks. All rights reserved. // import UIKit import SwiftyJSON class GsPullListViewController: GsListViewController { var _segmentedControl:UISegmentedControl? override func viewDidLoad() { super.viewDidLoad() self.delegate = self self.initSegmentedControl() } func initSegmentedControl(){ let items = ["open", "closed"] _segmentedControl = UISegmentedControl(items: items) _segmentedControl?.selectedSegmentIndex = 0 _segmentedControl?.addTarget(self, action: Selector(("segmentDidchange:")), for: .valueChanged) self.navigationItem.titleView = _segmentedControl } func segmentDidchange(segmented:UISegmentedControl){ let v = segmented.selectedSegmentIndex _tableView?.contentOffset.y = -(self.getNavBarHeight()) var url:String! if v == 0 { url = _fixedUrl + "?state=open" } else { url = _fixedUrl + "?state=closed" } self.refreshUrlFunc(url: url) } override func refreshUrl(){ super.refreshUrl() var url:String! if _segmentedControl?.selectedSegmentIndex == 0 { url = _fixedUrl + "?state=open" } else if _segmentedControl?.selectedSegmentIndex == 1 { url = _fixedUrl + "?state=closed" } else { url = _fixedUrl + "?state=open" } self.refreshUrlFunc(url: url) } func refreshUrlFunc(url:String){ self.startPull() GitHubApi.instance.urlGet(url: url) { (data, response, error) -> Void in self.pullingEnd() self._tableData = Array<JSON>() if data != nil { let _dataJson = self.gitJsonParse(data: data!) //print(_dataJson) for i in _dataJson { self._tableData.append(i.1) } let rep = response as! HTTPURLResponse if rep.allHeaderFields["Link"] != nil { let r = self.gitParseLink(urlLink: rep.allHeaderFields["Link"] as! String) self.pageInfo = r } self.asynTask(callback: { () -> Void in self._tableView?.reloadData() }) } } } func setUrlData(url:String){ _fixedUrl = url } } extension GsPullListViewController { func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var h:CGFloat = 50 let indexData = self.getSelectTableData(indexPath: indexPath) let cell = GsRepoPullCell(style: .default, reuseIdentifier: cellIdentifier) cell.pullName.text = indexData["title"].stringValue let size = cell.getSize(label: cell.pullName) if size.height > 18 { h += size.height - 18 } return h } } extension GsPullListViewController:GsListViewDelegate { func listTableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let indexData = self.getSelectTableData(indexPath: indexPath) let cell = GsRepoPullCell(style: .default, reuseIdentifier: cellIdentifier) cell.imageView?.MDCacheImage(url: indexData["user"]["avatar_url"].stringValue, defaultImage: "avatar_default") cell.setPullNameText(text: indexData["title"].stringValue) cell.timeShow.text = self.gitNowBeforeTime(gitTime: indexData["created_at"].stringValue) return cell } func listTableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let indexData = self.getSelectTableData(indexPath: indexPath) let v = GsPullHomeViewController() v.setPullUrlData(data: indexData) self.push(v: v) } func applyFilter(searchKey:String, data:JSON) -> Bool { let title = data["title"].stringValue.lowercased() if title.contains(searchKey.lowercased() ) { return true } return false } func pullUrlLoad(url: String){ GitHubApi.instance.webGet(absoluteUrl: url) { (data, response, error) -> Void in self.pullingEnd() if data != nil { let _dataJson = self.gitJsonParse(data: data!) for i in _dataJson { self._tableData.append(i.1) } let rep = response as! HTTPURLResponse if rep.allHeaderFields["Link"] != nil { let r = self.gitParseLink(urlLink: rep.allHeaderFields["Link"] as! String) self.pageInfo = r } self._tableView?.reloadData() } } } }
apache-2.0
e97237a66afd753de8ee9e0ca79a9294
30.118343
118
0.55752
4.924157
false
false
false
false
yangxiaodongcn/iOSAppBase
iOSAppBase/Carthage/Checkouts/ObjectMapper/Sources/DateFormatterTransform.swift
8
1831
// // DateFormatterTransform.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-03-09. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // 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 open class DateFormatterTransform: TransformType { public typealias Object = Date public typealias JSON = String let dateFormatter: DateFormatter public init(dateFormatter: DateFormatter) { self.dateFormatter = dateFormatter } open func transformFromJSON(_ value: Any?) -> Date? { if let dateString = value as? String { return dateFormatter.date(from: dateString) } return nil } open func transformToJSON(_ value: Date?) -> String? { if let date = value { return dateFormatter.string(from: date) } return nil } }
mit
848eadd259c0a1598d892a6bce2957df
32.907407
81
0.737302
4.170843
false
false
false
false
mrfour0004/AVScanner
Sources/AVScannerView/AVScannerView.swift
1
6637
// // AVScannerView.swift // AVScanner // // Created by mrfour on 2019/9/30. // import AVFoundation import UIKit public class AVScannerView: AVScannerPreviewView { // MARK: - Properties /// A boolean value represents whether the capture session is running. public var isSessionRunning: Bool { return sessionController.isSessionRunning } public var videoOrientation: AVCaptureVideoOrientation? { get { videoPreviewLayer.connection?.videoOrientation } set { guard let newValue = newValue else { return } videoPreviewLayer.connection?.videoOrientation = newValue if isSessionRunning { focusView.startAnimation() } } } /// An array of strings identifying the types of metadata objects which can be recoganized. /// /// Set this property to any types of metadata you want to support. The default value of this property is /// `[.qr]`. public var supportedMetadataObjectTypes: [AVMetadataObject.ObjectType] { get { sessionController.metadataObjectTypes } set { sessionController.metadataObjectTypes = newValue } } /// The object acts as the delegate of the scanner view. open weak var delegate: AVScannerViewDelegate? private let sessionController: AVCaptureSessionController private var windowOrientation: UIInterfaceOrientation { if #available(iOS 13.0, *) { return window?.windowScene?.interfaceOrientation ?? .unknown } else { return UIApplication.shared.statusBarOrientation } } // MARK: - Focus view private let focusView = AVScannerFocusView() // MARK: - Initializers public init(controller: AVCaptureSessionController = .init()) { self.sessionController = controller super.init(frame: .zero) prepareView() } public required init?(coder: NSCoder) { self.sessionController = AVCaptureSessionController() super.init(coder: coder) prepareView() } // MARK: - View lifecycle public override func layoutSubviews() { super.layoutSubviews() } } // MARK: - Camera Control extension AVScannerView { public func flip() { sessionController.stop() let blurEffectView = UIVisualEffectView() blurEffectView.frame = bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(blurEffectView) UIView.transition(with: self, duration: 0.4, options: [.transitionFlipFromLeft, .curveEaseInOut], animations: { blurEffectView.effect = UIBlurEffect(style: .light) }, completion: { _ in self.sessionController.flipCamera { [unowned sessionController = self.sessionController] in DispatchQueue.main.async { UIView.animate(withDuration: 0.2) { self.alpha = 0 } sessionController.start { _ in DispatchQueue.main.async { UIView.animate(withDuration: 0.2, animations: { self.alpha = 1 blurEffectView.effect = nil }, completion: { _ in blurEffectView.removeFromSuperview() }) } } } } }) } } // MARK: - Session Control extension AVScannerView { /// Initializes the capture session. /// /// You need to call this function to initialize the capture session before you calling `startSession()`. public func initSession() { session = sessionController.session videoPreviewLayer.videoGravity = .resizeAspectFill sessionController.initSession(withMetadataObjectsDelegate: self) { result in DispatchQueue.main.async { switch result { case .success: var initialVideoOrientation: AVCaptureVideoOrientation = .portrait if self.windowOrientation != .unknown, let videoOrientation = AVCaptureVideoOrientation(interfaceOrientation: self.windowOrientation) { initialVideoOrientation = videoOrientation } self.videoPreviewLayer.connection?.videoOrientation = initialVideoOrientation self.delegate?.scannerViewDidFinishConfiguration(self) case .failure(let error): self.delegate?.scannerView(self, didFailConfigurationWithError: error) } } } } /// Starts running the capture session. /// /// If the session has started, calling this function does nothing. public func startSession() { sessionController.start { result in DispatchQueue.main.async { switch result { case .success: self.focusView.startAnimation() self.delegate?.scannerViewDidStartSession(self) case .failure(let error): self.delegate?.scannerView(self, didFailStartingSessionWithError: error) } } } } /// Stops the capture session if the capture session is running. public func stopSession() { sessionController.stop() } } // MARK: - Prepare view private extension AVScannerView { func prepareView() { prepareFocusView() } func prepareFocusView() { addSubview(focusView) } } // MARK: - AVCaptureMetadataOutputObjectsDelegate extension AVScannerView: AVCaptureMetadataOutputObjectsDelegate { public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { DispatchQueue.main.async { guard let barcodeObject = metadataObjects.first, let transformedMetadataObject = self.videoPreviewLayer.transformedMetadataObject(for: barcodeObject) as? AVMetadataMachineReadableCodeObject else { return } self.sessionController.stop { [weak self] in guard let self = self else { return } DispatchQueue.main.async { self.focusView.transform(to: transformedMetadataObject.__corners) { self.delegate?.scannerView(self, didCapture: transformedMetadataObject) } } } } } }
mit
9c9cc744df16007285a838b3d7247ca1
33.21134
156
0.607805
5.910062
false
false
false
false
KenHeglund/Cavalla
Cavalla/CAVHIDElement.swift
1
2231
/*=========================================================================== CAVHIDElement.swift Cavalla Copyright (c) 2015-2016 Ken Heglund. All rights reserved. ===========================================================================*/ import Foundation import HIDSpecification /*==========================================================================*/ class CAVHIDElement: NSObject { private unowned let device: CAVHIDDevice let hidElementRef: IOHIDElement @objc dynamic var cookie: IOHIDElementCookie @objc dynamic let canEnable: Bool @objc dynamic var enabled: Bool { get { return self.device.queueContainsHIDElementRef( self.hidElementRef ) } set { guard self.canEnable else { return } if newValue == self.device.queueContainsHIDElementRef( self.hidElementRef ) { return } if newValue { self.device.enqueueHIDElementRef( self.hidElementRef ) } else { self.device.dequeueHIDElementRef( self.hidElementRef ) } } } @objc dynamic var nameString: String @objc dynamic var usageString: String @objc dynamic var sizeString: String /*==========================================================================*/ init( withHIDElementRef hidElementRef: IOHIDElement, device: CAVHIDDevice ) { self.device = device self.hidElementRef = hidElementRef self.cookie = IOHIDElementGetCookie( hidElementRef ) self.canEnable = ( IOHIDElementGetReportSize( hidElementRef ) > 0 ) let usage = Int( IOHIDElementGetUsage( hidElementRef ) & 0x0000FFFF ) let usagePage = Int( IOHIDElementGetUsagePage( hidElementRef ) & 0x0000FFFF ) self.nameString = HIDSpecification.nameForUsagePage( usagePage, usage: usage ) ?? "Custom Control" self.usageString = String( format: "0x%04X:0x%04X", usagePage, usage ) let size = Int( IOHIDElementGetReportSize( hidElementRef ) ) self.sizeString = String( format: "%lu", size ) } }
mit
7e8986f468c6b8b4bed0914117b14461
33.859375
106
0.528463
5.024775
false
false
false
false
vanab/ExpandableCell
ExpandableCellDemo/ViewController.swift
1
5941
// // ViewController.swift // ExpandableCellDemo // // Created by YiSeungyoun on 2017. 8. 6.. // Copyright © 2017년 SeungyounYi. All rights reserved. // import UIKit import ExpandableCell class ViewController: UIViewController { @IBOutlet weak var tableView: ExpandableTableView! var cell: UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: ExpandedCell.ID)! } override func viewDidLoad() { super.viewDidLoad() tableView.expandableDelegate = self tableView.register(UINib(nibName: "NormalCell", bundle: nil), forCellReuseIdentifier: NormalCell.ID) tableView.register(UINib(nibName: "ExpandedCell", bundle: nil), forCellReuseIdentifier: ExpandedCell.ID) tableView.register(UINib(nibName: "ExpandableCell", bundle: nil), forCellReuseIdentifier: ExpandableCell2.ID) CloseAllButton.action = #selector(closeAllButtonClicked) CloseAllButton.target = self } @IBOutlet var CloseAllButton: UIBarButtonItem! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func closeAllButtonClicked() { tableView.closeAll() } } extension ViewController: ExpandableDelegate { func expandableTableView(_ expandableTableView: ExpandableTableView, expandedCellsForRowAt indexPath: IndexPath) -> [UITableViewCell]? { switch indexPath.section { case 0: switch indexPath.row { case 0: let cell1 = tableView.dequeueReusableCell(withIdentifier: ExpandedCell.ID) as! ExpandedCell cell1.titleLabel.text = "First Expanded Cell" let cell2 = tableView.dequeueReusableCell(withIdentifier: ExpandedCell.ID) as! ExpandedCell cell2.titleLabel.text = "Sceond Expanded Cell" let cell3 = tableView.dequeueReusableCell(withIdentifier: ExpandedCell.ID) as! ExpandedCell cell3.titleLabel.text = "Third Expanded Cell" return [cell1, cell2, cell3] case 2: return [cell, cell] case 3: return [cell] default: break } default: break } return nil } func expandableTableView(_ expandableTableView: ExpandableTableView, heightsForExpandedRowAt indexPath: IndexPath) -> [CGFloat]? { switch indexPath.section { case 0: switch indexPath.row { case 0: return [44, 44, 44] case 2: return [33, 33, 33] case 3: return [22] default: break } default: break } return nil } func numberOfSections(in tableView: ExpandableTableView) -> Int { return 2 } func expandableTableView(_ expandableTableView: ExpandableTableView, numberOfRowsInSection section: Int) -> Int { return 5 } func expandableTableView(_ expandableTableView: ExpandableTableView, didSelectRowAt indexPath: IndexPath) { print("didSelectRow:\(indexPath)") } func expandableTableView(_ expandableTableView: ExpandableTableView, didSelectExpandedRowAt indexPath: IndexPath) { print("didSelectExpandedRowAt:\(indexPath)") } func expandableTableView(_ expandableTableView: ExpandableTableView, expandedCell: UITableViewCell, didSelectExpandedRowAt indexPath: IndexPath) { if let cell = expandedCell as? ExpandedCell { print("\(cell.titleLabel.text ?? "")") print(expandableTableView.) } } func expandableTableView(_ expandableTableView: ExpandableTableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: switch indexPath.row { case 0, 2, 3: guard let cell = expandableTableView.dequeueReusableCell(withIdentifier: ExpandableCell2.ID) else { return UITableViewCell() } return cell case 1, 4: guard let cell = expandableTableView.dequeueReusableCell(withIdentifier: NormalCell.ID) else { return UITableViewCell() } return cell default: break } case 1: switch indexPath.row { case 0, 1, 2, 3, 4: guard let cell = expandableTableView.dequeueReusableCell(withIdentifier: NormalCell.ID) else { return UITableViewCell() } return cell default: break } default: break } return UITableViewCell() } func expandableTableView(_ expandableTableView: ExpandableTableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: switch indexPath.row { case 0, 2, 3: return 66 case 1, 4: return 55 default: break } case 1: switch indexPath.row { case 0, 1, 2, 3, 4: return 55 default: break } default: break } return 44 } // func expandableTableView(_ expandableTableView: ExpandableTableView, titleForHeaderInSection section: Int) -> String? { // return "Section \(section)" // } // // func expandableTableView(_ expandableTableView: ExpandableTableView, heightForHeaderInSection section: Int) -> CGFloat { // return 33 // } }
mit
5817f7faf15cf010ddc98180b0d07939
31.271739
150
0.583361
5.518587
false
false
false
false
Keanyuan/SwiftContact
SwiftContent/SwiftContent/Classes/2.14构造过程/Animal.swift
1
714
// // Animal.swift // SwiftContent // // Created by 祁志远 on 2017/6/19. // Copyright © 2017年 祁志远. All rights reserved. // import UIKit enum TemperatureUnit{ case Kelvin, Celsius, Fahrenheit init?(symbol: Character) { switch symbol { case "K": self = .Kelvin case "C": self = .Celsius case "F": self = .Fahrenheit default: return nil } } } enum TemperatureUnitE: Character{ case Kelvin = "K", Celsius = "C", Fahrenheit = "F" } struct Animal { let species: String init?(species: String) { if species.isEmpty {return nil} self.species = species } }
mit
f32dd7a07d3901521163ded0ee94df24
16.475
54
0.542203
3.758065
false
false
false
false
rainpour/RPRxTableView
RPRxTableView/Classes/RPRxTableViewController.swift
1
4469
// // RPRxTableViewController.swift // RPRxTableView // // Created by Hoyeon KIM on 2017. 6. 8.. // Copyright © 2017 [email protected]. All rights reserved. // import UIKit import RxSwift import RxCocoa class RPRxTableViewController: UIViewController { // 꼭 스토리보드에서 UIViewController를 만든 후 TableView를 추가하고 이 해당 아웃렛을 연결해 준 후 사용해야 한다. @IBOutlet var tableView: UITableView! var refreshControl = UIRefreshControl() let disposeBag = DisposeBag() var viewModel = RPRxTableViewModel() override func viewDidLoad() { super.viewDidLoad() } internal func setCommonTableViewActions() { self.bindViewModelWithTableView() self.setPullToRefreshControl() self.setScrollToBottomLoading() } private func bindViewModelWithTableView() { self.viewModel.listItems.asObservable() .bind(to: self.tableView.rx.items) { _, _, item in // tableView, index, item return self.getTableViewCell(item: item) } .addDisposableTo(self.disposeBag) } internal func getTableViewCell(item _: RPRxTableModel) -> UITableViewCell { // Override return UITableViewCell() } internal func getNoItemsCell(text: String) -> UITableViewCell { let noItemsCell = UITableViewCell.init(style: .default, reuseIdentifier: "noItemsCell") noItemsCell.textLabel?.text = text noItemsCell.textLabel?.textColor = UIColor.red return noItemsCell } private func setPullToRefreshControl() { if #available(iOS 10.0, *) { self.tableView.refreshControl = self.refreshControl } else { // Fallback on earlier versions self.tableView.addSubview(self.refreshControl) } self.refreshControl.rx .controlEvent(.valueChanged) .filter { self.refreshControl.isRefreshing } .bind(to: self.viewModel.pullToRefresh) .addDisposableTo(self.disposeBag) self.viewModel.isEndRefresh .bind(onNext: { isEnd in if isEnd { self.refreshControl.endRefreshing() } }) .addDisposableTo(self.disposeBag) } private func setScrollToBottomLoading() { let marginOfBottomLoading: CGFloat = 40 self.tableView.rx .contentOffset .filter({ [unowned self] _ -> Bool in return self.tableView.contentSize.height != 0 }) .map { [unowned self] offset -> Bool in return (offset.y + self.tableView.frame.size.height + marginOfBottomLoading > self.tableView.contentSize.height) } .subscribe(onNext: { isBottom in if isBottom == true { self.viewModel.getTableItems(isFirst: false) } }, onError: { error in preconditionFailure("error[\(error)]") }) .addDisposableTo(self.disposeBag) } internal func setSelectedTableItem() { self.tableView.rx.itemSelected .subscribe(onNext: { indexPath in self.didSelectTableViewCell(indexPath: indexPath) }) .addDisposableTo(self.disposeBag) } internal func didSelectTableViewCell(indexPath _: IndexPath) { // Need Override } 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. } */ } extension RPRxTableViewController: UITableViewDelegate { func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_: UITableView, estimatedHeightForRowAt _: IndexPath) -> CGFloat { return 80 } func tableView(_: UITableView, heightForFooterInSection _: Int) -> CGFloat { return 0.01 } }
mit
8fdfc2322f8642aa2d951f5985714fa7
30.640288
128
0.615052
4.986395
false
false
false
false
Alecrim/AlecrimCoreData
Sources/Core/Query/Predicate.swift
1
3682
// // Predicate.swift // AlecrimCoreData // // Created by Vanderlei Martinelli on 11/03/18. // Copyright © 2018 Alecrim. All rights reserved. // import Foundation import CoreData // MARK: - public class Predicate<Entity: ManagedObject> { public let rawValue: NSPredicate public var predicateFormat: String { return self.rawValue.predicateFormat } public convenience init(format predicateFormat: String, argumentArray arguments: [Any]?) { self.init(rawValue: NSPredicate(format: predicateFormat, argumentArray: arguments)) } public convenience init(format predicateFormat: String, arguments argList: CVaListPointer) { self.init(rawValue: NSPredicate(format: predicateFormat, arguments: argList)) } public convenience init(value: Bool) { self.init(rawValue: NSPredicate(value: value)) } public init(rawValue: NSPredicate) { self.rawValue = rawValue } } // MARK: - public final class ComparisonPredicate<Entity: ManagedObject>: Predicate<Entity> { public typealias Modifier = NSComparisonPredicate.Modifier public typealias Operator = NSComparisonPredicate.Operator public typealias Options = NSComparisonPredicate.Options public let leftExpression: NSExpression public let rightExpression: NSExpression public let modifier: Modifier public let operatorType: Operator public let options: Options public init(leftExpression left: Expression, rightExpression right: Expression, modifier: Modifier, type operatorType: Operator, options: Options = []) { // self.leftExpression = left self.rightExpression = right self.modifier = modifier self.operatorType = operatorType self.options = options // let predicate = NSComparisonPredicate( leftExpression: self.leftExpression, rightExpression: self.rightExpression, modifier: self.modifier, type: self.operatorType, options: self.options ) super.init(rawValue: predicate) } } // MARK: - public final class CompoundPredicate<Entity: ManagedObject>: Predicate<Entity> { public typealias LogicalType = NSCompoundPredicate.LogicalType public let type: LogicalType public let subpredicates: [Predicate<Entity>] public init(type: LogicalType, subpredicates: [Predicate<Entity>]) { // self.type = type self.subpredicates = subpredicates // let predicate = NSCompoundPredicate(type: self.type, subpredicates: self.subpredicates.map { $0.rawValue }) super.init(rawValue: predicate) } public convenience init(andPredicateWithSubpredicates subpredicates: [Predicate<Entity>]) { self.init(type: .and, subpredicates: subpredicates) } public convenience init(orPredicateWithSubpredicates subpredicates: [Predicate<Entity>]) { self.init(type: .or, subpredicates: subpredicates) } public convenience init(notPredicateWithSubpredicate predicate: Predicate<Entity>) { self.init(type: .not, subpredicates: [predicate]) } } // MARK: - public func &&<Entity>(left: Predicate<Entity>, right: Predicate<Entity>) -> Predicate<Entity> { return CompoundPredicate<Entity>(type: .and, subpredicates: [left, right]) } public func ||<Entity>(left: Predicate<Entity>, right: Predicate<Entity>) -> Predicate<Entity> { return CompoundPredicate<Entity>(type: .or, subpredicates: [left, right]) } prefix public func !<Entity>(left: Predicate<Entity>) -> Predicate<Entity> { return CompoundPredicate<Entity>(type: .not, subpredicates: [left]) }
mit
cf1597eecbbf2ac4d9e02f9e60824d4d
28.214286
157
0.697365
4.824377
false
false
false
false
wdxgtsh/SwiftPasscodeLock
SwiftPasscodeLockTests/GenericPasscodeLockTests.swift
5
8220
// // GenericPasscodeLockTests.swift // SwiftPasscodeLock // // Created by Yanko Dimitrov on 11/27/14. // Copyright (c) 2014 Yanko Dimitrov. All rights reserved. // import UIKit import XCTest class PasscodeLockStub: PasscodeLock { var passcode: [String] { return [String]() } var state: PasscodeLockState? weak var delegate: PasscodeLockDelegate? func enterSign(sign: String) {} func removeSign(){} func resetSigns(){} init(){} } class PasscodeLockDelegateStub: PasscodeLockDelegate { func passcodeLockDidSucceed(passcodeLock: PasscodeLock) {} func passcodeLockDidFailed(passcodeLock: PasscodeLock) {} func passcodeLockDidReset(passcodeLock: PasscodeLock) {} func passcodeLock(passcodeLock: PasscodeLock, changedToState state: PasscodeLockState) {} func passcodeLock(passcodeLock: PasscodeLock, addedSignAtIndex index: Int) {} func passcodeLock(passcodeLock: PasscodeLock, removedSignAtIndex index: Int) {} } class PasscodeLockStateStub: PasscodeLockState { var title = "title" var description = "description" weak var passcodeLock: PasscodeLock? weak var stateFactory: PasscodeLockStateFactory? func verifyPasscode() {} init() {} } class PasscodeRepositoryStub: PasscodeRepository { var hasPasscode = true func savePasscode(passcode: [String]) -> Bool { return false } func updatePasscode(passcode: [String]) -> Bool { return false } func deletePasscode() -> Bool { return false } func getPasscode() -> [String] { return [String]() } } class PasscodeLockStateFactoryStub: PasscodeLockStateFactory { func makeEnterPasscodeState() -> PasscodeLockState { return PasscodeLockStateStub() } func makeSetPasscodeState() -> PasscodeLockState { return PasscodeLockStateStub() } func makeConfirmPasscodeState() -> PasscodeLockState { return PasscodeLockStateStub() } func makePasscodesMismatchState() -> PasscodeLockState { return PasscodeLockStateStub() } func makeChangePasscodeState() -> PasscodeLockState { return PasscodeLockStateStub() } } class GenericPasscodeLockTests: XCTestCase { let repository = PasscodeRepositoryStub() let passcodeLength: UInt = 4 var lock: PasscodeLock! var stateFactory: PasscodeLockStateFactory! override func setUp() { super.setUp() let passcodeLock = GenericPasscodeLock(length: passcodeLength, repository: repository) lock = passcodeLock stateFactory = passcodeLock } /////////////////////////////////////////////////////// // MARK: - Tests /////////////////////////////////////////////////////// func testThatWeCanMakeAnInstance() { let passcodeLength: UInt = 6 let lock = GenericPasscodeLock(length: passcodeLength, repository: repository) XCTAssertEqual(lock.passcode.count, 0, "Passcode stack should be empty on PasscodeLock init") } func testThatWeCanEnterAPasscodeSign() { let sign = "a" lock.enterSign(sign) XCTAssertEqual(lock.passcode, [sign], "We should be able to enter a passcode sign") } func testThatDelegateIsCalledWhenWeEnterAPasscodeSign() { class LockDelegate: PasscodeLockDelegateStub { var signIndex: Int? override func passcodeLock(passcodeLock: PasscodeLock, addedSignAtIndex index: Int) { signIndex = index } } let lockDelegate = LockDelegate() lock.delegate = lockDelegate lock.enterSign("a") XCTAssertEqual(lockDelegate.signIndex!, 0, "Delegate method should be called when we enter a passcode sign") } func testThatWeCanRemoveAPasscodeSign() { let sign = "a" lock.enterSign(sign) lock.removeSign() XCTAssertEqual(lock.passcode.count, 0, "We should be able to remove a passcode sign") } func testThatDelegateIsCalledWhenWeRemoveAPasscodeSign() { class LockDelegate: PasscodeLockDelegateStub { var signIndex: Int? override func passcodeLock(passcodeLock: PasscodeLock, removedSignAtIndex index: Int) { signIndex = index } } let lockDelegate = LockDelegate() lock.delegate = lockDelegate lock.enterSign("a") lock.removeSign() XCTAssertEqual(lockDelegate.signIndex!, 0, "Delegate method should be called when we remove a passcode sign") } func testThatWeCanResetPasscodeSigns() { lock.enterSign("2") lock.enterSign("1") lock.resetSigns() XCTAssertEqual(lock.passcode.count, 0, "We should be able to reset the passcode signs") } func testThatDelegateIsCalledWhenPasscodeResets() { class LockDelegate: PasscodeLockDelegateStub { var didReset = false override func passcodeLockDidReset(passcodeLock: PasscodeLock) { didReset = true } } let lockDelegate = LockDelegate() lock.delegate = lockDelegate lock.enterSign("a") lock.enterSign("b") lock.resetSigns() XCTAssertEqual(lockDelegate.didReset, true, "Delegate method should be called when we reset the passcode signs") } func testThatDelegateIsCalledWhenPasscodeLockChangesItsState() { class LockDelegate: PasscodeLockDelegateStub { var changedState = false override func passcodeLock(passcodeLock: PasscodeLock, changedToState state: PasscodeLockState) { changedState = true } } let lockDelegate = LockDelegate() lock.delegate = lockDelegate lock.state = PasscodeLockStateStub() XCTAssertEqual(lockDelegate.changedState, true, "Delegate method should be called when PasscodeLock changes its state") } func testThatVerifyPasscodeIsCalledOnCurrentStateWhenWeEnterThePasscode() { class LockState: PasscodeLockStateStub { var didVrifyPasscode = false override func verifyPasscode() { didVrifyPasscode = true } } let mockState = LockState() lock.state = mockState for _ in 0..<Int(passcodeLength) { lock.enterSign("1") } XCTAssertEqual(mockState.didVrifyPasscode, true, "We should call the current state to verify the passcode") } func testThatWeCanMakeEnterPasscodeState() { let state = stateFactory.makeEnterPasscodeState() XCTAssertTrue(state is EnterPasscodeState, "We should be able to make an EnterPasscodeState isntance") } func testThatWeCanMakeSetPasscodeState() { let state = stateFactory.makeSetPasscodeState() XCTAssertTrue(state is SetPasscodeState, "We should be able to make an SetPasscodeState isntance") } func testThatWeCanMakeConfirmPasscodeState() { lock.enterSign("a") let state = stateFactory.makeConfirmPasscodeState() XCTAssertTrue(state is ConfirmPasscodeState, "We should be able to make an ConfirmPasscodeState isntance") } func testThatWeCanMakePasscodesMismatchState() { let state = stateFactory.makePasscodesMismatchState() XCTAssertTrue(state is PasscodesMismatchState, "We should be able to make an PasscodesMismatchState isntance") } func testThatWeCanMakeChangePasscodeState() { let state = stateFactory.makeChangePasscodeState() XCTAssertTrue(state is ChangePasscodeState, "We should be able to make an ChangePasscodeState isntance") } }
mit
59b63fe01841298e8b3fd7c05ef7e94b
31.109375
127
0.623236
5.41502
false
true
false
false
morgz/SwiftGoal
SwiftGoal/Stores/RemoteStore.swift
1
6403
// // Store.swift // SwiftGoal // // Created by Martin Richter on 10/05/15. // Copyright (c) 2015 Martin Richter. All rights reserved. // import Argo import ReactiveCocoa import RxSwift import RxCocoa class RemoteStore: StoreType { enum RequestMethod { case GET case POST case PUT case DELETE } private let baseURL: NSURL private let matchesURL: NSURL private let playersURL: NSURL private let rankingsURL: NSURL // MARK: Lifecycle init(baseURL: NSURL) { self.baseURL = baseURL self.matchesURL = NSURL(string: "matches", relativeToURL: baseURL)! self.playersURL = NSURL(string: "players", relativeToURL: baseURL)! self.rankingsURL = NSURL(string: "rankings", relativeToURL: baseURL)! } // MARK: - Matches func fetchMatches() -> SignalProducer<[Match], NSError> { let request = mutableRequestWithURL(matchesURL, method: .GET) return NSURLSession.sharedSession().rac_dataWithRequest(request) .map { data, response in if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []), matches: [Match] = decode(json) { return matches } else { return [] } } } func createMatch(parameters: MatchParameters) -> Observable<Bool> { return Observable.just(true) } func updateMatch(match: Match, parameters: MatchParameters) -> Observable<Bool> { return Observable.just(true) } // func createMatch(parameters: MatchParameters) -> SignalProducer<Bool, NSError> { // // let request = mutableRequestWithURL(matchesURL, method: .POST) // request.HTTPBody = httpBodyForMatchParameters(parameters) // // return NSURLSession.sharedSession().rac_dataWithRequest(request) // .map { data, response in // if let httpResponse = response as? NSHTTPURLResponse { // return httpResponse.statusCode == 201 // } else { // return false // } // } // } // func updateMatch(match: Match, parameters: MatchParameters) -> SignalProducer<Bool, NSError> { // // let request = mutableRequestWithURL(urlForMatch(match), method: .PUT) // request.HTTPBody = httpBodyForMatchParameters(parameters) // // return NSURLSession.sharedSession().rac_dataWithRequest(request) // .map { data, response in // if let httpResponse = response as? NSHTTPURLResponse { // return httpResponse.statusCode == 200 // } else { // return false // } // } // } func deleteMatch(match: Match) -> SignalProducer<Bool, NSError> { let request = mutableRequestWithURL(urlForMatch(match), method: .DELETE) return NSURLSession.sharedSession().rac_dataWithRequest(request) .map { data, response in if let httpResponse = response as? NSHTTPURLResponse { return httpResponse.statusCode == 200 } else { return false } } } // MARK: Players func fetchPlayers() -> SignalProducer<[Player], NSError> { let request = NSURLRequest(URL: playersURL) return NSURLSession.sharedSession().rac_dataWithRequest(request) .map { data, response in if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []), players: [Player] = decode(json) { return players } else { return [] } } } func createPlayerWithName(name: String) -> SignalProducer<Bool, NSError> { let request = mutableRequestWithURL(playersURL, method: .POST) request.HTTPBody = httpBodyForPlayerName(name) return NSURLSession.sharedSession().rac_dataWithRequest(request) .map { data, response in if let httpResponse = response as? NSHTTPURLResponse { return httpResponse.statusCode == 201 } else { return false } } } // MARK: Rankings func fetchRankings() -> SignalProducer<[Ranking], NSError> { let request = NSURLRequest(URL: rankingsURL) return NSURLSession.sharedSession().rac_dataWithRequest(request) .map { data, response in if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []), rankings: [Ranking] = decode(json) { return rankings } else { return [] } } } // MARK: Private Helpers private func httpBodyForMatchParameters(parameters: MatchParameters) -> NSData? { let jsonObject = [ "home_player_ids": Array(parameters.homePlayers).map { $0.identifier }, "away_player_ids": Array(parameters.awayPlayers).map { $0.identifier }, "home_goals": parameters.homeGoals, "away_goals": parameters.awayGoals ] return try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: []) } private func httpBodyForPlayerName(name: String) -> NSData? { let jsonObject = [ "name": name ] return try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: []) } private func urlForMatch(match: Match) -> NSURL { return matchesURL.URLByAppendingPathComponent(match.identifier) } private func mutableRequestWithURL(url: NSURL, method: RequestMethod) -> NSMutableURLRequest { let request = NSMutableURLRequest(URL: url) switch method { case .GET: request.HTTPMethod = "GET" case .POST: request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") case .PUT: request.HTTPMethod = "PUT" request.setValue("application/json", forHTTPHeaderField: "Content-Type") case .DELETE: request.HTTPMethod = "DELETE" } return request } }
mit
5181c9250e901f931aeae96d35f5e317
32.7
100
0.577542
5.025903
false
false
false
false
tootbot/tootbot
Tootbot/Source/Client/Keychain.swift
1
3454
// // Copyright (C) 2017 Tootbot Contributors // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import SAMKeychain protocol KeychainProtocol { func allAccounts() -> [(serviceName: String, account: String)]? func allServiceNames() -> Set<String>? func accounts(forService serviceName: String) -> [String]? func passwordData(forService serviceName: String, account: String) -> Data? @discardableResult func deletePassword(forService serviceName: String, account: String) -> Bool @discardableResult func setPasswordData(_ passwordData: Data, forService serviceName: String, account: String) -> Bool } extension KeychainProtocol { func password(forService serviceName: String, account: String) -> String? { return passwordData(forService: serviceName, account: account) .flatMap { passwordData in String(data: passwordData, encoding: .utf8) } } @discardableResult func setPassword(_ password: String, forService serviceName: String, account: String) -> Bool { guard let passwordData = password.data(using: .utf8) else { return false } return setPasswordData(passwordData, forService: serviceName, account: account) } } struct Keychain: KeychainProtocol { init() { } func allAccounts() -> [(serviceName: String, account: String)]? { guard let accounts = SAMKeychain.allAccounts() else { return nil } return accounts.flatMap { properties in if let serviceName = properties[kSecAttrService as String] as? String, let account = properties[kSecAttrAccount as String] as? String { return (serviceName, account) } else { return nil } } } func allServiceNames() -> Set<String>? { guard let accounts = allAccounts() else { return nil } return Set(accounts.map({ $0.serviceName })) } func accounts(forService serviceName: String) -> [String]? { guard let accounts = SAMKeychain.accounts(forService: serviceName) else { return nil } return accounts.flatMap { account in account[kSecAttrAccount as String] as? String } } func passwordData(forService serviceName: String, account: String) -> Data? { return SAMKeychain.passwordData(forService: serviceName, account: account) } @discardableResult func deletePassword(forService serviceName: String, account: String) -> Bool { return SAMKeychain.deletePassword(forService: serviceName, account: account) } @discardableResult func setPasswordData(_ passwordData: Data, forService serviceName: String, account: String) -> Bool { return SAMKeychain.setPasswordData(passwordData, forService: serviceName, account: account) } }
agpl-3.0
dad3a788d2ed52473c9a8424afe8ce00
35.744681
147
0.686161
4.837535
false
false
false
false
IT-Department-Projects/POP-II
iOS App/notesNearby_iOS_finalUITests/notesNearby_iOS_final/AppDelegate.swift
2
4733
// // AppDelegate.swift // notesNearby_iOS_final // // Created by Aiman Abdullah Anees on 11/03/17. // Copyright © 2017 Aiman Abdullah Anees. All rights reserved. // import UIKit import CoreData import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FIRApp.configure() IQKeyboardManager.sharedManager().enable=true return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "notesNearby_iOS_final") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
791e988243bcf383875910fc2d6f2145
48.291667
285
0.68787
5.813268
false
false
false
false
andrzejsemeniuk/ASToolkit
ASToolkit/GenericControllerOfPickerOfColor.swift
1
11332
// // GenericControllerOfColor // ASToolkit // // Created by Andrzej Semeniuk on 3/25/16. // Copyright © 2017 Andrzej Semeniuk. All rights reserved. // import Foundation import UIKit open class GenericControllerOfPickerOfColor : UITableViewController { public enum Flavor { case list (selected:UIColor, colors:[UIColor]) case matrixOfSolidCircles (selected:UIColor, colors:[[UIColor]], diameter:CGFloat, space:CGFloat) case matrixOfSolidSquares (selected:UIColor, colors:[[UIColor]], side:CGFloat, space:CGFloat) case matrix (selected:UIColor, colors:[[UIColor]]) case slidersForRGB (selected:UIColor) case slidersForRGBA (selected:UIColor) case slidersForHSB (selected:UIColor) case slidersForHSBA (selected:UIColor) } public var rowHeight : CGFloat = 44 // public var flavor : Flavor = .list(selected:.white, colors:GenericControllerOfPickerOfColor.generateListOfDefaultColors()) { public var flavor : Flavor = .matrixOfSolidCircles(selected : .white, colors : UIColor.generateMatrixOfColors(columns:5), diameter : 36, space : 8) { didSet { switch flavor { case .list(let selected, let colors): self.selected = selected case .matrixOfSolidCircles(let selected, let colors, let diameter, let space): self.selected = selected case .matrixOfSolidSquares(let selected, let colors, let side, let space): self.selected = selected case .matrix(let selected, let colors): self.selected = selected case .slidersForHSB(let selected): self.selected = selected case .slidersForRGB(let selected): self.selected = selected case .slidersForHSBA(let selected): self.selected = selected case .slidersForRGBA(let selected): self.selected = selected } reload() } } private var buttons : [AnyObject] = [] public var selected : UIColor = .white override open func viewDidLoad() { tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none reload() super.viewDidLoad() } // typealias RowGenerator = (UITableViewCell)->() // // private var rows : [RowGenerator] = [] // // public var margin : CGFloat = 8 { // didSet { // self.tableView.scrollIndicatorInsets = UIEdgeInsets(all: margin) // } // } // // open func clear() { // self.rows = [] // } // // open func addFlavor() { // // } override open func numberOfSections (in: UITableView) -> Int { return 1 } override open func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch flavor { case .list (_, let colors) : return colors.count case .matrixOfSolidCircles (_, let colors, _, _) : return colors.count case .matrixOfSolidSquares (_, let colors, _, _) : return colors.count case .matrix (_, let colors) : return colors.count case .slidersForHSB : return 3 case .slidersForRGB : return 3 case .slidersForHSBA : return 4 case .slidersForRGBA : return 4 } } override open func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : UITableViewCell cell = UITableViewCell(style:.default,reuseIdentifier:nil) switch flavor { case .list(let selected, let colors): let color = colors[indexPath.row] cell.backgroundColor = color cell.selectionStyle = .default if color.components_RGBA_UInt8_equals(selected) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case .matrixOfSolidCircles(let selected, let colors, let diameter, let space): let stack = UIStackView() stack.axis = .horizontal stack.alignment = .center stack.distribution = .equalSpacing stack.spacing = space for color in colors[indexPath.row] { let circle = UIButtonWithCenteredCircle(frame:CGRect(side:diameter)) circle.circle(for: .normal).radius = diameter/2 circle.circle(for: .normal).fillColor = color.cgColor circle.circle(for: .selected).radius = diameter/2+space/2 circle.circle(for: .selected).fillColor = color.cgColor circle.widthAnchor.constraint(equalToConstant: diameter).isActive=true circle.heightAnchor.constraint(equalToConstant: diameter).isActive=true circle.addTarget(self, action: #selector(GenericControllerOfPickerOfColor.handleTapOnCircle(_:)), for: .touchUpInside) self.buttons.append(circle) stack.addArrangedSubview(circle) if color == self.selected { circle.isSelected = true } } cell.contentView.backgroundColor = self.selected //UIColor(white:0.97) // TODO: ADD ASSOCIATED VALUE TO ENUM ? cell.contentView.addSubview(stack) stack.translatesAutoresizingMaskIntoConstraints=false stack.centerXAnchor.constraint(equalTo: stack.superview!.centerXAnchor).isActive=true stack.centerYAnchor.constraint(equalTo: stack.superview!.centerYAnchor).isActive=true break case .matrixOfSolidSquares(let selected, let colors, let side, let space): var views = [UIView]() for color in colors[indexPath.row] { let frame = CGRect(x:0, y:rowHeight/2-side/2, width:side/2, height:side/2) var circle = UIView(frame:frame) views.append(circle) circle.backgroundColor = color } let stack = UIStackView.init(arrangedSubviews: views) stack.axis = .horizontal stack.alignment = .center stack.distribution = .equalSpacing cell.contentView.addSubview(stack) // cell.backgroundColor = self.tableView.backgroundColor break case .matrix(let selected, let colors): break case .slidersForHSB(let selected): break case .slidersForRGB(let selected): break case .slidersForHSBA(let selected): break case .slidersForRGBA(let selected): break } return cell } open func handleTapOnCircle(_ control:UIControl) { if let button = control as? UIButtonWithCenteredCircle { self.selected = UIColor.init(cgColor:button.circle(for: .normal).fillColor ?? UIColor.clear.cgColor) for element in self.buttons { if let button = element as? UIButtonWithCenteredCircle { let color = UIColor.init(cgColor:button.circle(for: .normal).fillColor ?? UIColor.clear.cgColor) button.isSelected = color == self.selected } } self.update() self.reload() } } override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return rowHeight } open func reload() { self.view.backgroundColor = self.selected self.buttons = [] tableView.reloadData() } override open func viewWillAppear(_ animated: Bool) { reload() switch flavor { case .list(_, let colors): for (row,color) in colors.enumerated() { if color.components_RGBA_UInt8_equals(selected) { let path = IndexPath(row:row, section:0) tableView.scrollToRow(at: path as IndexPath,at:.middle,animated:true) break } } case .matrixOfSolidCircles(let selected, let colors, let diameter, let space): break case .matrixOfSolidSquares(let selected, let colors, let side, let space): break case .matrix(let selected, let colors): break case .slidersForHSB(let selected): break case .slidersForRGB(let selected): break case .slidersForHSBA(let selected): break case .slidersForRGBA(let selected): break } super.viewWillAppear(animated) } public var update: (() -> ()) = {} override open func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return false } override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch flavor { case .list(let selected, let colors): self.selected = colors[indexPath.row] case .matrixOfSolidCircles(let selected, let colors, let diameter, let space): return case .matrixOfSolidSquares(let selected, let colors, let side, let space): self.selected = selected case .matrix(let selected, let colors): self.selected = selected case .slidersForHSB(let selected): self.selected = selected case .slidersForRGB(let selected): self.selected = selected case .slidersForHSBA(let selected): self.selected = selected case .slidersForRGBA(let selected): self.selected = selected } reload() update() } }
mit
e765cab1b2ff11bf8a3bd65cd4ea4e62
32.823881
151
0.516371
5.530015
false
false
false
false
Harry-L/5-3-1
ios-charts-master/Charts/Classes/Renderers/RadarChartRenderer.swift
3
9792
// // RadarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class RadarChartRenderer: LineScatterCandleRadarChartRenderer { public weak var chart: RadarChartView? public init(chart: RadarChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart } public override func drawData(context context: CGContext) { guard let chart = chart else { return } let radarData = chart.data if (radarData != nil) { for set in radarData!.dataSets as! [IRadarChartDataSet] { if set.isVisible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set) } } } } internal func drawDataSet(context context: CGContext, dataSet: IRadarChartDataSet) { guard let chart = chart else { return } CGContextSaveGState(context) let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let entryCount = dataSet.entryCount let path = CGPathCreateMutable() var hasMovedToPoint = false for (var j = 0; j < entryCount; j++) { guard let e = dataSet.entryForIndex(j) else { continue } let p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value - chart.chartYMin) * factor, angle: sliceangle * CGFloat(j) + chart.rotationAngle) if (p.x.isNaN) { continue } if (!hasMovedToPoint) { CGPathMoveToPoint(path, nil, p.x, p.y) hasMovedToPoint = true } else { CGPathAddLineToPoint(path, nil, p.x, p.y) } } CGPathCloseSubpath(path) // draw filled if (dataSet.isDrawFilledEnabled) { CGContextSetFillColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextSetAlpha(context, dataSet.fillAlpha) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextFillPath(context) } // draw the line (only if filled is disabled or alpha is below 255) if (!dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextSetLineWidth(context, dataSet.lineWidth) CGContextSetAlpha(context, 1.0) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextStrokePath(context) } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let chart = chart, data = chart.data else { return } let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let yoffset = CGFloat(5.0) for (var i = 0, count = data.dataSetCount; i < count; i++) { let dataSet = data.getDataSetByIndex(i) as! IRadarChartDataSet if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let entryCount = dataSet.entryCount for (var j = 0; j < entryCount; j++) { guard let e = dataSet.entryForIndex(j) else { continue } let p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value) * factor, angle: sliceangle * CGFloat(j) + chart.rotationAngle) let valueFont = dataSet.valueFont let valueTextColor = dataSet.valueTextColor guard let formatter = dataSet.valueFormatter else { continue } ChartUtils.drawText(context: context, text: formatter.stringFromNumber(e.value)!, point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } public override func drawExtras(context context: CGContext) { drawWeb(context: context) } private var _webLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public func drawWeb(context context: CGContext) { guard let chart = chart, data = chart.data else { return } let sliceangle = chart.sliceAngle CGContextSaveGState(context) // calculate the factor that is needed for transforming the value to // pixels let factor = chart.factor let rotationangle = chart.rotationAngle let center = chart.centerOffsets // draw the web lines that come from the center CGContextSetLineWidth(context, chart.webLineWidth) CGContextSetStrokeColorWithColor(context, chart.webColor.CGColor) CGContextSetAlpha(context, chart.webAlpha) let xIncrements = 1 + chart.skipWebLineCount for var i = 0, xValCount = data.xValCount; i < xValCount; i += xIncrements { let p = ChartUtils.getPosition(center: center, dist: CGFloat(chart.yRange) * factor, angle: sliceangle * CGFloat(i) + rotationangle) _webLineSegmentsBuffer[0].x = center.x _webLineSegmentsBuffer[0].y = center.y _webLineSegmentsBuffer[1].x = p.x _webLineSegmentsBuffer[1].y = p.y CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2) } // draw the inner-web CGContextSetLineWidth(context, chart.innerWebLineWidth) CGContextSetStrokeColorWithColor(context, chart.innerWebColor.CGColor) CGContextSetAlpha(context, chart.webAlpha) let labelCount = chart.yAxis.entryCount for (var j = 0; j < labelCount; j++) { for (var i = 0, xValCount = data.xValCount; i < xValCount; i++) { let r = CGFloat(chart.yAxis.entries[j] - chart.chartYMin) * factor let p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle) let p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle) _webLineSegmentsBuffer[0].x = p1.x _webLineSegmentsBuffer[0].y = p1.y _webLineSegmentsBuffer[1].x = p2.x _webLineSegmentsBuffer[1].y = p2.y CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let chart = chart, data = chart.data as? RadarChartData else { return } CGContextSaveGState(context) CGContextSetLineWidth(context, data.highlightLineWidth) if (data.highlightLineDashLengths != nil) { CGContextSetLineDash(context, data.highlightLineDashPhase, data.highlightLineDashLengths!, data.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let sliceangle = chart.sliceAngle let factor = chart.factor let center = chart.centerOffsets for (var i = 0; i < indices.count; i++) { guard let set = chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as? IRadarChartDataSet else { continue } if !set.isHighlightEnabled { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) // get the index to highlight let xIndex = indices[i].xIndex let e = set.entryForXIndex(xIndex) if e?.xIndex != xIndex { continue } let j = set.entryIndex(entry: e!) let y = (e!.value - chart.chartYMin) if (y.isNaN) { continue } _highlightPointBuffer = ChartUtils.getPosition(center: center, dist: CGFloat(y) * factor, angle: sliceangle * CGFloat(j) + chart.rotationAngle) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
mit
2259aeaad5b11cb9c5a743387aa6e5b3
32.768966
272
0.561377
5.554169
false
false
false
false
RiBj1993/CodeRoute
QwizSongViewController.swift
1
15289
// // ViewController.swift // TrueFalseStarter // // Orginally Created by Pasan Premaratne on 3/9/16. // Copyright © 2016 Treehouse. All rights reserved. // // Treehouse iOS TechDegree Project 2 - Enhancing a Quiz App in iOS // James D. McMillan started 6/27/2016 // import UIKit import GameKit import AudioToolbox import FirebaseDatabase import FirebaseStorage import Firebase class QwizSongViewController: UIViewController { var olympicTriviaQuestions: [Trivia] = [] // removed the 'magic number' of 4 that was in the starter and replaced with .count to adjust to the amount of questions in the TriviaModel var questionsAsked = 0 var correctQuestions = 0 var indexOfSelectedQuestion: Int = 0 var previousQuestionsArray: [Int] = [] var questionsPerRound : Int = 0 // Sound Effects Variables var gameSound: SystemSoundID = 0 // global variables for the additional sound effects var gameSoundCorrect: SystemSoundID = 0 var gameSoundWrong: SystemSoundID = 0 var gameSoundFinished: SystemSoundID = 0 var gameSoundRetry: SystemSoundID = 0 var gameSoundTimerEnd: SystemSoundID = 0 // Lightning Timer Variables var lightningTimer = Timer() var seconds = 15 var timerRunning = false var i = 0 @IBOutlet weak var questionField: UILabel! @IBOutlet weak var firstChoiceButton: UIButton! @IBOutlet weak var secondChoiceButton: UIButton! @IBOutlet weak var thirdChoiceButton: UIButton! @IBOutlet weak var fourthChoiceButton: UIButton! @IBOutlet weak var playAgainButton: UIButton! @IBOutlet weak var timerLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() bbbbbbc () loadGameStartSound() // Start game indexOfSelectedQuestion = olympicTriviaQuestions.count playGameStartSound() questionsPerRound = olympicTriviaQuestions.count displayQuestion() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // locking screen orientation into Portrait Mode only override var shouldAutorotate : Bool { return false } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } func displayQuestion() { indexOfSelectedQuestion = GKRandomSource.sharedRandom().nextInt(upperBound: /*olympicTriviaQuestions.count*-*/ i) // while loop for making sure that questions are not repeated while previousQuestionsArray.contains(indexOfSelectedQuestion) { indexOfSelectedQuestion = GKRandomSource.sharedRandom().nextInt(upperBound:/* olympicTriviaQuestions.count*/ i) } // appending global previousQuestionsArray varialbe with asked questions so that they are not repeated previousQuestionsArray.append(indexOfSelectedQuestion) // print("olympicTriviaQuestions[0]",olympicTriviaQuestions[0]) // print("olympicTriviaQuestions[1]",olympicTriviaQuestions[1]) // print("olympicTriviaQuestions[2]",olympicTriviaQuestions[3]) print("olympicTriviaQuestions[4]",olympicTriviaQuestions.count) print("i",i) let triviaQuestions = olympicTriviaQuestions[indexOfSelectedQuestion] questionField.text = triviaQuestions.question playAgainButton.isHidden = true enableButtons() // Display choice text in answer buttons firstChoiceButton.setTitle(triviaQuestions.firstChoice, for: UIControlState()) secondChoiceButton.setTitle(triviaQuestions.secondChoice, for: UIControlState()) thirdChoiceButton.setTitle(triviaQuestions.thirdChoice, for: UIControlState()) fourthChoiceButton.setTitle(triviaQuestions.fourthChoice, for: UIControlState()) resetTimer() beginTimer() } func displayScore() { // Hide the answer buttons firstChoiceButton.isHidden = true secondChoiceButton.isHidden = true thirdChoiceButton.isHidden = true fourthChoiceButton.isHidden = true timerLabel.isHidden = true // Display play again button playAgainButton.isHidden = false if correctQuestions == questionsAsked { questionField.text = "You've won the GOLD!\nYou got \(correctQuestions) out of \(questionsPerRound) correct!" loadGameSoundFinished() playGameSoundFinished() } else if correctQuestions <= 11 && correctQuestions >= 10 { questionField.text = "You've won the SILVER!\n You got \(correctQuestions) out of \(questionsPerRound)" loadGameSoundFinished() playGameSoundFinished() } else if correctQuestions <= 9 && correctQuestions >= 8 { questionField.text = "You've won the BRONZE!\n You got \(correctQuestions) out of \(questionsPerRound)" loadGameSoundFinished() playGameSoundFinished() } else { questionField.text = "Try Again!\n You got \(correctQuestions) out of \(questionsPerRound)" loadGameSoundRetry() playGameSoundRetry() } } @IBAction func checkAnswer(_ sender: UIButton) { // Increment the questions asked counter questionsAsked += 1 print("indexOfSelectedQuestion", indexOfSelectedQuestion) print("olympicTriviaQuestions[1]", olympicTriviaQuestions[1]) print("olympicTriviaQuestions[0]", olympicTriviaQuestions[0]) print("olympicTriviaQuestions[0]", olympicTriviaQuestions[2]) print("indexOfSelectedQuestion", indexOfSelectedQuestion) let selectedQuestionDict = olympicTriviaQuestions[indexOfSelectedQuestion] let correctAnswer = selectedQuestionDict.correctAnswer if sender.titleLabel!.text == correctAnswer { correctQuestions += 1 questionField.text = "Correct!" disableButtons() loadGameSoundCorrect() playGameSoundCorrect() lightningTimer.invalidate() } else { questionField.text = "Sorry, wrong answer! \n\n Correct Answer: \(correctAnswer)" loadGameSoundWrong() playGameSoundWrong() disableButtons() lightningTimer.invalidate() } loadNextRoundWithDelay(seconds: 3) } func nextRound() { if questionsAsked == questionsPerRound { // Game is over displayScore() lightningTimer.invalidate() resetTimer() } else { // Continue game displayQuestion() } } @IBAction func playAgain() { // Show the answer buttons firstChoiceButton.isHidden = false secondChoiceButton.isHidden = false thirdChoiceButton.isHidden = false fourthChoiceButton.isHidden = false timerLabel.isHidden = false questionsAsked = 0 correctQuestions = 0 previousQuestionsArray.removeAll() playGameStartSound() nextRound() } // Lightning Timer Methods func beginTimer() { if timerRunning == false { lightningTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(QwizSongViewController.countdownTimer), userInfo: nil, repeats: true) timerRunning = true } } func countdownTimer() { let selectedQuestionDict = olympicTriviaQuestions[indexOfSelectedQuestion] let correctAnswer = selectedQuestionDict.correctAnswer // countdown by 1 second seconds -= 1 timerLabel.text = "Seconds Remaining: \(seconds)" if seconds == 0 { lightningTimer.invalidate() questionsAsked += 1 questionField.text = "Sorry, time ran out! \n\n Correct Answer: \(correctAnswer)" loadGameSoundTimerEnd() playGameSoundTimerEnd() disableButtons() loadNextRoundWithDelay(seconds: 3) } } func resetTimer() { seconds = 15 timerLabel.text = "Seconds Remaining: \(seconds)" timerRunning = false } // MARK: Helper Methods // Helper Method to enable and disable the buttons after user has answered a question or began another func enableButtons() { firstChoiceButton.isUserInteractionEnabled = true secondChoiceButton.isUserInteractionEnabled = true thirdChoiceButton.isUserInteractionEnabled = true fourthChoiceButton.isUserInteractionEnabled = true } func disableButtons() { firstChoiceButton.isUserInteractionEnabled = false secondChoiceButton.isUserInteractionEnabled = false thirdChoiceButton.isUserInteractionEnabled = false fourthChoiceButton.isUserInteractionEnabled = false } func loadNextRoundWithDelay(seconds: Int) { // Converts a delay in seconds to nanoseconds as signed 64 bit integer let delay = Int64(NSEC_PER_SEC * UInt64(seconds)) // Calculates a time value to execute the method given current time and delay let dispatchTime = DispatchTime.now() + Double(delay) / Double(NSEC_PER_SEC) // Executes the nextRound method at the dispatch time on the main queue DispatchQueue.main.asyncAfter(deadline: dispatchTime) { self.nextRound() } } func loadGameStartSound() { let pathToSoundFile = Bundle.main.path(forResource: "GameSound", ofType: "wav") let soundURL = URL(fileURLWithPath: pathToSoundFile!) AudioServicesCreateSystemSoundID(soundURL as CFURL, &gameSound) } func playGameStartSound() { AudioServicesPlaySystemSound(gameSound) } // Adding new soundeffects helper methods func loadGameSoundCorrect() { let pathToSoundFile = Bundle.main.path(forResource: "GameSoundCorrect", ofType: "wav") let soundURL = URL(fileURLWithPath: pathToSoundFile!) AudioServicesCreateSystemSoundID(soundURL as CFURL, &gameSoundCorrect) } func playGameSoundCorrect() { AudioServicesPlaySystemSound(gameSoundCorrect) } func loadGameSoundWrong() { let pathToSoundFile = Bundle.main.path(forResource: "GameSoundWrong", ofType: "wav") let soundURL = URL(fileURLWithPath: pathToSoundFile!) AudioServicesCreateSystemSoundID(soundURL as CFURL, &gameSoundWrong) } func playGameSoundWrong() { AudioServicesPlaySystemSound(gameSoundWrong) } func loadGameSoundTimerEnd() { let pathToSoundFile = Bundle.main.path(forResource: "GameSoundTimerEnd", ofType: "wav") let soundURL = URL(fileURLWithPath: pathToSoundFile!) AudioServicesCreateSystemSoundID(soundURL as CFURL, &gameSoundTimerEnd) } func playGameSoundTimerEnd() { AudioServicesPlaySystemSound(gameSoundTimerEnd) } func loadGameSoundFinished() { let pathToSoundFile = Bundle.main.path(forResource: "GameSoundFinished", ofType: "wav") let soundURL = URL(fileURLWithPath: pathToSoundFile!) AudioServicesCreateSystemSoundID(soundURL as CFURL, &gameSoundFinished) } func playGameSoundFinished() { AudioServicesPlaySystemSound(gameSoundFinished) } func loadGameSoundRetry() { let pathToSoundFile = Bundle.main.path(forResource: "GameSoundRetry", ofType: "wav") let soundURL = URL(fileURLWithPath: pathToSoundFile!) AudioServicesCreateSystemSoundID(soundURL as CFURL, &gameSoundRetry) } func playGameSoundRetry() { AudioServicesPlaySystemSound(gameSoundRetry) } func bbbbbbc () { let ref: FIRDatabaseReference! ref = FIRDatabase.database().reference() //var i : Int = 1 var stringValue: String = "1" var count: Int = 0 let nbDeLignes: Int = 0 print(nbDeLignes) ref.child("qwiz").observeSingleEvent(of: .value, with: { (snapshot) in if !( snapshot.value is NSNull){ count = Int(snapshot.childrenCount ) print("count",count) for nbDeLignes in 0...(count+1) { self.butto(VV:stringValue) count += 1 stringValue = "\(nbDeLignes)" } } }) { (error) in print(error.localizedDescription) } } func butto(VV:String) { let ref: FIRDatabaseReference! ref = FIRDatabase.database().reference() ref.child("qwiz").child(VV).observeSingleEvent(of: .value, with: { (snapshot) in // Get user value if !( snapshot.value is NSNull){ let value = snapshot.value as? NSDictionary let choix1 = value?["choix1"] as? String ?? "" let choix2 = value?["choix2"] as? String ?? "" let choix3 = value?["choix3"] as? String ?? "" // let choix4 = value?["choix4"] as? String ?? "" let Breponse = value?["reponse"] as? String ?? "" let IMAGE = value?["image"] as? String ?? "" /* print(choix1) print(choix2) print(choix3) print(choix4 ) print(IMAGE) print(Breponse) print("ppppppppppppppp",snapshot.childrenCount)*/ let room = Trivia(question: choix1, firstChoice: choix2, secondChoice: choix3, thirdChoice: Breponse, fourthChoice: IMAGE, correctAnswer: Breponse) //self.olympicTriviaQuestions.append(room) self.olympicTriviaQuestions.insert(room, at: self.i) print("self.olympicTriviaQuestions.insert(room, at: self.i)", self.olympicTriviaQuestions[self.i]) self.i += 1 } }) { (error) in print(error.localizedDescription) } } // self.bbbbbbc() }
apache-2.0
44fdc36102fa707c0f2a82e86f510933
32.526316
170
0.598639
5.262651
false
false
false
false
swiftsanyue/TestKitchen
TestKitchen/TestKitchen/classes/common(公共类)/KTCDownloader.swift
1
1856
// // KTCDownloader.swift // TestKitchen // // Created by ZL on 16/10/24. // Copyright © 2016年 zl. All rights reserved. // import UIKit import Alamofire protocol KTCDownloaderDelegate:NSObjectProtocol { //下载失败的方法 func downloader(downloader:KTCDownloader,didFailWithError error:NSError) //下载成功 func downloader(downloder:KTCDownloader,didFinishWithData data:NSData?) } class KTCDownloader: NSObject { //代理属性 代理一定要用弱引用 weak var dalegate:KTCDownloaderDelegate? //下载类型 var downloadType:KTCDownloadType = .Normal //POST 请求 func postWithUrl(urlString:String,params:Dictionary<String,AnyObject>){ //methodName=MaterialSubtype&token=&user_id=&version=4.32 var tmpDict = NSDictionary(dictionary: params) as! Dictionary<String,AnyObject> //设置所有接口的公共参数 tmpDict["token"] = "" tmpDict["user_id"] = "" tmpDict["version"] = "4.5" Alamofire.request(.POST,urlString, parameters: tmpDict, encoding: ParameterEncoding.URL, headers: nil).responseData { (response) in switch response.result{ case .Failure(let error): //出错了 self.dalegate?.downloader(self, didFailWithError: error) case .Success : //下载成功 self.dalegate?.downloader(self, didFinishWithData: response.data) } } } } enum KTCDownloadType: Int { case Normal = 0 case IngreRecommend //首页食材的推荐 case IngreMaterial //首页食材的食材 case IngreCategory //首页食材的分类 case IngreFoodCourseDetail //食材课程的详情 case IngreFoodCourseComment //食材课程的评论 }
mit
31f54c3ee70347f2083764b0f7228cc0
25.777778
139
0.635448
4.314578
false
false
false
false
haginile/SwiftDate
SwiftDate/DayCounter.swift
1
2223
// // This file is derived from QuantLib. The license of QuantLib is available online at <http://quantlib.org/license.shtml>. // // DayCounter.swift // SHSLib // // Created by Helin Gai on 7/7/14. // Copyright (c) 2014 Helin Gai. All rights reserved. // import Foundation public class DayCounter { class Impl { func name() -> String { return "Day Counter" } func shortName() -> String { return "Day Counter" } func dayCount(date1 : Date, date2 : Date) -> Int { return date2 - date1 } func dayCountFraction(date1 : Date, date2 : Date, referenceStartDate : Date = Date(), referenceEndDate : Date = Date()) -> Double { return Double(dayCount(date1, date2: date2)) / 365.25 } } var impl : Impl /** * Construct a generic day counter (Actual/365.25 convention is used) */ public init() { impl = DayCounter.Impl() } public func name() -> String { return impl.name() } public func shortName() -> String { return impl.shortName() } /** * Returns the number of days between two dates based on the day counter * * @param date1 Starting date * @param date2 End date * * @return the number of days between two dates based on the day counter */ public func dayCount(date1 : Date, date2 : Date) -> Int { return impl.dayCount(date1, date2: date2) } /** * Returns the day count fraction (i.e., year fraction) between two dates based on the day counter * * @param date1 Starting date * @param date2 End date * @param referenceStartDate Reference start date (used for actual/actual) * @param referenceEndDate Reference end date (used for actual/actual) * * @return a double representing the day count fraction */ public func dayCountFraction(date1 : Date, date2 : Date, referenceStartDate : Date = Date(), referenceEndDate : Date = Date()) -> Double { return impl.dayCountFraction(date1, date2: date2, referenceStartDate: referenceStartDate, referenceEndDate: referenceEndDate) } }
mit
d35993cb0ad646441c9e784e2b1d24ca
29.888889
142
0.607287
4.086397
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Models/Decision/Decision.swift
1
9199
// // Decision.swift // MEGameTracker // // Created by Emily Ivie on 3/13/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit public struct Decision: Codable { enum CodingKeys: String, CodingKey { case id case gameSequenceUuid case isSelected case selectedDate } // MARK: Constants // MARK: Properties public var rawData: Data? // transient public var generalData: DataDecision public internal(set) var id: String /// (GameModifying, GameRowStorable Protocol) /// This value's game identifier. public var gameSequenceUuid: UUID? /// (DateModifiable Protocol) /// Date when value was created. public var createdDate = Date() /// (DateModifiable Protocol) /// Date when value was last changed. public var modifiedDate = Date() /// (CloudDataStorable Protocol) /// Flag for whether the local object has changes not saved to the cloud. public var isSavedToCloud = false /// (CloudDataStorable Protocol) /// A set of any changes to the local object since the last cloud sync. public var pendingCloudChanges = CodableDictionary() /// (CloudDataStorable Protocol) /// A copy of the last cloud kit record. public var lastRecordData: Data? // used only in CoreData queries public var selectedDate: Date? public private(set) var isSelected = false // MARK: Computed Properties public var gameVersion: GameVersion { return generalData.gameVersion } public var name: String { return generalData.name } public var description: String? { return generalData.description } public var loveInterestId: String? { return generalData.loveInterestId } public var sortIndex: Int { return generalData.sortIndex } public var blocksDecisionIds: [String] { return generalData.blocksDecisionIds } public var linkedEventIds: [String] { return generalData.linkedEventIds } public var isAvailable: Bool { if generalData.dependsOnDecisions.isEmpty { return true } var isAvailable = true for set in generalData.dependsOnDecisions { if let decision = Decision.get(id: set.id), decision.isSelected != set.value { isAvailable = false break } } return isAvailable } // MARK: Change Listeners And Change Status Flags /// (DateModifiable, GameRowStorable) Flag to indicate that there are changes pending a core data sync. public var hasUnsavedChanges = false public static var onChange = Signal<(id: String, object: Decision?)>() // MARK: Initialization public init( id: String, gameSequenceUuid: UUID? = App.current.game?.uuid, generalData: DataDecision ) { self.id = id self.gameSequenceUuid = gameSequenceUuid self.generalData = generalData setGeneralData() } public mutating func setGeneralData() { // nothing for now } public mutating func setGeneralData(_ generalData: DataDecision) { self.generalData = generalData setGeneralData() } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) gameSequenceUuid = try container.decode(UUID.self, forKey: .gameSequenceUuid) generalData = DataDecision(id: id) // faulted for now isSelected = try container.decodeIfPresent(Bool.self, forKey: .isSelected) ?? isSelected selectedDate = try container.decodeIfPresent(Date.self, forKey: .selectedDate) try unserializeDateModifiableData(decoder: decoder) try unserializeGameModifyingData(decoder: decoder) try unserializeLocalCloudData(decoder: decoder) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(gameSequenceUuid, forKey: .gameSequenceUuid) try container.encode(isSelected, forKey: .isSelected) try container.encode(selectedDate, forKey: .selectedDate) try serializeDateModifiableData(encoder: encoder) try serializeGameModifyingData(encoder: encoder) try serializeLocalCloudData(encoder: encoder) } // func unsetBlockedDecisionIds(with manager: CodableCoreDataStorable? = nil) { // let manager = manager ?? defaultManager // guard isSelected else { return } // for decisionId in blocksDecisionIds { // if var decision = Decision.get(id: decisionId, with: manager), decision.isSelected { // decision.isSelected = false // _ = decision.saveAnyChanges(with: manager) // } // } // } } // MARK: Data Change Actions extension Decision { /// Returns a copy of this Decision with a set of changes applies public func changed(fromActionData data: [String: Any?]) -> Decision { if let isSelected = data["isSelected"] as? Bool { return changed(isSelected: isSelected) } return self } /// Return a copy of this Decision with isSelected changed public func changed( isSelected: Bool, isSave: Bool = true, isNotify: Bool = true, isCascadeChanges: EventDirection = .all ) -> Decision { guard isSelected != self.isSelected else { return self } var decision = self decision.isSelected = isSelected decision.selectedDate = isSelected ? Date() : nil decision.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["isSelected": isSelected, "selectedDate": selectedDate] ) if isCascadeChanges != .none && !GamesDataBackup.current.isSyncing { if decision.loveInterestId != nil { decision.cascadeChangeLoveInterest(isSave: isSave, isNotify: isNotify) } if isSelected { for decisionId in decision.blocksDecisionIds { // new thread? _ = Decision.get(id: decisionId)? .changed(isSelected: false, isSave: true, isCascadeChanges: .none) } } for event in linkedEventIds.map({ Event.get(id: $0) }).filter({ $0 != nil }).map({ $0! }) { _ = event.changed(isTriggered: isSelected, isSave: isSave, isNotify: isNotify) } } return decision } /// Performs common behaviors after an object change private mutating func changeEffects( isSave: Bool = true, isNotify: Bool = true, cloudChanges: [String: Any?] = [:] ) { markChanged() notifySaveToCloud(fields: cloudChanges) if isSave { _ = saveAnyChanges() } if isNotify { Decision.onChange.fire((id: id, object: self)) } } private func cascadeChangeLoveInterest( isSave: Bool = true, isNotify: Bool = true ) { // mark the correlating love interest decision for later tracking guard let loveInterestId = self.loveInterestId, let loveInterest = Person.get(id: loveInterestId, gameVersion: gameVersion), loveInterest.isParamour, // require exclusive love interest to change shepard let shepard = App.current.game?.getShepardFromVersion(gameVersion) ?? App.current.game?.shepard else { return } if isSelected && shepard.loveInterestId != loveInterestId { _ = shepard.changed(loveInterestId: loveInterestId, isSave: isSave, isNotify: isNotify, isCascadeChanges: .none) } else if !isSelected && shepard.loveInterestId == loveInterestId { _ = shepard.changed(loveInterestId: nil, isSave: isSave, isNotify: isNotify, isCascadeChanges: .none) } } } // MARK: Dummy data for Interface Builder extension Decision { public static func getDummy(json: String? = nil) -> Decision? { // swiftlint:disable line_length let json = json ?? "{\"id\":\"1.1\",\"gameVersion\":\"1\",\"name\":\"Helped Jenna in Chora's Den\",\"description\":\"If you help Jenna in Citadel: Rita's Sister, she can save Conrad Verner's life in Game 3.\"}" if var baseDecision = try? defaultManager.decoder.decode(DataDecision.self, from: json.data(using: .utf8)!) { baseDecision.isDummyData = true let decision = Decision(id: "1", generalData: baseDecision) return decision } // swiftlint:enable line_length return nil } } // MARK: DateModifiable extension Decision: DateModifiable {} // MARK: GameModifying extension Decision: GameModifying {} // MARK: Sorting extension Decision { /// Sorts by availability, then by sortIndex, then by name static func sort(_ first: Decision, _ second: Decision) -> Bool { if first.gameVersion != second.gameVersion { return first.gameVersion.stringValue < second.gameVersion.stringValue } else if first.sortIndex != second.sortIndex { return first.sortIndex < second.sortIndex } else { return first.id < second.id } } } // MARK: Equatable extension Decision: Equatable { public static func == (_ lhs: Decision, _ rhs: Decision) -> Bool { // not true equality, just same db row return lhs.id == rhs.id } } //// MARK: Hashable //extension Decision: Hashable { // public var hashValue: Int { return id.hashValue } //}
mit
31290b822e421ac192b155767618520f
33.449438
212
0.674821
4.139514
false
false
false
false
dduan/swift
test/SourceKit/CursorInfo/cursor_usr.swift
1
3797
// The RUN lines are at the bottom in case we ever need to rely on line:col info. import Foo import FooSwiftModule var global: Int struct S1 {} func foo(x: FooStruct1) -> S1 {} // RUN: rm -rf %t // RUN: mkdir %t // RUN: %swiftc_driver -emit-module -o %t/FooSwiftModule.swiftmodule %S/Inputs/FooSwiftModule.swift // Sanity check that we have identical responses when things work. // RUN: %sourcekitd-test -req=cursor -pos=5:5 %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s > %t.from_offset.txt // RUN: %sourcekitd-test -req=cursor -usr "s:v10cursor_usr6globalSi" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s > %t.from_usr.txt // RUN: FileCheck %s -check-prefix=CHECK_SANITY1 < %t.from_offset.txt // RUN: FileCheck %s -check-prefix=CHECK_SANITY1 < %t.from_usr.txt // RUN: diff -u %t.from_usr.txt %t.from_offset.txt // CHECK_SANITY1: source.lang.swift.decl.var.global (5:5-5:11) // CHECK_SANITY1-NEXT: global // CHECK_SANITY1-NEXT: s:v10cursor_usr6globalSi // CHECK_SANITY1-NEXT: Int // CHECK_SANITY1-NEXT: <Declaration>var global: <Type usr="s:Si">Int</Type></Declaration> // CHECK_SANITY1-NEXT: <decl.var.global><syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>global</decl.name>: <decl.var.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.type></decl.var.global> // Bogus USR. // RUN: %sourcekitd-test -req=cursor -usr "s:blahblahblah" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck %s -check-prefix=EMPTY // Missing s: prefix. // RUN: %sourcekitd-test -req=cursor -usr "v10cursor_usr6globalSi" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck %s -check-prefix=EMPTY // FIXME: no support for clang USRs. // RUN: %sourcekitd-test -req=cursor -usr "c:@S@FooStruct1" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck %s -check-prefix=EMPTY // EMPTY: <empty cursor info> // FIXME: missing symbol shows up as some other part of the USR (the type here). // RUN: %sourcekitd-test -req=cursor -usr "s:v10cursor_usr11global_noneSi" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck %s -check-prefix=SHOULD_BE_EMPTY // SHOULD_BE_EMPTY: source.lang.swift.decl.struct () // SHOULD_BE_EMPTY: Int // RUN: %sourcekitd-test -req=cursor -usr "s:V10cursor_usr2S1" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck %s -check-prefix=CHECK1 // CHECK1: source.lang.swift.decl.struct (7:8-7:10) // CHECK1: S1 // CHECK1: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>S1</decl.name></decl.struct> // RUN: %sourcekitd-test -req=cursor -usr "s:F14FooSwiftModule12fooSwiftFuncFT_Si" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck %s -check-prefix=CHECK2 // CHECK2: source.lang.swift.decl.function.free () // CHECK2: fooSwiftFunc() // CHECK2: () -> Int // CHECK2: FooSwiftModule // CHECK2: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>fooSwiftFunc</decl.name>() -&gt; <decl.function.returntype><ref.struct usr="s:Si">Int</ref.struct></decl.function.returntype></decl.function.free> // RUN: %sourcekitd-test -req=cursor -usr "s:F10cursor_usr3fooFVSC10FooStruct1VS_2S1" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck %s -check-prefix=CHECK3 // CHECK3: source.lang.swift.decl.function.free (9:6-9:24) // CHECK3: foo(_:) // CHECK3: (FooStruct1) -> S1 // CHECK3: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>(<decl.var.parameter><decl.var.parameter.name>x</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr="c:@S@FooStruct1">FooStruct1</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr="s:V10cursor_usr2S1">S1</ref.struct></decl.function.returntype></decl.function.free>
apache-2.0
0f555a5f573367392e71caf383e0f394
65.614035
441
0.70187
2.793966
false
true
false
false
roothybrid7/SharedKit
Tests/SharedKitTests/DictionaryExtensions.swift
1
1243
// // DictionaryExtensions.swift // SharedKit // // Created by Satoshi Ohki on 2016/10/10. // // import XCTest @testable import SharedKit class DictionaryExtensions: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testFiltered() { let sources: [String: Any] = ["foo": 1, "bar": "hoge", "buz": true, "spam": NSObject()] let expecters = ( foo: ["foo"], fooBuz: ["foo", "buz"], barSpam: ["bar", "spam"] ) var results = filtered(forKeyValues: sources, by: expecters.foo) XCTAssertEqual(results.keys.map { $0 }, expecters.foo) results = filtered(forKeyValues: sources, by: expecters.fooBuz) XCTAssertEqual(results.keys.map { $0 }.sorted(), expecters.fooBuz.sorted()) results = filtered(forKeyValues: sources, by: expecters.barSpam) XCTAssertEqual(results.keys.map { $0 }.sorted(), expecters.barSpam.sorted()) } }
mit
f04468c0ed41bdcb3a038c143ae6f930
30.871795
111
0.620274
3.933544
false
true
false
false
antitypical/Manifold
Manifold/Module+Maybe.swift
1
621
// Copyright © 2015 Rob Rix. All rights reserved. extension Module { public static var maybe: Module { let Maybe = Declaration.Datatype("Maybe", .Argument("A", .Type, [ "just": .Argument("a", "A", .End), "nothing": .End ] )) let just: Term = "just" let nothing: Term = "nothing" let map = Declaration("Maybe.map", type: (nil, nil) => { A, B in (A --> B) --> Maybe.ref[A] --> Maybe.ref[B] }, value: (nil, nil) => { A, B in (A --> B, nil) => { transform, maybe in maybe[nil, nil => { just[nil, transform[$0]] }, nothing[Term.Implicit]] } }) return Module("Maybe", [ Maybe, map ]) } }
mit
4ffdbc0876cad4518bee3b14a7ec388a
30
150
0.567742
2.910798
false
false
false
false
JGiola/swift-package-manager
Sources/Basic/OrderedDictionary.swift
2
3672
/* This source file is part of the Swift.org open source project Copyright (c) 2018 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 Swift project authors */ /// A generic collection to store key-value pairs in the order they were inserted in. /// /// This is modelled after the stdlib's Dictionary. public struct OrderedDictionary<Key: Hashable, Value> { /// The element type of a dictionary: a tuple containing an individual /// key-value pair. public typealias Element = (key: Key, value: Value) /// The underlying storage for the OrderedDictionary. fileprivate var array: [Key] fileprivate var dict: [Key: Value] /// Create an empty OrderedDictionary object. public init() { self.array = [] self.dict = [:] } /// Accesses the value associated with the given key for reading and writing. /// /// This *key-based* subscript returns the value for the given key if the key /// is found in the dictionary, or `nil` if the key is not found. public subscript(key: Key) -> Value? { get { return dict[key] } set { if let newValue = newValue { updateValue(newValue, forKey: key) } else { removeValue(forKey: key) } } } /// Updates the value stored in the dictionary for the given key, or adds a /// new key-value pair if the key does not exist. /// /// Use this method instead of key-based subscripting when you need to know /// whether the new value supplants the value of an existing key. If the /// value of an existing key is updated, `updateValue(_:forKey:)` returns /// the original value. @discardableResult public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? { // If there is already a value for this key, replace and return the old value. if let oldValue = dict[key] { dict[key] = value return oldValue } // Otherwise, create a new entry. dict[key] = value array.append(key) return nil } /// Removes the given key and its associated value from the dictionary. /// /// If the key is found in the dictionary, this method returns the key's /// associated value. @discardableResult public mutating func removeValue(forKey key: Key) -> Value? { guard let value = dict[key] else { return nil } dict[key] = nil array.remove(at: array.index(of: key)!) return value } } extension OrderedDictionary: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (Key, Value)...) { self.init() for element in elements { updateValue(element.1, forKey: element.0) } } } extension OrderedDictionary: CustomStringConvertible { public var description: String { var string = "[" for (idx, key) in array.enumerated() { string += "\(key): \(dict[key]!)" if idx != array.count - 1 { string += ", " } } string += "]" return string } } extension OrderedDictionary: RandomAccessCollection { public var startIndex: Int { return array.startIndex } public var endIndex: Int { return array.endIndex } public subscript(index: Int) -> Element { let key = array[index] let value = dict[key]! return (key, value) } }
apache-2.0
c686836f69d0f7218a655a76d7a87935
31.210526
86
0.614107
4.601504
false
false
false
false
MiniDOM/MiniDOM
Sources/MiniDOM/Search.swift
1
2585
// // Search.swift // MiniDOM // // Copyright 2017-2020 Anodized Software, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import Foundation class ElementSearch: Visitor { private(set) var elements: [Element] = [] let predicate: (Element) -> Bool init(predicate: @escaping (Element) -> Bool) { self.predicate = predicate } func beginVisit(_ element: Element) { if predicate(element) { elements.append(element) } } } public extension Document { /** Traverses the document tree, collecting `Element` nodes with the specified tag name from anywhere in the document. - parameter name: Collect elements with this tag name. - returns: An array of elements with the specified tag name. */ final func elements(withTagName name: String) -> [Element] { return elements(where: { $0.tagName == name }) } /** Traverses the document tree, collecting `Element` nodes that satisfy the given predicate from anywhere in the document. - parameter predicate: A closure that takes an element as its argument and returns a Boolean value indicating whether the element should be included in the returned array. - returns: An array of the elements that `predicate` allowed. */ final func elements(where predicate: @escaping (Element) -> Bool) -> [Element] { let visitor = ElementSearch(predicate: predicate) documentElement?.accept(visitor) return visitor.elements } }
mit
2ad3eb960984a516b5c937d909bfa85d
34.902778
84
0.700193
4.487847
false
false
false
false
dathtcheapgo/Jira-Demo
Driver/Extension/UIViewExtension.swift
1
16282
// // UIViewExtension.swift // drivers // // Created by Đinh Anh Huy on 10/10/16. // Copyright © 2016 Đinh Anh Huy. All rights reserved. // import UIKit extension UIView { //MARK: Layer func makeRoundedConner(radius: CGFloat = 10) { self.layer.cornerRadius = radius self.clipsToBounds = true } func copyView() -> UIView { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! UIView } } //MARK: Indicator extension UIView { func showIndicator(indicatorStyle: UIActivityIndicatorViewStyle, blockColor: UIColor, alpha: CGFloat) { OperationQueue.main.addOperation { for currentView in self.subviews { if currentView.tag == 9999 { return } } let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = blockColor viewBlock.alpha = alpha viewBlock.translatesAutoresizingMaskIntoConstraints = false self.addSubview(viewBlock) _ = viewBlock.addConstraintFillInView(view: self, commenParrentView: self) let indicator = UIActivityIndicatorView(activityIndicatorStyle: indicatorStyle) indicator.frame = CGRect( x: self.frame.width/2-25, y: self.frame.height/2-25, width: 50, height: 50) viewBlock.addSubview(indicator) indicator.startAnimating() } } func showIndicator() { OperationQueue.main.addOperation { for currentView in self.subviews { if currentView.tag == 9999 { return } } let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = UIColor.black viewBlock.alpha = 0.3 viewBlock.layer.cornerRadius = self.layer.cornerRadius let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white) viewBlock.translatesAutoresizingMaskIntoConstraints = false self.addSubview(viewBlock) _ = viewBlock.addConstraintFillInView(view: self, commenParrentView: self) indicator.translatesAutoresizingMaskIntoConstraints = false viewBlock.addSubview(indicator) _ = indicator.addConstraintCenterXToView(view: self, commonParrentView: self) _ = indicator.addConstraintCenterYToView(view: self, commonParrentView: self) indicator.startAnimating() } } func showIndicator(frame: CGRect, blackStyle: Bool = false) { let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = UIColor.white viewBlock.frame = frame let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) indicator.frame = CGRect( x: self.frame.width/2-25, y: self.frame.height/2-25, width: 50, height: 50) viewBlock.addSubview(indicator) self.addSubview(viewBlock) indicator.startAnimating() } func hideIndicator() { let indicatorView = self.viewWithTag(9999) indicatorView?.removeFromSuperview() for currentView in self.subviews { if currentView.tag == 9999 { let _view = currentView OperationQueue.main.addOperation { _view.removeFromSuperview() } } } } } //MARK: Animation extension UIView { func moveToFrameWithAnimation(newFrame: CGRect, delay: TimeInterval, time: TimeInterval) { UIView.animate(withDuration: time, delay: delay, options: .curveEaseOut, animations: { self.frame = newFrame }, completion:nil) } func fadeOut(time: TimeInterval, delay: TimeInterval) { self.isUserInteractionEnabled = false UIView.animate(withDuration: time, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: { self.alpha = 0.0 }, completion: { (finished: Bool) -> Void in if finished == true { self.isHidden = true } }) } func fadeIn(time: TimeInterval, delay: TimeInterval) { self.isUserInteractionEnabled = true self.alpha = 0 self.isHidden = false UIView.animate(withDuration: time, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: { self.alpha = 1.0 }, completion: { (finished: Bool) -> Void in if finished == true { } }) } } //MARK: Add constraint extension UIView { func leadingMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func trailingMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintTopToBot(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintBotToTop(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintBotMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintTopMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { // self.setTranslatesAutoresizingMaskIntoConstraints(false) let constraint = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintWidth(parrentView: UIView, width: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: width) parrentView.addConstraint(constraint) return constraint } func addConstraintHeight(parrentView: UIView, height: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: height) parrentView.addConstraint(constraint) return constraint } func addConstraintLeftToRight(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.right, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintRightToLeft(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintCenterYToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintCenterXToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintEqualHeightToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.height, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintEqualWidthToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintFillInView(view: UIView, commenParrentView: UIView, margins: [CGFloat]? = nil) -> (top: NSLayoutConstraint, bot: NSLayoutConstraint, lead: NSLayoutConstraint, trail: NSLayoutConstraint) { var mutableMargins = margins if mutableMargins == nil { mutableMargins = [0, 0, 0, 0] } let top = addConstraintTopMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![0]) let trail = trailingMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![1]) let bot = addConstraintBotMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![2]) let lead = leadingMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![3]) return (top, bot, lead, trail) } } //MARK: Get constraint from superview extension UIView { func constraintTop() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isTopConstraint() else { continue } return constraint } return nil } func constraintBot() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isBotConstraint() else { continue } return constraint } return nil } func constraintLead() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isLeadConstraint() else { continue } return constraint } return nil } func constraintTrail() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isTrailConstraint() else { continue } return constraint } return nil } }
mit
94da2428a15f7e7af789cf06c87d5419
41.064599
123
0.532834
6.177989
false
false
false
false
benlangmuir/swift
test/Concurrency/Runtime/actor_keypaths.swift
8
2241
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking) // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime actor Page { let initialNumWords : Int private let numWordsMem: UnsafeMutablePointer<Int> nonisolated var numWords : Int { get { numWordsMem.pointee } set { numWordsMem.pointee = newValue } } private init(withWords words : Int) { initialNumWords = words numWordsMem = .allocate(capacity: 1) numWordsMem.initialize(to: words) } convenience init(_ words: Int) { self.init(withWords: words) numWords = words } deinit { numWordsMem.deallocate() } } actor Book { let pages : [Page] init(_ numPages : Int) { var stack : [Page] = [] for i in 0 ..< numPages { stack.append(Page(i)) } pages = stack } nonisolated subscript(_ page : Int) -> Page { return pages[page] } } func bookHasChanged(_ b : Book, currentGetter : KeyPath<Page, Int>, initialGetter : (Page) -> Int) -> Bool { let numPages = b[keyPath: \.pages.count] for i in 0 ..< numPages { let pageGetter = \Book.[i] let currentWords = pageGetter.appending(path: currentGetter) if (b[keyPath: currentWords] != initialGetter(b[keyPath: pageGetter])) { return true } } return false } func enumeratePageKeys(from : Int, to : Int) -> [KeyPath<Book, Page>] { var keys : [KeyPath<Book, Page>] = [] for i in from ..< to { keys.append(\Book.[i]) } return keys } func erasePages(_ book : Book, badPages: [KeyPath<Book, Page>]) { for page in badPages { book[keyPath: page].numWords = 0 } } let book = Book(100) if bookHasChanged(book, currentGetter: \Page.numWords, initialGetter: \Page.initialNumWords) { fatalError("book should not be changed") } erasePages(book, badPages: enumeratePageKeys(from: 0, to: 100)) guard bookHasChanged(book, currentGetter: \Page.numWords, initialGetter: \Page.initialNumWords) else { fatalError("book should be wiped!") }
apache-2.0
933640a52b23ed4ad9179bd87ea72722
23.096774
102
0.610442
3.779089
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Settings/SettingsContentViewController.swift
2
6329
// 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 Shared import SnapKit import UIKit import WebKit let DefaultTimeoutTimeInterval = 10.0 // Seconds. We'll want some telemetry on load times in the wild. /** * A controller that manages a single web view and provides a way for * the user to navigate back to Settings. */ class SettingsContentViewController: UIViewController, WKNavigationDelegate, Themeable { var themeManager: ThemeManager var themeObserver: NSObjectProtocol? var notificationCenter: NotificationProtocol var settingsTitle: NSAttributedString? var url: URL! var timer: Timer? var isLoaded: Bool = false { didSet { if isLoaded { UIView.transition( from: interstitialView, to: settingsWebView, duration: 0.5, options: .transitionCrossDissolve, completion: { finished in self.interstitialView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } fileprivate var isError: Bool = false { didSet { if isError { interstitialErrorView.isHidden = false UIView.transition( from: interstitialSpinnerView, to: interstitialErrorView, duration: 0.5, options: .transitionCrossDissolve, completion: { finished in self.interstitialSpinnerView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } // The view shown while the content is loading in the background web view. fileprivate var interstitialView: UIView! fileprivate var interstitialSpinnerView: UIActivityIndicatorView! fileprivate var interstitialErrorView: UILabel! // The web view that displays content. var settingsWebView: WKWebView! fileprivate func startLoading(_ timeout: Double = DefaultTimeoutTimeInterval) { if self.isLoaded { return } if timeout > 0 { self.timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(didTimeOut), userInfo: nil, repeats: false) } else { self.timer = nil } self.settingsWebView.load(PrivilegedRequest(url: url) as URLRequest) self.interstitialSpinnerView.startAnimating() } init(title: NSAttributedString? = nil, themeManager: ThemeManager = AppContainer.shared.resolve(), notificationCenter: NotificationCenter = NotificationCenter.default) { self.settingsTitle = title self.themeManager = themeManager self.notificationCenter = notificationCenter super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.settingsWebView = makeWebView() view.addSubview(settingsWebView) self.settingsWebView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } // Destructuring let causes problems. let ret = makeInterstitialViews() self.interstitialView = ret.view self.interstitialSpinnerView = ret.activityView self.interstitialErrorView = ret.label view.addSubview(interstitialView) self.interstitialView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } startLoading() applyTheme() listenForThemeChange() } func makeWebView() -> WKWebView { let config = TabManager.makeWebViewConfig(isPrivate: true, prefs: nil) config.preferences.javaScriptCanOpenWindowsAutomatically = false let webView = WKWebView( frame: CGRect(width: 1, height: 1), configuration: config ) webView.allowsLinkPreview = false webView.navigationDelegate = self // This is not shown full-screen, use mobile UA webView.customUserAgent = UserAgent.mobileUserAgent() return webView } struct InterstitialViews { let view: UIView let activityView: UIActivityIndicatorView let label: UILabel } fileprivate func makeInterstitialViews() -> InterstitialViews { let view = UIView() let spinner = UIActivityIndicatorView(style: .medium) spinner.color = themeManager.currentTheme.colors.iconSpinner view.addSubview(spinner) let error = UILabel() if settingsTitle != nil { error.text = .SettingsContentPageLoadError error.textColor = themeManager.currentTheme.colors.textWarning error.textAlignment = .center } error.isHidden = true view.addSubview(error) spinner.snp.makeConstraints { make in make.center.equalTo(view) return } error.snp.makeConstraints { make in make.center.equalTo(view) make.left.equalTo(view.snp.left).offset(20) make.right.equalTo(view.snp.right).offset(-20) make.height.equalTo(44) return } return InterstitialViews(view: view, activityView: spinner, label: error) } @objc func didTimeOut() { self.timer = nil self.isError = true } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { didTimeOut() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { didTimeOut() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.timer?.invalidate() self.timer = nil self.isLoaded = true } func applyTheme() { view.backgroundColor = themeManager.currentTheme.colors.layer2 } }
mpl-2.0
99f0deb4f01acc90bb5ed1170ceb7a4c
31.623711
146
0.626323
5.423308
false
false
false
false
benlangmuir/swift
test/IRGen/dynamic_replaceable_opaque_return.swift
22
4374
// RUN: %target-swift-frontend -disable-availability-checking -module-name A -swift-version 5 -primary-file %s -emit-ir | %FileCheck %s // The arm64e test is in ptrauth-dynamic_replaceable.sil. // UNSUPPORTED: CPU=arm64e // REQUIRES: objc_interop // No 32bit for now. // UNSUPPORTED: CPU=armv7 // UNSUPPORTED: CPU=armv7s // UNSUPPORTED: CPU=i386 // CHECK: @"$s1A3baryQrSiFQOMk" = global %swift.dyn_repl_link_entry { {{.*}}@"$s1A3baryQrSiFQOMh" to i8*), %swift.dyn_repl_link_entry* null } // CHECK: @"$s1A3baryQrSiFQOMj" = constant %swift.dyn_repl_key { {{.*}}%swift.dyn_repl_link_entry* @"$s1A3baryQrSiFQOMk"{{.*}}, i32 0 }, section "__TEXT,__const" // CHECK: @"$s1A16_replacement_bar1yQrSi_tFQOMk" = global %swift.dyn_repl_link_entry zeroinitializer // CHECK: @"\01l_unnamed_dynamic_replacements" = // CHECK-SAME: private constant { i32, i32, [4 x { i32, i32, i32, i32 }] } // CHECK-SAME: { i32 0, i32 4, [4 x { i32, i32, i32, i32 }] [ // CHECK-SAME: { i32, i32, i32, i32 } { {{.*}}%swift.dyn_repl_key* @"$s1A3baryQrSiFTx"{{.*}}@"$s1A16_replacement_bar1yQrSi_tF"{{.*}}%swift.dyn_repl_link_entry* @"$s1A16_replacement_bar1yQrSi_tFTX"{{.*}}, i32 0 }, { i32, i32, i32, i32 } { {{.*}}%swift.dyn_repl_key* @"$s1A9ContainerV4propQrvgTx"{{.*}}@"$s1A9ContainerV7_r_propQrvg"{{.*}}, i32 0 }, { i32, i32, i32, i32 } { {{.*}}%swift.dyn_repl_key* @"$s1A3baryQrSiFQOMj"{{.*}},{{.*}}@"$s1A16_replacement_bar1yQrSi_tFQOMg"{{.*}},{{.*}}@"$s1A16_replacement_bar1yQrSi_tFQOMk"{{.*}}, i32 0 }, { i32, i32, i32, i32 } { {{.*}}%swift.dyn_repl_key* @"$s1A9ContainerV4propQrvpQOMj"{{.*}},{{.*}}@"$s1A9ContainerV7_r_propQrvpQOMg"{{.*}},{{.*}}@"$s1A9ContainerV7_r_propQrvpQOMk"{{.*}}, i32 0 }] } // CHECK: , section "__TEXT,__const" public protocol P { func myValue() -> Int } extension Int: P { public func myValue() -> Int { return self } } // Opaque result type descriptor accessor for bar. // CHECK-LABEL: define{{.*}} swiftcc %swift.type_descriptor* @"$s1A3baryQrSiFQOMg"() // CHECK: entry: // CHECK: %0 = load i8*, i8** getelementptr inbounds (%swift.dyn_repl_link_entry, %swift.dyn_repl_link_entry* @"$s1A3baryQrSiFQOMk", i32 0, i32 0) // CHECK: %1 = bitcast i8* %0 to %swift.type_descriptor* ()* // CHECK: %2 = tail call swiftcc %swift.type_descriptor* %1() // CHECK: ret %swift.type_descriptor* %2 // CHECK: } // Opaque result type descriptor accessor impl. // CHECK-LABEL: define{{.*}} swiftcc %swift.type_descriptor* @"$s1A3baryQrSiFQOMh"() // CHECK: entry: // CHECK: ret %swift.type_descriptor* bitcast ({{.*}}* @"$s1A3baryQrSiFQOMQ" to %swift.type_descriptor*) // CHECK: } public dynamic func bar(_ x: Int) -> some P { return x } struct Pair : P { var x = 0 var y = 1 func myValue() -> Int{ return y } } // Opaque result type descriptor accessor for _replacement_bar. // CHECK: define{{.*}} swiftcc %swift.type_descriptor* @"$s1A16_replacement_bar1yQrSi_tFQOMg"() // CHECK: entry: // CHECK: ret %swift.type_descriptor* bitcast ({{.*}} @"$s1A16_replacement_bar1yQrSi_tFQOMQ" to %swift.type_descriptor*) // CHECK: } @_dynamicReplacement(for:bar(_:)) public func _replacement_bar(y x: Int) -> some P { return Pair() } struct Container { dynamic var prop : some P { get { return 0 } } } // CHECK: define{{.*}} hidden swiftcc %swift.type_descriptor* @"$s1A9ContainerV4propQrvpQOMg"() // CHECK: entry: // CHECK: %0 = load i8*, i8** getelementptr inbounds (%swift.dyn_repl_link_entry, %swift.dyn_repl_link_entry* @"$s1A9ContainerV4propQrvpQOMk", i32 0, i32 0) // CHECK: %1 = bitcast i8* %0 to %swift.type_descriptor* ()* // CHECK: %2 = tail call swiftcc %swift.type_descriptor* %1() // CHECK: ret %swift.type_descriptor* %2 // CHECK: define{{.*}} hidden swiftcc %swift.type_descriptor* @"$s1A9ContainerV4propQrvpQOMh"() // CHECK: entry: // CHECK: ret %swift.type_descriptor* bitcast ({{.*}} @"$s1A9ContainerV4propQrvpQOMQ" to %swift.type_descriptor*) extension Container { @_dynamicReplacement(for: prop) var _r_prop : some P { get { return 1 } } } // CHECK: define{{.*}} hidden swiftcc %swift.type_descriptor* @"$s1A9ContainerV7_r_propQrvpQOMg"() // CHECK: entry: // CHECK: ret %swift.type_descriptor* bitcast ({{.*}} @"$s1A9ContainerV7_r_propQrvpQOMQ" to %swift.type_descriptor*) // CHECK-NOT: s1A16noOpaqueAccessor{{.*}}Mg public func noOpaqueAccessor() -> some P { return 0 }
apache-2.0
83bafa5c370f66cd69ea6d7660828c87
41.882353
738
0.650206
2.871963
false
false
false
false
jfrowies/iEMI
iEMI/AccountEMIService.swift
1
5481
// // AccountEMIService.swift // iEMI // // Created by Fer Rowies on 8/18/15. // Copyright © 2015 Rowies. All rights reserved. // import UIKit class AccountEMIService: NSObject { var service: EMIService = EMIService() func accountBalance(licensePlate licensePlate:String, completion: (result: () throws -> Double) -> Void) -> Void { let endpointURL = "WorkWithDevicesEMCredito_EMCredito_List" let parameters = ["CreditoChapa":licensePlate] service.get(endpointURL, parameters: parameters) { (response) -> Void in completion (result: { () -> Double in do { if let jsonBalance = try response() as? [String:String] { if let balance = jsonBalance["Creditosaldo"] { return (balance as NSString).doubleValue } } //if reached this point the response data was not valid throw ServiceError.ResponseInformationError } }) } } func credits(licensePlate licensePlate:String, start:Int, cant:Int ,completion: (result: () throws -> [Credit]) -> Void) -> Void { let endpointURL = "WorkWithDevicesEMCredito_EMCredito_List_Grid1" let parameters = ["CreditoChapa":licensePlate,"start":String(start), "count":String(cant)] service.get(endpointURL, parameters: parameters) { (response) -> Void in completion (result: { () -> [Credit] in do { if let jsonCredits = try response() as? [[String:AnyObject]] { var credits = [Credit]() for jsonCredit in jsonCredits { credits.append(Credit(json: jsonCredit)) } return credits } //if reached this point the response data was not valid throw ServiceError.ResponseInformationError } }) } } func debits(licensePlate licensePlate:String, fromTimeStamp:String ,completion: (result: () throws -> [Debit]) -> Void) -> Void { let endpointURL = "WorkWithDevicesTarjetas_UltimosConsumos_List_Grid2" let parameters = ["TarChapa":licensePlate, "Tarhoraini":fromTimeStamp] service.get(endpointURL, parameters: parameters) { (response) -> Void in completion (result: { () -> [Debit] in do { if let jsonDebits = try response() as? [[String:AnyObject]] { var debits = [Debit]() for jsonDebit in jsonDebits { debits.append(Debit(json: jsonDebit)) } return debits } //if reached this point the response data was not valid throw ServiceError.ResponseInformationError } }) } } func balance(licensePlate licensePlate:String, completion: (result: () throws -> [Transaction]) -> Void) -> Void { var transactions = [Transaction]() self.credits(licensePlate: licensePlate, start: 0, cant: 5) { [unowned self] (result) -> Void in do { let credits = try result() guard credits.count != 0 else { completion() { return transactions } return } for credit in credits { transactions.append(credit) } self.sortElements(&transactions) self.debits(licensePlate: licensePlate, fromTimeStamp: transactions.last!.timestamp) { [unowned self, transactions] (result) -> Void in do { var creditsAndDebits = [Transaction]() creditsAndDebits.appendContentsOf(transactions) let debits = try result() for debit in debits { creditsAndDebits.append(debit) } self.sortElements(&creditsAndDebits) completion() { return creditsAndDebits } } catch let error{ completion () { throw error } } } } catch let error{ completion () { throw error } } } } private func sortElements(inout elements:[Transaction]) { elements.sortInPlace({ (mov1: Transaction, mov2: Transaction) -> Bool in if mov1.timestamp > mov2.timestamp { return true } if mov1.timestamp == mov2.timestamp { if mov1.isKindOfClass(Debit) { //debits first return true }else { return false } } //mov1.timestamp < mov2.timestamp return false }) } }
apache-2.0
7271955b7747ed116b3a1bf2c8df106b
35.785235
151
0.471168
5.632066
false
false
false
false
mattt/Euler
Sources/Euler/Vectors.swift
1
2190
import Foundation // MARK: Dot Product /// The dot product operator. infix operator ⋅ /// Returns the dot product of two vectors. /// /// - Parameters: /// - lhs: A vector of numbers. /// - rhs: Another vector of numbers. public func ⋅ <T>(lhs: [T], rhs: [T]) -> T where T : Numeric & ExpressibleByIntegerLiteral { precondition(lhs.count == rhs.count, "arguments must have same count") return ∑zip(lhs, rhs).map(×) } // MARK: Cross Product /// Returns the cross product of two three-element vectors. /// /// - Parameters: /// - lhs: A vector of three numbers. /// - rhs: Another vector of three numbers. public func × <T>(lhs: (T, T, T), rhs: (T, T, T)) -> (T, T, T) where T : Numeric { let a = lhs.1 * rhs.2 - lhs.2 * rhs.1 let b = lhs.2 * rhs.0 - lhs.0 * rhs.2 let c = lhs.0 * rhs.1 - lhs.1 * rhs.0 return (a, b, c) } // Mark: Norm /// The norm operator. prefix operator ‖ /// Returns the norm of a vector. /// /// - Parameters: /// - vector: A vector of numbers. public prefix func ‖ <S: Sequence>(vector: S) -> Double where S.Element == Double { return √(∑vector.map({$0 * $0})) } /// Returns the norm of a vector. /// /// - Parameters: /// - vector: A vector of numbers. public prefix func ‖ <S: Sequence>(vector: S) -> Float where S.Element == Float { return √(∑vector.map({$0 * $0})) } // MARK: Angle /// The angle operator. infix operator ⦡ /// Returns the angle between two vectors. /// /// - Parameters: /// - lhs: A vector of numbers. /// - rhs: Another vector of numbers. /// - Important: Arguments must have the same count. public func ⦡ (lhs: [Double], rhs: [Double]) -> Double { precondition(lhs.count == rhs.count, "arguments must have same count") return acos((lhs ⋅ rhs) / (‖lhs * ‖rhs)) } /// Returns the angle between two vectors. /// /// - Parameters: /// - lhs: A vector of numbers. /// - rhs: Another vector of numbers. /// - Important: Arguments must have the same count. public func ⦡ (lhs: [Float], rhs: [Float]) -> Float { precondition(lhs.count == rhs.count, "arguments must have same count") return acos((lhs ⋅ rhs) / (‖lhs * ‖rhs)) }
mit
6f91d88c834293ee4b643a48d7cad793
26.21519
92
0.610233
3.189911
false
false
false
false
awswift/swiftda
Sources/SwiftLambdaKit/LineChunker.swift
1
720
class LineChunker { private var chunk: String private var callback: (_: String) -> Void init(callback: @escaping (_: String) -> Void) { self.chunk = "" self.callback = callback } func append(_ string: String) { chunk.append(string) while let newlineRange = chunk.rangeOfCharacter(from: .newlines) { let line = chunk.substring(to: newlineRange.lowerBound) callback(line) chunk = chunk.substring(from: newlineRange.upperBound) } } func remainder() -> String? { defer { chunk = "" } if chunk.characters.count > 0 { return chunk } else { return nil } } }
apache-2.0
44fc0918d97facd529ccaf58cbe01d23
23.827586
74
0.547222
4.47205
false
false
false
false
sudiptasahoo/IVP-Luncheon
IVP Luncheon/SSNetworkHandshake.swift
1
1953
// // SSNetworkHandshake.swift // IVP Luncheon // // Created by Sudipta Sahoo on 22/05/17. // Copyright © 2017 Sudipta Sahoo <[email protected]>. This file is part of Indus Valley Partners interview process. This file can not be copied and/or distributed without the express permission of Sudipta Sahoo. All rights reserved. // import UIKit import Foundation //This is the Network Interceptor and single point of entry/exit for any network call throughout the app class SSNetworkHandshake: NSObject { func getJsonResponse(fromRequest request: URLRequest, success: @escaping (_ data: Data) -> Void, failure:@escaping (_ error: Error)->Void){ print(String(describing: request.url)) let session = URLSession.shared if(currentReachabilityState != .notReachable){ //Network connectivity present //This cud have been achieved through AlamofireNetworkActivityIndicator //But below is my custom implimentation to handle iOS Network Indicator effectively SSCommonUtilities.addTaskToNetworkQueue() let task = session.dataTask(with: request, completionHandler: { (data, response, error) in SSCommonUtilities.removeTaskFromNetworkQueue() if(error == nil) { success(data!); } else { failure(error!); } }) task.resume() } else { //Network connectivity not present let userInfo: [String : AnyHashable] = [ NSLocalizedDescriptionKey : NSLocalizedString("Internet Not Available", value: "", comment: "Please check your network."), ] let err = NSError(domain: "com.sudipta.apiResponseErrorDomain", code: 400, userInfo: userInfo) failure(err) } } }
apache-2.0
7acbb31482521f26c767e9caf75fd189
38.04
236
0.609631
5.191489
false
false
false
false
quaderno/quaderno-ios
Source/Client.swift
2
8504
// // Client.swift // // Copyright (c) 2015 Recrea (http://recreahq.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 Foundation import Alamofire /// An HTTP client sending requests to a web service exposing the Quaderno API. /// /// - Seealso: [Quaderno API](https://quaderno.io/docs/api/). open class Client { /// The base URL of the service. public let baseURL: URL /// The token authenticating every request. public let authenticationToken: String /// The HTTP headers authorizing every request. var authorizationHeaders: [String: String] { guard let credentialData = "\(authenticationToken):".data(using: String.Encoding.utf8) else { assertionFailure("Failed to encode the authentication token to UTF-8.") return [:] } let base64Credentials = credentialData.base64EncodedString() return ["Authorization": "Basic \(base64Credentials)"] } // MARK: Initialization /// Initialize a client with a base URL and an authentication token. /// /// - Parameters: /// - baseURL: The base URL of the web service. /// - authenticationToken: The token authenticating every request. public init(baseURL: URL, authenticationToken: String) { self.baseURL = baseURL self.authenticationToken = authenticationToken } // MARK: Connection Entitlements /// The entitlements granted to a client for using the web service. /// /// - Seealso: [Rate Limiting](https://quaderno.io/docs/api/#rate-limiting). public struct Entitlements { /// The time interval in seconds until `remainingRequests` is set to the maximum allowed value. public let resetInterval: TimeInterval /// The number of remaining requests until the next cycle. public let remainingRequests: Int /// Keys in HTTP header related to entitlements. enum HTTPHeader: String { case rateLimitReset = "X-RateLimit-Reset" case rateLimitRemainingRequests = "X-RateLimit-Remaining" } } /// The entitlements currently granted. public fileprivate(set) var entitlements: Entitlements? } // MARK: - Sending Requests private func noop<T>(_ value: T) {} private extension HTTPMethod { var alamofired: Alamofire.HTTPMethod { guard let afMethod = Alamofire.HTTPMethod(rawValue: rawValue) else { fatalError("Failed to create the equivalent HTTP method of \(self) in Alamofire") } return afMethod } } extension Client.Entitlements { /// Initialize a set of entitlements with a dictionary of HTTP headers. /// /// - Precondition: All expected headers MUST be present. /// /// - Parameter httpHeaders: A dictionary of HTTP headers, as represented in `HTTPURLResponse`. init?(httpHeaders: [String: Any]) { guard let resetIntervalValue = httpHeaders[HTTPHeader.rateLimitReset.rawValue] as? String else { return nil } guard let resetInterval = TimeInterval(resetIntervalValue) else { return nil } guard let remainingRequestsValue = httpHeaders[HTTPHeader.rateLimitRemainingRequests.rawValue] as? String else { return nil } guard let remainingRequests = Int(remainingRequestsValue) else { return nil } self.resetInterval = resetInterval self.remainingRequests = remainingRequests } fileprivate static func updateEntitlements(of client: Client, with response: HTTPURLResponse?) { guard let httpHeaders = response?.allHeaderFields as? [String: Any] else { return } client.entitlements = Client.Entitlements(httpHeaders: httpHeaders) } } extension Client { private func dataRequest(validating request: Request) -> Alamofire.DataRequest { return Alamofire.request(request.uri(using: baseURL), method: request.method.alamofired, parameters: request.parameters, encoding: JSONEncoding.default, headers: authorizationHeaders).validate() } /// Send a request to the web service expecting a given response. /// /// - Parameters: /// - request: The request to send. /// - completion: A closure to execute once the request is finished. public func send<T>(_ request: Request, completion: @escaping (Response<T>) -> Void = noop) { dataRequest(validating: request).responseJSON { response in Entitlements.updateEntitlements(of: self, with: response.response) switch response.result { case .success(let value): if let transformedValue = value as? T { completion(.success(transformedValue, Page(httpResponse: response.response))) } else { let error = ErrorResponse.typeMismatch(expected: T.self, found: type(of: value)) completion(.failure(error)) } case .failure(let error): let serviceError = ErrorResponse.serviceError(error as NSError) completion(.failure(serviceError)) } } } /// Send a request to the web service expecting an empty response. /// /// - Parameters: /// - request: The request to send. /// - completion: A closure to execute once the request is finished. public func send(_ request: Request, completion: @escaping EmptyResponseHandler = noop) { dataRequest(validating: request).response { response in Entitlements.updateEntitlements(of: self, with: response.response) if let error = response.error { completion(.serviceError(error as NSError)) } else { completion(nil) } } } } // MARK: - Sending a Ping Request extension Client { struct PingRequest: Request { func uri(using baseURL: URL) -> URL { return baseURL.appendingPathComponent("ping").toJSON } } /// Ping the service. /// /// - Parameter completion: A closure to execute once the request is finished. /// /// - Seealso: [Ping the API](https://quaderno.io/docs/api/#authentication). public func ping(_ completion: @escaping EmptyResponseHandler = noop) { send(PingRequest(), completion: completion) } } // MARK: - Sending an Authorization Request extension Client { struct AuthorizationRequest: Request { func uri(using baseURL: URL) -> URL { // Input base URL is ignored because the authorization resource is not tied to any account. guard let baseURL = URL(string: "https://quadernoapp.com/api") else { fatalError("Cannot build base URL for authorization") } return baseURL.appendingPathComponent("authorization").toJSON } } /// Ask the service for the account associated with an authorized user. /// /// - Parameter completion: A closure to execute once the request if finished /// /// - Seealso: [Authorization](https://quaderno.io/docs/api/#authorization). public func account(_ completion: @escaping JSONResponseHandler = noop) { send(AuthorizationRequest(), completion: completion) } }
mit
515b9c12b747905f6f9eb28cce91e581
33.42915
120
0.647695
4.929855
false
false
false
false
serp1412/LazyTransitions
LazyTransitions/TransitionProgressCalculator.swift
1
1926
// // TransitionProgressCalculator.swift // LazyTransitions // // Created by Serghei Catraniuc on 12/2/16. // Copyright © 2016 BeardWare. All rights reserved. // import Foundation public enum TransitionOrientation: CaseIterable { case unknown case topToBottom case bottomToTop case leftToRight case rightToLeft } public struct TransitionProgressCalculator { public static func progress(for view: UIView, withGestureTranslation translation: CGPoint, withTranslationOffset translationOffset: CGPoint, with orientation: TransitionOrientation) -> CGFloat { var progress:Float = 0 let adjustedTranslation = translation - translationOffset switch orientation { case .topToBottom: let verticalMovement = Float(adjustedTranslation.y / view.bounds.height) let downwardMovement = fmaxf(verticalMovement, 0.0) progress = fminf(downwardMovement, 1.0) case .bottomToTop: let verticalMovement = Float(adjustedTranslation.y / view.bounds.height) let upwardMovement = abs(fminf(verticalMovement, 0.0)) progress = fminf(upwardMovement, 1.0) case .leftToRight: let horizontalMovement = Float(adjustedTranslation.x / view.bounds.width) let leftToRightMovement = fmaxf(horizontalMovement, 0.0) progress = fminf(leftToRightMovement, 1.0) case .rightToLeft: let horizontalMovement = Float(adjustedTranslation.x / view.bounds.width) let rightToLeftMovement = abs(fminf(horizontalMovement, 0)) progress = fminf(rightToLeftMovement, 1) default: break } return CGFloat(progress) } } func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) }
bsd-2-clause
e779c533f140ef9a90653259f4100355
34.648148
85
0.645714
4.638554
false
false
false
false
netease-app/NIMSwift
Example/NIMSwift/Supporting Files/AppDelegate.swift
1
2586
// // AppDelegate.swift // NIMSwift // // Created by [email protected] on 06/29/2017. // Copyright (c) 2017 [email protected]. All rights reserved. // import UIKit import CFExtension @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { setupStyle() setupNIM() setupMainUI() NotificationCenter.default.addObserver(self, selector: #selector(setupMainUI), name: NSNotification.Name(rawValue: Constants.kNotificationTypeLogout), object: nil) return true } func setupStyle(){ UIApplication.shared.statusBarStyle = .default UINavigationBar.appearance().tintColor = UIColor(netHex: 0x1296db, alpha: 1) UINavigationBar.appearance().barTintColor = UIColor(netHex: 0xFFFFFF, alpha: 1) UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor(netHex: 0x1296db, alpha: 1)] UINavigationBar.appearance().autoresizingMask = [.flexibleWidth,.flexibleBottomMargin,.flexibleLeftMargin] UITabBar.appearance().barTintColor = UIColor(netHex:0xFFFFFF, alpha: 1) UITabBar.appearance().tintColor = UIColor(netHex: 0x1296db, alpha: 1) } func setupNIM(){ NIMSDK.shared().register(withAppID: Constants.kNIMKey, cerName: Constants.kNIMCerName) //关闭https(否则部分头像显示不出来) NIMSDKConfig.shared().enabledHttpsForInfo = false NIMSDKConfig.shared().enabledHttpsForMessage = false //print("###################" + NIMSDK.shared().currentLogFilepath()) } func setupMainUI(){ window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white if LoginManager.shareInstance.isLogin() { let data = LoginManager.shareInstance.loginData! NIMSDK.shared().loginManager.autoLogin(data.nimAccount!, token: data.nimToken!) window?.rootViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateInitialViewController() }else{ let vc = UIStoryboard.init(name: "User", bundle: nil).instantiateViewController(withIdentifier: "LoginController") let nav = UINavigationController(rootViewController: vc) window?.rootViewController = nav } window?.makeKeyAndVisible() } }
mit
03808bc80b5f184cb8efce06ff94fc4f
35.514286
171
0.676839
4.915385
false
false
false
false
mlgoogle/wp
wp/Other/AppDataHelper.swift
1
11614
// // AppDataHelper.swift // wp // // Created by 木柳 on 2017/1/18. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit import SVProgressHUD import Alamofire class AppDataHelper: NSObject { fileprivate static var helper = AppDataHelper() class func instance() -> AppDataHelper{ return helper } private var productTimer: Timer? func initData() { productTimer = Timer.scheduledTimer(timeInterval: 5 , target: self, selector: #selector(initProductData), userInfo: nil, repeats: AppConst.isRepeate) Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(initAllKlineChartData), userInfo: nil, repeats: AppConst.isRepeate) initProductData() if let userUUID = UIDevice.current.identifierForVendor?.uuidString{ UserModel.share().uuid = userUUID } checkTokenLogin() // ipAndPort() } //请求商品数据 func initProductData() { if UserModel.share().token.length() <= 0{ return } var allProducets: [ProductModel] = [] let param = ProductParam() AppAPIHelper.deal().products(param: param, complete: {[weak self](result) -> ()? in self?.productTimer?.invalidate() if let products: [ProductModel] = result as! [ProductModel]?{ //拼接所有商品 allProducets += products //商品分类 self?.checkAllProductKinds(allProducts: allProducets) DealModel.share().allProduct = allProducets //默认选择商品 if allProducets.count > 0{ DealModel.share().selectProduct = allProducets[0] } self?.initAllKlineChartData() } return nil }) {(error) -> ()? in SVProgressHUD.showErrorMessage(ErrorMessage: "商品数据获取失败,请稍候再试", ForDuration: 1.5, completion: nil) return nil } } //对所有商品进行分类 func checkAllProductKinds(allProducts: [ProductModel]) { for product in allProducts { if DealModel.share().productKinds.count == 0 { DealModel.share().productKinds.append(product) }else{ var isContent = false for kind in DealModel.share().productKinds{ if product.symbol == kind.symbol { isContent = true } } if isContent == false{ DealModel.share().productKinds.append(product) } } } } //根据商品分时数据 func initLineChartData(){ for product in DealModel.share().productKinds { let now = Date.nowTimestemp() var last = KLineModel.maxTime(type: .miu, symbol:product.symbol) if last < Date.startTimestemp(){ last = Date.startTimestemp() } if now - last < 60{ return } let end = now - 60*AppConst.klineCount lineChartData(product: product, fromTime: now, endTime: end) } } func moreLineChartData(){ if let product = DealModel.share().selectProduct{ let zero = Date.startTimestemp() let min = KLineModel.minTime(type: .miu, symbol:product.symbol) let last = min - 300 if last < zero{ return } lineChartData(product: product, fromTime: min, endTime: zero) } } func lineChartData(product: ProductModel, fromTime: Double, endTime: Double){ let param = KChartParam() param.symbol = product.symbol param.exchangeName = product.exchangeName param.platformName = product.platformName param.aType = 4 param.startTime = Int64(fromTime) // param.endTime = Int64(endTime)Ø AppAPIHelper.deal().timeline(param: param, complete: {(result) -> ()? in if let models: [KChartModel] = result as? [KChartModel]{ if param.symbol == AppConst.JapanMoney{ var japanModels:[KChartModel] = [] for model in models{ for index in 0...4{ let janpanModel: KChartModel = KChartModel() model.convertToTargetObject(janpanModel) janpanModel.priceTime = model.priceTime - index*60 japanModels.append(janpanModel) } } KLineModel.cacheTimelineModels(models: japanModels) }else{ KLineModel.cacheTimelineModels(models: models) } } return nil }, error: { (error) ->()? in // SVProgressHUD.showErrorMessage(ErrorMessage: error.description, ForDuration: 1, completion: nil) return nil }) } //根据商品请求K线数据 func initAllKlineChartData() { // checkTokenLogin() // if UserModel.share().currentUserId > 0{ // heartBeat() // } if DealModel.share().haveStopKline { return } initLineChartData() initKLineChartData(type: .miu5) initKLineChartData(type: .miu15) initKLineChartData(type: .miu30) initKLineChartData(type: .miu60) } func initSelectKlineChartData() { let type = DealModel.share().klineTye initKLineChartData(type: type) } func initKLineChartData(type: KLineModel.KLineType) { for product in DealModel.share().productKinds{ let now = Date.nowTimestemp() var last = KLineModel.maxTime(type: type, symbol:product.symbol) if last < Date.startTimestemp(){ last = Date.startTimestemp() } let future = last + Double(type.rawValue) if future > now{ return } let end = now - Double(type.rawValue)*AppConst.klineCount kLineChartData(type: type, product: product, fromTime: now, endTime: end) } } func moreSelectKlineChartData() { let type = DealModel.share().klineTye moreKLineChartData(type: type) } func moreKLineChartData(type: KLineModel.KLineType) { if type == .miu{ return } for product in DealModel.share().productKinds { let zero = Date.startTimestemp() let min = KLineModel.minTime(type: type, symbol:product.symbol) let last = min - Double(type.rawValue*5) if last < zero{ return } kLineChartData(type: type, product: product, fromTime: min, endTime: zero) } } func kLineChartData(type: KLineModel.KLineType, product: ProductModel, fromTime: Double, endTime: Double) { let param = KChartParam() param.symbol = product.symbol param.exchangeName = product.exchangeName param.platformName = product.platformName param.chartType = type.rawValue param.startTime = Int64(fromTime) AppAPIHelper.deal().kChartsData(param: param, complete: { (result) -> ()? in if let chart: ChartModel = result as? ChartModel{ KLineModel.cacheKChartModels(chart: chart) } return nil }, error:{ (error) ->()? in return nil }) } //验证token登录 func checkTokenLogin() { //token是否存在 if let token = UserDefaults.standard.value(forKey: SocketConst.Key.token){ if let id = UserDefaults.standard.value(forKey: SocketConst.Key.uid){ let param = ChecktokenParam() param.token = token as! String param.id = id as! Int AppAPIHelper.login().tokenLogin(param: param, complete: { [weak self]( result) -> ()? in //存储用户信息 if let model = result as? UserInfoModel { if let modelToken = model.token{ //更新token UserDefaults.standard.setValue(modelToken, forKey: SocketConst.Key.token) } if let user = model.userinfo { UserDefaults.standard.setValue(user.id, forKey: SocketConst.Key.id) } UserModel.share().upateUserInfo(userObject: model as AnyObject) NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.NotifyDefine.RequestPrice), object: nil) }else{ self?.clearUserInfo() } return nil }, error: {[weak self] (error) ->()? in self?.clearUserInfo() return nil }) } }else{ clearUserInfo() } } //清楚用户数据 func clearUserInfo() { UserDefaults.standard.removeObject(forKey: SocketConst.Key.uid) UserDefaults.standard.removeObject(forKey: SocketConst.Key.token) UserModel.share().token = "" UserModel.share().currentUserId = 0 NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.NoticeKey.logoutNotice.rawValue), object: nil, userInfo: nil) } //获取错误信息 func initErrorCode() { AppAPIHelper.commen().errorCode(complete: { (result) -> ()? in if let errorDic: NSDictionary = result as? NSDictionary{ let path = Bundle.main.path(forResource: "errorcode.plist", ofType:nil) let success = errorDic.write(toFile: path!, atomically: true) print(success ? "错误码写入成功" : "错误码写入失败") } return nil }, error: nil) } //获取用户余额 func userCash() { AppAPIHelper.user().accinfo(complete: { (result) -> ()? in if let resultDic = result as? [String: AnyObject] { if let money = resultDic["balance"] as? Double{ UserModel.share().balance = money UserModel.updateUser(info: { (resultDic) -> ()? in UserModel.share().currentUser?.balance = money }) } } return nil }, error: nil) } //心跳包 func heartBeat() { AppAPIHelper.commen().heartBeat(complete: { (result) -> ()? in return nil }, error: nil) } //获取IP和Port func ipAndPort() { Alamofire.request(AppConst.ipLocation, method: .post).responseJSON { (result) in if let resultJson = result.result.value as? [String: AnyObject] { if let status = resultJson["result"] as? Int{ if status == 0{ return } } if let ipStr = resultJson["ip"] as? String { UserModel.share().ipStr = ipStr } if let portStr = resultJson["port"] as? String { UserModel.share().portStr = portStr } } } } }
apache-2.0
379eacd2faeca598604bec97a0bf65f8
36.787375
157
0.534552
4.709731
false
false
false
false
28stephlim/Heartbeat-Analyser
VoiceMemos/Controller/ApexLDOutputViewController.swift
2
3119
// // ApexLDOutputViewController.swift // VoiceMemos // // Created by Stepanie Lim on 07/10/2016. // Copyright © 2016 Zhouqi Mo. All rights reserved. // import UIKit class ApexLDOutputViewController: UIViewController { var apexld = "emptiness" var URL : NSURL! var ald = ["ALD-MOSnDM", "ALD-S3Gallop", "ALD-S3nHSM", "ALD-S4Gallop", "ALD-S4nMSM", "ALD-SCwLSM"] //Target Connections @IBOutlet weak var waveform: FDWaveformView! @IBOutlet weak var diagnosis1: UILabel! //unwind segue @IBAction func unwindtoALDOutput(segue: UIStoryboardSegue){ } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //preparing data for 2nd VC override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "aldout" { let VC2 : ApexLDConditionViewController = segue.destinationViewController as! ApexLDConditionViewController VC2.condition = apexld VC2.URL = self.URL } } override func viewDidAppear(animated: Bool) { self.waveform.audioURL = URL self.waveform.progressSamples = 0 self.waveform.doesAllowScroll = true self.waveform.doesAllowStretch = true self.waveform.doesAllowScrubbing = false self.waveform.wavesColor = UIColor.blueColor() signalCompare(self.ald) } func signalCompare(type: [String]){ let bundle = NSBundle.mainBundle() var matchArray = [Float]() var match: Float = 0.0 for name in type { let sequenceURL = bundle.URLForResource(name, withExtension: "aiff")! match = compareFingerprint(self.URL, sequenceURL) print("Match = \(match)") matchArray.append(match) } let maxMatch = matchArray.maxElement() //this is the max match let maxLocationIndex = matchArray.indexOf(maxMatch!) //this is the index of the max match if you want to use it for something //var maxLocationInt = matchArray.startIndex.distanceTo(maxLocationIndex!) //this is the index cast as an int if you need to use it if (maxMatch<0.6) { self.diagnosis1.text = "Error have occured. Please re-record the audio file." } else{ self.diagnosis1.text = type[maxLocationIndex!] apexld = type[maxLocationIndex!] } } /* // 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
fdfbda5a12ff4bbd189d427b2343cd3e
30.18
141
0.626042
4.518841
false
false
false
false
ryuichis/swift-lint
Sources/Lint/Rule/RemoveGetForReadOnlyComputedPropertyRule.swift
2
2180
/* Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import AST class RemoveGetForReadOnlyComputedPropertyRule: RuleBase, ASTVisitorRule { let name = "Remove Get For Read-Only Computed Property" var description: String? { return """ A computed property with a getter but no setter is known as a *read-only computed property*. You can simplify the declaration of a read-only computed property by removing the get keyword and its braces. """ } var examples: [String]? { return [ """ var foo: Int { get { return 1 } } // var foo: Int { // return 1 // } """, ] } let category = Issue.Category.badPractice func visit(_ varDecl: VariableDeclaration) throws -> Bool { if case let .getterSetterBlock(name, typeAnnotation, getterSetterBlock) = varDecl.body, getterSetterBlock.setter == nil, getterSetterBlock.getter.attributes.isEmpty, getterSetterBlock.getter.mutationModifier == nil { let refactoredVarDecl = VariableDeclaration( attributes: varDecl.attributes, modifiers: varDecl.modifiers, variableName: name, typeAnnotation: typeAnnotation, codeBlock: getterSetterBlock.getter.codeBlock ) emitIssue( varDecl.sourceRange, description: "read-only computed property `\(name)` " + "can be simplified by removing the `get` keyword and its braces", correction: Correction(suggestion: refactoredVarDecl.formatted) ) } return true } }
apache-2.0
5bef211f0be71fbbdc848230bd8353c1
29.277778
91
0.679358
4.718615
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/Core/User/UserStandardAttributeModels.swift
1
16621
// // UserStandardAttributeModels.swift // MobileMessaging // // Created by Andrey Kadochnikov on 29/11/2018. // import Foundation @objc public enum MMGenderNonnull: Int { case Female case Male case Undefined var toGender: MMGender? { switch self { case .Female : return .Female case .Male : return .Male case .Undefined : return nil } } static func make(from gender: MMGender?) -> MMGenderNonnull { if let gender = gender { switch gender { case .Female: return .Female case .Male: return .Male } } else { return .Undefined } } } public enum MMGender: Int { case Female case Male public var name: String { switch self { case .Female : return "Female" case .Male : return "Male" } } static func make(with name: String) -> MMGender? { switch name { case "Female": return MMGender.Female case "Male": return MMGender.Male default: return nil } } } @objcMembers public final class MMPhone: NSObject, NSCoding, JSONDecodable, DictionaryRepresentable { public let number: String public var preferred: Bool // more properties needed? ok but look at the code below first. required init?(dictRepresentation dict: DictionaryRepresentation) { fatalError("init(dictRepresentation:) has not been implemented") } var dictionaryRepresentation: DictionaryRepresentation { return ["number": number] } public override var hash: Int { return number.hashValue// ^ preferred.hashValue // use hasher combine } public override func isEqual(_ object: Any?) -> Bool { guard let object = object as? MMPhone else { return false } return self.number == object.number // preferred is not supported yet on mobile api } convenience init?(json: JSON) { let preferred = false guard let number = json["number"].string else { // preferred is not supported yet on mobile api return nil } self.init(number: number, preferred: preferred) } public init(number: String, preferred: Bool) { self.number = number self.preferred = preferred } required public init?(coder aDecoder: NSCoder) { number = aDecoder.decodeObject(forKey: "number") as! String preferred = aDecoder.decodeBool(forKey: "preferred") } public func encode(with aCoder: NSCoder) { aCoder.encode(number, forKey: "number") aCoder.encode(preferred, forKey: "preferred") } } @objcMembers public final class MMEmail: NSObject, NSCoding, JSONDecodable, DictionaryRepresentable { public let address: String public var preferred: Bool // more properties needed? ok but look at the code below first. required init?(dictRepresentation dict: DictionaryRepresentation) { fatalError("init(dictRepresentation:) has not been implemented") } var dictionaryRepresentation: DictionaryRepresentation { return ["address": address] } public override var hash: Int { return address.hashValue// ^ preferred.hashValue // use hasher combine } public override func isEqual(_ object: Any?) -> Bool { guard let object = object as? MMEmail else { return false } return self.address == object.address } convenience init?(json: JSON) { let preferred = false guard let address = json["address"].string else { // preferred is not supported yet on mobile api return nil } self.init(address: address, preferred: preferred) } public init(address: String, preferred: Bool) { self.address = address self.preferred = preferred } required public init?(coder aDecoder: NSCoder) { address = aDecoder.decodeObject(forKey: "address") as! String preferred = aDecoder.decodeBool(forKey: "preferred") } public func encode(with aCoder: NSCoder) { aCoder.encode(address, forKey: "address") aCoder.encode(preferred, forKey: "preferred") } } @objcMembers public class MMUserIdentity: NSObject { public let phones: [String]? public let emails: [String]? public let externalUserId: String? /// Default initializer. The object won't be initialized if all three arguments are nil/empty. Unique user identity must have at least one value. @objc public init?(phones: [String]?, emails: [String]?, externalUserId: String?) { if (phones == nil || phones!.isEmpty) && (emails == nil || emails!.isEmpty) && externalUserId == nil { return nil } self.phones = phones self.emails = emails self.externalUserId = externalUserId } } @objcMembers public class MMUserAttributes: NSObject, DictionaryRepresentable { /// The user's first name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var firstName: String? /// A user's middle name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var middleName: String? /// A user's last name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var lastName: String? /// A user's tags. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var tags: Set<String>? /// A user's gender. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var gender: MMGender? public var genderNonnull: MMGenderNonnull { set { gender = newValue.toGender } get { return MMGenderNonnull.make(from: gender) } } /// A user's birthday. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var birthday: Date? /// Returns user's custom data. Arbitrary attributes that are related to a particular user. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var customAttributes: [String: MMAttributeType]? { willSet { newValue?.assertCustomAttributesValid() } } convenience public init(firstName: String? ,middleName: String? ,lastName: String? ,tags: Set<String>? ,genderNonnull: MMGenderNonnull ,birthday: Date? ,customAttributes: [String: MMAttributeType]?) { self.init(firstName: firstName, middleName: middleName, lastName: lastName, tags: tags, gender: genderNonnull.toGender, birthday: birthday, customAttributes: customAttributes) } public init(firstName: String? ,middleName: String? ,lastName: String? ,tags: Set<String>? ,gender: MMGender? ,birthday: Date? ,customAttributes: [String: MMAttributeType]?) { self.firstName = firstName self.middleName = middleName self.lastName = lastName self.tags = tags self.gender = gender self.birthday = birthday self.customAttributes = customAttributes } public required convenience init?(dictRepresentation dict: DictionaryRepresentation) { let value = JSON.init(dict) self.init(firstName: value["firstName"].string, middleName: value["middleName"].string, lastName: value["lastName"].string, tags: arrayToSet(arr: value["tags"].arrayObject as? [String]), gender: value["gender"].string.ifSome({ MMGender.make(with: $0) }), birthday: value["birthday"].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }), customAttributes: value["customAttributes"].dictionary?.decodeCustomAttributesJSON) } public var dictionaryRepresentation: DictionaryRepresentation { return [ "firstName" : firstName as Any, "middleName" : middleName as Any, "lastName" : lastName as Any, "tags" : tags?.asArray as Any, "gender" : gender?.name as Any, "birthday" : birthday.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.string(from: $0) }) as Any, "customAttributes" : UserDataMapper.makeCustomAttributesPayload(customAttributes) as Any ] } } @objcMembers public final class MMUser: MMUserAttributes, JSONDecodable, NSCoding, NSCopying, Archivable { var version: Int = 0 static var currentPath = getDocumentsDirectory(filename: "user") static var dirtyPath = getDocumentsDirectory(filename: "dirty-user") static var cached = ThreadSafeDict<MMUser>() static var empty: MMUser { return MMUser(externalUserId: nil, firstName: nil, middleName: nil, lastName: nil, phones: nil, emails: nil, tags: nil, gender: nil, birthday: nil, customAttributes: nil, installations: nil) } func removeSensitiveData() { if MobileMessaging.privacySettings.userDataPersistingDisabled == true { self.firstName = nil self.middleName = nil self.lastName = nil self.gender = nil self.emails = nil self.phones = nil self.customAttributes = nil self.birthday = nil self.externalUserId = nil } } func handleCurrentChanges(old: MMUser, new: MMUser) { // nothing to do } func handleDirtyChanges(old: MMUser, new: MMUser) { // nothing to do } // static var delta: [String: Any]? { guard let currentUserDict = MobileMessaging.sharedInstance?.currentUser().dictionaryRepresentation, let dirtyUserDict = MobileMessaging.sharedInstance?.dirtyUser().dictionaryRepresentation else { return [:] } return deltaDict(currentUserDict, dirtyUserDict) } /// The user's id you can provide in order to link your own unique user identifier with Mobile Messaging user id, so that you will be able to send personalised targeted messages to exact user and other nice features. public var externalUserId: String? /// User's phone numbers. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var phones: Array<String>? { set { phonesObjects = newValue?.map({ return MMPhone(number: $0, preferred: false) }) } get { return phonesObjects?.map({ return $0.number }) } } var phonesObjects: Array<MMPhone>? /// User's email addresses. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features. public var emails: Array<String>? { set { emailsObjects = newValue?.map({ return MMEmail(address: $0, preferred: false) }) } get { return emailsObjects?.map({ return $0.address }) } } var emailsObjects: Array<MMEmail>? /// All installations personalized with the user public internal(set) var installations: Array<MMInstallation>? convenience init(userIdentity: MMUserIdentity, userAttributes: MMUserAttributes?) { self.init(externalUserId: userIdentity.externalUserId, firstName: userAttributes?.firstName, middleName: userAttributes?.middleName, lastName: userAttributes?.lastName, phones: userIdentity.phones, emails: userIdentity.emails, tags: userAttributes?.tags, gender: userAttributes?.gender, birthday: userAttributes?.birthday, customAttributes: userAttributes?.customAttributes, installations: nil) } init(externalUserId: String? ,firstName: String? ,middleName: String? ,lastName: String? ,phones: Array<String>? ,emails: Array<String>? ,tags: Set<String>? ,gender: MMGender? ,birthday: Date? ,customAttributes: [String: MMAttributeType]? ,installations: Array<MMInstallation>?) { super.init(firstName: firstName, middleName: middleName, lastName: lastName, tags: tags, gender: gender, birthday: birthday, customAttributes: customAttributes) self.installations = installations self.externalUserId = externalUserId self.phones = phones self.emails = emails } convenience init?(json value: JSON) { self.init(externalUserId: value[Attributes.externalUserId.rawValue].string, firstName: value[Attributes.firstName.rawValue].string, middleName: value[Attributes.middleName.rawValue].string, lastName: value[Attributes.lastName.rawValue].string, phones: value[Attributes.phones.rawValue].array?.compactMap({ return MMPhone(json: $0)?.number }), emails: value[Attributes.emails.rawValue].array?.compactMap({ return MMEmail(json: $0)?.address }), tags: arrayToSet(arr: value[Attributes.tags.rawValue].arrayObject as? [String]), gender: value[Attributes.gender.rawValue].string.ifSome({ MMGender.make(with: $0) }), birthday: value[Attributes.birthday.rawValue].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }), customAttributes: value[Attributes.customAttributes.rawValue].dictionary?.decodeCustomAttributesJSON, installations: value[Attributes.instances.rawValue].array?.compactMap({ MMInstallation(json: $0) })) } // must be extracted to cordova plugin srcs public required convenience init?(dictRepresentation dict: DictionaryRepresentation) { let value = JSON.init(dict) self.init(externalUserId: value["externalUserId"].string, firstName: value["firstName"].string, middleName: value["middleName"].string, lastName: value["lastName"].string, phones: (value["phones"].arrayObject as? [String])?.compactMap({ return MMPhone(number: $0, preferred: false).number }), emails: (value["emails"].arrayObject as? [String])?.compactMap({ return MMEmail(address: $0, preferred: false).address }), tags: arrayToSet(arr: value["tags"].arrayObject as? [String]), gender: value["gender"].string.ifSome({ MMGender.make(with: $0) }), birthday: value["birthday"].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }), customAttributes: value["customAttributes"].dictionary?.decodeCustomAttributesJSON, installations: value["installations"].array?.compactMap({ MMInstallation(json: $0) })) } public override var dictionaryRepresentation: DictionaryRepresentation { var ret = super.dictionaryRepresentation ret["externalUserId"] = externalUserId as Any ret["phones"] = phones as Any ret["emails"] = emails as Any ret["installations"] = installations?.map({ return $0.dictionaryRepresentation }) as Any return ret } public override func isEqual(_ object: Any?) -> Bool { guard let object = object as? MMUser else { return false } return externalUserId == object.externalUserId && firstName == object.firstName && middleName == object.middleName && lastName == object.lastName && phones == object.phones && emails == object.emails && tags == object.tags && gender == object.gender && contactsServiceDateEqual(birthday, object.birthday) && customAttributes == object.customAttributes && installations == object.installations } required public init?(coder aDecoder: NSCoder) { super.init(firstName: aDecoder.decodeObject(forKey: "firstName") as? String, middleName: aDecoder.decodeObject(forKey: "middleName") as? String, lastName: aDecoder.decodeObject(forKey: "lastName") as? String, tags: arrayToSet(arr: aDecoder.decodeObject(forKey: "tags") as? [String]), gender: MMGender(rawValue: (aDecoder.decodeObject(forKey: "gender") as? Int) ?? 999) , birthday: aDecoder.decodeObject(forKey: "birthday") as? Date, customAttributes: aDecoder.decodeObject(forKey: "customAttributes") as? [String: MMAttributeType]) externalUserId = aDecoder.decodeObject(forKey: "externalUserId") as? String phonesObjects = aDecoder.decodeObject(forKey: "phones") as? Array<MMPhone> emailsObjects = aDecoder.decodeObject(forKey: "emails") as? Array<MMEmail> installations = aDecoder.decodeObject(forKey: "installations") as? Array<MMInstallation> } public func encode(with aCoder: NSCoder) { aCoder.encode(externalUserId, forKey: "externalUserId") aCoder.encode(firstName, forKey: "firstName") aCoder.encode(middleName, forKey: "middleName") aCoder.encode(lastName, forKey: "lastName") aCoder.encode(phonesObjects, forKey: "phones") aCoder.encode(emailsObjects, forKey: "emails") aCoder.encode(tags, forKey: "tags") aCoder.encode(gender?.rawValue, forKey: "gender") aCoder.encode(birthday, forKey: "birthday") aCoder.encode(customAttributes, forKey: "customAttributes") aCoder.encode(installations, forKey: "installations") } public func copy(with zone: NSZone? = nil) -> Any { return MMUser(externalUserId: externalUserId, firstName: firstName, middleName: middleName, lastName: lastName, phones: phones, emails: emails, tags: tags, gender: gender, birthday: birthday, customAttributes: customAttributes, installations: installations) } }
apache-2.0
b2d797a0314e358c5f4724a24c5a7179
37.74359
396
0.7372
3.976316
false
false
false
false
trvslhlt/games-for-impact-final
projects/WinkWink_11/WinkWink/Utilities/AppUtilities.swift
1
760
// // AppUtilities.swift // WinkWink_11 // // Created by trvslhlt on 4/9/17. // Copyright © 2017 travis holt. All rights reserved. // import Foundation func delay(duration: TimeInterval, instructions: @escaping () -> ()) { let when = DispatchTime.now() + duration DispatchQueue.main.asyncAfter(deadline: when) { instructions() } } func bundleContainsFile(withName filename: String) -> Bool { return Bundle.main.path(forResource: filename, ofType: nil) != nil } //class Weak<T: AnyObject> { // weak var value: T? // init(value: T) { // self.value = value // } //} //extension Array where Element: Weak<AnyObject> { // // mutating func reap() { // self = self.filter { nil != $0.value } // } // //}
mit
c0f5115bf5616af2552df94e119ce190
20.685714
70
0.617918
3.358407
false
false
false
false
raeidsaqur/teachings-ios-animation-playground
Animation.playground/Pages/Animations.xcplaygroundpage/Contents.swift
1
1796
//: [Previous](@previous) import Foundation import UIKit import XCPlayground //Define a screen (typical iPhone device size) let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0)) XCPShowView(identifier: "Container View", view: containerView) let circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0)) circle.center = containerView.center circle.layer.cornerRadius = 25.0 let startingColor = UIColor(red: (253.0/255.0), green: (159.0/255.0), blue: (47.0/255.0), alpha: 1.0) circle.backgroundColor = startingColor containerView.addSubview(circle); let rectangle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0)) rectangle.center = containerView.center rectangle.layer.cornerRadius = 5.0 rectangle.backgroundColor = UIColor.white containerView.addSubview(rectangle) //Mark: - UIView Animate Code UIView.animate(withDuration: 2.0, animations: { () -> Void in let endingColor = UIColor.orange let scaleTransform = CGAffineTransform(scaleX: 5.0, y: 5.0) let rotationTransform = CGAffineTransform(rotationAngle: 3.14) circle.backgroundColor = endingColor circle.transform = scaleTransform rectangle.transform = rotationTransform }) //UIView.animate(withDuration: 1.0, delay: 0, options:[.repeat, .autoreverse], animations: { () -> Void in // // //Step 2: Define end state // let endingColor = UIColor.orange // let scaleTransform = CGAffineTransform(scaleX: 5.0, y: 5.0) // let rotationTransform = CGAffineTransform(rotationAngle: 3.14) // // circle.backgroundColor = endingColor // circle.transform = scaleTransform // rectangle.transform = rotationTransform // //}) { (success) -> Void in // //Success: Revert back // print("Success") //} //: [Next](@next)
mit
24c94b708f0935157bd4c631de4594b2
28.442623
106
0.707127
3.563492
false
false
false
false
geocore/geocore-swift
GeocoreKit/GeocoreTag.swift
1
6456
// // GeocoreTag.swift // GeocoreKit // // Created by Purbo Mohamad on 11/22/15. // // import Foundation import Alamofire import SwiftyJSON import PromiseKit public enum GeocoreTagType: String { case System = "SYSTEM_TAG" case User = "USER_TAG" case Unknown = "" } open class GeocoreTaggableOperation: GeocoreObjectOperation { private var tagIdsToAdd: [String]? private var tagIdsToDelete: [String]? private var tagNamesToAdd: [String]? private var tagNamesToDelete: [String]? open func tag(_ tagIdsOrNames: [String]) -> Self { for tagIdOrName in tagIdsOrNames { // for now, assume that if the tag starts with 'TAG-', it's a tag id, otherwise it's a name if tagIdOrName.hasPrefix("TAG-") { if self.tagIdsToAdd == nil { self.tagIdsToAdd = [tagIdOrName] } else { self.tagIdsToAdd?.append(tagIdOrName) } } else { if self.tagNamesToAdd == nil { self.tagNamesToAdd = [tagIdOrName] } else { self.tagNamesToAdd?.append(tagIdOrName) } } } return self } open func untag(_ tagIdsOrNames: [String]) -> Self { for tagIdOrName in tagIdsOrNames { // for now, assume that if the tag starts with 'TAG-', it's a tag id, otherwise it's a name if tagIdOrName.hasPrefix("TAG-") { if self.tagIdsToDelete == nil { self.tagIdsToDelete = [tagIdOrName] } else { self.tagIdsToDelete?.append(tagIdOrName) } } else { if self.tagNamesToDelete == nil { self.tagNamesToDelete = [tagIdOrName] } else { self.tagNamesToDelete?.append(tagIdOrName) } } } return self } open override func buildQueryParameters() -> Alamofire.Parameters { var dict = super.buildQueryParameters() if let tagIdsToAdd = self.tagIdsToAdd { if tagIdsToAdd.count > 0 { dict["tag_ids"] = tagIdsToAdd.joined(separator: ",") } } if let tagNamesToAdd = self.tagNamesToAdd { if tagNamesToAdd.count > 0 { dict["tag_names"] = tagNamesToAdd.joined(separator: ",") } } if let tagIdsToDelete = self.tagIdsToDelete { if tagIdsToDelete.count > 0 { dict["del_tag_ids"] = tagIdsToDelete.joined(separator: ",") } } if let tagNamesToDelete = self.tagNamesToDelete { if tagNamesToDelete.count > 0 { dict["del_tag_names"] = tagNamesToDelete.joined(separator: ",") } } return dict as [String : AnyObject]; } } open class GeocoreTaggableQuery: GeocoreObjectQuery { private var tagIds: [String]? private var tagNames: [String]? private var excludedTagIds: [String]? private var excludedTagNames: [String]? private var tagDetails = false /** Set tag IDs to be submitted as request parameter. - parameter tagIds: Tag IDs to be submitted - returns: The updated query object to be chain-called. */ open func with(tagIds: [String]) -> Self { self.tagIds = tagIds return self } open func exclude(tagIds: [String]) -> Self { self.excludedTagIds = tagIds return self } /** Set tag names to be submitted as request parameter. - parameter tagNames: Tag names to be submitted - returns: The updated query object to be chain-called. */ open func with(tagNames: [String]) -> Self { self.tagNames = tagNames return self } open func exclude(tagNames: [String]) -> Self { self.excludedTagNames = tagNames return self } open func withTagDetails() -> Self { self.tagDetails = true return self } open override func buildQueryParameters() -> [String: Any] { var dict = super.buildQueryParameters() if let tagIds = self.tagIds { dict["tag_ids"] = tagIds.joined(separator: ",") } if let tagNames = self.tagNames { dict["tag_names"] = tagNames.joined(separator: ",") } if let excludedTagIds = self.excludedTagIds { dict["excl_tag_ids"] = excludedTagIds.joined(separator: ",") } if let excludedTagNames = self.excludedTagNames { dict["excl_tag_names"] = excludedTagNames.joined(separator: ",") } if tagDetails { dict["tag_detail"] = "true" } return dict as [String : Any] } } open class GeocoreTaggable: GeocoreObject { open var tags: [GeocoreTag]? public override init() { super.init() } public required init(_ json: JSON) { if let tagsJSON = json["tags"].array { self.tags = tagsJSON.map({ GeocoreTag($0) }) } super.init(json) } } open class GeocoreTagQuery: GeocoreObjectQuery { private(set) open var idPrefix: String? open func with(idPrefix: String) -> Self { self.idPrefix = idPrefix return self } open override func buildQueryParameters() -> Alamofire.Parameters { var dict = super.buildQueryParameters() if let idPrefix = self.idPrefix { dict["id_prefix"] = idPrefix } return dict } open func get() -> Promise<GeocoreTag> { return self.get(forService: "/tags") } open class func get(_ id: String) -> Promise<GeocoreTag> { return GeocoreTagQuery().with(id: id).get() } open func all() -> Promise<[GeocoreTag]> { return self.all(forService: "/tags") } } open class GeocoreTag: GeocoreObject { open var type: GeocoreTagType? public override init() { super.init() } public required init(_ json: JSON) { if let type = json["type"].string { self.type = GeocoreTagType(rawValue: type) } super.init(json) } open override func asDictionary() -> [String : Any] { var dict = super.asDictionary() if let type = self.type { dict["type"] = type.rawValue as AnyObject? } return dict } }
apache-2.0
2a8ef621e18652d45891c86ab9066535
28.479452
124
0.562423
4.38587
false
false
false
false
yeti/emojikeyboard
EmojiKeyboard/Classes/EKBInputView.swift
1
12563
// // EKBInputView.swift // GottaGo // // Created by Lee McDole on 1/25/16. // Copyright © 2016 Yeti LLC. All rights reserved. // import Foundation import UIKit public protocol EKBInputViewDelegate { // Action handler for whenever a button is pressed. Probably want to send a character to the UIResponder func buttonPressed(groupIndex: Int, index: Int) // Return the number of groups in this keyboard func getGroupCount() -> Int // Return the name of the specified group func getGroupName(groupIndex: Int) -> String // Return the number of items within this group func getItemCount(groupIndex: Int) -> Int // Get the emoji for a specified group and index func getEmojiAt(groupIndex: Int, index: Int) -> EKBEmoji? } public class EKBInputView: UIView, UICollectionViewDataSource, UICollectionViewDelegate { // UI Outlets @IBOutlet weak var collectionView: UICollectionView! var variantSelector: EKBVariantSelector! @IBOutlet weak var groupButton1: UIButton! @IBOutlet weak var groupButton2: UIButton! @IBOutlet weak var groupButton3: UIButton! @IBOutlet weak var groupButton4: UIButton! @IBOutlet weak var groupButton5: UIButton! @IBOutlet weak var groupButton6: UIButton! @IBOutlet weak var groupButton7: UIButton! @IBOutlet weak var groupButton8: UIButton! @IBOutlet weak var groupButtonsContainer: UIView! var highlightCircle: UIView! let highlightCircleExtraSize = CGFloat(0.0) // size per side, total extra is 2x this! (placeholder in case we want non-zero extra) var groupButtons: [UIButton]! var currentScrollGroup: Int! = 0 var ekbInputViewDelegate: EKBInputViewDelegate? var currentEmojiSection: Int? var currentEmojiIndex: Int? let edgeOffsetX: CGFloat = 10 let edgeOffsetY: CGFloat = 6 // GroupHeader encapsulates the information we need to maintain our headers private struct GroupHeader { var label: UILabel var minX: CGFloat var maxX: CGFloat } private var groupHeaders = [GroupHeader]() public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func awakeFromNib() { collectionView.delegate = self collectionView.dataSource = self autoresizingMask = .None; let cellNib = UINib(nibName: "EKBEmojiViewCell", bundle: EKBUtils.resourceBundle()) collectionView.registerNib(cellNib, forCellWithReuseIdentifier: "EKBEmojiViewCell") variantSelector = EKBVariantSelector.instanceFromNib() addSubview(variantSelector) variantSelector.hidden = true groupButtons = [UIButton]() groupButtons.append(groupButton1) groupButtons.append(groupButton2) groupButtons.append(groupButton3) groupButtons.append(groupButton4) groupButtons.append(groupButton5) groupButtons.append(groupButton6) groupButtons.append(groupButton7) groupButtons.append(groupButton8) // Initialize group button highlighter let buttonSize = groupButton1.frame.size.width let highlightSize = buttonSize + highlightCircleExtraSize * 2 // *2 to include extra on both sides highlightCircle = UIView(frame: CGRectMake(groupButton1.frame.origin.x - highlightCircleExtraSize, groupButton1.frame.origin.y - highlightCircleExtraSize, highlightSize, highlightSize)) highlightCircle.layer.cornerRadius = highlightSize / 2.0 // /2 to make it a perfect circle highlightCircle.backgroundColor = UIColor.darkGrayColor() highlightCircle.alpha = 0.16 groupButtonsContainer.addSubview(highlightCircle) setSelectedButton(0) } /////////////////// // UIView Overrides /////////////////// override public func layoutMarginsDidChange() { self.setNeedsUpdateConstraints() self.setNeedsLayout() self.updateConstraintsIfNeeded() self.layoutIfNeeded() let groupCount = (ekbInputViewDelegate?.getGroupCount())! for var index = 0; index < groupCount; ++index { // Create UILabel let label = UILabel(frame: CGRectMake(0, 0, CGFloat.max, 20)) // CGFloat.max so that we guarantee we only shrink the label label.textAlignment = .Left label.font = UIFont.systemFontOfSize(13, weight: UIFontWeightMedium) label.text = ekbInputViewDelegate!.getGroupName(index) label.textColor = UIColor(red: 160.0/255, green: 160.0/255, blue: 160.0/255, alpha: 255.0/255) // This ensures our UILabel's width fits our text snugly, so the UILabel scrolls out at the correct location. label.numberOfLines = 0 label.sizeToFit() // Label is now configured. Calculate its drawing bounds let firstItemIndexPath = NSIndexPath(forItem: 0, inSection: index) let firstElementAttributes = collectionView.layoutAttributesForItemAtIndexPath(firstItemIndexPath) let minX = (firstElementAttributes?.frame.origin.x)! + edgeOffsetX let lastItemIndexPath = NSIndexPath(forItem: (ekbInputViewDelegate?.getItemCount(index))! - 1, inSection: index) let lastElementAttributes = collectionView.layoutAttributesForItemAtIndexPath(lastItemIndexPath) let maxX = (lastElementAttributes?.frame.origin.x)! + (lastElementAttributes?.frame.width)! - label.frame.width - edgeOffsetX // Initialize the bounds to starting position var bounds: CGRect = label.bounds bounds.origin.x = minX bounds.origin.y = edgeOffsetY label.bounds = bounds // Create GroupHeader, add label as subview let header = GroupHeader(label: label, minX: minX, maxX: maxX) groupHeaders.append(header) self.addSubview(label) } // Put all the headers in their proper locations updateHeaderOffsets() } //////////////////////////////////////////////// // UICollectionViewDataSource protocol functions //////////////////////////////////////////////// public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (ekbInputViewDelegate?.getItemCount(section))! } public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return (ekbInputViewDelegate?.getGroupCount())! } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("EKBEmojiViewCell", forIndexPath: indexPath) as! EKBEmojiViewCell let index = indexPath.row let groupIndex = indexPath.section let emoji = ekbInputViewDelegate?.getEmojiAt(groupIndex, index: index) cell.setEmoji(emoji!.getModifiedString()) return cell } ////////////////////////////////////////////// // UICollectionViewDelegate protocol functions ////////////////////////////////////////////// func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(UIScreen.mainScreen().bounds.width / 8, collectionView.frame.height / 5) } ////////////////////////////////////////// // UIScrollViewDelegate protocol functions ////////////////////////////////////////// public func scrollViewDidScroll(scrollView: UIScrollView) { updateHeaderOffsets() } private func updateHeaderOffsets() { let offset = collectionView.contentOffset for (index, header) in groupHeaders.enumerate() { // Desired position is at offset.x + edgeOffsetX if possible var xPos = offset.x + edgeOffsetX // Clamp to max/min limits var clamped = false if xPos < header.minX { xPos = header.minX clamped = true } else if xPos > header.maxX { xPos = header.maxX clamped = true } if !clamped && currentScrollGroup != index { // Ensure that the current group is reflected in the buttons at the bottom setSelectedButton(index) } // Translate back to screen coordinates var frame = header.label.frame frame.origin.x = xPos - offset.x frame.origin.y = edgeOffsetY header.label.frame = frame } } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches[touches.startIndex] let location: CGPoint = touch.locationInView(collectionView) let indexPath = collectionView.indexPathForItemAtPoint(location) if let indexPath = indexPath { currentEmojiSection = indexPath.section currentEmojiIndex = indexPath.row let emoji = ekbInputViewDelegate?.getEmojiAt(currentEmojiSection!, index: currentEmojiIndex!) // TODO: Possibly make the EKBVariantSelector support displaying even when there is no modifiers. For now, only if modifiers. if emoji?.modifiers?.count > 1 { // Calculate the ideal position for the selector to draw (horizontally centered, top of the current indexPath) let layoutAttributes = collectionView.layoutAttributesForItemAtIndexPath(indexPath) let targetX = (layoutAttributes?.frame.origin.x)! + ((layoutAttributes?.size.width)! / 2) - collectionView.contentOffset.x let targetY = (layoutAttributes?.frame.origin.y)! - (layoutAttributes?.size.height)! let targetPos = CGPoint(x: targetX, y: targetY) bringSubviewToFront(variantSelector) variantSelector.displaySelection(emoji!, targetPos: targetPos) } } } override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches[touches.startIndex] // Pass moves to variantSelector if it's active if !variantSelector.hidden { variantSelector.updateTouchPosition(touch.locationInView(variantSelector)) } } override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if let emojiIndex = currentEmojiIndex, let emojiSection = currentEmojiSection { let indexPath = NSIndexPath(forItem: emojiIndex, inSection: emojiSection) collectionView.reloadItemsAtIndexPaths([indexPath]) ekbInputViewDelegate?.buttonPressed(indexPath.section, index: indexPath.row) // Clear bookkeeping info currentEmojiIndex = nil currentEmojiSection = nil // Hide selector variantSelector.hide() } } func scrollToGroup(index: Int) { let indexPath = NSIndexPath(forItem: 0, inSection: index) let layoutAttributes = collectionView.layoutAttributesForItemAtIndexPath(indexPath) let offsetPosX = layoutAttributes!.frame.origin.x var contentOffset = collectionView.contentOffset contentOffset.x = offsetPosX collectionView.contentOffset = contentOffset } func setSelectedButton(selectedIndex: Int) { for (index, button) in groupButtons.enumerate() { if index == selectedIndex { button.selected = true button.alpha = 1.0 setButtonHighlight(index) } else { button.selected = false button.alpha = 0.4 } } currentScrollGroup = selectedIndex } func setButtonHighlight(selectedIndex: Int) { highlightCircle.frame.origin.x = groupButtons[selectedIndex].frame.origin.x - highlightCircleExtraSize highlightCircle.frame.origin.y = groupButtons[selectedIndex].frame.origin.y - highlightCircleExtraSize } // TODO: A less ugly way to map button presses to these functions! @IBAction func button1Touched(sender: AnyObject) { scrollToGroup(0) setSelectedButton(0) } @IBAction func button2Touched(sender: AnyObject) { scrollToGroup(1) setSelectedButton(1) } @IBAction func button3Touched(sender: AnyObject) { scrollToGroup(2) setSelectedButton(2) } @IBAction func button4Touched(sender: AnyObject) { scrollToGroup(3) setSelectedButton(3) } @IBAction func button5Touched(sender: AnyObject) { scrollToGroup(4) setSelectedButton(4) } @IBAction func button6Touched(sender: AnyObject) { scrollToGroup(5) setSelectedButton(5) } @IBAction func button7Touched(sender: AnyObject) { scrollToGroup(6) setSelectedButton(6) } @IBAction func button8Touched(sender: AnyObject) { scrollToGroup(7) setSelectedButton(7) } }
mit
79c8f308f1bb8fa36a651f76eefc98c7
34.586402
135
0.687152
4.903201
false
false
false
false
jkolb/midnightbacon
MidnightBacon/Reddit/Request/PrivateMessages/UnreadMessageRequest.swift
1
2067
// // UnreadMessageRequest.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // 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 Common import ModestProposal import FranticApparatus class UnreadMessageRequest : APIRequest { let prototype: NSURLRequest let id: [String] init(prototype: NSURLRequest, id: [String]) { self.prototype = prototype self.id = id } typealias ResponseType = Bool func parse(response: URLResponse) throws -> Bool { return try redditJSONMapper(response) { (object) -> Bool in return true } } func build() -> NSMutableURLRequest { var parameters = [String:String](minimumCapacity: 1) parameters["id"] = id.joinWithSeparator(",") return prototype.POST(path: "/api/unread_message", parameters: parameters) } var requiresModhash : Bool { return true } var scope : OAuthScope? { return .PrivateMessages } }
mit
7eeb70d927f0728f7d6e04b48ca182ad
33.45
82
0.699565
4.644944
false
false
false
false
leschlogl/Programming-Contests
Hackerrank/Interview Preparation Kit/seaLevel.swift
1
1155
import Foundation // Complete the countingValleys function below. func countingValleys(n: Int, s: String) -> Int { var seaLevel = 0 var numberOfValleys = 0 var isInsideValley = false //basically check the "line" of sea level to detect if is valley or not for c in s { if c == "U" { seaLevel += 1 } else { seaLevel -= 1 } if seaLevel < 0 { isInsideValley = true } if seaLevel == 0 && isInsideValley { isInsideValley = false numberOfValleys += 1 } } return numberOfValleys } let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]! FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil) let fileHandle = FileHandle(forWritingAtPath: stdout)! guard let n = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!) else { fatalError("Bad input") } guard let s = readLine() else { fatalError("Bad input") } let result = countingValleys(n: n, s: s) fileHandle.write(String(result).data(using: .utf8)!) fileHandle.write("\n".data(using: .utf8)!)
mit
fd17d4432f5895ca988f8cccacf7b5bd
27.170732
81
0.622511
3.955479
false
false
false
false
Beaconstac/iOS-SDK
BeaconstacSampleApp/Pods/EddystoneScanner/EddystoneScanner/DispatchTimer.swift
1
1783
// // DispatchTimer.swift // EddystoneScanner // // Created by Amit Prabhu on 30/11/17. // Copyright © 2017 Amit Prabhu. All rights reserved. // import Foundation /// /// DispatchTimerDelegate /// /// Implement this to receive callbacks when the timer is called @objc public protocol DispatchTimerDelegate { func timerCalled(timer: DispatchTimer?) } /// /// DispatchTimer /// /// Timer class to create a background timer on a queue /// public class DispatchTimer: NSObject { // MARK: Public properties /// Interval to run the timer public let repeatingInterval: Double /// DispatchTimerDelegate to recieve delegate callbacks public var delegate: DispatchTimerDelegate? // MARK: Private properties private var sourceTimer: DispatchSourceTimer? private let queue: DispatchQueue private var isTimerRunning = false public init(repeatingInterval: Double, queueLabel: String) { queue = DispatchQueue(label: queueLabel) sourceTimer = DispatchSource.makeTimerSource(queue: queue) self.repeatingInterval = repeatingInterval super.init() } /// Start the timer public func startTimer() { guard !isTimerRunning else { return } isTimerRunning = true sourceTimer?.schedule(deadline: .now() + repeatingInterval, repeating: repeatingInterval, leeway: .seconds(10)) sourceTimer?.setEventHandler { [weak self] in self?.delegate?.timerCalled(timer: self) } sourceTimer?.resume() } /// Stop the timer public func stopTimer() { guard isTimerRunning else { return } isTimerRunning = false self.sourceTimer?.suspend() } }
mit
9337ff715a19e30643c1b65f3e9c2686
25.205882
119
0.64927
4.868852
false
false
false
false
nirix/swift-screencapture
ScreenCapture/ScreenRecorder.swift
1
1611
// // ScreenRecorder.swift // ScreenCapture // // Created by Jack P. on 11/12/2015. // Copyright © 2015 Jack P. All rights reserved. // import Foundation import AVFoundation open class ScreenRecorder: NSObject, AVCaptureFileOutputRecordingDelegate { let destinationUrl: URL let session: AVCaptureSession let movieFileOutput: AVCaptureMovieFileOutput open var destination: URL { get { return self.destinationUrl } } public init(destination: URL) { destinationUrl = destination session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetHigh let displayId: CGDirectDisplayID = CGDirectDisplayID(CGMainDisplayID()) let input: AVCaptureScreenInput = AVCaptureScreenInput(displayID: displayId) if session.canAddInput(input) { session.addInput(input) } movieFileOutput = AVCaptureMovieFileOutput() if session.canAddOutput(movieFileOutput) { session.addOutput(movieFileOutput) } } open func start() { session.startRunning() movieFileOutput.startRecording(toOutputFileURL: self.destinationUrl, recordingDelegate: self) } open func stop() { movieFileOutput.stopRecording() } open func capture( _ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error! ) { // session.stopRunning() } }
mit
90f304f097e37066f6686ef7757fc760
24.15625
101
0.640373
5.457627
false
false
false
false
Abdul-Moiz/AMProgressBar
AMProgressBar/Classes/AMProgressView.swift
1
16340
// // AMProgressView.swift // AMProgressView // // Created by Abdul Moiz on 2017-04-13. // Copyright © 2017 AppBakery. All rights reserved. // import UIKit public enum AMProgressBarStripesOrientation: Int { case vertical = 0 case diagonalRight = 1 case diagonalLeft = 2 } public enum AMProgressBarStripesMotion: Int { case none = 0 case right = 1 case left = -1 } public enum AMProgressBarMode: Int { case determined = 0 case undetermined = 1 } public enum AMProgressBarTextPosition: Int { case topLeft = 0 case topRight = 1 case bottomLeft = 2 case bottomRight = 3 case middleLeft = 4 case middleRight = 5 case middleRightUnderBar = 6 case middle = 7 case onBar = 8 } @IBDesignable open class AMProgressBar: UIView { // MARK: - Global Configs public struct config { // Track Configs static public var cornerRadius: CGFloat = 10 static public var borderColor: UIColor = .white static public var borderWidth: CGFloat = 2 // Bar Configs static public var barCornerRadius: CGFloat = 10 static public var barColor: UIColor = .blue static public var barMode: AMProgressBarMode = .determined // Stripes Configs static public var hideStripes: Bool = false static public var stripesColor: UIColor = .red static public var stripesMotion: AMProgressBarStripesMotion = .right static public var stripesOrientation: AMProgressBarStripesOrientation = .diagonalRight static public var stripesWidth: CGFloat = 30 static public var stripesSpacing: CGFloat = 30 static public var stripesDelta: CGFloat = 80 // Percentage Text Config static public var textColor: UIColor = .black static public var textFont: UIFont = UIFont.systemFont(ofSize: 18) static public var textPosition: AMProgressBarTextPosition = .onBar } // MARK: - Inspectable Properties @IBInspectable open var cornerRadius: CGFloat = config.cornerRadius { didSet { configureView() } } @IBInspectable open var borderColor: UIColor = config.borderColor { didSet { configureView() } } @IBInspectable open var borderWidth: CGFloat = config.borderWidth { didSet { configureView() } } @IBInspectable open var barCornerRadius: CGFloat = config.barCornerRadius { didSet { configureView() } } @IBInspectable open var barColor: UIColor = config.barColor { didSet { configureView() } } @IBInspectable open var barMode: Int = 0 { didSet { barMode_ = AMProgressBarMode(rawValue: barMode) ?? .determined configureView() } } @IBInspectable open var hideStripes: Bool = config.hideStripes { didSet { configureView() } } @IBInspectable open var stripesColor: UIColor = config.stripesColor { didSet { configureView() } } @IBInspectable open var stripesWidth: CGFloat = config.stripesWidth { didSet { configureView() } } @IBInspectable open var stripesSpacing: CGFloat = config.stripesSpacing { didSet { configureView() } } @IBInspectable open var stripesDelta: CGFloat = config.stripesDelta { didSet { configureView() } } @IBInspectable open var stripesMotion: Int = config.barMode.rawValue { didSet { stripesMotion_ = AMProgressBarStripesMotion(rawValue: stripesMotion) ?? .right configureView() } } @IBInspectable open var stripesOrientation: Int = config.stripesOrientation.rawValue { didSet { stripesOrientation_ = AMProgressBarStripesOrientation(rawValue: stripesOrientation) ?? .diagonalRight configureView() } } @IBInspectable open var textColor: UIColor = config.textColor { didSet { configureView() } } @IBInspectable open var textFont: UIFont = config.textFont { didSet { configureView() } } @IBInspectable open var textPosition: Int = config.textPosition.rawValue { didSet { textPosition_ = AMProgressBarTextPosition(rawValue: textPosition) ?? .onBar configureView() } } @IBInspectable open var progressValue: CGFloat = 0 { didSet { if (progressValue >= 1) { progressValue = 1 } else if (progressValue <= 0) { progressValue = 0 } } } // MARK: - Private Properties private var barMode_: AMProgressBarMode = config.barMode private var stripesMotion_: AMProgressBarStripesMotion = config.stripesMotion private var stripesOrientation_: AMProgressBarStripesOrientation = config.stripesOrientation private var textPosition_: AMProgressBarTextPosition = config.textPosition private var barLayer: CAShapeLayer? = nil private var stripeLayers: [CAShapeLayer]? = nil private var textLabel: UILabel? = nil private var animationDuration: CGFloat = 0.25 private var customizing: Bool = false private var isStripesAnimating: Bool = false // MARK: - Override properties open override var isHidden: Bool { didSet { if isHidden == false && isStripesAnimating == false { self.perform(#selector(addStripeAnimation), with: nil, afterDelay: 0.2) } else if isHidden == true { isStripesAnimating = false } } } // MARK: - UIView Methods open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() configureView() } public override init(frame: CGRect) { super.init(frame: frame) configureView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } open override func layoutSubviews() { super.layoutSubviews() if barMode_ == .undetermined { configureView() } else { let rect = CGRect(x:0, y: 0, width: frame.width, height: frame.height) let path = UIBezierPath(roundedRect: rect, cornerRadius: barCornerRadius) barLayer?.path = path.cgPath } } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Listener Methods @objc private func resumeActions(notification: Notification) { addStripeAnimation() } // MARK: - Bulk Customzations @discardableResult open func customize(_ block: (_ progressBar: AMProgressBar) -> ()) -> AMProgressBar { customizing = true block(self) customizing = false configureView() return self } // MARK: - Configuration Methods private func configureView() { if customizing == true { return } clipsToBounds = false layer.cornerRadius = cornerRadius layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor configureListeners() configureBarLayer() configureStripesLayer() configureText() addStripeAnimation() } private func configureBarLayer() { //Remove old bar if barLayer != nil { barLayer?.removeFromSuperlayer() } // Calculate new frames let width = barMode_ == .undetermined ? frame.width : frame.width * progressValue let frameRect = CGRect(x:0, y: 0, width: width, height: frame.height) let rect = CGRect(x:0, y: 0, width: frame.width, height: frame.height) let path = UIBezierPath(roundedRect: rect, cornerRadius: barCornerRadius) // Add new bar barLayer = CAShapeLayer() barLayer?.anchorPoint = .zero barLayer?.path = path.cgPath barLayer?.fillColor = barColor.cgColor barLayer?.masksToBounds = true barLayer?.frame = frameRect barLayer?.cornerRadius = barCornerRadius barLayer?.zPosition = 1 self.layer.addSublayer(barLayer!) } private func configureStripesLayer() { // Remove old stripes stripeLayers?.forEach({ (layer: CAShapeLayer) in layer.removeFromSuperlayer() }) stripeLayers?.removeAll() // if is hide stripes is true then return if hideStripes == true { return } // Add stripes let stripesCount = Int(frame.width/stripesWidth) stripeLayers = [] for i in -1...stripesCount + 1 { let stripe = CAShapeLayer() let rect = CGRect(x:((stripesWidth + stripesSpacing) * CGFloat(i)), y: 0, width: stripesWidth, height: frame.height) let path = getStripeShape(rect: rect) stripe.path = path.cgPath stripe.fillColor = stripesColor.cgColor self.barLayer?.addSublayer(stripe) stripeLayers?.append(stripe) } } private func configureText() { if textLabel != nil { textLabel?.removeFromSuperview() } textLabel = UILabel() textLabel?.numberOfLines = 1 textLabel?.font = textFont textLabel?.textColor = textColor textLabel?.text = barMode_ == .undetermined ? "" : String(format: "%i%%", Int(progressValue * 100)) textLabel?.layer.zPosition = 2 textLabel?.sizeToFit() updateTextPosition() self.addSubview(textLabel!) } private func configureListeners() { NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(resumeActions(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil) } // MARK: - Helping Methods // This method will generate stripes path private func getStripeShape(rect: CGRect) -> UIBezierPath { var path: UIBezierPath! switch stripesOrientation_ { case .diagonalLeft: let diagonalValue: CGFloat = -40 path = UIBezierPath() path.move(to: CGPoint(x: rect.origin.x + diagonalValue, y: rect.origin.y)) path.addLine(to: CGPoint(x: rect.origin.x + rect.width + diagonalValue, y: rect.origin.y)) path.addLine(to: CGPoint(x: rect.origin.x + rect.width, y: rect.origin.y + rect.height)) path.addLine(to: CGPoint(x: rect.origin.x, y: rect.origin.y + rect.height)) case .diagonalRight: let diagonalValue: CGFloat = 40 path = UIBezierPath() path.move(to: CGPoint(x: rect.origin.x + diagonalValue, y: rect.origin.y)) path.addLine(to: CGPoint(x: rect.origin.x + rect.width + diagonalValue, y: rect.origin.y)) path.addLine(to: CGPoint(x: rect.origin.x + rect.width, y: rect.origin.y + rect.height)) path.addLine(to: CGPoint(x: rect.origin.x, y: rect.origin.y + rect.height)) case .vertical: path = UIBezierPath(roundedRect: rect, cornerRadius: 0) } return path } // MARK: - Animation Methods public func startAnimation() { addStripeAnimation() } @objc private func addStripeAnimation() { guard let stripeLayers = stripeLayers, hideStripes == false && stripesMotion_ != .none else { // If there are any stripes but animation is none self.isStripesAnimating = false self.stripeLayers?.forEach { (stripeLayer: CAShapeLayer) in stripeLayer.removeAllAnimations() } return } let direction = stripesMotion_.rawValue stripeLayers.forEach { (stripeLayer: CAShapeLayer) in stripeLayer.removeAllAnimations() let anim = CABasicAnimation(keyPath: "transform.translation.x") anim.duration = CFTimeInterval(stripesDelta/60) anim.repeatCount = Float.greatestFiniteMagnitude anim.fromValue = 0 anim.toValue = (stripesWidth + stripesSpacing) * CGFloat(direction) stripeLayer.add(anim, forKey: "transform.translation.x") } isStripesAnimating = true } // MARK: - Update Methods private func updateProgress(animated: Bool) { guard let barLayer = barLayer, barMode_ != .undetermined else { return } barLayer.removeAllAnimations() let oldBounds = barLayer.frame let newBounds = CGRect(x: 0, y: 0, width: frame.width * progressValue, height: frame.height) barLayer.bounds = newBounds if animated == true { let anim = CABasicAnimation(keyPath: "bounds") anim.duration = CFTimeInterval(animationDuration) anim.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) anim.fromValue = NSValue(cgRect: oldBounds) anim.toValue = NSValue(cgRect: newBounds) anim.isRemovedOnCompletion = true barLayer.add(anim, forKey: "bounds") } } private func updateTextPosition(animated: Bool = false) { guard let textLabel = textLabel else { return } clipsToBounds = false textLabel.layer.zPosition = 2 textLabel.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) switch textPosition_ { case .topLeft: textLabel.center = CGPoint(x: textLabel.frame.width/2, y: -textLabel.frame.height/2) case .topRight: textLabel.center = CGPoint(x: frame.width - textLabel.frame.width/2, y: -textLabel.frame.height/2) case .bottomLeft: textLabel.center = CGPoint(x: textLabel.frame.width/2, y: frame.height + textLabel.frame.height/2) case .bottomRight: textLabel.center = CGPoint(x: frame.width - textLabel.frame.width/2, y: frame.height + textLabel.frame.height/2) case .middleLeft: textLabel.center = CGPoint(x: textLabel.frame.width/2 + 10, y: frame.height/2) case .middleRight: textLabel.center = CGPoint(x: frame.width - textLabel.frame.width/2 - 10, y: frame.height/2) case .middleRightUnderBar: textLabel.layer.zPosition = 0 textLabel.center = CGPoint(x: frame.width - textLabel.frame.width/2 - 10, y: frame.height/2) case .middle: textLabel.center = CGPoint(x: frame.width/2, y: frame.height/2) case .onBar: clipsToBounds = true textLabel.layer.anchorPoint = CGPoint(x: 1, y: 0.5) let oldCenter = textLabel.layer.position let newCenter = CGPoint(x: (frame.width * progressValue) - 10, y: frame.height/2) textLabel.layer.position = newCenter if animated == true { textLabel.layer.removeAllAnimations() let anim = CABasicAnimation(keyPath: "position") anim.duration = CFTimeInterval(animationDuration) anim.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) anim.fromValue = NSValue(cgPoint: oldCenter) anim.toValue = NSValue(cgPoint: newCenter) anim.isRemovedOnCompletion = true textLabel.layer.add(anim, forKey: "position") } } } // MARK: - Public Methods public func setProgress(progress: CGFloat, animated: Bool) { progressValue = progress textLabel?.text = barMode_ == .undetermined ? "" : String(format: "%i%%", Int(progressValue * 100)) textLabel?.sizeToFit() updateTextPosition(animated: animated) updateProgress(animated: animated) } }
mit
8e45774a8e9aa6f7efaa6831744bf235
33.253669
169
0.601138
4.931784
false
true
false
false
davbeck/TNKFoundation
TNKFoundation/NSPredicate/NSComparisonPredicate+TNKFoundation.swift
1
2265
// // NSPredicate+TNKFoundation.swift // TNKFoundation // // Created by David Beck on 10/29/15. // Copyright (c) 2015 Think Ultimate. All rights reserved. // import Foundation private func asExpression(_ value: Any) -> NSExpression { if let expression = value as? NSExpression { return expression } else { return NSExpression(forConstantValue: value) } } infix operator %==: ComparisonPrecedence public func %== (left: Any, right: Any) -> NSPredicate { return NSComparisonPredicate( leftExpression: asExpression(left), rightExpression: asExpression(right), modifier: .direct, type: .equalTo, options: [] ) } infix operator %!=: ComparisonPrecedence public func %!= (left: Any, right: Any) -> NSPredicate { return NSComparisonPredicate( leftExpression: asExpression(left), rightExpression: asExpression(right), modifier: .direct, type: .notEqualTo, options: [] ) } infix operator %<=: ComparisonPrecedence public func %<= (left: Any, right: Any) -> NSPredicate { return NSComparisonPredicate( leftExpression: asExpression(left), rightExpression: asExpression(right), modifier: .direct, type: .lessThanOrEqualTo, options: [] ) } infix operator %<: ComparisonPrecedence public func %< (left: Any, right: Any) -> NSPredicate { return NSComparisonPredicate( leftExpression: asExpression(left), rightExpression: asExpression(right), modifier: .direct, type: .lessThan, options: [] ) } infix operator %>=: ComparisonPrecedence public func %>= (left: Any, right: Any) -> NSPredicate { return NSComparisonPredicate( leftExpression: asExpression(left), rightExpression: asExpression(right), modifier: .direct, type: .greaterThanOrEqualTo, options: [] ) } infix operator %>: ComparisonPrecedence public func %> (left: Any, right: Any) -> NSPredicate { return NSComparisonPredicate( leftExpression: asExpression(left), rightExpression: asExpression(right), modifier: .direct, type: .greaterThan, options: [] ) } extension NSComparisonPredicate { public convenience init(_ left: Any, _ type: Operator, _ right: Any) { self.init( leftExpression: asExpression(left), rightExpression: asExpression(right), modifier: .direct, type: type, options: [] ) } }
mit
d0e7942683135331c0e8b73fd36e16f8
19.972222
71
0.7117
3.641479
false
false
false
false
JackLearning/Weibo
Weibo/Weibo/Classes/ViewModel/StatusListViewModel.swift
1
1926
// // StatusListViewModel.swift // Weibo // // Created by ZhuZongchao on 15/12/23. // Copyright © 2015年 apple. All rights reserved. // import UIKit import SVProgressHUD class StatusListViewModel: NSObject { //since_id实现下拉刷新 新的微博的字段 class func loadHomePageData(since_id:Int64,max_id:Int64,finished: (statuses: [Status]?) ->()) { // 实现网络请求 // get 请求 let urlString = "2/statuses/home_timeline.json" // 判断token 是否为空 guard let token = UserAccountViewModel().token else { print("token 为空") SVProgressHUD.showInfoWithStatus("请重新登录") return } var parameters = ["access_token" : token] // 判断since_id 是否大于0 if since_id > 0 { parameters["since_id"] = "\(since_id)" } if max_id > 0 { parameters["max_id"] = "\(max_id - 1)" } NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in if error != nil { //执行失败的回调的 SVProgressHUD.showInfoWithStatus("您的网络正在睡觉,请稍后...") finished(statuses: nil) return } //请求成功 if let array = dict!["statuses"] as? [[String : AnyObject]] { // print(array) //TODO: 遍历数组中 所有的字典 做字典转模型的操作 var list = [Status]() for item in array { let s = Status(dict: item) list.append(s) } //执行成功的回调 finished(statuses: list) } } } }
mit
0829c55dd5b4f16b815b960b266c3828
27.606557
125
0.480802
4.462916
false
false
false
false
jawwad/RWPickFlavor
RWPickFlavor/PickFlavorViewController.swift
1
2476
// // ViewController.swift // IceCreamShop // // Created by Joshua Greene on 2/8/15. // Copyright (c) 2015 Razeware, LLC. All rights reserved. // import UIKit import Alamofire import MBProgressHUD import BetterBaseClasses public class PickFlavorViewController: BaseViewController, UICollectionViewDelegate { // MARK: Instance Variables var flavors: [Flavor] = [] { didSet { pickFlavorDataSource?.flavors = flavors } } private var pickFlavorDataSource: PickFlavorDataSource? { return collectionView?.dataSource as! PickFlavorDataSource? } private let flavorFactory = FlavorFactory() // MARK: Outlets @IBOutlet var contentView: UIView! @IBOutlet var collectionView: UICollectionView! @IBOutlet var iceCreamView: IceCreamView! @IBOutlet var label: UILabel! // MARK: View Lifecycle public override func viewDidLoad() { super.viewDidLoad() loadFlavors() } private func loadFlavors() { let urlString = "http://www.raywenderlich.com/downloads/Flavors.plist" // 1 showLoadingHUD() Alamofire.request(.GET, urlString, encoding: .PropertyList(.XMLFormat_v1_0, 0)) .responsePropertyList { request, response, array, error in self.hideLoadingHUD() // 2 if let error = error { println("Error: \(error)") // 3 } else if let array = array as? [[String: String]] { // 4 if array.isEmpty { println("No flavors were found!") // 5 } else { self.flavors = self.flavorFactory.flavorsFromDictionaryArray(array) self.collectionView.reloadData() self.selectFirstFlavor() } } } } private func showLoadingHUD() { let hud = MBProgressHUD.showHUDAddedTo(contentView, animated: true) hud.labelText = "Loading..." } private func hideLoadingHUD() { MBProgressHUD.hideAllHUDsForView(contentView, animated: true) } private func selectFirstFlavor() { if let flavor = flavors.first { updateWithFlavor(flavor) } } // MARK: UICollectionViewDelegate public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let flavor = flavors[indexPath.row] updateWithFlavor(flavor) } // MARK: Internal private func updateWithFlavor(flavor: Flavor) { iceCreamView.updateWithFlavor(flavor) label.text = flavor.name } }
mit
d7770c1a491cfe260c30de2258b0885d
22.140187
113
0.663166
4.734226
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxDataSources/Sources/RxDataSources/CollectionViewSectionedDataSource.swift
2
8469
// // CollectionViewSectionedDataSource.swift // RxDataSources // // Created by Krunoslav Zaher on 7/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxCocoa #endif import Differentiator open class _CollectionViewSectionedDataSource : NSObject , UICollectionViewDataSource { open func _rx_numberOfSections(in collectionView: UICollectionView) -> Int { return 0 } open func numberOfSections(in collectionView: UICollectionView) -> Int { return _rx_numberOfSections(in: collectionView) } open func _rx_collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _rx_collectionView(collectionView, numberOfItemsInSection: section) } open func _rx_collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return (nil as UICollectionViewCell?)! } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return _rx_collectionView(collectionView, cellForItemAt: indexPath) } open func _rx_collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: IndexPath) -> UICollectionReusableView { return (nil as UICollectionReusableView?)! } open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { return _rx_collectionView(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) } open func _rx_collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return true } public func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return _rx_collectionView(collectionView, canMoveItemAt: indexPath) } open func _rx_collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { } public func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { _rx_collectionView(collectionView, moveItemAt: sourceIndexPath, to: destinationIndexPath) } } open class CollectionViewSectionedDataSource<S: SectionModelType> : _CollectionViewSectionedDataSource , SectionedViewDataSourceType { public typealias I = S.Item public typealias Section = S public typealias CellFactory = (CollectionViewSectionedDataSource<S>, UICollectionView, IndexPath, I) -> UICollectionViewCell public typealias SupplementaryViewFactory = (CollectionViewSectionedDataSource<S>, UICollectionView, String, IndexPath) -> UICollectionReusableView #if DEBUG // If data source has already been bound, then mutating it // afterwards isn't something desired. // This simulates immutability after binding var _dataSourceBound: Bool = false private func ensureNotMutatedAfterBinding() { assert(!_dataSourceBound, "Data source is already bound. Please write this line before binding call (`bindTo`, `drive`). Data source must first be completely configured, and then bound after that, otherwise there could be runtime bugs, glitches, or partial malfunctions.") } #endif // This structure exists because model can be mutable // In that case current state value should be preserved. // The state that needs to be preserved is ordering of items in section // and their relationship with section. // If particular item is mutable, that is irrelevant for this logic to function // properly. public typealias SectionModelSnapshot = SectionModel<S, I> private var _sectionModels: [SectionModelSnapshot] = [] open var sectionModels: [S] { return _sectionModels.map { Section(original: $0.model, items: $0.items) } } open subscript(section: Int) -> S { let sectionModel = self._sectionModels[section] return S(original: sectionModel.model, items: sectionModel.items) } open subscript(indexPath: IndexPath) -> I { get { return self._sectionModels[indexPath.section].items[indexPath.item] } set(item) { var section = self._sectionModels[indexPath.section] section.items[indexPath.item] = item self._sectionModels[indexPath.section] = section } } open func model(at indexPath: IndexPath) throws -> Any { return self[indexPath] } open func setSections(_ sections: [S]) { self._sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) } } open var configureCell: CellFactory! = nil { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var supplementaryViewFactory: SupplementaryViewFactory { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var moveItem: ((CollectionViewSectionedDataSource<S>, _ sourceIndexPath:IndexPath, _ destinationIndexPath:IndexPath) -> Void)? { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var canMoveItemAtIndexPath: ((CollectionViewSectionedDataSource<S>, IndexPath) -> Bool)? { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } public override init() { self.configureCell = {_, _, _, _ in return (nil as UICollectionViewCell?)! } self.supplementaryViewFactory = {_, _, _, _ in (nil as UICollectionReusableView?)! } super.init() self.configureCell = { [weak self] _, _, _, _ in precondition(false, "There is a minor problem. `cellFactory` property on \(self!) was not set. Please set it manually, or use one of the `rx_bindTo` methods.") return (nil as UICollectionViewCell!)! } self.supplementaryViewFactory = { [weak self] _, _, _, _ in precondition(false, "There is a minor problem. `supplementaryViewFactory` property on \(self!) was not set.") return (nil as UICollectionReusableView?)! } } // UICollectionViewDataSource open override func _rx_numberOfSections(in collectionView: UICollectionView) -> Int { return _sectionModels.count } open override func _rx_collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _sectionModels[section].items.count } open override func _rx_collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { precondition(indexPath.item < _sectionModels[indexPath.section].items.count) return configureCell(self, collectionView, indexPath, self[indexPath]) } open override func _rx_collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: IndexPath) -> UICollectionReusableView { return supplementaryViewFactory(self, collectionView, kind, indexPath) } open override func _rx_collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { guard let canMoveItem = canMoveItemAtIndexPath?(self, indexPath) else { return super._rx_collectionView(collectionView, canMoveItemAt: indexPath) } return canMoveItem } open override func _rx_collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { self._sectionModels.moveFromSourceIndexPath(sourceIndexPath, destinationIndexPath: destinationIndexPath) self.moveItem?(self, sourceIndexPath, destinationIndexPath) } } #endif
mit
bd54590448d81d7e7b36257f029fbfb0
39.132701
280
0.687293
5.687038
false
false
false
false
qmchenry/Plaster
Sources/main.swift
1
3523
// // main.swift // plaster // // Created by Quinn McHenry on 12/15/15. // Copyright © 2015 Quinn McHenry. All rights reserved. // import Foundation import CommandLineKit import FileKit // todo - option to change name of outer struct, default Config // indent options let cli = CommandLine() let inputPath = StringOption(shortFlag: "i", longFlag: "input", required: true, helpMessage: "Input plist dictionary file") let outputPath = StringOption(shortFlag: "o", longFlag: "output", required: false, helpMessage: "Output file path, otherwise stdout") cli.setOptions(inputPath, outputPath) do { try cli.parse() } catch { cli.printUsage(error) exit(EX_USAGE) } let input = inputPath.value.map { Path($0) } guard let input = input else { print("Error: input path could not be opened") exit(-1) } let output = outputPath.value.map { Path($0) } let outputExists = output?.exists ?? false let outputEmpty = output?.fileSize ?? 0 == 0 let outputNewer: Bool if let inputModDate = input.modificationDate, let outputModDate = output?.modificationDate { outputNewer = outputModDate > inputModDate } else { outputNewer = false } // should we perform the conversion? if !outputEmpty && outputNewer { print("Plaster skipping conversion") exit(0) } let indent = " " func process(_ dictionary: NSDictionary) -> String { var output = "" var depth = 0 func processLevel(_ dictionary: NSDictionary) { func indention(_ depth: Int) -> String { return ([String](repeating: indent, count: depth)).reduce(""){ $0 + $1 } } func cleanName(_ key: String) -> String { if String(key.characters.first!).isNumeric { return "_\(key)" } return key } func valueCode(_ value: AnyObject) -> String { if let value = value as? Int { return String(value) } if let value = value as? Double { return String(value) } guard let value = value as? String else { return "" } if value.isNumeric { return value } if let colorCode = value.colorCode { return colorCode } let cleaned = value.replacingOccurrences(of: "\"", with: "\\\"") return "\"\(cleaned)\"" } func processValue(_ value: AnyObject, forKey key: String) { output += indention(depth) + "static let \(cleanName(key)) = \(valueCode(value)) \n" } depth += 1 for (key, value) in dictionary { if let value = value as? NSDictionary { output += indention(depth) + "struct \(cleanName(key as! String)) {\n" processLevel(value) output += indention(depth) + "}\n" } else { processValue(value as AnyObject, forKey: key as! String) } } depth -= 1 } output = "import Foundation\nimport UIKit\n\n" + "struct Config {\n\n" processLevel(dictionary) output += "\n}\n" return output } if let path = inputPath.value, let dictionary = NSDictionary(contentsOfFile: path) { let out = process(dictionary) if let output = output { let outputFile = TextFile(path: output) try out |> outputFile } else { print(out) } exit(0) } print("Error: unable to process file") exit(-1)
mit
5e00261da334eae59d586ccabaa9a0e4
26.732283
133
0.577513
4.177936
false
false
false
false
theScud/Lunch
lunchPlanner/das-Quadart/Endpoints/Updates.swift
2
1432
// // Updates.swift // Quadrat // // Created by Constantine Fry on 06/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation open class Updates: Endpoint { override var endpoint: String { return "updates" } /** https://developer.foursquare.com/docs/updates/updates */ open func get(_ updateId: String, completionHandler: ResponseClosure? = nil) -> Task { return self.getWithPath(updateId, parameters: nil, completionHandler: completionHandler) } // MARK: - General /** https://developer.foursquare.com/docs/updates/notifications */ open func notifications(_ limit: String?, completionHandler: ResponseClosure? = nil) -> Task { let path = "notifications" var parameters: Parameters? if let limit = limit { parameters = [Parameter.limit:limit] } return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } // MARK: - Actions /** https://developer.foursquare.com/docs/updates/marknotificationsread */ open func notifications(_ highWatermark: String, completionHandler: ResponseClosure? = nil) -> Task { let path = "marknotificationsread" let parameters = [Parameter.highWatermark: highWatermark] return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler) } }
apache-2.0
5cd6016e7ea3465c99a1583f9a8b3437
33.926829
105
0.671788
4.741722
false
false
false
false
sivu22/AnyTracker
AnyTracker/ItemCell.swift
1
2296
// // ItemCell.swift // AnyTracker // // Created by Cristian Sava on 24/06/16. // Copyright © 2016 Cristian Sava. All rights reserved. // import UIKit class ItemCell: UITableViewCell { @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var datesLabel: UILabel! 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 } func initCell(withItem item: Item, separator: Bool, longFormat: Bool) { nameLabel.text = item.name descriptionLabel.text = item.description if descriptionLabel.text == "" { for constraint in self.contentView.constraints { if constraint.identifier == "descriptionToValue" { constraint.constant = 0 } } } if item.useDate { datesLabel.text = Utils.stringFrom(date: item.startDate, longFormat: longFormat) + " - " + Utils.stringFrom(date: item.endDate, longFormat: longFormat) } else { datesLabel.text = "" for constraint in self.contentView.constraints { if constraint.identifier == "dateToDescription" { constraint.constant = 0 } } } if let sumItem = item as? ItemSum { typeLabel.backgroundColor = Constants.Colors.ItemSum valueLabel.text = sumItem.sum.asString(withSeparator: separator) } else if let counterItem = item as? ItemCounter { typeLabel.backgroundColor = Constants.Colors.ItemCounter valueLabel.text = counterItem.counter.asString(withSeparator: separator) } else if let journalItem = item as? ItemJournal { typeLabel.backgroundColor = Constants.Colors.ItemJournal valueLabel.text = journalItem.entries.count == 0 ? "No entries" : journalItem.entries.count == 1 ? "1 entry" : "\(journalItem.entries.count) entries" } } }
mit
32ecaa53d57909e6a488bc1327b9c6eb
35.428571
163
0.620915
4.741736
false
false
false
false
yaoshenglong/GFDouYuZhiBo
DouYuZhiBo/DouYuZhiBo/Classes/Main/View/PageContentView.swift
1
5900
// // PageContentView.swift // DouYuZhiBo // // Created by DragonYao on 2017/3/12. // Copyright © 2017年 DragonYao. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) } let ContentCellId: String = "ContentCellId" class PageContentView: UIView { //保存子控制器的数组 var childVCs : [UIViewController] //父控制器 因为外面的控制器对PageContentView有一个强引用 PageContentView对UIViewController又有一次引用 这里使用弱引用 weak var parentViewController: UIViewController? var startOffsetx: CGFloat = 0.0 //再点击时间的时候 判断是否执行滑动代理 var isForbidScrollDelegate: Bool = false weak var delegate: PageContentViewDelegate? //闭包中要使用weak self类型 lazy var collectionVew: UICollectionView = {[weak self] in //1创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0.0 layout.minimumInteritemSpacing = 0.0 layout.scrollDirection = .horizontal //2 创建CollectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.scrollsToTop = false; //register cell collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellId) return collectionView }() //构造函数 init(frame: CGRect, childViewControllers:[UIViewController], parentViewController:UIViewController?) { // self.childVCs = childViewControllers self.parentViewController = parentViewController super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 设置UI extension PageContentView { //1设置UI func setupUI() { for childVC in childVCs { parentViewController?.addChildViewController(childVC) } //2添加UICollectionView addSubview(collectionVew) collectionVew.frame = bounds } } //MARK : - 遵守UICollectionViewDataSource协议 extension PageContentView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVCs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //1、创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellId, for: indexPath) as UICollectionViewCell //每次复用的时候将子控件移除掉 for view in cell.contentView.subviews { view.removeFromSuperview() } //给cell设置内容 let childVC = childVCs[indexPath.item] childVC.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVC.view) return cell } } //MARK : 遵守UICollectionViewDelegate协议 extension PageContentView: UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetx = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { //1判断时是否是点击事件 if isForbidScrollDelegate { return } //获取数据 var progress: CGFloat = 0 var sourceIndex: Int = 0 var targetIndex: Int = 0 //2判断是左滑还是右滑 let scrollViewW = scrollView.bounds.width let currentOffsetx = scrollView.contentOffset.x if currentOffsetx > startOffsetx { //左滑 1计算左滑的比例 progress = currentOffsetx/scrollViewW - floor(currentOffsetx/scrollViewW) //2 计算sourceIndex sourceIndex = Int(currentOffsetx/scrollViewW) targetIndex = sourceIndex + 1 if targetIndex >= childVCs.count { targetIndex = childVCs.count - 1 } //3完全划过去 if currentOffsetx - startOffsetx == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { //右滑 1计算左滑的比例 progress = 1 - (currentOffsetx/scrollViewW - floor(currentOffsetx/scrollViewW)) //2 计算targetIndex targetIndex = Int(currentOffsetx/scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVCs.count { sourceIndex = childVCs.count - 1 } } //4将progress、sourceIndex、targetIndex 传给titleView delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) // print("progress\(progress) sourceIndex\(sourceIndex) targetIndex\(targetIndex)") } } //MARK : - 对外开放的方法 extension PageContentView { public func setCurrentIndex(currentIndex: Int) { //执行点击时间的方法时,禁止代理方法 没必要都执行 isForbidScrollDelegate = true let offsetX = CGFloat(currentIndex) * collectionVew.frame.width collectionVew.setContentOffset(CGPoint(x:offsetX, y:0.0), animated: false) } }
apache-2.0
53523ba42ae5b53b0ab99b7c125168c5
31.56213
129
0.654734
5.411013
false
false
false
false
justin999/gitap
gitap/PhotoManager.swift
1
1159
// // Photo.swift // gitap // // Created by Koichi Sato on 2017/02/05. // Copyright © 2017 Koichi Sato. All rights reserved. // import UIKit import Photos struct PhotoManager { static let shared = PhotoManager() var allPhotos: PHFetchResult<PHAsset>! var smartAlbums: PHFetchResult<PHAssetCollection>! var userCollections: PHFetchResult<PHCollection>! var fetchResult: PHFetchResult<PHAsset>? let sectionLocalizedTitles = ["", NSLocalizedString("Smart Albums", comment: ""), NSLocalizedString("Albums", comment: "")] init() { if allPhotos == nil { // Create a PHFetchResult object for each section in the table view. let allPhotosOptions = PHFetchOptions() allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] allPhotos = PHAsset.fetchAssets(with: allPhotosOptions) smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) userCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil) } } }
mit
343522371136502ad1b4e07640a34acb
31.166667
127
0.673575
5.239819
false
false
false
false
cxchope/NyaaCatAPP_iOS
nyaacatapp/MapVC.swift
1
15146
// // MapVC.swift // nyaacatapp // // Created by 神楽坂雅詩 on 16/3/12. // Copyright © 2016年 KagurazakaYashi. All rights reserved. // import UIKit import WebKit class MapVC: UIViewController , WKNavigationDelegate { var 浏览器:WKWebView? = nil let 动态地图登录接口:String = 全局_喵窩API["动态地图登录接口"]! var 登录步骤:Int = 0 var 左上按钮:UIBarButtonItem? = nil var 右上按钮:UIBarButtonItem? = nil var 等待提示:UIAlertController? = nil var 解析延迟定时器:MSWeakTimer? = nil // var 上次请求网址:String = "about:blank" @IBOutlet weak var 动态地图工具栏: UIView! @IBOutlet weak var 动态: UISwitch! @IBOutlet weak var 三维: UISwitch! @IBOutlet weak var 转到: UIButton! var 地图名:String = "world" override func viewDidLoad() { super.viewDidLoad() 创建UI() 动态地图工具栏可用(false) 创建地图浏览器() } func 创建UI() { 左上按钮 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.compose, target: self, action: #selector(MapVC.左上按钮点击)) navigationItem.leftBarButtonItem = 左上按钮 右上按钮 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.bookmarks, target: self, action: #selector(MapVC.右上按钮点击)) navigationItem.rightBarButtonItem = 右上按钮 } func 左上按钮点击() { 动态地图工具栏.isHidden = !动态地图工具栏.isHidden 转到.isHidden = 动态地图工具栏.isHidden } func 右上按钮点击() { //TODO: 预留地图切换接口 let 选择地图 = UIAlertController(title: "选择地图", message: nil, preferredStyle: UIAlertControllerStyle.alert) let 地图按钮 = UIAlertAction(title: "主世界地图", style: UIAlertActionStyle.default, handler: { (动作:UIAlertAction) -> Void in self.地图名 = "world" self.装入地图(nil, y: nil, z: nil) }) 选择地图.addAction(地图按钮) let 地图S = UIAlertAction(title: "S 世界", style: UIAlertActionStyle.default, handler: { (动作:UIAlertAction) -> Void in self.地图名 = "S" self.装入地图(nil, y: nil, z: nil) }) 选择地图.addAction(地图S) let 地图M = UIAlertAction(title: "M 世界", style: UIAlertActionStyle.default, handler: { (动作:UIAlertAction) -> Void in self.地图名 = "M" self.装入地图(nil, y: nil, z: nil) }) 选择地图.addAction(地图M) // let 导航地图按钮 = UIAlertAction(title: "导航地图(by Miz)", style: UIAlertActionStyle.Default, handler: { (动作:UIAlertAction) -> Void in // self.装入网页(全局_喵窩API["Ilse地图"]!) // }) // 选择地图.addAction(导航地图按钮) let 取消按钮 = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in }) 选择地图.addAction(取消按钮) self.present(选择地图, animated: true, completion: nil) } func 装入地图(_ x:String?, y:String?, z:String?) { var 参数串:String = "\(全局_喵窩API["动态地图域名"]!)/?worldname=" 参数串 = "\(参数串)\(地图名)" if (三维.isOn == true) { 参数串 = "\(参数串)&mapname=surface" } else { 参数串 = "\(参数串)&mapname=flat" } if (动态.isOn == true) { 参数串 = "\(参数串)&nogui=false" } else { 参数串 = "\(参数串)&nogui=true" } if (x != nil) { 参数串 = "\(参数串)&x=\(x!)" } if (y != nil) { 参数串 = "\(参数串)&y=\(y!)" } if (z != nil) { 参数串 = "\(参数串)&zoom=\(z!)" } // 上次请求网址 = 参数串 self.装入网页(参数串) } func 动态地图工具栏可用(_ 是否可用:Bool) { 左上按钮?.isEnabled = 是否可用 转到.isHidden = !是否可用 动态地图工具栏.isHidden = !是否可用 } func 创建地图浏览器() { let 浏览器设置:WKWebViewConfiguration = WKWebViewConfiguration() 浏览器设置.allowsPictureInPictureMediaPlayback = false 浏览器设置.allowsInlineMediaPlayback = false 浏览器设置.allowsAirPlayForMediaPlayback = false 浏览器设置.requiresUserActionForMediaPlayback = false 浏览器设置.suppressesIncrementalRendering = false 浏览器设置.applicationNameForUserAgent = 全局_浏览器标识 let 浏览器偏好设置:WKPreferences = WKPreferences() 浏览器偏好设置.javaScriptCanOpenWindowsAutomatically = false 浏览器偏好设置.javaScriptEnabled = true 浏览器设置.preferences = 浏览器偏好设置 浏览器设置.selectionGranularity = .dynamic let 浏览器坐标:CGRect = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.height) 浏览器 = WKWebView(frame: 浏览器坐标, configuration: 浏览器设置) 浏览器?.backgroundColor = UIColor.black self.view.insertSubview(浏览器!, at: 0) 自动登录动态地图() } func 自动登录动态地图() { if (全局_用户名 != nil && 全局_密码 != nil) { let 网络参数:String = "j_username=" + 全局_用户名! + "&j_password=" + 全局_密码! let 包含参数的网址:String = 动态地图登录接口 + "?" + 网络参数 let 要加载的网页URL:URL = URL(string: 包含参数的网址)! let 网络请求:NSMutableURLRequest = NSMutableURLRequest(url: 要加载的网页URL, cachePolicy: 全局_缓存策略, timeoutInterval: 30) 网络请求.httpMethod = "POST" 浏览器?.navigationDelegate = self 浏览器!.load(网络请求 as URLRequest) } else { 浏览器?.loadHTMLString("你正在处于游客模式,没有权限访问地图。", baseURL: nil) } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { UIApplication.shared.isNetworkActivityIndicatorVisible = false if (登录步骤 == 0) { 登录步骤 += 1 装入网页(全局_喵窩API["静态地图接口"]!) return } if (等待提示 != nil) { 等待提示?.dismiss(animated: false, completion: nil) 等待提示 = nil } let 当前网址:NSString = (webView.url?.absoluteString)! as NSString let 动态地图域名:NSString = 全局_喵窩API["动态地图域名"]! as NSString var 工具栏可用:Bool = false if (当前网址.length > 动态地图域名.length) { let 当前网址裁剪:String = 当前网址.substring(to: 动态地图域名.length) if (动态地图域名.isEqual(to: 当前网址裁剪)) { 工具栏可用 = true } } 请求页面源码() 动态地图工具栏可用(工具栏可用) } func 请求页面源码() { if (解析延迟定时器 == nil) { 解析延迟定时器 = MSWeakTimer.scheduledTimer(withTimeInterval: 0.9, target: self, selector: #selector(self.请求页面源码2), userInfo: nil, repeats: false, dispatchQueue: DispatchQueue.main) } } func 请求页面源码2() { 解析延迟定时器 = nil let 获取网页标题JS:String = "document.title" let 获取网页源码JS:String = "document.documentElement.innerHTML" var 网页源码:[String] = Array<String>() 浏览器!.evaluateJavaScript(获取网页标题JS) { (对象:Any?, 错误:Error?) -> Void in if (对象 == nil) { return } 网页源码.append(对象 as! String) self.浏览器!.evaluateJavaScript(获取网页源码JS) { (对象:Any?, 错误:Error?) -> Void in 网页源码.append(对象 as! String) self.处理返回源码(网页源码) } } } func 处理返回源码(_ 源码:[String]) { let 网页标题:String? = 源码[0] let 网页内容:String? = 源码[1] if (网页标题 == 全局_喵窩API["注册页面标题"]!) { //网页内容?.rangeOfString("Enter user ID and password") != nil if (网页内容?.range(of: "Login Failed") != nil) { let 提示:UIAlertController = UIAlertController(title: "地图连接失败", message: "缓存的登录信息鉴权失败,请重新启动此APP。", preferredStyle: UIAlertControllerStyle.alert) let 取消按钮 = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in UIApplication.shared.isNetworkActivityIndicatorVisible = false }) 提示.addAction(取消按钮) } else { 自动登录动态地图() } } else if (网页内容?.range(of: "Web files are not matched with plugin version") != nil) { 浏览器!.loadHTMLString("", baseURL: nil) let 提示:UIAlertController = UIAlertController(title: "地图连接失败", message: "请切换其他地图试试", preferredStyle: UIAlertControllerStyle.alert) let 取消按钮 = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in UIApplication.shared.isNetworkActivityIndicatorVisible = false }) 提示.addAction(取消按钮) } else if (网页标题 != 全局_喵窩API["地图页面标题"]!) { let 提示:UIAlertController = UIAlertController(title: "地图连接失败", message: "错误:\(网页标题)", preferredStyle: UIAlertControllerStyle.alert) let 取消按钮 = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in UIApplication.shared.isNetworkActivityIndicatorVisible = false }) 提示.addAction(取消按钮) } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { UIApplication.shared.isNetworkActivityIndicatorVisible = false 浏览器?.loadHTMLString("", baseURL: nil) if (等待提示 != nil) { 等待提示?.dismiss(animated: false, completion: nil) 等待提示 = nil } 动态地图工具栏可用(false) let 消息提示:UIAlertController = UIAlertController(title: "载入失败", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) let 取消按钮 = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil) 消息提示.addAction(取消按钮) self.present(消息提示, animated: true, completion: nil) } func 装入网页(_ 网址:String) { if (等待提示 == nil) { UIApplication.shared.isNetworkActivityIndicatorVisible = true 等待提示 = UIAlertController(title: "⌛️正在连接地图服务器", message: nil, preferredStyle: UIAlertControllerStyle.alert) let 取消按钮 = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in UIApplication.shared.isNetworkActivityIndicatorVisible = false self.浏览器?.reload() self.等待提示 = nil }) 等待提示!.addAction(取消按钮) self.present(等待提示!, animated: true, completion: nil) } let 要加载的网页URL:URL = URL(string: 网址)! let 加载地图网络请求:URLRequest = URLRequest(url: 要加载的网页URL, cachePolicy: 全局_缓存策略, timeoutInterval: 30) 浏览器!.load(加载地图网络请求) } @IBAction func 动态开关(_ sender: UISwitch) { 装入地图(nil, y: nil, z: nil) } @IBAction func 三维开关(_ sender: UISwitch) { 装入地图(nil, y: nil, z: nil) } @IBAction func 转到按钮(_ sender: UIButton) { let 提示框:UIAlertController = UIAlertController(title: "请输入转到目标", message: nil, preferredStyle: UIAlertControllerStyle.alert) let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.default, handler: { (动作:UIAlertAction) -> Void in }) let okAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in self.提示框处理(提示框) }) 提示框.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "X 坐标" textField.keyboardType = UIKeyboardType.numberPad } 提示框.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "Y 坐标" textField.keyboardType = UIKeyboardType.numberPad } 提示框.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "Z 放大倍数(0-10)" textField.keyboardType = UIKeyboardType.numberPad } 提示框.addAction(okAction) 提示框.addAction(cancelAction) self.present(提示框, animated: true, completion: nil) } func 提示框处理(_ 提示框:UIAlertController) { let x输入框:UITextField = 提示框.textFields![0] as UITextField let y输入框:UITextField = 提示框.textFields![1] as UITextField let z输入框:UITextField = 提示框.textFields![2] as UITextField //TODO: 坐标补偿、是否为纯数字校验 // 装入地图(x输入框.text, y: y输入框.text, z: z输入框.text) } // - (BOOL)isValidateNum:(NSString *)string // // { // // NSString *numCheck = @"[A-Z0-9a-z]"; // // NSPredicate *numTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",numCheck]; // // return [numTest evaluateWithObject:string]; // // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
b9028f37f8e75835459f22097bd32984
37.764706
186
0.592125
3.801154
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Jetpack/Branding/Button/JetpackButton.swift
1
4988
import UIKit import SwiftUI /// A "Jetpack powered" button with two different styles (`badge` or `banner`) class JetpackButton: CircularImageButton { enum ButtonStyle { case badge case banner } private let style: ButtonStyle init(style: ButtonStyle) { self.style = style super.init(frame: .zero) configureButton() } required init?(coder: NSCoder) { fatalError("Storyboard instantiation not supported.") } private var buttonBackgroundColor: UIColor { switch style { case .badge: return UIColor(light: .muriel(color: .jetpackGreen, .shade40), dark: .muriel(color: .jetpackGreen, .shade90)) case .banner: return .clear } } private var buttonTintColor: UIColor { switch style { case .badge: return UIColor(light: .white, dark: .muriel(color: .jetpackGreen, .shade40)) case .banner: return .muriel(color: .jetpackGreen, .shade40) } } private var buttonTitleColor: UIColor { switch style { case .badge: return .white case .banner: return UIColor(light: .black, dark: .white) } } private var imageBackgroundColor: UIColor { switch style { case .badge: return UIColor(light: .muriel(color: .jetpackGreen, .shade40), dark: .white) case .banner: return .white } } private func configureButton() { isUserInteractionEnabled = FeatureFlag.jetpackPoweredBottomSheet.enabled setTitle(Appearance.title, for: .normal) tintColor = buttonTintColor backgroundColor = buttonBackgroundColor setTitleColor(buttonTitleColor, for: .normal) titleLabel?.font = Appearance.titleFont titleLabel?.adjustsFontForContentSizeCategory = true titleLabel?.minimumScaleFactor = Appearance.minimumScaleFactor titleLabel?.adjustsFontSizeToFitWidth = true setImage(.gridicon(.plans), for: .normal) contentVerticalAlignment = .fill contentMode = .scaleAspectFit imageEdgeInsets = Appearance.iconInsets contentEdgeInsets = Appearance.contentInsets imageView?.contentMode = .scaleAspectFit flipInsetsForRightToLeftLayoutDirection() setImageBackgroundColor(imageBackgroundColor) } private enum Appearance { static let title = NSLocalizedString("jetpack.branding.badge_banner.title", value: "Jetpack powered", comment: "Title of the Jetpack powered badge.") static let minimumScaleFactor: CGFloat = 0.6 static let iconInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10) static let contentInsets = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 10) static let maximumFontPointSize: CGFloat = 22 static let imageBackgroundViewMultiplier: CGFloat = 0.75 static var titleFont: UIFont { let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .callout) let font = UIFont(descriptor: fontDescriptor, size: min(fontDescriptor.pointSize, maximumFontPointSize)) return UIFontMetrics.default.scaledFont(for: font, maximumPointSize: maximumFontPointSize) } } override func layoutSubviews() { super.layoutSubviews() if style == .badge { layer.cornerRadius = frame.height / 2 layer.cornerCurve = .continuous } } } // MARK: Badge view extension JetpackButton { /// Instantiates a view containing a Jetpack powered badge /// - Parameter topPadding: top padding, defaults to 30 pt /// - Parameter bottomPadding: bottom padding, defaults to 30 pt /// - Parameter target: optional target for the button action /// - Parameter selector: optional selector for the button action /// - Returns: the view containing the badge @objc static func makeBadgeView(topPadding: CGFloat = 30, bottomPadding: CGFloat = 30, target: Any? = nil, selector: Selector? = nil) -> UIView { let view = UIView() let badge = JetpackButton(style: .badge) badge.translatesAutoresizingMaskIntoConstraints = false view.addSubview(badge) NSLayoutConstraint.activate([ badge.centerXAnchor.constraint(equalTo: view.centerXAnchor), badge.topAnchor.constraint(equalTo: view.topAnchor, constant: topPadding), badge.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -bottomPadding) ]) if let target = target, let selector = selector { badge.addTarget(target, action: selector, for: .touchUpInside) } return view } }
gpl-2.0
4f331c1ebd58814e74c8574a902af4f0
35.948148
116
0.625702
5.369214
false
false
false
false
ZhipingYang/FlappyBird
FlappyBrid/FlappyBrid/Game/GameViewController.swift
1
1469
// // GameViewController.swift // FlappyBrid // // Created by Daniel on 2/2/16. // Copyright (c) 2016 XcodeYang. All rights reserved. // import SpriteKit import UIKit class GameViewController: UIViewController { override var shouldAutorotate: Bool { true } override var prefersStatusBarHidden: Bool { true } override var canBecomeFirstResponder: Bool { true } override var keyCommands: [UIKeyCommand]? { [ UIKeyCommand(input: "j", modifierFlags: .command, action: #selector(commandAction(_:)), discoverabilityTitle: "Jump"), ] } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } lazy var scene = GameScene(fileNamed: "GameScene")?.then { $0.scaleMode = .aspectFill } override func loadView() { view = SKView().then { $0.ignoresSiblingOrder = true $0.showsFPS = true $0.showsNodeCount = true } } override func viewDidLoad() { super.viewDidLoad() guard let scene = scene, let skView = self.view as? SKView else { return } skView.presentScene(scene) becomeFirstResponder() } @objc func commandAction(_ command: UIKeyCommand) { if command.input == "j" { ControlCentre.trigger(.jump(.keyboard)) } } }
mit
1b412d9136a10abb3ab55e1111aaee46
26.716981
126
0.624234
4.864238
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Helpers/Version.swift
1
746
// // Version.swift // // // Created by Vladislav Fitc on 14/04/2020. // public struct Version { public let major: Int public let minor: Int public let patch: Int public let prereleaseIdentifier: String? public init(major: Int, minor: Int, patch: Int = 0, prereleaseIdentifier: String? = nil) { self.major = major self.minor = minor self.patch = patch self.prereleaseIdentifier = prereleaseIdentifier } } extension Version: CustomStringConvertible { public var description: String { let main = [major, minor, patch].map(String.init).joined(separator: ".") if let prereleaseIdentifier = prereleaseIdentifier { return main + "-\(prereleaseIdentifier)" } else { return main } } }
mit
841ca2a3590243bf1967108f2ca33020
20.314286
92
0.674263
3.926316
false
false
false
false
netcosports/Gnomon
Sources/Core/XPath.swift
1
1188
// // Created by Vladimir Burdukov on 10/21/16. // Copyright © 2016 NetcoSports. All rights reserved. // import Foundation extension Dictionary where Key == String, Value: Any { func dictionary(byPath path: Key) -> [Key: Value]? { guard path.count > 0 else { return nil } let components = path.components(separatedBy: "/") guard components.count > 0 else { return self } return dictionary(byPathComponents: ArraySlice(components)) } func array(byPath path: Key) -> [[Key: Value]]? { guard path.count > 0 else { return nil } let components = path.components(separatedBy: "/") guard components.count > 0 else { return nil } guard let lastKey = components.last else { return nil } if let dict = dictionary(byPathComponents: components.dropLast()) { return dict[lastKey] as? [[Key: Value]] } else { return self[lastKey] as? [[Key: Value]] } } private func dictionary(byPathComponents path: ArraySlice<Key>) -> [Key: Value]? { guard let key = path.first else { return self } guard let value = self[key] as? [Key: Value] else { return nil } return value.dictionary(byPathComponents: path.dropFirst()) } }
mit
9c83b043b21e8742fe334bf8ef457f23
32.914286
84
0.666386
3.930464
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Data/ChartDataSet.swift
3
9529
// // ChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartDataSet: NSObject { public var colors = [UIColor]() internal var _yVals: [ChartDataEntry]! internal var _yMax = Float(0.0) internal var _yMin = Float(0.0) internal var _yValueSum = Float(0.0) public var label = "DataSet" public var visible = true; public var drawValuesEnabled = true; /// the color used for the value-text public var valueTextColor: UIColor = UIColor.blackColor() /// the font for the value-text labels public var valueFont: UIFont = UIFont.systemFontOfSize(7.0) /// the formatter used to customly format the values public var valueFormatter: NSNumberFormatter? /// the axis this DataSet should be plotted against. public var axisDependency = ChartYAxis.AxisDependency.Left public var yVals: [ChartDataEntry] { return _yVals } public var yValueSum: Float { return _yValueSum } public var yMin: Float { return _yMin } public var yMax: Float { return _yMax } public override init() { super.init(); } public init(yVals: [ChartDataEntry]?, label: String) { super.init(); self.label = label; _yVals = yVals == nil ? [ChartDataEntry]() : yVals; // default color colors.append(UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)); self.calcMinMax(); self.calcYValueSum(); } public convenience init(yVals: [ChartDataEntry]?) { self.init(yVals: yVals, label: "DataSet") } /// Use this method to tell the data set that the underlying data has changed public func notifyDataSetChanged() { calcMinMax(); calcYValueSum(); } internal func calcMinMax() { if _yVals!.count == 0 { return; } _yMin = yVals[0].value; _yMax = yVals[0].value; for var i = 0; i < _yVals.count; i++ { let e = _yVals[i]; if (e.value < _yMin) { _yMin = e.value; } if (e.value > _yMax) { _yMax = e.value; } } } private func calcYValueSum() { _yValueSum = 0; for var i = 0; i < _yVals.count; i++ { _yValueSum += fabsf(_yVals[i].value); } } public var entryCount: Int { return _yVals!.count; } public func yValForXIndex(x: Int) -> Float { let e = self.entryForXIndex(x); if (e !== nil) { return e.value } else { return Float.NaN } } /// Returns the first Entry object found at the given xIndex with binary search. /// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index. /// Returns nil if no Entry object at that index. public func entryForXIndex(x: Int) -> ChartDataEntry! { var index = self.entryIndex(xIndex: x); if (index > -1) { return _yVals[index]; } return nil; } public func entriesForXIndex(x: Int) -> [ChartDataEntry] { var entries = [ChartDataEntry](); var low = 0; var high = _yVals.count - 1; while (low <= high) { var m = Int((high + low) / 2); var entry = _yVals[m]; if (x == entry.xIndex) { while (m > 0 && _yVals[m - 1].xIndex == x) { m--; } high = _yVals.count; for (; m < high; m++) { entry = _yVals[m]; if (entry.xIndex == x) { entries.append(entry); } else { break; } } } if (x > _yVals[m].xIndex) { low = m + 1; } else { high = m - 1; } } return entries; } public func entryIndex(xIndex x: Int) -> Int { var low = 0; var high = _yVals.count - 1; var closest = -1; while (low <= high) { var m = (high + low) / 2; var entry = _yVals[m]; if (x == entry.xIndex) { while (m > 0 && _yVals[m - 1].xIndex == x) { m--; } return m; } if (x > entry.xIndex) { low = m + 1; } else { high = m - 1; } closest = m; } return closest; } public func entryIndex(entry e: ChartDataEntry, isEqual: Bool) -> Int { if (isEqual) { for (var i = 0; i < _yVals.count; i++) { if (_yVals[i].isEqual(e)) { return i; } } } else { for (var i = 0; i < _yVals.count; i++) { if (_yVals[i] === e) { return i; } } } return -1 } /// Returns the number of entries this DataSet holds. public var valueCount: Int { return _yVals.count; } public func addEntry(e: ChartDataEntry) { var val = e.value; if (_yVals == nil) { _yVals = [ChartDataEntry](); } if (_yVals.count == 0) { _yMax = val; _yMin = val; } else { if (_yMax < val) { _yMax = val; } if (_yMin > val) { _yMin = val; } } _yValueSum += val; _yVals.append(e); } public func removeEntry(entry: ChartDataEntry) -> Bool { var removed = false; for (var i = 0; i < _yVals.count; i++) { if (_yVals[i] === entry) { _yVals.removeAtIndex(i); removed = true; break; } } if (removed) { _yValueSum -= entry.value; calcMinMax(); } return removed; } public func removeEntry(#xIndex: Int) -> Bool { var index = self.entryIndex(xIndex: xIndex); if (index > -1) { var e = _yVals.removeAtIndex(index); _yValueSum -= e.value; calcMinMax(); return true; } return false; } public func resetColors() { colors.removeAll(keepCapacity: false); } public func addColor(color: UIColor) { colors.append(color); } public func setColor(color: UIColor) { colors.removeAll(keepCapacity: false); colors.append(color); } public func colorAt(var index: Int) -> UIColor { if (index < 0) { index = 0; } return colors[index % colors.count]; } public var isVisible: Bool { return visible; } public var isDrawValuesEnabled: Bool { return drawValuesEnabled; } /// Checks if this DataSet contains the specified Entry. /// :returns: true if contains the entry, false if not. public func contains(e: ChartDataEntry) -> Bool { for entry in _yVals { if (entry.isEqual(e)) { return true; } } return false; } /// Removes all values from this DataSet and recalculates min and max value. public func clear() { _yVals.removeAll(keepCapacity: true); notifyDataSetChanged(); } // MARK: NSObject public override var description: String { return String(format: "ChartDataSet, label: %@, %i entries", arguments: [self.label, _yVals.count]); } public override var debugDescription: String { var desc = description + ":"; for (var i = 0; i < _yVals.count; i++) { desc += "\n" + _yVals[i].description; } return desc; } // MARK: NSCopying public func copyWithZone(zone: NSZone) -> AnyObject { var copy = self.dynamicType.allocWithZone(zone) as ChartDataSet; copy.colors = colors; copy._yVals = _yVals; copy._yMax = _yMax; copy._yMin = _yMin; copy._yValueSum = _yValueSum; copy.label = self.label; return copy; } }
gpl-2.0
bd34db534398404ebb19d2417e6b2432
22.412776
112
0.443593
4.643762
false
false
false
false
sealiver/himachat_iOS
himachat_iOS/AppDelegate.swift
1
6386
// // AppDelegate.swift // himachat_iOS // // Created by A13129 on 2015/01/07. // Copyright (c) 2015年 A13129. 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. let navigationController = self.window!.rootViewController as UINavigationController let controller = navigationController.topViewController as MasterViewController controller.managedObjectContext = self.managedObjectContext 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 "com.ios.pitapat.himachat_iOS" 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("himachat_iOS", 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("himachat_iOS.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. let dict = NSMutableDictionary() 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() } } } }
mit
d74adf8b2846ed3aa5b59837cd99707e
55
290
0.719768
5.761733
false
false
false
false
pkc456/Roastbook
Roastbook/Roastbook/View Controller/Mirror view controller/MirrorViewController.swift
1
3317
// // MirrorViewController.swift // Roastbook // // Created by Pradeep Choudhary on 4/23/17. // Copyright © 2017 Pardeep chaudhary. All rights reserved. // import UIKit import AVFoundation class MirrorViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,PinterestLayoutDelegate { @IBOutlet weak var collectionView: UICollectionView! var mirrorObject = MirrorRoot() var arrayMirrors = [MirrorContentItem]() var pageIndex = 0 override func viewDidLoad() { super.viewDidLoad() self.title = "Mirrors" setUpNavBarButton() fetchMirrorData(pageIndex: pageIndex,isLoaderShown: true) if let layout = collectionView?.collectionViewLayout as? PininterestLayout { layout.delegate = self } } private func setUpNavBarButton(){ let search = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.search, target: nil, action: nil) self.navigationItem.rightBarButtonItem = search } private func fetchMirrorData(pageIndex:Int, isLoaderShown:Bool){ WebServiceHandler.sharedInstance.getMirrorInformation(paginationIndex: pageIndex, isShowLoader: isLoaderShown, successBlock: { (MirrorRoot) in self.mirrorObject = MirrorRoot self.arrayMirrors.append(contentsOf: MirrorRoot.content) DispatchQueue.main.async { let layout : PininterestLayout = self.collectionView.collectionViewLayout as! PininterestLayout layout.invalidateLayout() self.collectionView.reloadData() } }) { (error) in self.showAlert(title: "Error", message: error.localizedDescription) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: Collection view delegates func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // let numberOfRow = self.arrayMirrors?.count ?? 0 return self.arrayMirrors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MirrorCollectionViewCell", for: indexPath)as! MirrorCollectionViewCell cell.mirrorModel = arrayMirrors[indexPath.item] return cell } func collectionView(collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat { let mirrorModelObject = arrayMirrors[indexPath.item] // let boundingRect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT)) // let rect = AVMakeRect(aspectRatio: photo.image.size, insideRect: boundingRect) // return rect.size.height //Calculate height on base of hate percentage var minHeight : CGFloat = 100.0 let hatePercentage = CGFloat(mirrorModelObject.percentage) minHeight = minHeight + hatePercentage return minHeight } public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath){ if(arrayMirrors.count-2 == indexPath.row && pageIndex-1 < mirrorObject.totalPages){ pageIndex += 1 fetchMirrorData(pageIndex: pageIndex,isLoaderShown: false) } } }
mit
e7e56b22c5719c2abdcf882c93f0855d
33.541667
157
0.738239
5.039514
false
false
false
false
balthild/Mathemalpha
Mathemalpha/KeyEvent.swift
1
5492
// // KeyEvent.swift // Mathemalpha // // Created by Balthild Ires on 12/09/2017. // Copyright © 2017 Balthild Ires. All rights reserved. // import CoreGraphics import Cocoa import Carbon.HIToolbox.Events import Magnet import KeyHolder final class KeyEvent { fileprivate(set) static var instance: KeyEvent! let eventSource = CGEventSource(stateID: .privateState) let appDelegate: AppDelegate = NSApp.delegate as! AppDelegate var hotKey: HotKey! fileprivate init() { let keyCombo = KeyEvent.getDefaultKeyCombo() hotKey = HotKey(identifier: "ShowWindow", keyCombo: keyCombo, target: appDelegate.mainWindowController, action: #selector(MainWindowController.showAndOrderFront)) hotKey.register() NSEvent.addLocalMonitorForEvents(matching: NSEventMask.keyDown, handler: keyPressed) #if DEBUG NSLog("Added local keyboard event listener") #endif } func keyPressed(e: NSEvent) -> NSEvent? { if !appDelegate.mainWindowController.shouldHandleKeyEvent { return e } var allowRepeat = false var handler: () -> Void = {} switch (e.keyCode, e.modifierFlags.intersection(.deviceIndependentFlagsMask)) { case (53, []), (13, [.command]): // Esc, Cmd + W handler = self.appDelegate.mainWindowController.close case (49, []): // Space handler = { // We must temporarily hide the window before sending a key event, otherwise // the event will be sent to the window itself, which is not expected to self.appDelegate.mainWindowController.window?.orderOut(self) self.sendChar(self.appDelegate.mainWindowController.getCurrentChar()); self.appDelegate.mainWindowController.window?.makeKeyAndOrderFront(self) } case (36, []): // Enter handler = { self.appDelegate.mainWindowController.hide(self) self.sendChar(self.appDelegate.mainWindowController.getCurrentChar()); } case (51, []): // Backspace handler = { self.appDelegate.mainWindowController.window?.orderOut(self) self.sendBackspace() self.appDelegate.mainWindowController.window?.makeKeyAndOrderFront(self) } case (123...126, _): // Arrows allowRepeat = true handler = { self.appDelegate.mainWindowController.navigate(e.keyCode) } case (48, []): // Tab handler = self.appDelegate.mainWindowController.flipFocused default: #if DEBUG debugPrint(e) #endif return e } if allowRepeat || !e.isARepeat { handler() } return e } func sendChar(_ char: Character) { let event = CGEvent.init(keyboardEventSource: eventSource, virtualKey: 0, keyDown: true) let str = NSString(string: String(char)) let unicode: UnsafeMutablePointer<unichar> = UnsafeMutablePointer.allocate(capacity: str.length) str.getCharacters(unicode) event?.keyboardSetUnicodeString(stringLength: str.length, unicodeString: unicode) event?.post(tap: .cghidEventTap) event?.type = .keyUp event?.post(tap: .cghidEventTap) #if DEBUG NSLog("Sent a character: %@", str) #endif } func sendBackspace() { let event = CGEvent.init(keyboardEventSource: eventSource, virtualKey: 51, keyDown: true) event?.post(tap: .cghidEventTap) event?.type = .keyUp event?.post(tap: .cghidEventTap) #if DEBUG NSLog("Sent a backspace") #endif } static func getDefaultKeyCombo() -> KeyCombo { if let data = UserDefaults.standard.data(forKey: "keyCombo"), let keyCombo = NSKeyedUnarchiver.unarchiveObject(with: data) as? KeyCombo { return keyCombo } else { // Default is Option + Cmd + Space return KeyCombo(keyCode: 49, cocoaModifiers: [.option, .command])! } } } extension KeyEvent: RecordViewDelegate { func recordViewShouldBeginRecording(_ recordView: RecordView) -> Bool { return true } func recordView(_ recordView: RecordView, canRecordKeyCombo keyCombo: KeyCombo) -> Bool { // You can customize validation return true } func recordViewDidClearShortcut(_ recordView: RecordView) { #if DEBUG NSLog("Clear shortcut") #endif hotKey.unregister() } func recordViewDidEndRecording(_ recordView: RecordView) { #if DEBUG NSLog("End recording") #endif } func recordView(_ recordView: RecordView, didChangeKeyCombo keyCombo: KeyCombo) { #if DEBUG NSLog("Recorded") #endif hotKey.unregister() hotKey = HotKey(identifier: "ShowWindow", keyCombo: keyCombo, target: appDelegate.mainWindowController, action: #selector(MainWindowController.showAndOrderFront)) hotKey.register() DispatchQueue.main.async { let data = NSKeyedArchiver.archivedData(withRootObject: keyCombo) UserDefaults.standard.set(data, forKey: "keyCombo") UserDefaults.standard.synchronize() } } static func initialize() { instance = KeyEvent() } static func stop() { instance.hotKey.unregister() } }
gpl-3.0
c7b6affdac2bd72aee5af4cf69f061ff
28.207447
170
0.624659
4.733621
false
false
false
false
liuxuan30/ios-charts
ChartsDemo-iOS/Swift/Demos/MultipleBarChartViewController.swift
3
5607
// // MultipleBarChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class MultipleBarChartViewController: DemoBaseViewController { @IBOutlet var chartView: BarChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Multiple Bar Chart" self.options = [.toggleValues, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData, .toggleBarBorders] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.pinchZoomEnabled = false chartView.drawBarShadowEnabled = false let marker = BalloonMarker(color: UIColor(white: 180/255, alpha: 1), font: .systemFont(ofSize: 12), textColor: .white, insets: UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8)) marker.chartView = chartView marker.minimumSize = CGSize(width: 80, height: 40) chartView.marker = marker let l = chartView.legend l.horizontalAlignment = .right l.verticalAlignment = .top l.orientation = .vertical l.drawInside = true l.font = .systemFont(ofSize: 8, weight: .light) l.yOffset = 10 l.xOffset = 10 l.yEntrySpace = 0 // chartView.legend = l let xAxis = chartView.xAxis xAxis.labelFont = .systemFont(ofSize: 10, weight: .light) xAxis.granularity = 1 xAxis.centerAxisLabelsEnabled = true xAxis.valueFormatter = IntAxisValueFormatter() let leftAxisFormatter = NumberFormatter() leftAxisFormatter.maximumFractionDigits = 1 let leftAxis = chartView.leftAxis leftAxis.labelFont = .systemFont(ofSize: 10, weight: .light) leftAxis.valueFormatter = LargeValueFormatter() leftAxis.spaceTop = 0.35 leftAxis.axisMinimum = 0 chartView.rightAxis.enabled = false sliderX.value = 10 sliderY.value = 100 slidersValueChanged(nil) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let groupSpace = 0.08 let barSpace = 0.03 let barWidth = 0.2 // (0.2 + 0.03) * 4 + 0.08 = 1.00 -> interval per "group" let randomMultiplier = range * 100000 let groupCount = count + 1 let startYear = 1980 let endYear = startYear + groupCount let block: (Int) -> BarChartDataEntry = { (i) -> BarChartDataEntry in return BarChartDataEntry(x: Double(i), y: Double(arc4random_uniform(randomMultiplier))) } let yVals1 = (startYear ..< endYear).map(block) let yVals2 = (startYear ..< endYear).map(block) let yVals3 = (startYear ..< endYear).map(block) let yVals4 = (startYear ..< endYear).map(block) let set1 = BarChartDataSet(entries: yVals1, label: "Company A") set1.setColor(UIColor(red: 104/255, green: 241/255, blue: 175/255, alpha: 1)) let set2 = BarChartDataSet(entries: yVals2, label: "Company B") set2.setColor(UIColor(red: 164/255, green: 228/255, blue: 251/255, alpha: 1)) let set3 = BarChartDataSet(entries: yVals3, label: "Company C") set3.setColor(UIColor(red: 242/255, green: 247/255, blue: 158/255, alpha: 1)) let set4 = BarChartDataSet(entries: yVals4, label: "Company D") set4.setColor(UIColor(red: 255/255, green: 102/255, blue: 0/255, alpha: 1)) let data = BarChartData(dataSets: [set1, set2, set3, set4]) data.setValueFont(.systemFont(ofSize: 10, weight: .light)) data.setValueFormatter(LargeValueFormatter()) // specify the width each bar should have data.barWidth = barWidth // restrict the x-axis range chartView.xAxis.axisMinimum = Double(startYear) // groupWidthWithGroupSpace(...) is a helper that calculates the width each group needs based on the provided parameters chartView.xAxis.axisMaximum = Double(startYear) + data.groupWidth(groupSpace: groupSpace, barSpace: barSpace) * Double(groupCount) data.groupBars(fromX: Double(startYear), groupSpace: groupSpace, barSpace: barSpace) chartView.data = data } override func optionTapped(_ option: Option) { super.handleOption(option, forChartView: chartView) } // MARK: - Actions @IBAction func slidersValueChanged(_ sender: Any?) { let startYear = 1980 let endYear = startYear + Int(sliderX.value) sliderTextX.text = "\(startYear)-\(endYear)" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
apache-2.0
9b013d781f99efd096f29fdfb2f576be
34.935897
187
0.598823
4.602627
false
false
false
false
SPECURE/rmbt-ios-client
Sources/LocaleManager/LocaleManager.swift
1
19096
// // LocaleManager.swift // LocaleManager // // Created by Amir Abbas Mousavian. // Copyright © 2018 Mousavian. Distributed under MIT license. // #if os(iOS) import UIKit #endif import ObjectiveC // MARK: -Languages /** This class handles changing locale/language on the fly, while change interface direction for right-to-left languages. To use, first call `LocaleManager.setup()` method in AppDelegate's `application(_:didFinishLaunchingWithOptions:)` method, then use `LocaleManager.apply(identifier:)` method to change locale. - Note: If you encounter a problem in updating localized strings (e.g. tabbar items' title) set `LocaleManager.updateHandler` variable to fix issue. - Important: Due to an underlying bug in iOS, if you have an image which should be flipped for RTL languages, don't use asset's direction property to mirror image, use `image.imageFlippedForRightToLeftLayoutDirection()` to initialize flippable image instead. - Important: If you used other libraries like maximbilan/ios_language_manager before, call `applyLocale(identifier: nil)` for the first time to remove remnants in order to avoid conflicting. */ public class LocaleManager: NSObject { /// This handler will be called after every change in language. You can change it to handle minor localization issues in user interface. @objc public static var updateHandler: () -> Void = { return } /** This handler will be called to get root viewController to initialize. - Important: Either this property or storyboard identifier's of root view controller must be set. */ @objc public static var rootViewController: ((_ window: UIWindow) -> UIViewController?)? = nil /** This handler will be called to get localized string before checking bundle. Allows custom translation for system strings. - Important: **DON'T USE** `NSLocalizedString()` inside the closure body. Use a `Dictionary` instead. */ @objc public static var customTranslation: ((_ key: String) -> String?)? = nil /// Returns Base localization identifier @objc public class var base: String { return "Base" } public class var isUseSystemLanguage: Bool { get { if let value = UserDefaults.standard.object(forKey: "LocaleManagerUseSystemLanguage") as? Bool { return value } else { return false } } set { UserDefaults.standard.set(newValue, forKey: "LocaleManagerUseSystemLanguage") UserDefaults.standard.synchronize() } } /** Iterates all localization done by developer in app. It can be used to show available option for user. Key in returned dictionay can be used as identifer for passing to `apply(identifier:)`. Value is localized name of language according to current locale and should be shown in user interface. - Note: First item will be `Base` localization. - Return: A dictionary that keys are language identifiers and values are localized language name */ @objc public class var availableLocalizations: [String: String] { let keys = Bundle.main.localizations let vals = keys.map({ Locale.userPreferred.localizedString(forIdentifier: $0) ?? $0 }) return [String: String].init(zip(keys, vals), uniquingKeysWith: { v, _ in v }) } /** Reloads all windows to apply orientation changes in user interface. - Important: Either rootViewController must be set or storyboardIdentifier of root viewcontroller in Main.storyboard must set to a string. */ internal class func reloadWindows(animated: Bool = true) { let windows = UIApplication.shared.windows for window in windows { if let rootViewController = self.rootViewController?(window) { window.rootViewController = rootViewController } else if let storyboard = window.rootViewController?.storyboard, let id = window.rootViewController?.value(forKey: "storyboardIdentifier") as? String { window.rootViewController = storyboard.instantiateViewController(withIdentifier: id) } for view in (window.subviews) { view.removeFromSuperview() window.addSubview(view) } } if animated { windows.first.map { UIView.transition(with: $0, duration: 0.55, options: .transitionFlipFromLeft, animations: nil, completion: nil) } } } /** Overrides system-wide locale in application setting. - Parameter identifier: Locale identifier to be applied, e.g. `en`, `fa`, `de_DE`, etc. */ private class func setLocale(identifiers: [String]) { UserDefaults.standard.set(identifiers, forKey: "AppleLanguages") UserDefaults.standard.synchronize() } /// Removes user preferred locale and resets locale to system-wide. private class func removeLocale() { UserDefaults.standard.removeObject(forKey: "AppleLanguages") // These keys are used in maximbilan/ios_language_manager and may conflict with this implementation. // We remove them here. UserDefaults.standard.removeObject(forKey: "AppleTextDirection") UserDefaults.standard.removeObject(forKey: "NSForceRightToLeftWritingDirection") UserDefaults.standard.synchronize() } /** Overrides system-wide locale in application and reloads interface. - Parameter identifier: Locale identifier to be applied, e.g. `en` or `fa_IR`. `nil` value will change locale to system-wide. */ @objc public class func apply(locale: Locale?, animated: Bool = true) { let semantic: UISemanticContentAttribute if let locale = locale { let identifier = locale.languageCode ?? locale.identifier setLocale(identifiers: [identifier]) semantic = locale.isRTL ? .forceRightToLeft : .forceLeftToRight isUseSystemLanguage = false } else { removeLocale() semantic = Locale.baseLocale.isRTL ? .forceRightToLeft : .forceLeftToRight isUseSystemLanguage = true } Locale.cachePreffered = nil UIView.appearance().semanticContentAttribute = semantic UITableView.appearance().semanticContentAttribute = semantic #if os(iOS) UISwitch.appearance().semanticContentAttribute = semantic #endif reloadWindows(animated: animated) updateHandler() } /** Overrides system-wide locale in application and reloads interface. - Parameter identifier: Locale identifier to be applied, e.g. `en` or `fa_IR`. `nil` value will change locale to system-wide. */ @objc public class func apply(identifier: String?, animated: Bool = true) { let locale = identifier.map(Locale.init(identifier:)) apply(locale: locale, animated: animated) } /** This method MUST be called in `application(_:didFinishLaunchingWithOptions:)` method. */ @objc public class func setup() { // Allowing to update localized string on the fly. Bundle.swizzleMethod(#selector(Bundle.localizedString(forKey:value:table:)), with: #selector(Bundle.mn_custom_localizedString(forKey:value:table:))) // Enforcing userInterfaceLayoutDirection based on selected locale. Fixes pop gesture in navigation controller. UIApplication.swizzleMethod(#selector(getter: UIApplication.userInterfaceLayoutDirection), with: #selector(getter: UIApplication.mn_custom_userInterfaceLayoutDirection)) // Enforcing currect alignment for labels and texts which has `.natural` direction. UILabel.swizzleMethod(#selector(UILabel.layoutSubviews), with: #selector(UILabel.mn_custom_layoutSubviews)) UITextField.swizzleMethod(#selector(UITextField.layoutSubviews), with: #selector(UITextField.mn_custom_layoutSubviews)) } } public extension UITextField { private struct AssociatedKeys { static var originalAlignment = "lm_originalAlignment" static var forcedAlignment = "lm_forcedAlignment" } var originalAlignment: NSTextAlignment? { get { return (objc_getAssociatedObject(self, &AssociatedKeys.originalAlignment) as? Int).flatMap(NSTextAlignment.init(rawValue:)) } set { if let newValue = newValue { objc_setAssociatedObject( self, &AssociatedKeys.originalAlignment, newValue.rawValue as NSNumber, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } var forcedAlignment: NSTextAlignment? { get { return (objc_getAssociatedObject(self, &AssociatedKeys.forcedAlignment) as? Int).flatMap(NSTextAlignment.init(rawValue:)) } set { if let newValue = newValue { objc_setAssociatedObject( self, &AssociatedKeys.forcedAlignment, newValue.rawValue as NSNumber, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } @objc internal func mn_custom_layoutSubviews() { if originalAlignment == nil { originalAlignment = self.textAlignment } if let forcedAlignment = forcedAlignment { self.textAlignment = forcedAlignment } else if originalAlignment == .natural { self.textAlignment = Locale._userPreferred.isRTL ? .right : .left } self.mn_custom_layoutSubviews() } } public extension UILabel { private struct AssociatedKeys { static var originalAlignment = "lm_originalAlignment" static var forcedAlignment = "lm_forcedAlignment" } var originalAlignment: NSTextAlignment? { get { return (objc_getAssociatedObject(self, &AssociatedKeys.originalAlignment) as? Int).flatMap(NSTextAlignment.init(rawValue:)) } set { if let newValue = newValue { objc_setAssociatedObject( self, &AssociatedKeys.originalAlignment, newValue.rawValue as NSNumber, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } var forcedAlignment: NSTextAlignment? { get { return (objc_getAssociatedObject(self, &AssociatedKeys.forcedAlignment) as? Int).flatMap(NSTextAlignment.init(rawValue:)) } set { if let newValue = newValue { objc_setAssociatedObject( self, &AssociatedKeys.forcedAlignment, newValue.rawValue as NSNumber, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } @objc internal func mn_custom_layoutSubviews() { if originalAlignment == nil { originalAlignment = self.textAlignment } if let forcedAlignment = forcedAlignment { self.textAlignment = forcedAlignment } else if originalAlignment == .natural { self.textAlignment = Locale._userPreferred.isRTL ? .right : .left } self.mn_custom_layoutSubviews() } } extension UIApplication { @objc var mn_custom_userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection { get { let _ = self.mn_custom_userInterfaceLayoutDirection // DO NOT OPTIMZE! return Locale._userPreferred.isRTL ? .rightToLeft : .leftToRight } } } extension Bundle { private static var savedLanguageNames: [String: String] = [:] private func languageName(for lang: String) -> String? { if let langName = Bundle.savedLanguageNames[lang] { return langName } let langName = Locale(identifier: "en").localizedString(forLanguageCode: lang) Bundle.savedLanguageNames[lang] = langName return langName } fileprivate func resourcePath(for locale: Locale) -> String? { /* After swizzling localizedString() method, this procedure will be used even for system provided frameworks. Thus we shall try to find appropriate localization resource in current bundle, not main. Apple's framework Trying to find appropriate lproj resource in the bundle ordered by: 1. Locale identifier (e.g: en_GB, fa_IR) 2. Locale language code (e.g en, fa) 3. Locale language name (e.g English, Japanese), used as resource name in Apple system bundles' localization (Foundation, UIKit, ...) */ if let path = self.path(forResource: locale.identifier, ofType: "lproj") { return path } else if let path = locale.languageCode.flatMap(languageName(for:)).flatMap({ self.path(forResource: $0, ofType: "lproj") }) { return path } else if let path = languageName(for: locale.identifier).flatMap({ self.path(forResource: $0, ofType: "lproj") }) { return path } else { return nil } } @objc func mn_custom_localizedString(forKey key: String, value: String?, table tableName: String?) -> String { if let customString = LocaleManager.customTranslation?(key) { return customString } /* Trying to find lproj resource first in user preferred locale, then system-wide current locale, and finally "Base" */ let bundle: Bundle if let path = resourcePath(for: Locale._userPreferred) { bundle = Bundle(path: path)! } else if let path = resourcePath(for: Locale.current) { bundle = Bundle(path: path)! } else if let path = self.path(forResource: LocaleManager.base, ofType: "lproj") { bundle = Bundle(path: path)! } else { if let value = value, !value.isEmpty { return value } else { bundle = self } } return bundle.mn_custom_localizedString(forKey: key, value: value, table: tableName) } } public extension Locale { /** Caching prefered local to speed up as this method is called frequently in swizzled method. Must be set to nil when `AppleLanguages` has changed. */ fileprivate static var cachePreffered: Locale? fileprivate static var _userPreferred: Locale { if let cachePreffered = cachePreffered { return cachePreffered } cachePreffered = userPreferred return cachePreffered! } fileprivate static var baseLocale: Locale { let base = Locale.preferredLanguages.first(where: { $0 != LocaleManager.base }) ?? "en_US" return Locale.init(identifier: base) } /** Locale selected by user. */ static var userPreferred: Locale { let preffered = Locale.preferredLanguages.first.map(Locale.init(identifier:)) ?? Locale.current let localizations = Bundle.main.localizations.map( { $0.replacingOccurrences(of: "-", with: "_") } ) let preferredId = preffered.identifier.replacingOccurrences(of: "-", with: "_") return localizations.contains(preferredId) ? preffered : baseLocale } /** Checking the locale writing direction is right to left. */ var isRTL: Bool { return Locale.characterDirection(forLanguage: self.languageCode!) == .rightToLeft } } public extension NSLocale { /** Locale selected by user. */ @objc class var userPreferred: Locale { return Locale.userPreferred } /** Checking the locale writing direction is right to left. */ @objc var isRTL: Bool { return (self as Locale).isRTL } } public extension NSNumber { /** Returns localized formatted number with maximum fraction digit according to `precision`. - Parameter precision: The maximum number of digits after the decimal separator allowed. - Parameter style: The number style. */ @objc func localized(precision: Int = 0, style: NumberFormatter.Style = .decimal) -> String { let formatter = NumberFormatter() formatter.maximumFractionDigits = precision formatter.numberStyle = style formatter.locale = Locale.userPreferred return formatter.string(from: self)! } } public extension String { /** Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to user preferred locale information. */ func localizedFormat(_ args: CVarArg...) -> String { if args.isEmpty { return self } return String(format: self, locale: Locale.userPreferred, arguments: args) } } internal extension NSObject { @discardableResult class func swizzleMethod(_ selector: Selector, with withSelector: Selector) -> Bool { var originalMethod: Method? var swizzledMethod: Method? originalMethod = class_getInstanceMethod(self, selector) swizzledMethod = class_getInstanceMethod(self, withSelector) if (originalMethod != nil && swizzledMethod != nil) { if class_addMethod(self, selector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) { class_replaceMethod(self, withSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!)) } else { method_exchangeImplementations(originalMethod!, swizzledMethod!) } return true } return false } @discardableResult class func swizzleStaticMethod(_ selector: Selector, with withSelector: Selector) -> Bool { var originalMethod: Method? var swizzledMethod: Method? originalMethod = class_getClassMethod(self, selector) swizzledMethod = class_getClassMethod(self, withSelector) if (originalMethod != nil && swizzledMethod != nil) { if class_addMethod(self, selector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) { class_replaceMethod(self, withSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!)) } else { method_exchangeImplementations(originalMethod!, swizzledMethod!) } return true } return false } }
apache-2.0
9de8b6a00259120206be2957a2d8c713
37.653846
164
0.633674
5.18604
false
false
false
false
xedin/swift
test/Driver/Dependencies/fail-with-bad-deps.swift
8
2605
/// main ==> depends-on-main | bad ==> depends-on-bad // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-with-bad-deps/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled main.swift // CHECK-FIRST: Handled bad.swift // CHECK-FIRST: Handled depends-on-main.swift // CHECK-FIRST: Handled depends-on-bad.swift // Reset the .swiftdeps files. // RUN: cp -r %S/Inputs/fail-with-bad-deps/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-NONE %s // CHECK-NONE-NOT: Handled // Reset the .swiftdeps files. // RUN: cp -r %S/Inputs/fail-with-bad-deps/*.swiftdeps %t // RUN: touch -t 201401240006 %t/bad.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BUILD-ALL %s // CHECK-BUILD-ALL-NOT: warning // CHECK-BUILD-ALL: Handled bad.swift // CHECK-BUILD-ALL-DAG: Handled main.swift // CHECK-BUILD-ALL-DAG: Handled depends-on-main.swift // CHECK-BUILD-ALL-DAG: Handled depends-on-bad.swift // Reset the .swiftdeps files. // RUN: cp -r %S/Inputs/fail-with-bad-deps/*.swiftdeps %t // RUN: touch -t 201401240007 %t/bad.swift %t/main.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-WITH-FAIL %s // RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps // CHECK-WITH-FAIL: Handled main.swift // CHECK-WITH-FAIL-NOT: Handled depends // CHECK-WITH-FAIL: Handled bad.swift // CHECK-WITH-FAIL-NOT: Handled depends // CHECK-RECORD-DAG: "./bad.swift": !private [ // CHECK-RECORD-DAG: "./main.swift": [ // CHECK-RECORD-DAG: "./depends-on-main.swift": !dirty [ // CHECK-RECORD-DAG: "./depends-on-bad.swift": [
apache-2.0
c022957a00d2d4c2df215d5d124681d0
53.270833
306
0.699424
2.95017
false
false
false
false
edragoev1/pdfjet
Sources/PDFjet/LZWEncode.swift
1
3142
/** * LZWEncode.swift * Copyright 2020 Innovatics Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public class LZWEncode { private var table = LZWHashTable() private var bitBuffer: UInt32 = 0 private var bitsInBuffer = 0 private var eight = 8 @discardableResult public init( _ output: inout [UInt8], _ source: inout [UInt8]) { var code1: UInt32 = 0 var code2: UInt32 = 258 var length = 9 writeCode(256, length, &output) // Clear Table code var i1 = 0 var i2 = 0 while i2 < source.count { if let code = table.get(&source, i1, i2, /* put: */ code2) { code1 = code i2 += 1 if i2 < source.count { continue } writeCode(code1, length, &output) } else { writeCode(code1, length, &output) code2 += 1 if code2 == 512 { length = 10 } else if code2 == 1024 { length = 11 } else if code2 == 2048 { length = 12 } else if code2 == 4095 { // EarlyChange is 1 writeCode(256, length, &output) // Clear Table code code2 = 258 length = 9 table.clear() } i1 = i2 } } writeCode(257, length, &output) // EOD if bitsInBuffer > 0 { output.append(UInt8((bitBuffer &<< (eight - bitsInBuffer)) & 0xFF)) } } private func writeCode( _ code: UInt32, _ length: Int, _ output: inout [UInt8]) { bitBuffer = bitBuffer &<< length bitBuffer |= code bitsInBuffer += length while bitsInBuffer >= 8 { output.append(UInt8((bitBuffer >> (bitsInBuffer - eight)) & 0xFF)) bitsInBuffer -= 8 } } }
mit
d37bc336bcbf3cf6d1eba8b3c66ecbed
32.073684
79
0.551241
4.682563
false
false
false
false
domenicosolazzo/practice-swift
Views/CollectionView/FlickrSearch/FlickrSearch/FlickrSearcher.swift
1
4918
// // FlickrSearcher.swift // flickrSearch // // Created by Richard Turton on 31/07/2014. // Copyright (c) 2014 Razeware. All rights reserved. // import Foundation import UIKit let apiKey = "5b1c424cce01c1c1d818e0e12722c10c" struct FlickrSearchResults { let searchTerm : String let searchResults : [FlickrPhoto] } class FlickrPhoto : Equatable { var thumbnail : UIImage? var largeImage : UIImage? let photoID : String let farm : Int let server : String let secret : String init (photoID:String,farm:Int, server:String, secret:String) { self.photoID = photoID self.farm = farm self.server = server self.secret = secret } func flickrImageURL(_ size:String = "m") -> URL { return URL(string: "http://farm\(farm).staticflickr.com/\(server)/\(photoID)_\(secret)_\(size).jpg")! } func loadLargeImage(_ completion: @escaping (_ flickrPhoto:FlickrPhoto, _ error: NSError?) -> Void) { let loadURL = flickrImageURL("b") let loadRequest = URLRequest(url:loadURL) NSURLConnection.sendAsynchronousRequest(loadRequest, queue: OperationQueue.main) { response, data, error in if error != nil { completion(self, error as NSError?) return } if data != nil { let returnedImage = UIImage(data: data!) self.largeImage = returnedImage completion(self, nil) return } completion(self, nil) } } func sizeToFillWidthOfSize(_ size:CGSize) -> CGSize { if thumbnail == nil { return size } let imageSize = thumbnail!.size var returnSize = size let aspectRatio = imageSize.width / imageSize.height returnSize.height = returnSize.width / aspectRatio if returnSize.height > size.height { returnSize.height = size.height returnSize.width = size.height * aspectRatio } return returnSize } } func == (lhs: FlickrPhoto, rhs: FlickrPhoto) -> Bool { return lhs.photoID == rhs.photoID } class Flickr { let processingQueue = OperationQueue() func searchFlickrForTerm(_ searchTerm: String, completion : @escaping (_ results: FlickrSearchResults?, _ error : NSError?) -> Void){ let searchURL = flickrSearchURLForSearchTerm(searchTerm) let searchRequest = URLRequest(url: searchURL) NSURLConnection.sendAsynchronousRequest(searchRequest, queue: processingQueue) {response, data, error in if error != nil { completion(nil,error as NSError?) return } let JSONError : NSError? do{ let resultsDictionary = try JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions(rawValue: 0)) as? NSDictionary if JSONError != nil { completion(nil, JSONError) return } switch (resultsDictionary!["stat"] as! String) { case "ok": print("Results processed OK") case "fail": let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:resultsDictionary!["message"]!]) completion(nil, APIError) return default: let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Uknown API response"]) completion(nil, APIError) return } let photosContainer = resultsDictionary!["photos"] as! NSDictionary let photosReceived = photosContainer["photo"] as! [NSDictionary] let flickrPhotos : [FlickrPhoto] = photosReceived.map { photoDictionary in let photoID = photoDictionary["id"] as? String ?? "" let farm = photoDictionary["farm"] as? Int ?? 0 let server = photoDictionary["server"] as? String ?? "" let secret = photoDictionary["secret"] as? String ?? "" let flickrPhoto = FlickrPhoto(photoID: photoID, farm: farm, server: server, secret: secret) let imageData = try? Data(contentsOf: flickrPhoto.flickrImageURL()) flickrPhoto.thumbnail = UIImage(data: imageData!) return flickrPhoto } DispatchQueue.main.async(execute: { completion(FlickrSearchResults(searchTerm: searchTerm, searchResults: flickrPhotos), nil) }) }catch { print("Something went wrong!") } } } fileprivate func flickrSearchURLForSearchTerm(_ searchTerm:String) -> URL { let escapedTerm = searchTerm.addingPercentEscapes(using: String.Encoding.utf8)! let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(escapedTerm)&per_page=20&format=json&nojsoncallback=1" return URL(string: URLString)! } }
mit
b82328f7d3a1330e40f2316020d6063c
29.930818
166
0.628508
4.688275
false
false
false
false
liuduoios/POMVVMDemo
Pods/Bond/Bond/Extensions/iOS/UITableView+Bond.swift
4
11363
// // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit @objc public protocol BNDTableViewProxyDataSource { optional func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? optional func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? optional func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool optional func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool optional func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? optional func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int optional func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) optional func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) /// Override to specify custom row animation when row is being inserted, deleted or updated optional func tableView(tableView: UITableView, animationForRowAtIndexPaths indexPaths: [NSIndexPath]) -> UITableViewRowAnimation /// Override to specify custom row animation when section is being inserted, deleted or updated optional func tableView(tableView: UITableView, animationForRowInSections sections: Set<Int>) -> UITableViewRowAnimation } private class BNDTableViewDataSource<T>: NSObject, UITableViewDataSource { private let array: ObservableArray<ObservableArray<T>> private weak var tableView: UITableView! private let createCell: (NSIndexPath, ObservableArray<ObservableArray<T>>, UITableView) -> UITableViewCell private weak var proxyDataSource: BNDTableViewProxyDataSource? private let sectionObservingDisposeBag = DisposeBag() private init(array: ObservableArray<ObservableArray<T>>, tableView: UITableView, proxyDataSource: BNDTableViewProxyDataSource?, createCell: (NSIndexPath, ObservableArray<ObservableArray<T>>, UITableView) -> UITableViewCell) { self.tableView = tableView self.createCell = createCell self.proxyDataSource = proxyDataSource self.array = array super.init() tableView.dataSource = self tableView.reloadData() setupPerSectionObservers() array.observeNew { [weak self] arrayEvent in guard let unwrappedSelf = self, let tableView = unwrappedSelf.tableView else { return } switch arrayEvent.operation { case .Batch(let operations): tableView.beginUpdates() for diff in changeSetsFromBatchOperations(operations) { BNDTableViewDataSource.applySectionUnitChangeSet(diff, tableView: tableView, dataSource: unwrappedSelf.proxyDataSource) } tableView.endUpdates() case .Reset: tableView.reloadData() default: BNDTableViewDataSource.applySectionUnitChangeSet(arrayEvent.operation.changeSet(), tableView: tableView, dataSource: unwrappedSelf.proxyDataSource) } unwrappedSelf.setupPerSectionObservers() }.disposeIn(bnd_bag) } private func setupPerSectionObservers() { sectionObservingDisposeBag.dispose() for (sectionIndex, sectionObservableArray) in array.enumerate() { sectionObservableArray.observeNew { [weak tableView, weak self] arrayEvent in guard let tableView = tableView else { return } switch arrayEvent.operation { case .Batch(let operations): tableView.beginUpdates() for diff in changeSetsFromBatchOperations(operations) { BNDTableViewDataSource.applyRowUnitChangeSet(diff, tableView: tableView, sectionIndex: sectionIndex, dataSource: self?.proxyDataSource) } tableView.endUpdates() case .Reset: let indices = Set([sectionIndex]) tableView.reloadSections(NSIndexSet(index: sectionIndex), withRowAnimation: self?.proxyDataSource?.tableView?(tableView, animationForRowInSections: indices) ?? .Automatic) default: BNDTableViewDataSource.applyRowUnitChangeSet(arrayEvent.operation.changeSet(), tableView: tableView, sectionIndex: sectionIndex, dataSource: self?.proxyDataSource) } }.disposeIn(sectionObservingDisposeBag) } } private class func applySectionUnitChangeSet(changeSet: ObservableArrayEventChangeSet, tableView: UITableView, dataSource: BNDTableViewProxyDataSource?) { switch changeSet { case .Inserts(let indices): tableView.insertSections(NSIndexSet(set: indices), withRowAnimation: dataSource?.tableView?(tableView, animationForRowInSections: indices) ?? .Automatic) case .Updates(let indices): tableView.reloadSections(NSIndexSet(set: indices), withRowAnimation: dataSource?.tableView?(tableView, animationForRowInSections: indices) ?? .Automatic) case .Deletes(let indices): tableView.deleteSections(NSIndexSet(set: indices), withRowAnimation: dataSource?.tableView?(tableView, animationForRowInSections: indices) ?? .Automatic) } } private class func applyRowUnitChangeSet(changeSet: ObservableArrayEventChangeSet, tableView: UITableView, sectionIndex: Int, dataSource: BNDTableViewProxyDataSource?) { switch changeSet { case .Inserts(let indices): let indexPaths = indices.map { NSIndexPath(forItem: $0, inSection: sectionIndex) } tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: dataSource?.tableView?(tableView, animationForRowAtIndexPaths: indexPaths) ?? .Automatic) case .Updates(let indices): let indexPaths = indices.map { NSIndexPath(forItem: $0, inSection: sectionIndex) } tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: dataSource?.tableView?(tableView, animationForRowAtIndexPaths: indexPaths) ?? .Automatic) case .Deletes(let indices): let indexPaths = indices.map { NSIndexPath(forItem: $0, inSection: sectionIndex) } tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: dataSource?.tableView?(tableView, animationForRowAtIndexPaths: indexPaths) ?? .Automatic) } } /// MARK - UITableViewDataSource @objc func numberOfSectionsInTableView(tableView: UITableView) -> Int { return array.count } @objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array[section].count } @objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return createCell(indexPath, array, tableView) } @objc func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return proxyDataSource?.tableView?(tableView, titleForHeaderInSection: section) } @objc func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return proxyDataSource?.tableView?(tableView, titleForFooterInSection: section) } @objc func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return proxyDataSource?.tableView?(tableView, canEditRowAtIndexPath: indexPath) ?? false } @objc func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return proxyDataSource?.tableView?(tableView, canMoveRowAtIndexPath: indexPath) ?? false } @objc func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { return proxyDataSource?.sectionIndexTitlesForTableView?(tableView) } @objc func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { if let section = proxyDataSource?.tableView?(tableView, sectionForSectionIndexTitle: title, atIndex: index) { return section } else { fatalError("Dear Sir/Madam, your table view has asked for section for section index title \(title). Please provide a proxy data source object in bindTo() method that implements `tableView(tableView:sectionForSectionIndexTitle:atIndex:)` method!") } } @objc func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { proxyDataSource?.tableView?(tableView, commitEditingStyle: editingStyle, forRowAtIndexPath: indexPath) } @objc func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { proxyDataSource?.tableView?(tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) } } extension UITableView { private struct AssociatedKeys { static var BondDataSourceKey = "bnd_BondDataSourceKey" } } public extension EventProducerType where EventType: ObservableArrayEventType, EventType.ObservableArrayEventSequenceType.Generator.Element: EventProducerType, EventType.ObservableArrayEventSequenceType.Generator.Element.EventType: ObservableArrayEventType { private typealias ElementType = EventType.ObservableArrayEventSequenceType.Generator.Element.EventType.ObservableArrayEventSequenceType.Generator.Element public func bindTo(tableView: UITableView, proxyDataSource: BNDTableViewProxyDataSource? = nil, createCell: (NSIndexPath, ObservableArray<ObservableArray<ElementType>>, UITableView) -> UITableViewCell) -> DisposableType { let array: ObservableArray<ObservableArray<ElementType>> if let downcastedObservableArray = self as? ObservableArray<ObservableArray<ElementType>> { array = downcastedObservableArray } else { array = self.map { $0.crystallize() }.crystallize() } let dataSource = BNDTableViewDataSource(array: array, tableView: tableView, proxyDataSource: proxyDataSource, createCell: createCell) objc_setAssociatedObject(tableView, &UITableView.AssociatedKeys.BondDataSourceKey, dataSource, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return BlockDisposable { [weak tableView] in if let tableView = tableView { objc_setAssociatedObject(tableView, &UITableView.AssociatedKeys.BondDataSourceKey, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } }
mit
1357e05fe70492f21476445449fb2040
52.347418
252
0.767579
5.426457
false
false
false
false
roecrew/AudioKit
Examples/iOS/SporthEditor/SporthEditor/ViewController.swift
2
5897
// // ViewController.swift // SporthEditor // // Created by Aurelius Prochazka on 7/10/16. // Copyright © 2016 AudioKit. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate { @IBOutlet var codeEditorTextView: UITextView! @IBOutlet var nameTextField: UITextField! @IBOutlet var listOfSavedCodes: UIPickerView! @IBOutlet var slider1: UISlider! @IBOutlet var slider2: UISlider! @IBOutlet var slider3: UISlider! @IBOutlet var slider4: UISlider! var brain = SporthEditorBrain() @IBAction func run(sender: UIButton) { slider1.value = 0.0 slider2.value = 0.0 slider3.value = 0.0 slider4.value = 0.0 brain.run(codeEditorTextView.text) } @IBAction func stop(sender: UIButton) { brain.stop() } func updateUI() { listOfSavedCodes.reloadAllComponents() } func setupUI() { do { try brain.save(Constants.File.chat, code: String(contentsOfFile: Constants.Path.chat, encoding: NSUTF8StringEncoding)) try brain.save(Constants.File.drone, code: String(contentsOfFile: Constants.Path.drone, encoding: NSUTF8StringEncoding)) try brain.save(Constants.File.rhythmic, code: String(contentsOfFile: Constants.Path.rhythmic, encoding: NSUTF8StringEncoding)) listOfSavedCodes.selectRow(0, inComponent: 1, animated: true) codeEditorTextView.text = brain.knownCodes[brain.names.first!] nameTextField.text = brain.names.first! } catch { NSLog(Constants.Error.Loading) } } func presentAlert(error: Error) { let alert = UIAlertController() switch error { case .Code: alert.title = Constants.Code.title alert.message = Constants.Code.message case .Name: alert.title = Constants.Name.title alert.message = Constants.Name.message } alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } @IBAction func save(sender: UIButton) { guard let name = nameTextField.text where !name.isEmpty else { presentAlert(Error.Name) return } guard let code = codeEditorTextView.text where !code.isEmpty else { presentAlert(Error.Code) return } brain.save(name, code: code) updateUI() } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { // The number of components (or “columns”) that the picker view should display. return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return brain.names.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return brain.names[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { codeEditorTextView.text = brain.knownCodes[brain.names[row]] } func textFieldShouldReturn(textField: UITextField) -> Bool { nameTextField.resignFirstResponder() return true } override func viewDidLoad() { super.viewDidLoad() setupUI() listOfSavedCodes.dataSource = self listOfSavedCodes.delegate = self nameTextField.delegate = self } @IBAction func trigger1(sender: UIButton) { print("triggering 1") brain.generator?.trigger(0) } @IBAction func trigger2(sender: UIButton) { print("triggering 2") brain.generator?.trigger(1) } @IBAction func trigger3(sender: UIButton) { print("triggering 3") brain.generator?.trigger(2) } @IBAction func trigger4(sender: UIButton) { print("triggering 4") brain.generator?.trigger(3) } @IBAction func activateGate1(sender: UIButton) { brain.generator?.parameters[0] = 1.0 slider1.value = 1 } @IBAction func deactivateGate1(sender: UIButton) { brain.generator?.parameters[0] = 0.0 slider1.value = 0 } @IBAction func activateGate2(sender: UIButton) { brain.generator?.parameters[1] = 1.0 slider2.value = 1 } @IBAction func deactivateGate2(sender: UIButton) { brain.generator?.parameters[1] = 0.0 slider2.value = 0 } @IBAction func activateGate3(sender: UIButton) { brain.generator?.parameters[2] = 1.0 slider3.value = 1 } @IBAction func deactivateGate3(sender: UIButton) { brain.generator?.parameters[2] = 0.0 slider3.value = 0 } @IBAction func activateGate4(sender: UIButton) { brain.generator?.parameters[3] = 1.0 slider4.value = 1 } @IBAction func deactivateGate4(sender: UIButton) { brain.generator?.parameters[3] = 0.0 slider4.value = 0 } @IBAction func updateParameter1(sender: UISlider) { print("value 1 = \(sender.value)") brain.generator?.parameters[0] = Double(sender.value) } @IBAction func updateParameter2(sender: UISlider) { print("value 2 = \(sender.value)") brain.generator?.parameters[1] = Double(sender.value) } @IBAction func updateParameter3(sender: UISlider) { print("value 3 = \(sender.value)") brain.generator?.parameters[2] = Double(sender.value) } @IBAction func updateParameter4(sender: UISlider) { print("value 4 = \(sender.value)") brain.generator?.parameters[3] = Double(sender.value) } }
mit
d5b535cd04ec8e9d19e9de050ef9fc53
30.340426
138
0.624236
4.397015
false
false
false
false
hipposan/Oslo
Oslo/LikedPhotosCollectionViewController.swift
1
5207
// // LikedPhotoCollectionViewController.swift // Oslo // // Created by Ziyi Zhang on 01/12/2016. // Copyright © 2016 Ziyideas. All rights reserved. // import UIKit class LikedPhotosCollectionViewController: UICollectionViewController { var userName: String = "" var likedTotalCount: Int = 0 fileprivate var width: CGFloat = 0.0 fileprivate var photoCache = NSCache<NSString, UIImage>() fileprivate var likedPhotos = [Photo]() fileprivate var downloadedLikedPhotos = [UIImage?]() fileprivate var currentLikedPhotoPage = 1 @IBOutlet var likedPhotosCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() currentLikedPhotoPage = 1 retryLoad() } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return likedPhotos.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LikedPhotoCell", for: indexPath) as! LikedPhotoCollectionViewCell cell.likedPhotoImageView.image = nil let photoURLString = likedPhotos[indexPath.row].imageURL if let photoURL = URL(string: photoURLString) { if let cachedImage = self.photoCache.object(forKey: photoURLString as NSString) { cell.likedPhotoImageView.image = cachedImage self.downloadedLikedPhotos[indexPath.row] = cachedImage } else { NetworkService.image(with: photoURL) { image in self.photoCache.setObject(image, forKey: photoURLString as NSString) self.downloadedLikedPhotos[indexPath.row] = image if let updateCell = collectionView.cellForItem(at: indexPath) as? LikedPhotoCollectionViewCell { updateCell.likedPhotoImageView.alpha = 0 UIView.animate(withDuration: 0.3) { updateCell.likedPhotoImageView.alpha = 1 updateCell.likedPhotoImageView.image = image } } } } } return cell } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == likedPhotos.count - 1 && indexPath.row != likedTotalCount - 1 { currentLikedPhotoPage += 1 load(with: currentLikedPhotoPage) } } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { performSegue(withIdentifier: "PhotoSegue", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "PhotoSegue" { if let selectedIndexPath = likedPhotosCollectionView.indexPathsForSelectedItems?[0].row, let destinationViewController = segue.destination as? PersonalPhotoViewController { destinationViewController.photo = likedPhotos[selectedIndexPath] destinationViewController.personalPhoto = downloadedLikedPhotos[selectedIndexPath] if let photosTableViewController = navigationController?.viewControllers[0] as? PhotosTableViewController { destinationViewController.delegate = photosTableViewController } } } } func load(with page: Int = 1) { let urlString = Constants.Base.UnsplashAPI + "/users/\(userName)/likes" let url = URL(string: urlString)! NetworkService.request(url: url, method: NetworkService.HTTPMethod.GET, parameters: [Constants.Parameters.ClientID as Dictionary<String, AnyObject>, ["page": page as AnyObject]], headers: ["Authorization": "Bearer " + Token.getToken()!]) { jsonData in OperationService.parseJsonWithPhotoData(jsonData as! [Dictionary<String, AnyObject>]) { photo in self.likedPhotos.append(photo) self.downloadedLikedPhotos.append(nil) } OperationQueue.main.addOperation { self.likedPhotosCollectionView.reloadData() } } } func retryLoad() { if userName != "" { load() return } else { delay(1.0) { self.retryLoad() } } } } extension LikedPhotosCollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: self.width, height: self.width) } } extension LikedPhotosCollectionViewController: PassDataDelegate { func pass(userName: String, photosCount: Int) { self.userName = userName self.likedTotalCount = photosCount } func pass(width: CGFloat) { self.width = width } }
mit
5812bc21dd0d8837f00eadf51ab73fce
35.921986
158
0.646754
5.48
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Login Management/NoLoginsView.swift
1
1392
/* 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 /// Empty state view when there is no logins to display. class NoLoginsView: UIView { // We use the search bar height to maintain visual balance with the whitespace on this screen. The // title label is centered visually using the empty view + search bar height as the size to center with. var searchBarHeight: CGFloat = 0 { didSet { setNeedsUpdateConstraints() } } lazy var titleLabel: UILabel = { let label = UILabel() label.font = LoginListViewModel.LoginListUX.NoResultsFont label.textColor = LoginListViewModel.LoginListUX.NoResultsTextColor label.text = .NoLoginsFound return label }() override init(frame: CGRect) { super.init(frame: frame) addSubview(titleLabel) } internal override func updateConstraints() { super.updateConstraints() titleLabel.snp.remakeConstraints { make in make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-(searchBarHeight / 2)) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
b85f54e107a08f0eb9c123e9b8c363e9
32.142857
108
0.661638
4.686869
false
false
false
false
madhusamuel/PlacesExplorer
PlacesExplorer/Networking/DataService.swift
1
981
// // DataService.swift // PlacesExplorer // // Created by Madhu Samuel on 26/10/2015. // Copyright © 2015 Madhu. All rights reserved. // import Foundation class DataService { let endpoint = "https://api.foursquare.com" let searchApiUrl = "/v2/venues/search" let clientId = "45OD3KD2OAX3IDGYPJ3FVXQX5VYIGWV5JDQGM1MDBGJEWFJF" let clientSecret = "E3G1JPJWTJF4XISJA5C5DYVKQLEXSOQGBLPWPLADBZFBTO2R&v=20130815" func login(userName: String, password: String, success:()->(), failure: (error: NSError)->()) { print("Loggin in \(userName)") } func createURLConstructorWithDataString(data: String) -> URLConstructor { let urlConstructor = URLConstructor() urlConstructor.endPoint = endpoint urlConstructor.webservice = searchApiUrl urlConstructor.clientId = clientId urlConstructor.clientSecret = clientSecret urlConstructor.dataURLString = data return urlConstructor } }
epl-1.0
cf2df6c3bc173665438fc35aefb0d7c8
30.612903
99
0.694898
3.726236
false
false
false
false
3vts/OnTheMap
OnTheMap/AppDelegate.swift
1
1903
// // AppDelegate.swift // OnTheMap // // Created by Alvaro Santiesteban on 6/14/17. // Copyright © 2017 3vts. All rights reserved. // import UIKit import FBSDKCoreKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) if FBSDKAccessToken.current() != nil || checkValidSession() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard.instantiateViewController(withIdentifier: "TabViewController") window?.rootViewController = initialViewController window?.makeKeyAndVisible() } return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { let handled: Bool = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) // Add any custom logic here. return handled } /** Method to check if the session is still valid. It validates the expiration date of the last login session - returns: A boolean indicating if the session is still valid */ func checkValidSession() -> Bool { if let expirationDate = UserDefaults.standard.value(forKey: "SESSION_EXPIRATION_DATE") as? Date { if expirationDate > Date() { return true } } return false } }
mit
07913b088d8df6d53672f5c0bcc82002
34.222222
167
0.664564
5.763636
false
false
false
false
rjstelling/HTTPFormRequest
Development.playground/Contents.swift
1
5837
import UIKit struct JSON: Codable { let foo: String //let moo: Int //let loo: [String] } ///------------------------------------------------------------- struct FormKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K var codingPath: [CodingKey] let encoder: FormEncoder fileprivate init(referencing encoder: FormEncoder, codingPath: [CodingKey]) { self.codingPath = codingPath self.encoder = encoder } mutating func encodeNil(forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: Bool, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: String, forKey key: K) throws { self.encoder.parameters[key.stringValue] = encoder.box( value ) as String } mutating func encode(_ value: Double, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: Float, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: Int, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: Int8, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: Int16, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: Int32, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: Int64, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: UInt, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: UInt8, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: UInt16, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: UInt32, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode(_ value: UInt64, forKey key: K) throws { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func encode<T>(_ value: T, forKey key: K) throws where T : Encodable { throw NSError(domain: "FormEncoder", code: -99, userInfo: nil) } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey { fatalError("NOT IMP") } mutating func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer { fatalError("NOT IMP") } mutating func superEncoder() -> Encoder { fatalError("NOT IMP") } mutating func superEncoder(forKey key: K) -> Encoder { fatalError("NOT IMP") } } class FormEncoder: Encoder { var codingPath: [CodingKey] var userInfo: [CodingUserInfoKey : Any] = [:] fileprivate var parameters: [String:String] = [:] fileprivate init(codingPath: [CodingKey] = []) { self.codingPath = codingPath } func encode<T : Encodable>(_ value: T) throws -> [String:String] { do { try value.encode(to: self) } catch { } return self.parameters } // func box_<T : Encodable>(_ value: T) throws -> NSObject? { // // // // } fileprivate func box(_ value: Bool) -> NSString { return NSString(string: "\(value ? "true" : "false")") } fileprivate func box(_ value: Int) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: Int8) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: Int16) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: Int32) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: Int64) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: UInt) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: UInt8) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: UInt16) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: UInt32) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: UInt64) -> NSString { return NSString(string: "\(value)") } fileprivate func box(_ value: String) -> NSString { return NSString(string: value) } } extension SingleValueEncodingContainer { public func encode(_ value: String) throws { //self.storage.push(container: self.box(value)) } } extension FormEncoder { func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey { let container = FormKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath) return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("NOT IMP") } func singleValueContainer() -> SingleValueEncodingContainer { fatalError("NOT IMP") } }
mit
9cc71b5c15592c61b9e8af2015fd64d5
32.354286
159
0.611102
4.369012
false
false
false
false
practicalswift/swift
test/SILGen/c_function_pointers.swift
6
2752
// RUN: %target-swift-emit-silgen -verify %s | %FileCheck %s func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int { return arg } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers6valuesyS2iXCS2iXCF // CHECK: bb0(%0 : $@convention(c) (Int) -> Int): // CHECK: return %0 : $@convention(c) (Int) -> Int @discardableResult func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int { return arg(x) } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers5callsyS3iXC_SitF // CHECK: bb0(%0 : $@convention(c) @noescape (Int) -> Int, %1 : $Int): // CHECK: [[RESULT:%.*]] = apply %0(%1) // CHECK: return [[RESULT]] @discardableResult func calls_no_args(_ arg: @convention(c) () -> Int) -> Int { return arg() } func global(_ x: Int) -> Int { return x } func no_args() -> Int { return 42 } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers0B19_to_swift_functionsyySiF func pointers_to_swift_functions(_ x: Int) { // CHECK: bb0([[X:%.*]] : $Int): func local(_ y: Int) -> Int { return y } // CHECK: [[GLOBAL_C:%.*]] = function_ref @$s19c_function_pointers6globalyS2iFTo // CHECK: [[CVT:%.*]] = convert_function [[GLOBAL_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls(global, x) // CHECK: [[LOCAL_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiF5localL_yS2iFTo // CHECK: [[CVT:%.*]] = convert_function [[LOCAL_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls(local, x) // CHECK: [[CLOSURE_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiFS2iXEfU_To // CHECK: [[CVT:%.*]] = convert_function [[CLOSURE_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls({ $0 + 1 }, x) calls_no_args(no_args) // CHECK: [[NO_ARGS_C:%.*]] = function_ref @$s19c_function_pointers7no_argsSiyFTo // CHECK: [[CVT:%.*]] = convert_function [[NO_ARGS_C]] // CHECK: apply {{.*}}([[CVT]]) } func unsupported(_ a: Any) -> Int { return 0 } func pointers_to_bad_swift_functions(_ x: Int) { calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}} } // CHECK-LABEL: sil private [ossa] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_ : $@convention(thin) () -> () { // CHECK-LABEL: sil private [thunk] [ossa] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_To : $@convention(c) () -> () { struct StructWithInitializers { let fn1: @convention(c) () -> () = {} init(a: ()) {} init(b: ()) {} } func pointers_to_nested_local_functions_in_generics<T>(x: T) -> Int{ func foo(y: Int) -> Int { return y } return calls(foo, 0) }
apache-2.0
296facedfa196e20d6c48f820495f246
35.693333
155
0.607195
3.020856
false
false
false
false
FTChinese/iPhoneApp
FT Academy/WKWebPageController.swift
1
8995
// // WKWebPageController.swift // FT Academy // // Created by Zhang Oliver on 14/12/25. // Copyright (c) 2014年 Zhang Oliver. All rights reserved. // import Foundation import UIKit import WebKit class WKWebPageController: UIViewController, UIWebViewDelegate, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler, UIScrollViewDelegate{ @IBOutlet weak var containerView: UIWebView! @IBOutlet weak var backBarButton: UIBarButtonItem! @IBOutlet weak var forwardBarButton: UIBarButtonItem! private lazy var webView: WKWebView? = { return nil }() var myContext = 0 let progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.default) deinit { self.webView?.removeObserver(self, forKeyPath: "estimatedProgress") self.webView?.removeObserver(self, forKeyPath: "canGoBack") self.webView?.removeObserver(self, forKeyPath: "canGoForward") // MARK: - Stop loading and remove message handlers to avoid leak self.webView?.stopLoading() self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "callbackHandler") self.webView?.configuration.userContentController.removeAllUserScripts() // MARK: - Remove delegate to deal with crashes on iOS 8 self.webView?.navigationDelegate = nil self.webView?.scrollView.delegate = nil print ("deinit WKWebPageController successfully") } override func loadView() { super.loadView() webPageTitle = webPageTitle0 webPageDescription = webPageDescription0 webPageImage = webPageImage0 webPageImageIcon = webPageImageIcon0 let contentController = WKUserContentController(); //get page information if it follows opengraph let jsCode = "function getContentByMetaTagName(c) {for (var b = document.getElementsByTagName('meta'), a = 0; a < b.length; a++) {if (c == b[a].name || c == b[a].getAttribute('property')) { return b[a].content; }} return '';} var gCoverImage = getContentByMetaTagName('og:image') || '';var gIconImage = getContentByMetaTagName('thumbnail') || '';var gDescription = getContentByMetaTagName('og:description') || getContentByMetaTagName('description') || '';gIconImage=encodeURIComponent(gIconImage);webkit.messageHandlers.callbackHandler.postMessage(gCoverImage + '|' + gIconImage + '|' + gDescription);" let userScript = WKUserScript( source: jsCode, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true ) contentController.addUserScript(userScript) contentController.add( LeakAvoider(delegate:self), name: "callbackHandler" ) let config = WKWebViewConfiguration() config.userContentController = contentController self.webView = WKWebView(frame: self.containerView.frame, configuration: config) self.containerView.addSubview(self.webView!) self.containerView.clipsToBounds = true self.webView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.webView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: &myContext) self.webView?.addObserver(self, forKeyPath: "canGoBack", options: .new, context: &myContext) self.webView?.addObserver(self, forKeyPath: "canGoForward", options: .new, context: &myContext) self.webView?.navigationDelegate = self self.webView?.uiDelegate = self self.webView?.scrollView.delegate = self } // MARK: - There's a bug on iOS 9 so that you can't set decelerationRate directly on webView // MARK: - http://stackoverflow.com/questions/31369538/cannot-change-wkwebviews-scroll-rate-on-ios-9-beta func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { scrollView.decelerationRate = UIScrollViewDecelerationRateNormal } // message sent back to native app func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if(message.name == "callbackHandler") { if let infoForShare = message.body as? String{ print(infoForShare) let toArray = infoForShare.components(separatedBy: "|") webPageDescription = toArray[2] webPageImage = toArray[0] webPageImageIcon = toArray[1] print("get image icon from web page: \(webPageImageIcon)") } } } override func viewDidLoad() { super.viewDidLoad() if let url = URL(string:webPageUrl) { let req = URLRequest(url:url) if let currentWebView = self.webView { currentWebView.load(req) progressView.frame = CGRect(x: 0,y: 0,width: UIScreen.main.bounds.width,height: 10) self.containerView.addSubview(progressView) backBarButton.isEnabled = false forwardBarButton.isEnabled = false } } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context != &myContext { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } if keyPath == "estimatedProgress" { let progress0 = self.webView!.estimatedProgress let progress = Float(progress0) self.progressView.setProgress(progress, animated: true) if progress == 1.0 { self.progressView.isHidden = true } else { self.progressView.isHidden = false } if let _ = self.webView!.url { webPageUrl = self.webView!.url!.absoluteString webPageTitle = self.webView!.title! if webPageTitle == "" { webPageTitle = webPageTitle0 } } return } if keyPath == "canGoBack" { let canGoBack = self.webView!.canGoBack backBarButton.isEnabled = canGoBack return } if keyPath == "canGoForward" { let canGoForward = self.webView!.canGoForward forwardBarButton.isEnabled = canGoForward return } } // this handles target=_blank links by opening them in the same view func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.targetFrame == nil { webView.load(navigationAction.request) } return nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func goBack(_ sender: AnyObject) { self.webView!.goBack() } @IBAction func goForward(_ sender: AnyObject) { self.webView!.goForward() } @IBAction func share(_ sender: AnyObject) { let share = ShareHelper() let ccodeInActionSheet = ccode["actionsheet"] ?? "iosaction" let urlString = self.webView?.url?.absoluteString ?? "http://www.ftchinese.com/" let urlStringClean = urlString.replacingOccurrences(of: "isad=1", with: "") .replacingOccurrences(of: "[&?]+$", with: "", options: .regularExpression) .replacingOccurrences(of: "[?]+[&]+", with: "?", options: .regularExpression) let urlStringWithCcode = "\(urlStringClean)#ccode=\(ccodeInActionSheet)" let url = URL(string: urlStringWithCcode) webPageUrl = urlStringWithCcode share.popupActionSheet(self as UIViewController, url: url) } @IBAction func dismissSegue(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } @IBAction func reload(_ sender: AnyObject) { self.webView!.reload() } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if webPageUrl.range(of: "d=landscape") != nil { return UIInterfaceOrientationMask.landscape } else if webPageUrl.range(of: "d=portrait") != nil { return UIInterfaceOrientationMask.portrait } else if UIDevice.current.userInterfaceIdiom == .pad { if UIScreen.main.bounds.width > UIScreen.main.bounds.height { return UIInterfaceOrientationMask.landscape } else { return UIInterfaceOrientationMask.portrait } } else { return UIInterfaceOrientationMask.all } } override var prefersStatusBarHidden: Bool { return true } }
mit
7f5d2ab714e026a59ccbc393026fa427
40.634259
610
0.636606
5.216357
false
false
false
false
crash-wu/SGRoutePlan
SGRoutePlan/Classes/SGRouteStruct.swift
1
1331
// // SGRouteStruct.swift // Pods // // Created by 吴小星 on 16/8/18. // // import Foundation public struct SGRouteStruct { /*** POI大头针图层 ***/ public static let POI_POPO_LAYER_NAME = "poi_popo_layer_name" /*** POI大头针选择图层 ***/ public static let POI_POPO_SELECT_LAYER_NAME = "poi_popo_select_layer_name" /*** 兴趣点点击弹出Callout名称 ****/ public static let POI_CALLOUT_LAYER_NAME = "poi_callout_layer_name" /*** 驾车路线图层 ****/ public static let CAR_LINE_LAYER_NAME = "car_line_layer_name" /******** 驾车路线起点图层 *********/ public static let CAR_LINE_ORIGIN_LAYER_NAME = "car_Line_origin_layer_name" /******** 驾车路线终点图层 *********/ public static let CAR_LINE_DESTION_LAYER_NAME = "car_line_destion_layer_name" /******** CallOut 类型 *********/ public static let CALLOUT_TYPE = "type" /******** POI 名称 *********/ public static let POI_NAME = "poi_name" /******** POI 地址 *********/ public static let POI_ADDRESS = "poi_address" /******** POI 联系电话 *********/ public static let POI_PHONE = "poi_phone" /******** POI 坐标 *********/ public static let POI_LONLAT = "poi_lonlat" }
mit
4c7a9db90ee0b2e6e5f0e888b794e82e
23.32
81
0.537449
3.155844
false
false
false
false