repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
LiuSky/XBDialog
refs/heads/master
XBDialog/Classes/Menu/MenuPresentationController.swift
mit
1
// // MenuPresentationController.swift // XBDialog // // Created by xiaobin liu on 2018/2/28. // Copyright © 2018年 Sky. All rights reserved. // import UIKit /// MARK - 菜单栏控制器 public class MenuPresentationController: BasePresentationController { public var firstOffset: CGPoint = .zero public var percent: CGFloat = 0.01 fileprivate var pan: UIPanGestureRecognizer? public override func presentationTransitionWillBegin() { super.presentationTransitionWillBegin() pan = UIPanGestureRecognizer.init(target: self, action: #selector(MenuPresentationController.pan(gesture:))) self.presentedView?.addGestureRecognizer(pan!) } public override var frameOfPresentedViewInContainerView: CGRect { get { if let frame = containerView?.frame { let width = frame.width let height = frame.height switch (config as! MenuConfig).menuType { case .bottomHeight(let h): let y = height - h return CGRect(x: 0, y: y, width: width, height: h) case .bottomHeightFromViewRate(let rate): let rateH = height * rate let y = height - rateH return CGRect(x: 0, y: y, width: width, height: rateH) case .leftWidth(let w): return CGRect(x: 0, y: 0, width: w, height: height) case .leftWidthFromViewRate(let rate): let rateW = rate * width return CGRect(x: 0, y: 0, width: rateW, height: height) case .rightWidth(let w): return CGRect(x: width - w, y: 0, width: w, height: height) case .rightWidthFromViewRate(let rate): let rateW = rate * width return CGRect(x: width - rateW , y: 0, width: rateW, height: height) case .leftFullScreen , .rightFullScreen: return CGRect(x: 0, y: 0, width: width, height: height) } } else if let f = self.presentedView?.frame { return f } return CGRect.zero } set {} } @objc func pan(gesture:UIPanGestureRecognizer) { if let c = config as? MenuConfig , c.isDraggable { let view = self.presentedViewController.view switch gesture.state { case .began: c.drivenInteractive = UIPercentDrivenInteractiveTransition() firstOffset = gesture.translation(in: view) self.presentedViewController.dismiss(animated: true, completion: nil) case .changed: let current = gesture.translation(in: view) let percent = self.calculatePercent(offset: current, config: c) self.presentingViewScale(percent: percent, animate: false) c.drivenInteractive?.update(percent) case .ended , .cancelled : let currentPercent = c.drivenInteractive?.percentComplete ?? 0.0 if c.draggableCompletedPrecent < currentPercent { c.drivenInteractive?.finish() } else { self.presentingViewScale(percent: 0.01, animate: true) c.drivenInteractive?.cancel() } c.drivenInteractive = nil default: break } } else { percent = 0.001 if let c = config as? MenuConfig { c.drivenInteractive?.cancel() c.drivenInteractive = nil } } } fileprivate func presentingViewScale(percent:CGFloat , animate:Bool) { self.percent = percent let fix = (CGFloat(1.0) - config.presentingScale) * percent + config.presentingScale if fix >= config.presentingScale { if animate { UIView.animate(withDuration: 0.1, animations: { self.presentingViewController.view.transform = CGAffineTransform(scaleX: fix, y: fix) }) } else { self.presentingViewController.view.transform = CGAffineTransform(scaleX: fix, y: fix) } } } fileprivate func calculatePercent (offset:CGPoint , config:MenuConfig) -> CGFloat { var percent: CGFloat = 0.001 if let view = presentedViewController.view { switch config.menuType { case .bottomHeight(_) , .bottomHeightFromViewRate(_): percent = (offset.y - firstOffset.y) / (view.frame.height + 1) case .rightWidth(_) , .rightWidthFromViewRate(_) , .rightFullScreen: percent = (offset.x - firstOffset.x) / (view.frame.width + 1) case .leftWidth(_) , .leftWidthFromViewRate(_) , .leftFullScreen: percent = (firstOffset.x - offset.x) / (view.frame.width + 1) } } if percent <= 0 { return 0.001 } else if percent >= 1 { return 0.99 } else { return percent } } }
42066c78097e673129b09322b3a44b0e
38.343284
116
0.542299
false
true
false
false
PlutoMa/Swift-LeetCode
refs/heads/master
Code/Problem083.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int) { self.val = val self.next = nil } } class Solution { func deleteDuplicates(_ head: ListNode?) -> ListNode? { guard head != nil else { return nil } var start = head var end = head!.next let result = start while end != nil { if end!.val > start!.val { start!.next = end start = end } end = end!.next } start!.next = end return result } } let head = ListNode(1) head.next = ListNode(1) head.next?.next = ListNode(2) head.next?.next?.next = ListNode(3) head.next?.next?.next?.next = ListNode(3) let result = Solution().deleteDuplicates(head) var output = result while output != nil { print(output!.val) output = output!.next }
78e96a645ae162a28fe2fe08cf02dc69
21
59
0.549495
false
false
false
false
bdougie/ios-exercises
refs/heads/master
SwiftExercises.playground/section-1.swift
mit
2
import UIKit /* Strings */ func favoriteCheeseStringWithCheese(cheese: String) -> String { // WORK HERE return "My favorite cheese is \(cheese)" } let fullSentence = favoriteCheeseStringWithCheese("cheddar") // Make fullSentence say "My favorite cheese is cheddar." /* Arrays & Dictionaries */ let numberArray = [1, 2, 3, 4] // Add 5 to this array // WORK HERE var newArray = numberArray newArray.append(5) let numberDictionary = [1 : "one", 2 : "two", 3 : "three", 4 : "four"] // Add 5 : "five" to this dictionary // WORK HERE var newDictionary = numberDictionary newDictionary[5] = "five" newDictionary /* Loops */ // Use a closed range loop to print 1 - 10, inclusively // WORK HERE for num in 1...10 { println(num) } // Use a half-closed range loop to print 1 - 10, inclusively // WORK HERE for num in 1..<10 { println(num) } let worf = [ "name": "Worf", "rank": "lieutenant", "information": "son of Mogh, slayer of Gowron", "favorite drink": "prune juice", "quote" : "Today is a good day to die."] let picard = [ "name": "Jean-Luc Picard", "rank": "captain", "information": "Captain of the USS Enterprise", "favorite drink": "tea, Earl Grey, hot"] let characters = [worf,picard] func favoriteDrinksArrayForCharacters(characters:Array<Dictionary<String, String>>) -> Array<String> { // return an array of favorite drinks, like ["prune juice", "tea, Earl Grey, hot"] // WORK HERE var characterArray = [String]() for i in 0...1 { characterArray.append(characters[i]["favorite drink"]!) } return characterArray } let favoriteDrinks = favoriteDrinksArrayForCharacters(characters) /* Functions */ // Make a function that inputs an array of strings and outputs the strings separated by a semicolon let strings = ["milk", "eggs", "bread", "challah"] // WORK HERE - make your function and pass `strings` in var foo = "" func concatArray (stringArray:Array<String>) -> String { for streeng in stringArray { foo += streeng + ";" } println(foo) return foo } let expectedOutput = "milk;eggs;bread;challah" /* Closures */ let cerealArray = ["Golden Grahams", "Cheerios", "Trix", "Cap'n Crunch OOPS! All Berries", "Cookie Crisp"] var sortedCereal = cerealArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending } sortedCereal // Use a closure to sort this array alphabetically // WORK HERE
6aa11b1b386bd993e57d6edf40e0bdcb
20.198276
119
0.673038
false
false
false
false
jordanhamill/Stated
refs/heads/master
Sources/Stated/DSL/StateTransitionTriggerDSL.swift
mit
1
extension StateTransitionTrigger { public func performingSideEffect(_ sideEffect: @escaping (StateMachine, StateTo, StateFrom, SentInput<Arguments>) -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> { return StateTransitionTriggerWithSideEffect( inputSlot: self.inputSlot, transition: self.transition, sideEffect: sideEffect ) } public func performingSideEffect(_ sideEffect: @escaping (StateMachine, StateTo, StateFrom) -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> { return self.performingSideEffect { stateMachine, to, from, input in sideEffect(stateMachine, to, from) } } public func performingSideEffect(_ sideEffect: @escaping (StateMachine, StateTo) -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> { return self.performingSideEffect { stateMachine, to, _, _ in sideEffect(stateMachine, to) } } public func performingSideEffect(_ sideEffect: @escaping (StateMachine) -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> { return self.performingSideEffect { stateMachine, _, _, _ in sideEffect(stateMachine) } } public func performingSideEffect(_ sideEffect: @escaping () -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> { return self.performingSideEffect { _, _, _, _ in sideEffect() } } } /// /// Sugar for performing a side effect when a state transition occurs. /// This is an alias for `StateTransitionTrigger.performingSideEffect`. /// ``` /// anInput.given(fromState).transition(to: toState).performingSideEffect { stateMachine, toState, fromState, input in print("Side Effect") } /// ``` /// Using operators you can get a table-like structure for easier reference: /// ``` /// let triggerableStateTransition = anInput | fromState => toState | { stateMachine, toState, fromState, input in print("Side Effect") } /// ``` /// public func |<ArgumentsForToState, StateFrom, StateTo>( stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>, sideEffect: @escaping (StateMachine, StateTo, StateFrom, SentInput<ArgumentsForToState>) -> Void) -> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> { return stateTransitionTrigger.performingSideEffect(sideEffect) } /// /// Sugar for performing a side effect when a state transition occurs. /// This is an alias for `StateTransitionTrigger.performingSideEffect`. /// ``` /// anInput.given(fromState).transition(to: toState).performingSideEffect { stateMachine, toState, fromState in print("Side Effect") } /// ``` /// Using operators you can get a table-like structure for easier reference: /// ``` /// let triggerableStateTransition = anInput | fromState => toState | { stateMachine, toState, fromState in print("Side Effect") } /// ``` /// public func |<ArgumentsForToState, StateFrom, StateTo>( stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>, sideEffect: @escaping (StateMachine, StateTo, StateFrom) -> Void) -> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> { return stateTransitionTrigger.performingSideEffect(sideEffect) } /// /// Sugar for performing a side effect when a state transition occurs. /// This is an alias for `StateTransitionTrigger.performingSideEffect`. /// ``` /// anInput.given(fromState).transition(to: toState).performingSideEffect { stateMachine, toState in print("Side Effect") } /// ``` /// Using operators you can get a table-like structure for easier reference: /// ``` /// let triggerableStateTransition = anInput | fromState => toState | { stateMachine, toState in print("Side Effect") } /// ``` /// public func |<ArgumentsForToState, StateFrom, StateTo>( stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>, sideEffect: @escaping (StateMachine, StateTo) -> Void) -> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> { return stateTransitionTrigger.performingSideEffect(sideEffect) } /// /// Sugar for performing a side effect when a state transition occurs. /// This is an alias for `StateTransitionTrigger.performingSideEffect`. /// ``` /// anInput.given(fromState).transition(to: toState).performingSideEffect { stateMachine in print("Side Effect") } /// ``` /// Using operators you can get a table-like structure for easier reference: /// ``` /// let triggerableStateTransition = anInput | fromState => toState | { stateMachine in print("Side Effect") } /// ``` /// public func |<ArgumentsForToState, StateFrom, StateTo>( stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>, sideEffect: @escaping (StateMachine) -> Void) -> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> { return stateTransitionTrigger.performingSideEffect(sideEffect) } /// /// Sugar for performing a side effect when a state transition occurs. /// This is an alias for `StateTransitionTrigger.performingSideEffect`. /// ``` /// anInput.given(fromState).transition(to: toState).performingSideEffect { print("Side Effect") } /// ``` /// Using operators you can get a table-like structure for easier reference: /// ``` /// let triggerableStateTransition = anInput | fromState => toState | { print("Side Effect") } /// ``` /// public func |<ArgumentsForToState, StateFrom, StateTo>( stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>, sideEffect: @escaping () -> Void) -> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> { return stateTransitionTrigger.performingSideEffect(sideEffect) }
b27f2d2769247a91b042042434108c16
47.430894
199
0.727715
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
refs/heads/master
Example/Pods/ZIPFoundation/Sources/ZIPFoundation/Archive+Reading.swift
bsd-3-clause
1
// // Archive+Reading.swift // ZIPFoundation // // Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation extension Archive { /// Read a ZIP `Entry` from the receiver and write it to `url`. /// /// - Parameters: /// - entry: The ZIP `Entry` to read. /// - url: The destination file URL. /// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed). /// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance. /// - progress: A progress object that can be used to track or cancel the extract operation. /// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`. /// - Throws: An error if the destination file cannot be written or the entry contains malformed content. public func extract(_ entry: Entry, to url: URL, bufferSize: UInt32 = defaultReadChunkSize, skipCRC32: Bool = false, progress: Progress? = nil) throws -> CRC32 { let fileManager = FileManager() var checksum = CRC32(0) switch entry.type { case .file: guard !fileManager.itemExists(at: url) else { throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path]) } try fileManager.createParentDirectoryStructure(for: url) let destinationRepresentation = fileManager.fileSystemRepresentation(withPath: url.path) guard let destinationFile: UnsafeMutablePointer<FILE> = fopen(destinationRepresentation, "wb+") else { throw CocoaError(.fileNoSuchFile) } defer { fclose(destinationFile) } let consumer = { _ = try Data.write(chunk: $0, to: destinationFile) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) case .directory: let consumer = { (_: Data) in try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) case .symlink: guard !fileManager.itemExists(at: url) else { throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path]) } let consumer = { (data: Data) in guard let linkPath = String(data: data, encoding: .utf8) else { throw ArchiveError.invalidEntryPath } try fileManager.createParentDirectoryStructure(for: url) try fileManager.createSymbolicLink(atPath: url.path, withDestinationPath: linkPath) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) } let attributes = FileManager.attributes(from: entry) try fileManager.setAttributes(attributes, ofItemAtPath: url.path) return checksum } /// Read a ZIP `Entry` from the receiver and forward its contents to a `Consumer` closure. /// /// - Parameters: /// - entry: The ZIP `Entry` to read. /// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed). /// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance. /// - progress: A progress object that can be used to track or cancel the extract operation. /// - consumer: A closure that consumes contents of `Entry` as `Data` chunks. /// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`.. /// - Throws: An error if the destination file cannot be written or the entry contains malformed content. public func extract(_ entry: Entry, bufferSize: UInt32 = defaultReadChunkSize, skipCRC32: Bool = false, progress: Progress? = nil, consumer: Consumer) throws -> CRC32 { var checksum = CRC32(0) let localFileHeader = entry.localFileHeader fseek(self.archiveFile, entry.dataOffset, SEEK_SET) progress?.totalUnitCount = self.totalUnitCountForReading(entry) switch entry.type { case .file: guard let compressionMethod = CompressionMethod(rawValue: localFileHeader.compressionMethod) else { throw ArchiveError.invalidCompressionMethod } switch compressionMethod { case .none: checksum = try self.readUncompressed(entry: entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, with: consumer) case .deflate: checksum = try self.readCompressed(entry: entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, with: consumer) } case .directory: try consumer(Data()) progress?.completedUnitCount = self.totalUnitCountForReading(entry) case .symlink: let localFileHeader = entry.localFileHeader let size = Int(localFileHeader.compressedSize) let data = try Data.readChunk(of: size, from: self.archiveFile) checksum = data.crc32(checksum: 0) try consumer(data) progress?.completedUnitCount = self.totalUnitCountForReading(entry) } return checksum } // MARK: - Helpers private func readUncompressed(entry: Entry, bufferSize: UInt32, skipCRC32: Bool, progress: Progress? = nil, with consumer: Consumer) throws -> CRC32 { let size = Int(entry.centralDirectoryStructure.uncompressedSize) return try Data.consumePart(of: size, chunkSize: Int(bufferSize), skipCRC32: skipCRC32, provider: { (_, chunkSize) -> Data in return try Data.readChunk(of: Int(chunkSize), from: self.archiveFile) }, consumer: { (data) in if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } try consumer(data) progress?.completedUnitCount += Int64(data.count) }) } private func readCompressed(entry: Entry, bufferSize: UInt32, skipCRC32: Bool, progress: Progress? = nil, with consumer: Consumer) throws -> CRC32 { let size = Int(entry.centralDirectoryStructure.compressedSize) return try Data.decompress(size: size, bufferSize: Int(bufferSize), skipCRC32: skipCRC32, provider: { (_, chunkSize) -> Data in return try Data.readChunk(of: chunkSize, from: self.archiveFile) }, consumer: { (data) in if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } try consumer(data) progress?.completedUnitCount += Int64(data.count) }) } }
bab8e655d982bab35ab4ba58b5245cd1
54.56391
120
0.624628
false
false
false
false
CocoaHeads-Shanghai/MeetupPresentations
refs/heads/master
2016_03_31 Meeting #15 Begin a New Start/Presentation && Demo/5 Swift Tips in 5 Minutes.playground/Pages/Easier Configuration.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import UIKit import XCPlayground /// - SeeAlso: [Reader Submissions - New Year's 2016](http://nshipster.com/new-years-2016/) @warn_unused_result public func Init<Type>(value : Type, @noescape block: (object: Type) -> Void) -> Type { block(object: value) return value } //: Good let textLabel = Init(UILabel()) { $0.font = UIFont.boldSystemFontOfSize(13.0) $0.text = "Hello, World" $0.textAlignment = .Center } //: Not that good let anotherLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFontOfSize(13.0) label.text = "Hello, World" label.textAlignment = .Center return label }() textLabel anotherLabel //: [Next](@next)
0cdefaf48fcbadd8ab9187da454aaaa1
21.34375
91
0.664336
false
false
false
false
flypaper0/ethereum-wallet
refs/heads/release/1.1
ethereum-wallet/Classes/BusinessLayer/Core/Services/Transaction/TransactionService.swift
gpl-3.0
1
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import Geth class TransactionService: TransactionServiceProtocol { private let context: GethContext private let client: GethEthereumClient private let keystore: KeystoreService private let chain: Chain private let factory: TransactionFactoryProtocol private let transferType: CoinType init(core: Ethereum, keystore: KeystoreService, transferType: CoinType) { self.context = core.context self.client = core.client self.chain = core.chain self.keystore = keystore self.transferType = transferType let factory = TransactionFactory(keystore: keystore, core: core) self.factory = factory } func sendTransaction(with info: TransactionInfo, passphrase: String, queue: DispatchQueue, result: @escaping (Result<GethTransaction>) -> Void) { Ethereum.syncQueue.async { do { let account = try self.keystore.getAccount(at: 0) let transaction = try self.factory.buildTransaction(with: info, type: self.transferType) let signedTransaction = try self.keystore.signTransaction(transaction, account: account, passphrase: passphrase, chainId: self.chain.chainId) try self.sendTransaction(signedTransaction) queue.async { result(.success(signedTransaction)) } } catch { queue.async { result(.failure(error)) } } } } private func sendTransaction(_ signedTransaction: GethTransaction) throws { try client.sendTransaction(context, tx: signedTransaction) } }
0e6c958f9eb62e33c577d744bba83c53
31.693878
149
0.71161
false
false
false
false
tqtifnypmb/huntaway
refs/heads/master
Sources/Huntaway/Request.swift
mit
1
// // Request.swift // Huntaway // // The MIT License (MIT) // // Copyright (c) 2016 tqtifnypmb // // 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 Request { private let url: NSURL private let method: HTTPClient.Method // auth var basic: (String, String)? var digest: (String, String)? var HTTPCookies: [String: String]? = nil var HTTPHeaders: [String: String]? = nil init(url: NSURL, method: HTTPClient.Method) { self.url = url self.method = method } public var allowRedirect: Bool = true public var timeoutInterval: NSTimeInterval = 240.0 public var cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy public var cellularAccess = true public var networkServiceType: NSURLRequestNetworkServiceType = .NetworkServiceTypeDefault public var shouldHandleCookies = true public var rememberRedirectHistory = false public var maxRedirect = Int.max var current_redirect_count = 0 var basicAuthSettings: NSURLCredential? { guard let basicSettings = self.basic else { return nil } let credential = NSURLCredential(user: basicSettings.0, password: basicSettings.1, persistence: .None) return credential } var diegestAuthSettings: NSURLCredential? { guard let digestSettings = self.digest else { return nil } let credential = NSURLCredential(user: digestSettings.0, password: digestSettings.1, persistence: .None) return credential } /// Indicate whether data of this request send in stream mode. /// If you want to send a file that's too big to be read into memory /// you should turn this on. public var stream: Bool = false /// Indicate whether this request should be handled by a session that /// outlast this life. public var outlast: Bool = false /// Data that's going to be sent. public var data: NSData? = nil /// File that's going to be sent public var filePath: NSURL? = nil public var URL: NSURL { return self.url } public var HTTPMethod: HTTPClient.Method { return self.method } public func setCookies(cookies: [String: String]) { self.HTTPCookies = self.HTTPCookies ?? [:] for (key, value) in cookies { self.HTTPCookies![key] = value } } public func setHeaders(headers: [String: String]) { self.HTTPHeaders = self.HTTPHeaders ?? [:] for (key, value) in headers { // Users're not allow to set these headers // see [NSURLSessionConfiguration] switch key.uppercaseString { case "AUTHORIZATION": continue case "CONNECTION": continue case "HOST": continue case "WWW-AUTHENTICATE": continue default: self.HTTPHeaders![key] = value } } } public func basicAuth(user user: String, passwd: String) { self.basic = (user, passwd) } public func digestAuth(user user: String, passwd: String) { self.digest = (user, passwd) } }
dc2d32da353f1e96cb2f88e16400aff1
32.469231
112
0.64353
false
false
false
false
astrokin/EZSwiftExtensions
refs/heads/master
EZSwiftExtensionsTests/UILabelTests.swift
mit
2
// // UILabelTests.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 8/25/16. // Copyright © 2016 Goktug Yilmaz. All rights reserved. // import XCTest @testable import EZSwiftExtensions class UILabelTests: XCTestCase { func testInit() { let label = UILabel(x: 0, y: 0, w: 200, h: 50) let expected = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) let label2 = UILabel(x: 0, y: 0, w: 200, h: 50, fontSize: 20) XCTAssertEqual(label.frame, expected.frame) XCTAssertEqual(label2.font.pointSize, 20) } func testSet() { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) label.set(text: "EZSwiftExtensions✅", duration: 1) XCTAssertEqual(label.text, "EZSwiftExtensions✅") label.text = "" label.set(text: "EZSwiftExtensions🚀", duration: 0) XCTAssertEqual(label.text, "EZSwiftExtensions🚀") label.text = "" label.set(text: "EZSwiftExtensions❤️", duration: 1) XCTAssertEqual(label.text, "EZSwiftExtensions❤️") } var waitExpectation: XCTestExpectation? func wait(duration: TimeInterval) { waitExpectation = expectation(description: "wait") Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(UILabelTests.onTimer), userInfo: nil, repeats: false) waitForExpectations(timeout: duration + 3, handler: nil) } func onTimer() { waitExpectation?.fulfill() } }
1437a2b36400760a27175dc2866d65e0
30.470588
120
0.603115
false
true
false
false
multinerd/Mia
refs/heads/master
Mia/Testing/NotificationAlerts/SANotificationView.swift
mit
1
import Foundation import UIKit open class SANotificationView { class var mainInstance : SANotificationView { struct Static { static let inst : SANotificationView = SANotificationView() } return Static.inst } fileprivate func currentViewController() -> UIViewController? { var presentedWindow = UIApplication.shared.keyWindow?.rootViewController while let pWindow = presentedWindow?.presentedViewController { presentedWindow = pWindow } return presentedWindow } fileprivate func currentWindow() -> UIWindow { let presentedWindow = UIApplication.shared.keyWindow return presentedWindow! } private var statusBarView = UIView() private var statusBarLabel = UILabel() private var isNavbarPresent : Bool = false private var SABarViewTimer : Timer! private var SABarView = UIView() private var SABarBgView = UIView() private var SABarTitleLabel = UILabel() private var SABarLabel = UILabel() private var SABarImageView = UIImageView() private var SABarPullView = UIImageView() // MARK: - showStatusBarBanner open class func showStatusBarBanner(message:String,backgroundColor:UIColor,textColor:UIColor,showTime:Int){ //statusBarView mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) mainInstance.statusBarView.backgroundColor = backgroundColor mainInstance.currentWindow().addSubview(mainInstance.statusBarView) //statusBarLabel mainInstance.statusBarLabel.frame = CGRect(x: 0, y: 0, width: mainInstance.currentWindow().frame.width, height: 0) mainInstance.statusBarLabel.text = message mainInstance.statusBarLabel.textAlignment = .center mainInstance.statusBarLabel.font = UIFont.systemFont(ofSize: 12) mainInstance.statusBarLabel.textColor = textColor mainInstance.statusBarLabel.numberOfLines = 1 mainInstance.statusBarView.addSubview(mainInstance.statusBarLabel) //Animation UIView.animate(withDuration: 0.3) { if UIDevice().userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height == 2436 { //iPhone X print("This view doesn't support iphoneX.Please use showTinyBanner") // mainInstance.statusBarView.frame = CGRect(x: 0, y:UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 20) // mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 20) }else{ mainInstance.statusBarView.window?.windowLevel = UIWindowLevelStatusBar+1 mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height) mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height) } } Timer.scheduledTimer(timeInterval: TimeInterval(showTime), target: self, selector: #selector(removeStatusView), userInfo: nil, repeats: false) } // MARK: - showBanner open class func showBanner(title:String,message:String,textColor:UIColor,image:UIImage,backgroundColor:UIColor,showTime:Int){ //SABarBgView mainInstance.SABarBgView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) mainInstance.SABarBgView.backgroundColor = backgroundColor mainInstance.currentWindow().addSubview(mainInstance.SABarBgView) //SABarView mainInstance.SABarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) mainInstance.SABarView.backgroundColor = backgroundColor mainInstance.SABarView.layer.masksToBounds = true mainInstance.currentWindow().addSubview(mainInstance.SABarView) //SABarTitleLabel mainInstance.SABarTitleLabel.frame = CGRect(x: 80, y: UIApplication.shared.statusBarFrame.height+5, width: mainInstance.currentWindow().frame.width-90, height: 10) mainInstance.SABarTitleLabel.text = title mainInstance.SABarTitleLabel.textAlignment = .left mainInstance.SABarTitleLabel.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 16) mainInstance.SABarTitleLabel.sizeToFit() mainInstance.SABarTitleLabel.textColor = textColor mainInstance.SABarTitleLabel.numberOfLines = 1 mainInstance.SABarView.addSubview(mainInstance.SABarTitleLabel) //SABarLabel mainInstance.SABarLabel.frame = CGRect(x: 80, y: UIApplication.shared.statusBarFrame.height+25, width: mainInstance.currentWindow().frame.width-90, height: 15) mainInstance.SABarLabel.text = message mainInstance.SABarLabel.textAlignment = .left mainInstance.SABarLabel.font = UIFont(name: "AppleSDGothicNeo-Light", size: 12) mainInstance.SABarLabel.lineBreakMode = .byWordWrapping mainInstance.SABarLabel.textColor = .black mainInstance.SABarLabel.numberOfLines = 1 mainInstance.SABarView.addSubview(mainInstance.SABarLabel) //SAImageView mainInstance.SABarImageView.frame = CGRect(x: 20, y: UIApplication.shared.statusBarFrame.height, width: 50, height: 50) mainInstance.SABarView.addSubview(mainInstance.SABarImageView) mainInstance.SABarImageView.image = image mainInstance.SABarImageView.layer.cornerRadius = mainInstance.SABarImageView.frame.height/2 mainInstance.SABarImageView.layer.masksToBounds = true //SAPullImageView mainInstance.SABarPullView.frame = CGRect(x: 0, y: 0, width: 70, height: 5) mainInstance.SABarPullView.center = CGPoint(x: mainInstance.currentWindow().frame.width/2, y: UIApplication.shared.statusBarFrame.height+64-7) mainInstance.SABarPullView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.7) mainInstance.SABarPullView.layer.cornerRadius = mainInstance.SABarPullView.frame.height/2 mainInstance.SABarView.addSubview(mainInstance.SABarPullView) //Gesture let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(removeBarView)) swipeUp.direction = UISwipeGestureRecognizerDirection.up mainInstance.SABarView.addGestureRecognizer(swipeUp) //Animation UIView.animate(withDuration: 0.3, animations: { mainInstance.SABarBgView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height+64) mainInstance.SABarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height+64) }) { (true) in dropShadow(view: mainInstance.SABarBgView, scale: true) } mainInstance.SABarViewTimer = Timer.scheduledTimer(timeInterval: TimeInterval(showTime), target: self, selector: #selector(removeBarView), userInfo: nil, repeats: false) } // MARK: - showBanner without bgcolor and text color open class func showBanner(title:String,message:String,image:UIImage,showTime:Int){ showBanner(title: title, message: message, textColor: .black, image: image, backgroundColor: .white, showTime: showTime) } // MARK: - showTinyBanner open class func showTinyBanner(message:String,backgroundColor:UIColor,textColor:UIColor,showTime:Int){ //statusBarView let nav = UIApplication.shared.keyWindow?.rootViewController if (nav is UINavigationController) { let navc = nav as? UINavigationController if navc?.isNavigationBarHidden ?? false { //no navigation bar mainInstance.isNavbarPresent = false mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) } else { // navigation bar mainInstance.isNavbarPresent = true mainInstance.statusBarView.frame = CGRect(x: 0, y:44+UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 0) } } mainInstance.statusBarView.backgroundColor = backgroundColor mainInstance.currentViewController()?.view.addSubview(mainInstance.statusBarView) //statusBarLabel mainInstance.statusBarLabel.frame = CGRect(x: 0, y: 0, width: mainInstance.currentWindow().frame.width, height: 0) mainInstance.statusBarLabel.text = message mainInstance.statusBarLabel.textAlignment = .center mainInstance.statusBarLabel.font = UIFont.systemFont(ofSize: 12) mainInstance.statusBarLabel.textColor = textColor mainInstance.statusBarLabel.numberOfLines = 1 mainInstance.statusBarView.addSubview(mainInstance.statusBarLabel) //Animation UIView.animate(withDuration: 0.3) { if mainInstance.isNavbarPresent{ mainInstance.statusBarView.frame = CGRect(x: 0, y:44+UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 20) mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 20) }else{ mainInstance.statusBarView.window?.windowLevel = UIWindowLevelStatusBar+1 mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height+20) mainInstance.statusBarLabel.frame = CGRect(x: 0, y:UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 20) } } if showTime == 0 {} else{ Timer.scheduledTimer(timeInterval: TimeInterval(showTime), target: self, selector: #selector(removeTinyBanner), userInfo: nil, repeats: false) } } //MARK: - show permanent tiny banner open class func showTinyBanner(message:String,backgroundColor:UIColor,textColor:UIColor){ showTinyBanner(message: message, backgroundColor: backgroundColor, textColor: textColor, showTime: 0) } //MARK:- Remove views @objc open class func removeStatusView(){ UIView.animate(withDuration: 0.3, animations: { mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) }) { (true) in mainInstance.statusBarView.window?.windowLevel = UIWindowLevelStatusBar-1 } } @objc private class func removeBarView(){ mainInstance.SABarViewTimer.invalidate() UIView.animate(withDuration: 0.3) { mainInstance.SABarBgView.layer.shadowOpacity = 0.0 mainInstance.SABarBgView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) mainInstance.SABarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) } } @objc public class func removeTinyBanner(){ UIView.animate(withDuration: 0.3) { if mainInstance.isNavbarPresent{ mainInstance.statusBarView.frame = CGRect(x: 0, y:44+UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 0) }else{ mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) mainInstance.statusBarView.window?.windowLevel = UIWindowLevelStatusBar-1 } mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0) } } private class func dropShadow(view:UIView,scale:Bool) { view.layer.masksToBounds = false view.layer.shadowColor = UIColor.darkText.cgColor view.layer.shadowOpacity = 0.5 view.layer.shadowOffset = CGSize(width: -1, height: 1) view.layer.shadowRadius = 1 view.layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath view.layer.shouldRasterize = true view.layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } }
a2d9f484fa343a5ad1a0e3005fadc860
42.811075
189
0.657546
false
false
false
false
pawanpoudel/CompositeValidation
refs/heads/master
CompositeValidationTests/Validators/PhoneNumberLengthValidatorSpec.swift
mit
1
import Quick import Nimble class PhoneNumberLengthValidatorSpec: QuickSpec { override func spec() { var validator: PhoneNumberLengthValidator! var phoneNumber: String! var error: NSError? var isPhoneNumberValid: Bool! beforeEach { validator = PhoneNumberLengthValidator() } afterEach { error = nil } context("when phone number is greater than or equal to 10 characters, but less than or equal to 20 characters") { beforeEach { phoneNumber = "1234512345" isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error) } it("it is valid") { expect(isPhoneNumberValid).to(beTrue()) } it("error should be nil") { expect(error).to(beNil()) } } context("when phone number is less than 10 characters") { beforeEach { phoneNumber = "123456789" isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error) } it("it is invalid") { expect(isPhoneNumberValid).to(beFalse()) } it("correct error domain is set") { expect(error?.domain).to(equal(PhoneNumberValidatorErrorDomain)) } it("correct error code is set") { expect(error?.code).to(equal(PhoneNumberValidatorErrorCode.InvalidLength.rawValue)) } } context("when phone number is greater than 20 characters") { beforeEach { phoneNumber = "123451234512345123451" isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error) } it("it is invalid") { expect(isPhoneNumberValid).to(beFalse()) } it("correct error domain is set") { expect(error?.domain).to(equal(PhoneNumberValidatorErrorDomain)) } it("correct error code is set") { expect(error?.code).to(equal(PhoneNumberValidatorErrorCode.InvalidLength.rawValue)) } } } }
fc40472990e74f8c1b42e7926abba263
31.589041
121
0.516604
false
false
false
false
qvacua/vimr
refs/heads/master
Workspace/Sources/Workspace/WorkspaceToolButton.swift
mit
1
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import Commons public final class WorkspaceToolButton: NSView, NSDraggingSource { private static let titlePadding = CGSize(width: 8, height: 2) private static let dummyButton = WorkspaceToolButton(title: "Dummy") private var isHighlighted = false private let title: NSMutableAttributedString private var trackingArea = NSTrackingArea() @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } static let toolUti = "com.qvacua.vimr.tool" static func == (left: WorkspaceToolButton, right: WorkspaceToolButton) -> Bool { guard let leftTool = left.tool, let rightTool = right.tool else { return false } return leftTool == rightTool } var location = WorkspaceBarLocation.top var isSelected: Bool { self.tool?.isSelected ?? false } var theme: Workspace.Theme { self.tool?.theme ?? Workspace.Theme.default } weak var tool: WorkspaceTool? static func dimension() -> CGFloat { self.dummyButton.intrinsicContentSize.height } static func size(forLocation loc: WorkspaceBarLocation) -> CGSize { switch loc { case .top, .bottom: return self.dummyButton.intrinsicContentSize case .right, .left: return CGSize( width: self.dummyButton.intrinsicContentSize.height, height: self.dummyButton.intrinsicContentSize.width ) } } init(title: String) { self.title = NSMutableAttributedString(string: title, attributes: [ NSAttributedString.Key.font: NSFont.systemFont(ofSize: 11), ]) super.init(frame: .zero) self.configureForAutoLayout() self.title.addAttribute( NSAttributedString.Key.foregroundColor, value: self.theme.foreground, range: NSRange(location: 0, length: self.title.length) ) self.wantsLayer = true } func repaint() { if self.isHighlighted { self.highlight() } else { self.dehighlight() } self.title.addAttribute( NSAttributedString.Key.foregroundColor, value: self.theme.foreground, range: NSRange(location: 0, length: self.title.length) ) self.needsDisplay = true } func highlight() { self.isHighlighted = true self.layer?.backgroundColor = self.theme.barButtonHighlight.cgColor } func dehighlight() { self.isHighlighted = false self.layer?.backgroundColor = self.theme.barButtonBackground.cgColor } } // MARK: - NSView public extension WorkspaceToolButton { override var intrinsicContentSize: NSSize { let titleSize = self.title.size() let padding = WorkspaceToolButton.titlePadding switch self.location { case .top, .bottom: return CGSize( width: titleSize.width + 2 * padding.width, height: titleSize.height + 2 * padding.height ) case .right, .left: return CGSize( width: titleSize.height + 2 * padding.height, height: titleSize.width + 2 * padding.width ) } } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) let padding = WorkspaceToolButton.titlePadding switch self.location { case .top, .bottom: self.title.draw(at: CGPoint(x: padding.width, y: padding.height)) case .right: self.title.draw( at: CGPoint(x: padding.height, y: self.bounds.height - padding.width), angle: -(.pi / 2) ) case .left: self.title.draw( at: CGPoint(x: self.bounds.width - padding.height, y: padding.width), angle: .pi / 2 ) } } override func updateTrackingAreas() { self.removeTrackingArea(self.trackingArea) self.trackingArea = NSTrackingArea( rect: self.bounds, options: [.mouseEnteredAndExited, .activeInActiveApp], owner: self, userInfo: nil ) self.addTrackingArea(self.trackingArea) super.updateTrackingAreas() } override func mouseDown(with event: NSEvent) { guard let nextEvent = self.window!.nextEvent(matching: [.leftMouseUp, .leftMouseDragged]) else { return } switch nextEvent.type { case .leftMouseUp: self.tool?.toggle() return case .leftMouseDragged: let pasteboardItem = NSPasteboardItem() pasteboardItem.setString( self.tool!.uuid, forType: NSPasteboard.PasteboardType(WorkspaceToolButton.toolUti) ) let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem) draggingItem.setDraggingFrame(self.bounds, contents: self.snapshot()) self.beginDraggingSession(with: [draggingItem], event: event, source: self) return default: return } } override func mouseEntered(with _: NSEvent) { if self.isSelected { return } self.highlight() } override func mouseExited(with _: NSEvent) { if self.isSelected { return } self.dehighlight() } // Modified version of snapshot() from https://www.raywenderlich.com/136272/drag-and-drop-tutorial-for-macos private func snapshot() -> NSImage { let pdfData = self.dataWithPDF(inside: self.bounds) guard let image = NSImage(data: pdfData) else { return NSImage() } let result = NSImage() let rect = CGRect(origin: .zero, size: image.size) result.size = rect.size result.lockFocus() self.theme.barButtonHighlight.set() rect.fill() image.draw(in: rect) result.unlockFocus() return result } } // MARK: - NSDraggingSource public extension WorkspaceToolButton { @objc(draggingSession: sourceOperationMaskForDraggingContext:) func draggingSession(_: NSDraggingSession, sourceOperationMaskFor _: NSDraggingContext) -> NSDragOperation { .move } @objc(draggingSession: endedAtPoint:operation:) func draggingSession( _: NSDraggingSession, endedAt screenPoint: NSPoint, operation _: NSDragOperation ) { guard let pointInWindow = self.window? .convertFromScreen(CGRect(origin: screenPoint, size: .zero)) else { return } let pointInView = self.convert(pointInWindow, from: nil) // Sometimes if the drag ends, the button does not get dehighlighted. if !self.frame.contains(pointInView), !(self.tool?.isSelected ?? false) { self.dehighlight() } } }
4a4152c09201ca22c546acc742e263e0
24.456
110
0.670333
false
false
false
false
OlenaPianykh/Garage48KAPU
refs/heads/master
KAPU/LoginVC.swift
mit
1
// // ViewController.swift // KAPU // // Created by Vasyl Khmil on 3/4/17. // Copyright © 2017 Vasyl Khmil. All rights reserved. // import UIKit import FirebaseCore import FirebaseAuth import FirebaseDatabase import FirebaseMessaging class LoginVC: UIViewController { var databaseRef: FIRDatabaseReference! @IBOutlet private weak var emailField: UITextField! @IBOutlet private weak var firstNameField: UITextField! @IBOutlet private weak var passwordField: UITextField! var loader: KapuLoader? override func viewDidLoad() { self.databaseRef = FIRDatabase.database().reference() self.loader = KapuLoader() } @IBAction private func signUpPressed() { self.signUp() } private func signUp() { guard let email = self.emailField.text, let password = self.passwordField.text, let firstname = self.firstNameField.text else { return } FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in guard let userId = user?.uid else { print("\(error)") return } if let user = user { let changeRequest = user.profileChangeRequest() changeRequest.displayName = firstname changeRequest.commitChanges { error in if error != nil { print("An error occured.") } else { print("name saved") } } } PushManager.shared.subscribeToAllFeeds() let usersTable = FIRDatabase.database().reference().child("users") usersTable.child(userId).setValue(["email" : email, "first_name" : firstname]) } } @IBAction private func logInPressed() { self.login() } private func login() { if let providerData = FIRAuth.auth()?.currentUser?.providerData { print("user is signed in") } else { FIRAuth.auth()?.createUser(withEmail: "[email protected]", password: "test123") { (user, error) in if error == nil { print("You have successfully logged in") PushManager.shared.subscribeToAllFeeds() FIRMessaging.messaging().subscribe(toTopic: "topics/app") /* let kapu = Kapu(title: "Peace On Earth A Wonderful Wish But No Way?", body: "The following article covers a topic that has recently moved to center stage–at least it seems that way. If you’ve been thinking you need to know more about unconditional love, here’s your", categoryName: "Transportation", creationDate: "05 Jan 2017, 10:30PM", creatorName: "Annie Roger") if let loader = self.loader { loader.addNew(kapu: kapu) }*/ } else { PushManager.shared.subscribeToAllFeeds() let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } } } } }
401a31e97906a6311623b6e6220ec0d1
32.857143
229
0.523734
false
false
false
false
powerytg/Accented
refs/heads/master
Accented/UI/Search/SearchViewController.swift
mit
1
// // SearchViewController.swift // Accented // // Created by Tiangong You on 8/27/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import KMPlaceholderTextView class SearchViewController: UIViewController, Composer, UITextViewDelegate { @IBOutlet weak var composerView: UIView! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var searchButton: UIButton! @IBOutlet weak var textView: KMPlaceholderTextView! @IBOutlet weak var titleView: UIView! @IBOutlet weak var composerHeightConstraint: NSLayoutConstraint! private let cornerRadius : CGFloat = 20 private let statusViewPaddingTop : CGFloat = 20 private let titleBarMaskLayer = CAShapeLayer() private let titleBarRectCorner = UIRectCorner([.topLeft, .topRight]) private let transitionController = ComposerPresentationController() private var currentStatusView : UIView? override var nibName: String? { return "SearchViewController" } init() { super.init(nibName: "SearchViewController", bundle: nil) modalPresentationStyle = .custom transitioningDelegate = transitionController } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() composerView.backgroundColor = ThemeManager.sharedInstance.currentTheme.composerBackground textView.placeholderColor = ThemeManager.sharedInstance.currentTheme.composerPlaceholderTextColor textView.textColor = ThemeManager.sharedInstance.currentTheme.composerTextColor composerView.alpha = 0 composerView.layer.cornerRadius = cornerRadius textView.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) textView.becomeFirstResponder() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updateTitlebarCorners() } private func updateTitlebarCorners() { let path = UIBezierPath(roundedRect: titleView.bounds, byRoundingCorners: titleBarRectCorner, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)) titleBarMaskLayer.path = path.cgPath titleView.layer.mask = titleBarMaskLayer } @IBAction func backButtonDidTap(_ sender: Any) { self.presentingViewController?.dismiss(animated: true, completion: nil) } @IBAction func searchButtonDidTap(_ sender: Any) { dismiss(animated: false) { NavigationService.sharedInstance.navigateToSearchResultPage(keyword: self.textView.text) } } // MARK: - EntranceAnimation func entranceAnimationWillBegin() { composerView.transform = CGAffineTransform(translationX: 0, y: -composerHeightConstraint.constant) } func performEntranceAnimation() { composerView.transform = CGAffineTransform.identity composerView.alpha = 1 } func entranceAnimationDidFinish() { // Ignore } // MARK: - ExitAnimation func exitAnimationWillBegin() { composerView.resignFirstResponder() } func performExitAnimation() { self.view.transform = CGAffineTransform(translationX: 0, y: -composerHeightConstraint.constant) self.view.alpha = 0 } func exitAnimationDidFinish() { // Ignore } // MARK: - UITextViewDelegate func textViewDidChange(_ textView: UITextView) { searchButton.isEnabled = (textView.text.lengthOfBytes(using: String.Encoding.utf8) != 0) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { if textView.text.lengthOfBytes(using: String.Encoding.utf8) != 0 { textView.resignFirstResponder() dismiss(animated: false) { NavigationService.sharedInstance.navigateToSearchResultPage(keyword: self.textView.text) } } return false } return true } }
6022cb042dcfbff3c382524c0b62b91e
32.192308
116
0.661414
false
false
false
false
Zeitblick/Zeitblick-iOS
refs/heads/master
Zeitblick/StartViewController.swift
gpl-3.0
1
// // StartViewController.swift // Zeitblick // // Created by Bastian Clausdorff on 29.10.16. // Copyright © 2016 Epic Selfie. All rights reserved. // import UIKit import Async import Alamofire import PromiseKit import SwiftyJSON enum StartError: Error { case invalidData } class StartViewController: UIViewController { typealias Me = StartViewController private static let hasSelfieTopConstant: CGFloat = 42 @IBOutlet weak var photoButton: DesignableButton! @IBOutlet weak var selfieImageView: DesignableImageView! var logoHasSelfieConstraint: NSLayoutConstraint! @IBOutlet var logoNoSelfieConstraint: NSLayoutConstraint! @IBOutlet weak var logo: UIImageView! @IBOutlet weak var logoSubtitle: UILabel! var resultImage: UIImage? var metadata: ImageMetadata? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. logoHasSelfieConstraint = logo.topAnchor.constraint(equalTo: view.topAnchor) logoHasSelfieConstraint.constant = Me.hasSelfieTopConstant resetController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func pickPhoto(_ sender: AnyObject) { let imagePicker = UIImagePickerController() imagePicker.delegate = self Alerts.photo(viewController: self, takePhotoAction: { [weak self] in guard let strongSelf = self else { return } imagePicker.sourceType = .camera imagePicker.cameraDevice = .front strongSelf.present(imagePicker, animated: true) { UIApplication.shared.setStatusBarHidden(true, with: .fade) } }, choosePhotoAction: { [weak self] in guard let strongSelf = self else { return } imagePicker.sourceType = .photoLibrary strongSelf.present(imagePicker, animated: true, completion: nil) }) } func resetController() { selfieImageView.image = nil selfieImageView.isHidden = true photoButton.isHidden = false logoHasSelfieConstraint.isActive = false logoNoSelfieConstraint.isActive = true logoSubtitle.isHidden = false } } extension StartViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { print("selected photo") dismiss(animated: true) { [weak self] in UIApplication.shared.setStatusBarHidden(false, with: .fade) self?.view.showLoading() } guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return } // Change UI selfieImageView.image = image selfieImageView.isHidden = false photoButton.isHidden = true logoNoSelfieConstraint.isActive = false logoHasSelfieConstraint.isActive = true logoSubtitle.isHidden = true let q = DispatchQueue.global() // Find match firstly { return try GoogleVision().analyse(image: image) }.then { visionResponseJson -> Promise<ImageMetadata> in dump(visionResponseJson) return try ZeitblickBackend().findSimilarEmotion(json: visionResponseJson) }.then { [weak self] metadata -> Promise<UIImage> in self?.metadata = metadata return try GoogleDatastore().getImage(inventoryNumber: metadata.inventoryNumber) }.then { [weak self] image -> Void in print("got image") self?.resultImage = image guard let result = self?.resultImage, let metadata = self?.metadata, let selfie = self?.selfieImageView.image else { throw StartError.invalidData } let controller = ResultController(resultImage: result , metadata: metadata, selfieImage: selfie, errorHappened: false) self?.present(controller, animated: false) { self?.resetController() } }.always(on: q) { [weak self] in self?.view.hideLoading() }.catch { [weak self] error in print(error) let errorImage = R.image.errorJpg() let controller = ResultController(resultImage: errorImage!, errorHappened: true) self?.present(controller, animated: false) { self?.resetController() } } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true) { UIApplication.shared.setStatusBarHidden(false, with: .fade) } } }
aedba5599a5a10a4323c5124a183a98c
32.472973
130
0.635042
false
false
false
false
brightec/CustomCollectionViewLayout
refs/heads/master
CustomCollectionLayout/CollectionViewController.swift
mit
1
// Copyright 2017 Brightec // // 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 UIKit class CollectionViewController: UIViewController { let contentCellIdentifier = "ContentCellIdentifier" @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collectionView.register(UINib(nibName: "ContentCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: contentCellIdentifier) } } // MARK: - UICollectionViewDataSource extension CollectionViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 50 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 8 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // swiftlint:disable force_cast let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCollectionViewCell if indexPath.section % 2 != 0 { cell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0) } else { cell.backgroundColor = UIColor.white } if indexPath.section == 0 { if indexPath.row == 0 { cell.contentLabel.text = "Date" } else { cell.contentLabel.text = "Section" } } else { if indexPath.row == 0 { cell.contentLabel.text = String(indexPath.section) } else { cell.contentLabel.text = "Content" } } return cell } } // MARK: - UICollectionViewDelegate extension CollectionViewController: UICollectionViewDelegate { }
9e6a8a88c22630878c2f649a3526c394
31.184211
121
0.653312
false
false
false
false
wenluma/swift
refs/heads/master
test/IRGen/generic_vtable.swift
mit
1
// RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK // REQUIRES: CPU=x86_64 public class Base { public func m1() {} public func m2() {} } public class Derived<T> : Base { public override func m2() {} public func m3() {} } // CHECK-LABEL: @_T014generic_vtable4BaseCMn = {{(protected )?}}constant // -- flags: has vtable // CHECK-SAME: i32 4, // -- vtable offset // CHECK-SAME: i32 10, // -- vtable size // CHECK-SAME: i32 3 // -- // CHECK-SAME: section "{{.*}}", align 8 // CHECK-LABEL: @_T014generic_vtable7DerivedCMn = {{(protected )?}}constant // -- flags: has vtable // CHECK-SAME: i32 4, // -- vtable offset // CHECK-SAME: i32 14, // -- vtable size // CHECK-SAME: i32 1 // -- // CHECK-SAME: section "{{.*}}", align 8 // CHECK-LABEL: define private %swift.type* @create_generic_metadata_Derived(%swift.type_pattern*, i8**) // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata({{.*}}) // CHECK: [[METADATA2:%.*]] = call %swift.type* @swift_initClassMetadata_UniversalStrategy({{.*}}) // CHECK: [[WORDS:%.*]] = bitcast %swift.type* [[METADATA2]] to i8** // CHECK: [[VTABLE0:%.*]] = getelementptr inbounds i8*, i8** [[WORDS]], i32 11 // CHECK: store i8* bitcast (void (%T14generic_vtable7DerivedC*)* @_T014generic_vtable7DerivedC2m2yyF to i8*), i8** [[VTABLE0]], align 8 // CHECK: [[VTABLE1:%.*]] = getelementptr inbounds i8*, i8** [[WORDS]], i32 12 // CHECK: store i8* bitcast (%T14generic_vtable7DerivedC* (%T14generic_vtable7DerivedC*)* @_T014generic_vtable7DerivedCACyxGycfc to i8*), i8** [[VTABLE1]], align 8 // CHECK: ret %swift.type* [[METADATA]]
19c6ff4ba84c546e811493d4d8fb1b5d
36.813953
163
0.646371
false
false
false
false
zxwWei/SWiftWeiBlog
refs/heads/master
XWWeibo/XWWeibo/Classes/Model(模型)/Profile(我)/Controller/XWProfileTableVC.swift
apache-2.0
2
// // XWProfileTableVC.swift // XWWeibo // // Created by apple on 15/10/26. // Copyright © 2015年 ZXW. All rights reserved. // import UIKit class XWProfileTableVC: XWcompassVc { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
7171d55104e7a3f6b7916400c6c3fa48
30.67033
157
0.676266
false
false
false
false
JQJoe/RxDemo
refs/heads/develop
Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Observable+BindingTest.swift
apache-2.0
7
// // Observable+BindingTest.swift // Tests // // Created by Krunoslav Zaher on 4/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import XCTest import RxSwift import RxTest class ObservableBindingTest : RxTest { } // multicast extension ObservableBindingTest { func testMulticast_Cold_Completed() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(40, 0), next(90, 1), next(150, 2), next(210, 3), next(240, 4), next(270, 5), next(330, 6), next(340, 7), completed(390) ]) let res = scheduler.start { xs.multicast({ PublishSubject<Int>() }) { $0 } } XCTAssertEqual(res.events, [ next(210, 3), next(240, 4), next(270, 5), next(330, 6), next(340, 7), completed(390) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) } func testMulticast_Cold_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(40, 0), next(90, 1), next(150, 2), next(210, 3), next(240, 4), next(270, 5), next(330, 6), next(340, 7), error(390, testError) ]) let res = scheduler.start { xs.multicast({ PublishSubject<Int>() }) { $0 } } XCTAssertEqual(res.events, [ next(210, 3), next(240, 4), next(270, 5), next(330, 6), next(340, 7), error(390, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) } func testMulticast_Cold_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(40, 0), next(90, 1), next(150, 2), next(210, 3), next(240, 4), next(270, 5), next(330, 6), next(340, 7), ]) let res = scheduler.start { xs.multicast({ PublishSubject<Int>() }) { $0 } } XCTAssertEqual(res.events, [ next(210, 3), next(240, 4), next(270, 5), next(330, 6), next(340, 7), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) } func testMulticast_Cold_Zip() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(40, 0), next(90, 1), next(150, 2), next(210, 3), next(240, 4), next(270, 5), next(330, 6), next(340, 7), completed(390) ]) let res = scheduler.start { xs.multicast({ PublishSubject<Int>() }) { Observable.zip($0, $0) { a, b in a + b } } } XCTAssertEqual(res.events, [ next(210, 6), next(240, 8), next(270, 10), next(330, 12), next(340, 14), completed(390) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) } func testMulticast_SubjectSelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 1), next(240, 2), completed(300) ]) let res = scheduler.start { xs.multicast({ () throws -> PublishSubject<Int> in throw testError }) { $0 } } XCTAssertEqual(res.events, [ error(200, testError) ]) XCTAssertEqual(xs.subscriptions, [ ]) } func testMulticast_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 1), next(240, 2), completed(300) ]) let res = scheduler.start { xs.multicast({ PublishSubject<Int>() }) { _ -> Observable<Int> in throw testError } } XCTAssertEqual(res.events, [ error(200, testError) ]) XCTAssertEqual(xs.subscriptions, [ ]) } } // refCount extension ObservableBindingTest { func testRefCount_DeadlockSimple() { let subject = MySubject<Int>() var nEvents = 0 let observable = TestConnectableObservable(o: Observable.of(0, 1, 2), s: subject) let d = observable.subscribe(onNext: { n in nEvents += 1 }) defer { d.dispose() } observable.connect().dispose() XCTAssertEqual(nEvents, 3) } func testRefCount_DeadlockErrorAfterN() { let subject = MySubject<Int>() var nEvents = 0 let observable = TestConnectableObservable(o: Observable.concat([Observable.of(0, 1, 2), Observable.error(testError)]), s: subject) let d = observable.subscribe(onError: { n in nEvents += 1 }) defer { d.dispose() } observable.connect().dispose() XCTAssertEqual(nEvents, 1) } func testRefCount_DeadlockErrorImmediatelly() { let subject = MySubject<Int>() var nEvents = 0 let observable = TestConnectableObservable(o: Observable.error(testError), s: subject) let d = observable.subscribe(onError: { n in nEvents += 1 }) defer { d.dispose() } observable.connect().dispose() XCTAssertEqual(nEvents, 1) } func testRefCount_DeadlockEmpty() { let subject = MySubject<Int>() var nEvents = 0 let observable = TestConnectableObservable(o: Observable.empty(), s: subject) let d = observable.subscribe(onCompleted: { nEvents += 1 }) defer { d.dispose() } observable.connect().dispose() XCTAssertEqual(nEvents, 1) } func testRefCount_ConnectsOnFirst() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 1), next(220, 2), next(230, 3), next(240, 4), completed(250) ]) let subject = MySubject<Int>() let conn = TestConnectableObservable(o: xs.asObservable(), s: subject) let res = scheduler.start { conn.refCount() } XCTAssertEqual(res.events, [ next(210, 1), next(220, 2), next(230, 3), next(240, 4), completed(250) ]) XCTAssertTrue(subject.isDisposed) } func testRefCount_NotConnected() { _ = TestScheduler(initialClock: 0) var disconnected = false var count = 0 let xs: Observable<Int> = Observable.deferred { count += 1 return Observable.create { obs in return Disposables.create { disconnected = true } } } let subject = MySubject<Int>() let conn = TestConnectableObservable(o: xs, s: subject) let refd = conn.refCount() let dis1 = refd.subscribe { _ -> Void in () } XCTAssertEqual(1, count) XCTAssertEqual(1, subject.subscribeCount) XCTAssertFalse(disconnected) let dis2 = refd.subscribe { _ -> Void in () } XCTAssertEqual(1, count) XCTAssertEqual(2, subject.subscribeCount) XCTAssertFalse(disconnected) dis1.dispose() XCTAssertFalse(disconnected) dis2.dispose() XCTAssertTrue(disconnected) disconnected = false let dis3 = refd.subscribe { _ -> Void in () } XCTAssertEqual(2, count) XCTAssertEqual(3, subject.subscribeCount) XCTAssertFalse(disconnected) dis3.dispose() XCTAssertTrue(disconnected) } func testRefCount_Error() { let xs: Observable<Int> = Observable.error(testError) let res = xs.publish().refCount() _ = res.subscribe { event in switch event { case .next: XCTAssertTrue(false) case .error(let error): XCTAssertErrorEqual(error, testError) case .completed: XCTAssertTrue(false) } } _ = res.subscribe { event in switch event { case .next: XCTAssertTrue(false) case .error(let error): XCTAssertErrorEqual(error, testError) case .completed: XCTAssertTrue(false) } } } func testRefCount_Publish() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 1), next(220, 2), next(230, 3), next(240, 4), next(250, 5), next(260, 6), next(270, 7), next(280, 8), next(290, 9), completed(300) ]) let res = xs.publish().refCount() var d1: Disposable! let o1 = scheduler.createObserver(Int.self) scheduler.scheduleAt(215) { d1 = res.subscribe(o1) } scheduler.scheduleAt(235) { d1.dispose() } var d2: Disposable! let o2 = scheduler.createObserver(Int.self) scheduler.scheduleAt(225) { d2 = res.subscribe(o2) } scheduler.scheduleAt(275) { d2.dispose() } var d3: Disposable! let o3 = scheduler.createObserver(Int.self) scheduler.scheduleAt(255) { d3 = res.subscribe(o3) } scheduler.scheduleAt(265) { d3.dispose() } var d4: Disposable! let o4 = scheduler.createObserver(Int.self) scheduler.scheduleAt(285) { d4 = res.subscribe(o4) } scheduler.scheduleAt(320) { d4.dispose() } scheduler.start() XCTAssertEqual(o1.events, [ next(220, 2), next(230, 3) ]) XCTAssertEqual(o2.events, [ next(230, 3), next(240, 4), next(250, 5), next(260, 6), next(270, 7) ]) XCTAssertEqual(o3.events, [ next(260, 6) ]) XCTAssertEqual(o4.events, [ next(290, 9), completed(300) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(215, 275), Subscription(285, 300) ]) } } // replay extension ObservableBindingTest { func testReplayCount_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 5), next(450, 6), next(450, 7), next(520, 11), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 550), Subscription(650, 800) ]) } func testReplayCount_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 5), next(450, 6), next(450, 7), next(520, 11), next(560, 20), error(600, testError), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayCount_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 5), next(450, 6), next(450, 7), next(520, 11), next(560, 20), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayCount_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(475) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 5), next(450, 6), next(450, 7), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 550), Subscription(650, 800), ]) } func testReplayOneCount_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 7), next(520, 11), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 550), Subscription(650, 800) ]) } func testReplayOneCount_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 7), next(520, 11), next(560, 20), error(600, testError), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayOneCount_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 7), next(520, 11), next(560, 20), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayOneCount_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(475) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 7), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 550), Subscription(650, 800), ]) } func testReplayAll_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replayAll() } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(200) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 3), next(450, 4), next(450, 1), next(450, 8), next(450, 5), next(450, 6), next(450, 7), next(520, 11), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400), Subscription(500, 550), Subscription(650, 800) ]) } func testReplayAll_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replayAll() } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 8), next(450, 5), next(450, 6), next(450, 7), next(520, 11), next(560, 20), error(600, testError), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayAll_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replayAll() } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() } scheduler.scheduleAt(300) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 8), next(450, 5), next(450, 6), next(450, 7), next(520, 11), next(560, 20), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(300, 400), Subscription(500, 600), ]) } func testReplayAll_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), completed(600) ]) var ys: ConnectableObservable<Int>! = nil var subscription: Disposable! = nil var connection: Disposable! = nil let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.replayAll() } scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) }) scheduler.scheduleAt(475) { subscription.dispose() } scheduler.scheduleAt(250) { connection = ys.connect() } scheduler.scheduleAt(400) { connection.dispose() } scheduler.scheduleAt(500) { connection = ys.connect() } scheduler.scheduleAt(550) { connection.dispose() } scheduler.scheduleAt(650) { connection = ys.connect() } scheduler.scheduleAt(800) { connection.dispose() } scheduler.start() XCTAssertEqual(res.events, [ next(450, 4), next(450, 1), next(450, 8), next(450, 5), next(450, 6), next(450, 7), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(250, 400), Subscription(500, 550), Subscription(650, 800), ]) } } // shareReplay(1) extension ObservableBindingTest { func _testIdenticalBehaviorOfShareReplayOptimizedAndComposed(_ action: @escaping (_ transform: @escaping ((Observable<Int>) -> Observable<Int>)) -> Void) { action { $0.shareReplay(1) } action { $0.replay(1).refCount() } } func testShareReplay_DeadlockImmediatelly() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in var nEvents = 0 let observable = transform(Observable.of(0, 1, 2)) _ = observable.subscribe(onNext: { n in nEvents += 1 }) XCTAssertEqual(nEvents, 3) } } func testShareReplay_DeadlockEmpty() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in var nEvents = 0 let observable = transform(Observable.empty()) _ = observable.subscribe(onCompleted: { n in nEvents += 1 }) XCTAssertEqual(nEvents, 1) } } func testShareReplay_DeadlockError() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in var nEvents = 0 let observable = transform(Observable.error(testError)) _ = observable.subscribe(onError: { _ in nEvents += 1 }) XCTAssertEqual(nEvents, 1) } } func testShareReplay1_DeadlockErrorAfterN() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in var nEvents = 0 let observable = transform(Observable.concat([Observable.of(0, 1, 2), Observable.error(testError)])) _ = observable.subscribe(onError: { n in nEvents += 1 }) XCTAssertEqual(nEvents, 1) } } func testShareReplay1_Basic() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: Observable<Int>! = nil var subscription1: Disposable! = nil var subscription2: Disposable! = nil let res1 = scheduler.createObserver(Int.self) let res2 = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = transform(xs.asObservable()) } scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(400) { subscription1.dispose() } scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) } scheduler.scheduleAt(415) { subscription2.dispose() } scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(455) { subscription1.dispose() } scheduler.start() XCTAssertEqual(res1.events, [ // 1rt batch next(340, 8), next(360, 5), next(370, 6), next(390, 7), // 2nd batch next(440, 13), next(450, 9) ]) XCTAssertEqual(res2.events, [ next(355, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(335, 415), Subscription(440, 455) ]) } } func testShareReplay1_Error() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), error(365, testError), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), ]) var ys: Observable<Int>! = nil var subscription1: Disposable! = nil var subscription2: Disposable! = nil let res1 = scheduler.createObserver(Int.self) let res2 = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = transform(xs.asObservable()) } scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(400) { subscription1.dispose() } scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) } scheduler.scheduleAt(415) { subscription2.dispose() } scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(455) { subscription1.dispose() } scheduler.start() XCTAssertEqual(res1.events, [ // 1rt batch next(340, 8), next(360, 5), error(365, testError), // 2nd batch next(440, 5), error(440, testError), ]) XCTAssertEqual(res2.events, [ next(355, 8), next(360, 5), error(365, testError), ]) // unoptimized version of replay subject will make a subscription and kill it immediatelly XCTAssertEqual(xs.subscriptions[0], Subscription(335, 365)) XCTAssertTrue(xs.subscriptions.count <= 2) XCTAssertTrue(xs.subscriptions.count == 1 || xs.subscriptions[1] == Subscription(440, 440)) } } func testShareReplay1_Completed() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), completed(365), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), ]) var ys: Observable<Int>! = nil var subscription1: Disposable! = nil var subscription2: Disposable! = nil let res1 = scheduler.createObserver(Int.self) let res2 = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = transform(xs.asObservable()) } scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(400) { subscription1.dispose() } scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) } scheduler.scheduleAt(415) { subscription2.dispose() } scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(455) { subscription1.dispose() } scheduler.start() XCTAssertEqual(res1.events, [ // 1rt batch next(340, 8), next(360, 5), completed(365), // 2nd batch next(440, 5), completed(440) ]) XCTAssertEqual(res2.events, [ next(355, 8), next(360, 5), completed(365) ]) // unoptimized version of replay subject will make a subscription and kill it immediatelly XCTAssertEqual(xs.subscriptions[0], Subscription(335, 365)) XCTAssertTrue(xs.subscriptions.count <= 2) XCTAssertTrue(xs.subscriptions.count == 1 || xs.subscriptions[1] == Subscription(440, 440)) } } func testShareReplay1_Canceled() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ completed(365), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), ]) var ys: Observable<Int>! = nil var subscription1: Disposable! = nil var subscription2: Disposable! = nil let res1 = scheduler.createObserver(Int.self) let res2 = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = transform(xs.asObservable()) } scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(400) { subscription1.dispose() } scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) } scheduler.scheduleAt(415) { subscription2.dispose() } scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(455) { subscription1.dispose() } scheduler.start() XCTAssertEqual(res1.events, [ // 1rt batch completed(365), // 2nd batch completed(440) ]) XCTAssertEqual(res2.events, [ completed(365) ]) // unoptimized version of replay subject will make a subscription and kill it immediatelly XCTAssertEqual(xs.subscriptions[0], Subscription(335, 365)) XCTAssertTrue(xs.subscriptions.count <= 2) XCTAssertTrue(xs.subscriptions.count == 1 || xs.subscriptions[1] == Subscription(440, 440)) } } } // shareReplay(1) extension ObservableBindingTest { func testShareReplayLatestWhileConnected_DeadlockImmediatelly() { var nEvents = 0 let observable = Observable.of(0, 1, 2).shareReplayLatestWhileConnected() _ = observable.subscribe(onNext: { n in nEvents += 1 }) XCTAssertEqual(nEvents, 3) } func testShareReplayLatestWhileConnected_DeadlockEmpty() { var nEvents = 0 let observable = Observable<Int>.empty().shareReplayLatestWhileConnected() _ = observable.subscribe(onCompleted: { n in nEvents += 1 }) XCTAssertEqual(nEvents, 1) } func testShareReplayLatestWhileConnected_DeadlockError() { var nEvents = 0 let observable = Observable<Int>.error(testError).shareReplayLatestWhileConnected() _ = observable.subscribe(onError: { _ in nEvents += 1 }) XCTAssertEqual(nEvents, 1) } func testShareReplayLatestWhileConnected_DeadlockErrorAfterN() { var nEvents = 0 let observable = Observable.concat([Observable.of(0, 1, 2), Observable.error(testError)]).shareReplayLatestWhileConnected() _ = observable.subscribe(onError: { n in nEvents += 1 }) XCTAssertEqual(nEvents, 1) } func testShareReplayLatestWhileConnected_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), error(600, testError) ]) var ys: Observable<Int>! = nil var subscription1: Disposable! = nil var subscription2: Disposable! = nil let res1 = scheduler.createObserver(Int.self) let res2 = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.shareReplayLatestWhileConnected() } scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(400) { subscription1.dispose() } scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) } scheduler.scheduleAt(415) { subscription2.dispose() } scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(455) { subscription1.dispose() } scheduler.start() XCTAssertEqual(res1.events, [ // 1rt batch next(340, 8), next(360, 5), next(370, 6), next(390, 7), // 2nd batch next(450, 9) ]) XCTAssertEqual(res2.events, [ next(355, 8), next(360, 5), next(370, 6), next(390, 7), next(410, 13) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(335, 415), Subscription(440, 455) ]) } func testShareReplayLatestWhileConnected_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), error(365, testError), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), ]) var ys: Observable<Int>! = nil var subscription1: Disposable! = nil var subscription2: Disposable! = nil let res1 = scheduler.createObserver(Int.self) let res2 = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.shareReplayLatestWhileConnected() } scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(400) { subscription1.dispose() } scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) } scheduler.scheduleAt(415) { subscription2.dispose() } scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(455) { subscription1.dispose() } scheduler.start() XCTAssertEqual(res1.events, [ // 1rt batch next(340, 8), next(360, 5), error(365, testError), // 2nd batch next(450, 9), ]) XCTAssertEqual(res2.events, [ next(355, 8), next(360, 5), error(365, testError), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(335, 365), Subscription(440, 455) ]) } func testShareReplayLatestWhileConnected_Completed() { _testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(110, 7), next(220, 3), next(280, 4), next(290, 1), next(340, 8), next(360, 5), completed(365), next(370, 6), next(390, 7), next(410, 13), next(430, 2), next(450, 9), next(520, 11), next(560, 20), ]) var ys: Observable<Int>! = nil var subscription1: Disposable! = nil var subscription2: Disposable! = nil let res1 = scheduler.createObserver(Int.self) let res2 = scheduler.createObserver(Int.self) scheduler.scheduleAt(Defaults.created) { ys = xs.shareReplayLatestWhileConnected() } scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(400) { subscription1.dispose() } scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) } scheduler.scheduleAt(415) { subscription2.dispose() } scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) } scheduler.scheduleAt(455) { subscription1.dispose() } scheduler.start() XCTAssertEqual(res1.events, [ // 1rt batch next(340, 8), next(360, 5), completed(365), // 2nd batch next(450, 9), ]) XCTAssertEqual(res2.events, [ next(355, 8), next(360, 5), completed(365) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(335, 365), Subscription(440, 455) ]) } } }
ef0f8cdfadf06d8e4dc8cadcbaeb04e1
28.914881
159
0.510348
false
true
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/DiscoveryV2/Models/QueryResultPassage.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2019, 2021. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** A passage query result. */ public struct QueryResultPassage: Codable, Equatable { /** The content of the extracted passage. */ public var passageText: String? /** The position of the first character of the extracted passage in the originating field. */ public var startOffset: Int? /** The position after the last character of the extracted passage in the originating field. */ public var endOffset: Int? /** The label of the field from which the passage has been extracted. */ public var field: String? /** Estimate of the probability that the passage is relevant. */ public var confidence: Double? /** An arry of extracted answers to the specified query. */ public var answers: [ResultPassageAnswer]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case passageText = "passage_text" case startOffset = "start_offset" case endOffset = "end_offset" case field = "field" case confidence = "confidence" case answers = "answers" } }
1f3dcc30f6b11ac84234590bf77ceeba
27.28125
93
0.674033
false
false
false
false
jaouahbi/OMCircularProgress
refs/heads/master
OMCircularProgress/Classes/Extensions/CGRect+Extensions.swift
apache-2.0
2
// // Copyright 2015 - Jorge Ouahbi // // 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. // // // CGRect+Extension.swift // // Created by Jorge Ouahbi on 25/11/15. // Copyright © 2015 Jorge Ouahbi. All rights reserved. // import UIKit /// CGRect Extension extension CGRect{ /// Apply affine transform /// /// - parameter t: affine transform mutating func apply(_ t:CGAffineTransform) { self = self.applying(t) } /// Center in rect /// /// - parameter mainRect: main rect /// /// - returns: center CGRect in main rect func center(_ mainRect:CGRect) -> CGRect{ let dx = mainRect.midX - self.midX let dy = mainRect.midY - self.midY return self.offsetBy(dx: dx, dy: dy); } /// Construct with size /// /// - parameter size: CGRect size /// /// - returns: CGRect public init(_ size:CGSize) { self.init(origin: CGPoint.zero,size: size) } /// Construct with origin /// /// - parameter origin: CGRect origin /// /// - returns: CGRect public init(_ origin:CGPoint) { self.init(origin: origin,size: CGSize.zero) } /// Min radius from rectangle public var minRadius:CGFloat { return size.min() * 0.5; } /// Max radius from a rectangle (pythagoras) public var maxRadius:CGFloat { return 0.5 * sqrt(size.width * size.width + size.height * size.height) } /// Construct with points /// /// - parameter point1: CGPoint /// - parameter point2: CGPoint /// /// - returns: CGRect public init(_ point1:CGPoint,point2:CGPoint) { self.init(point1) size.width = abs(point2.x-self.origin.x) size.height = abs(point2.y-self.origin.y) } }
4e518c19522bab7f68a2482257f7bd62
26.282353
78
0.61147
false
false
false
false
kyleduo/TinyPNG4Mac
refs/heads/master
source/tinypng4mac/views/SpinnerProgressIndicator.swift
mit
1
// // SpinnerProgressIndicator.swift // tinypng4mac // // Created by kyle on 16/7/6. // Copyright © 2016年 kyleduo. All rights reserved. // import Cocoa class SpinnerProgressIndicator: NSView { var progress: Double = 0 { didSet { self.needsDisplay = true } } var max: Double = 6 var min: Double = 0 var tintColor: NSColor required init?(coder: NSCoder) { tintColor = NSColor.white super.init(coder: coder) } override func draw(_ dirtyRect: NSRect) { let size = self.bounds.size let diam = [size.height, size.width].min()! let lineWidth: CGFloat = 1 let centerPoint = CGPoint(x: size.width / 2, y: size.height / 2) let rect = NSRect.init( x: centerPoint.x - diam / 2 + lineWidth / 2, y: centerPoint.y - diam / 2 + lineWidth / 2, width: diam - lineWidth, height: diam - lineWidth); let circle = NSBezierPath.init(ovalIn: rect) tintColor.set() circle.lineWidth = lineWidth circle.stroke() let path = NSBezierPath.init() path.move(to: centerPoint) let startAngle: Double = 90 let endAngle = startAngle - progress / max * 360 path.appendArc(withCenter: centerPoint, radius: diam / 2 - lineWidth / 2, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true); path.close() path.fill() } }
b235b3a4dd43aa252b71a7e01c3dd8e5
22.214286
155
0.668462
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Common/Exchange/OpenExchangeRates.swift
agpl-3.0
3
// // OpenExchangeRates.swift // SmartReceipts // // Created by Jaanus Siim on 02/06/16. // Copyright © 2016 Will Baumann. All rights reserved. // import Foundation private let OpenEchangeRatesAPIHistorycalAddress = "https://openexchangerates.org/api/historical/" class OpenExchangeRates { static let sharedInstance = OpenExchangeRates() fileprivate var rates = [String: [ExchangeRate]]() func exchangeRate(_ base: String, target: String, onDate date: Date, forceRefresh: Bool, completion: @escaping (NSDecimalNumber?, NSError?) -> ()) { let dayString = date.dayString() let dayCurrencyKey = "\(dayString)-\(base)" Logger.debug("Retrieve \(base) to \(target) on \(dayString)") if !forceRefresh, let dayValues = rates[dayCurrencyKey], let rate = dayValues.filter({ $0.currency == target}).first { Logger.debug("Have cache hit") completion(rate.rate, nil) return } else if (forceRefresh) { Logger.debug("Refresh forced") } Logger.debug("Perform remote fetch") let requestURL = URL(string: "\(OpenEchangeRatesAPIHistorycalAddress)\(dayString).json?base=\(base)&app_id=\(OpenExchangeAppID)")! Logger.debug("\(requestURL)") let request = URLRequest(url: requestURL) let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in Logger.debug("Request completed") if let error = error { completion(nil, error as NSError?) return } guard var rates = ExchangeRate.loadFromData(data!) else { completion(nil, nil) return } if let rate = rates.filter({ $0.currency == target }).first { completion(rate.rate, nil) } else { // add unsupported currency marker rates.append(ExchangeRate(currency: target, rate: .minusOne())) completion(.minusOne(), nil) } self.rates[dayCurrencyKey] = rates }) task.resume() } }
aff2af293dd3c5457ce55166e661bf45
34.857143
152
0.571492
false
false
false
false
SoySauceLab/CollectionKit
refs/heads/master
Examples/CollectionKitExamples/AnimatorExample/AnimatorExampleViewController.swift
mit
1
// // AnimatorExampleViewController.swift // CollectionKitExample // // Created by Luke Zhao on 2017-09-04. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit import CollectionKit class AnimatorExampleViewController: CollectionViewController { override func viewDidLoad() { super.viewDidLoad() let animators = [ ("Default", Animator()), ("Wobble", WobbleAnimator()), ("Edge Shrink", EdgeShrinkAnimator()), ("Zoom", ZoomAnimator()), ] let imagesCollectionView = CollectionView() let visibleFrameInsets = UIEdgeInsets(top: 0, left: -100, bottom: 0, right: -100) let imageProvider = BasicProvider( dataSource: testImages, viewSource: ClosureViewSource(viewGenerator: { (data, index) -> UIImageView in let view = UIImageView() view.layer.cornerRadius = 5 view.clipsToBounds = true return view }, viewUpdater: { (view: UIImageView, data: UIImage, at: Int) in view.image = data }), sizeSource: UIImageSizeSource(), layout: WaterfallLayout(columns: 2, spacing: 10).transposed().inset(by: bodyInset).insetVisibleFrame(by: visibleFrameInsets), animator: animators[0].1 ) imagesCollectionView.provider = imageProvider let buttonsCollectionView = CollectionView() buttonsCollectionView.showsHorizontalScrollIndicator = false let buttonsProvider = BasicProvider( dataSource: animators, viewSource: { (view: SelectionButton, data: (String, Animator), at: Int) in view.label.text = data.0 view.label.textColor = imageProvider.animator === data.1 ? .white : .black view.backgroundColor = imageProvider.animator === data.1 ? .lightGray : .white }, sizeSource: { _, data, maxSize in return CGSize(width: data.0.width(withConstraintedHeight: maxSize.height, font: UIFont.systemFont(ofSize:18)) + 20, height: maxSize.height) }, layout: FlowLayout(lineSpacing: 10).transposed() .inset(by: UIEdgeInsets(top: 10, left: 16, bottom: 0, right: 16)), animator: WobbleAnimator(), tapHandler: { context in imageProvider.animator = context.data.1 // clear previous styles for cell in imagesCollectionView.visibleCells { cell.alpha = 1 cell.transform = .identity } context.setNeedsReload() } ) buttonsCollectionView.provider = buttonsProvider let buttonsViewProvider = SimpleViewProvider( views: [buttonsCollectionView], sizeStrategy: (.fill, .absolute(44)) ) let providerViewProvider = SimpleViewProvider( identifier: "providerContent", views: [imagesCollectionView], sizeStrategy: (.fill, .fill) ) provider = ComposedProvider( layout: RowLayout("providerContent").transposed(), sections: [ buttonsViewProvider, providerViewProvider ] ) } }
9bd5f67bc931489bc281886e9071703b
31.054348
147
0.660563
false
false
false
false
Takanu/Pelican
refs/heads/master
Sources/Pelican/Session/Types/UserSession.swift
mit
1
// // UserSession.swift // party // // Created by Takanu Kyriako on 26/06/2017. // // import Foundation /** A high-level class for managing states and information for each user that attempts to interact with your bot (and that isn't immediately blocked by the bot's blacklist). UserSession is also used to handle InlineQuery and ChosenInlineResult routes, as ChatSessions cannot receive inline updates. */ open class UserSession: Session { // CORE INTERNAL VARIABLES public private(set) var tag: SessionTag public private(set) var dispatchQueue: SessionDispatchQueue /// The user information associated with this session. public private(set) var info: User /// The ID of the user associated with this session. public private(set) var userID: String /// The chat sessions this user is currently actively occupying. /// -- Not currently functional, undecided if it will be implemented //public var chatSessions: [SessionTag] = [] // API REQUESTS // Shortcuts for API requests. public private(set) var requests: MethodRequest // DELEGATES / CONTROLLERS /// Delegate for creating, modifying and getting other Sessions. public private(set) var sessions: SessionRequest /// Handles and matches user requests to available bot functions. public var baseRoute: Route /// Stores what Moderator-controlled permissions the User Session has. public private(set) var mod: SessionModerator /// Handles timeout conditions. public private(set) var timeout: TimeoutMonitor /// Handles flood conditions. public private(set) var flood: FloodMonitor /// Stores a link to the schedule, that allows events to be executed at a later date. public private(set) var schedule: Schedule /// Pre-checks and filters unnecessary updates. public private(set) var filter: UpdateFilter // TIME AND ACTIVITY public private(set) var timeStarted = Date() public required init?(bot: PelicanBot, tag: SessionTag) { if tag.user == nil { return nil } self.tag = tag self.info = tag.user! self.userID = tag.user!.tgID self.sessions = SessionRequest(bot: bot) self.baseRoute = Route(name: "base", routes: []) self.mod = SessionModerator(tag: tag, moderator: bot.mod)! self.timeout = TimeoutMonitor(tag: tag, schedule: bot.schedule) self.flood = FloodMonitor() self.filter = UpdateFilter() self.schedule = bot.schedule self.requests = MethodRequest(tag: tag) self.dispatchQueue = SessionDispatchQueue(tag: tag, label: "com.pelican.usersession_\(tag.sessionID)",qos: .userInitiated) } open func postInit() { } open func cleanup() { self.baseRoute.close() self.timeout.close() self.flood.clearAll() self.dispatchQueue.cancelAll() self.filter.reset() } public func update(_ update: Update) { if filter.verifyUpdate(update) == false { self.timeout.bump(update) self.flood.handle(update) return } dispatchQueue.async { // Bump the timeout controller first so if flood or another process closes the Session, a new timeout event will not be added. self.timeout.bump(update) // This needs revising, whatever... _ = self.baseRoute.handle(update) // Bump the flood controller after self.flood.handle(update) } } }
d184e319773e29a5a89a985c64b88272
25.152
129
0.718568
false
false
false
false
krevis/MIDIApps
refs/heads/main
Applications/SysExLibrarian/ImportController.swift
bsd-3-clause
1
/* Copyright (c) 2002-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Cocoa import SnoizeMIDI class ImportController { init(windowController: MainWindowController, library: Library) { self.mainWindowController = windowController self.library = library guard Bundle.main.loadNibNamed("Import", owner: self, topLevelObjects: &topLevelObjects) else { fatalError() } } // Main window controller sends this to begin the process func importFiles(_ paths: [String], showingProgress: Bool) { precondition(filePathsToImport.isEmpty) filePathsToImport = paths shouldShowProgress = showingProgress && areAnyFilesDirectories(paths) showImportWarning() } // MARK: Actions @IBAction func cancelImporting(_ sender: Any?) { // No need to lock just to set a boolean importCancelled = true } @IBAction func endSheetWithReturnCodeFromSenderTag(_ sender: Any?) { if let window = mainWindowController?.window, let sheet = window.attachedSheet, let senderView = sender as? NSView { window.endSheet(sheet, returnCode: NSApplication.ModalResponse(rawValue: senderView.tag)) } } // MARK: Private private var topLevelObjects: NSArray? @IBOutlet private var importSheetWindow: NSPanel! @IBOutlet private var progressIndicator: NSProgressIndicator! @IBOutlet private var progressMessageField: NSTextField! @IBOutlet private var progressIndexField: NSTextField! @IBOutlet private var importWarningSheetWindow: NSPanel! @IBOutlet private var doNotWarnOnImportAgainCheckbox: NSButton! private weak var mainWindowController: MainWindowController? private weak var library: Library? private var workQueue: DispatchQueue? // Transient data private var filePathsToImport: [String] = [] private var shouldShowProgress = false private var importCancelled = false } extension ImportController /* Preferences keys */ { static var showWarningOnImportPreferenceKey = "SSEShowWarningOnImport" } extension ImportController /* Private */ { private func areAnyFilesDirectories(_ paths: [String]) -> Bool { for path in paths { var isDirectory = ObjCBool(false) if FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && isDirectory.boolValue { return true } } return false } private func showImportWarning() { guard let library = library else { return } let areAllFilesInLibraryDirectory = filePathsToImport.allSatisfy({ library.isPathInFileDirectory($0) }) if areAllFilesInLibraryDirectory || UserDefaults.standard.bool(forKey: Self.showWarningOnImportPreferenceKey) == false { importFiles() } else { doNotWarnOnImportAgainCheckbox.intValue = 0 mainWindowController?.window?.beginSheet(importWarningSheetWindow, completionHandler: { modalResponse in self.importWarningSheetWindow.orderOut(nil) if modalResponse == .OK { if self.doNotWarnOnImportAgainCheckbox.integerValue == 1 { UserDefaults.standard.set(false, forKey: Self.showWarningOnImportPreferenceKey) } self.importFiles() } else { // Cancelled self.finishedImport() } }) } } private func importFiles() { if shouldShowProgress { importFilesShowingProgress() } else { // Add entries immediately let (newEntries, badFiles) = addFilesToLibrary(filePathsToImport) finishImport(newEntries, badFiles) } } // // Import with progress display // Main queue: setup, updating progress display, teardown // private func importFilesShowingProgress() { guard let mainWindow = mainWindowController?.window else { return } importCancelled = false updateImportStatusDisplay("", 0, 0) mainWindow.beginSheet(importSheetWindow) { _ in self.importSheetWindow.orderOut(nil) } let paths = self.filePathsToImport if workQueue == nil { workQueue = DispatchQueue(label: "Import", qos: .userInitiated) } workQueue?.async { self.workQueueImportFiles(paths) } } static private var scanningString = NSLocalizedString("Scanning...", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "Scanning...") static private var xOfYFormatString = NSLocalizedString("%u of %u", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "importing sysex: x of y") private func updateImportStatusDisplay(_ filePath: String, _ fileIndex: Int, _ fileCount: Int) { if fileCount == 0 { progressIndicator.isIndeterminate = true progressIndicator.usesThreadedAnimation = true progressIndicator.startAnimation(nil) progressMessageField.stringValue = Self.scanningString progressIndexField.stringValue = "" } else { progressIndicator.isIndeterminate = false progressIndicator.maxValue = Double(fileCount) progressIndicator.doubleValue = Double(fileIndex + 1) progressMessageField.stringValue = FileManager.default.displayName(atPath: filePath) progressIndexField.stringValue = String.localizedStringWithFormat(Self.xOfYFormatString, fileIndex + 1, fileCount) } } // // Import with progress display // Work queue: recurse through directories, filter out inappropriate files, and import // private func workQueueImportFiles(_ paths: [String]) { autoreleasepool { let expandedAndFilteredFilePaths = workQueueExpandAndFilterFiles(paths) var newEntries = [LibraryEntry]() var badFiles = [String]() if expandedAndFilteredFilePaths.count > 0 { (newEntries, badFiles) = addFilesToLibrary(expandedAndFilteredFilePaths) } DispatchQueue.main.async { self.doneImportingInWorkQueue(newEntries, badFiles) } } } private func workQueueExpandAndFilterFiles(_ paths: [String]) -> [String] { guard let library = library else { return [] } let fileManager = FileManager.default var acceptableFilePaths = [String]() for path in paths { if importCancelled { acceptableFilePaths.removeAll() break } var isDirectory = ObjCBool(false) if !fileManager.fileExists(atPath: path, isDirectory: &isDirectory) { continue } autoreleasepool { if isDirectory.boolValue { // Handle this directory's contents recursively do { let childPaths = try fileManager.contentsOfDirectory(atPath: path) var fullChildPaths = [String]() for childPath in childPaths { let fullChildPath = NSString(string: path).appendingPathComponent(childPath) as String fullChildPaths.append(fullChildPath) } let acceptableChildren = workQueueExpandAndFilterFiles(fullChildPaths) acceptableFilePaths.append(contentsOf: acceptableChildren) } catch { // ignore } } else { if fileManager.isReadableFile(atPath: path) && library.typeOfFile(atPath: path) != .unknown { acceptableFilePaths.append(path) } } } } return acceptableFilePaths } private func doneImportingInWorkQueue(_ newEntries: [LibraryEntry], _ badFiles: [String]) { if let window = mainWindowController?.window, let sheet = window.attachedSheet { window.endSheet(sheet) } finishImport(newEntries, badFiles) } // // Check if each file is already in the library, and then try to add each new one // private func addFilesToLibrary(_ paths: [String]) -> ([LibraryEntry], [String]) { // Returns successfully created library entries, and paths for files that could not // be successfully imported. // NOTE: This may be happening in the main queue or workQueue. guard let library = library else { return ([], []) } var addedEntries = [LibraryEntry]() var badFilePaths = [String]() // Find the files which are already in the library, and pull them out. let (existingEntries, filePaths) = library.findEntries(forFilePaths: paths) // Try to add each file to the library, keeping track of the successful ones. let fileCount = filePaths.count for (fileIndex, filePath) in filePaths.enumerated() { // If we're not in the main thread, update progress information and tell the main thread to update its UI. if !Thread.isMainThread { if importCancelled { break } DispatchQueue.main.async { self.updateImportStatusDisplay(filePath, fileIndex, fileCount) } } autoreleasepool { if let addedEntry = library.addEntry(forFile: filePath) { addedEntries.append(addedEntry) } else { badFilePaths.append(filePath) } } } addedEntries.append(contentsOf: existingEntries) return (addedEntries, badFilePaths) } // // Finishing up // private func finishImport(_ newEntries: [LibraryEntry], _ badFiles: [String]) { mainWindowController?.showNewEntries(newEntries) showErrorMessageForFilesWithNoSysEx(badFiles) finishedImport() } private func finishedImport() { filePathsToImport = [] importCancelled = false } private func showErrorMessageForFilesWithNoSysEx(_ badFiles: [String]) { let badFileCount = badFiles.count guard badFileCount > 0 else { return } guard let window = mainWindowController?.window, window.attachedSheet == nil else { return } var informativeText: String = "" if badFileCount == 1 { informativeText = NSLocalizedString("No SysEx data could be found in this file. It has not been added to the library.", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "message when no sysex data found in file") } else { let format = NSLocalizedString("No SysEx data could be found in %u of the files. They have not been added to the library.", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "format of message when no sysex data found in files") informativeText = String.localizedStringWithFormat(format, badFileCount) } let messageText = NSLocalizedString("Could not read SysEx", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of alert when can't read a sysex file") let alert = NSAlert() alert.alertStyle = .informational alert.messageText = messageText alert.informativeText = informativeText alert.beginSheetModal(for: window, completionHandler: nil) } }
32883f09fdbbba36186033ebc27fb46d
34.633929
249
0.620145
false
false
false
false
yonasstephen/swift-of-airbnb
refs/heads/master
airbnb-main/airbnb-main/ImageShrinkAnimationController.swift
mit
1
// // ImageShrinkAnimationController.swift // airbnb-main // // Created by Yonas Stephen on 11/4/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import UIKit protocol ImageShrinkAnimationControllerProtocol { func getInitialImageFrame() -> CGRect } class ImageShrinkAnimationController: NSObject, UIViewControllerAnimatedTransitioning { var destinationFrame = CGRect.zero func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: .from), fromVC is ImageShrinkAnimationControllerProtocol, let toVC = transitionContext.viewController(forKey: .to) else { return } let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height let containerView = transitionContext.containerView containerView.backgroundColor = UIColor.white containerView.addSubview(toVC.view) // setup cell image snapshot let initialFrame = (fromVC as! ImageShrinkAnimationControllerProtocol).getInitialImageFrame() let finalFrame = destinationFrame let snapshot = fromVC.view.resizableSnapshotView(from: initialFrame, afterScreenUpdates: false, withCapInsets: .zero)! snapshot.frame = initialFrame containerView.addSubview(snapshot) let widthDiff = initialFrame.width - finalFrame.width // setup snapshot to the left of selected cell image let leftFinalFrame = CGRect(x: 0, y: finalFrame.origin.y, width: finalFrame.origin.x, height: finalFrame.height) let leftInitialFrameWidth = leftFinalFrame.width + widthDiff let leftInitialFrame = CGRect(x: -leftInitialFrameWidth, y: initialFrame.origin.y, width: leftInitialFrameWidth, height: initialFrame.height) let leftSnapshot = toVC.view.resizableSnapshotView(from: leftFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)! leftSnapshot.frame = leftInitialFrame containerView.addSubview(leftSnapshot) // setup snapshot to the right of selected cell image let rightFinalFrameX = finalFrame.origin.x + finalFrame.width let rightFinalFrame = CGRect(x: rightFinalFrameX, y: finalFrame.origin.y, width: screenWidth - rightFinalFrameX, height: finalFrame.height) let rightInitialFrame = CGRect(x: screenWidth, y: initialFrame.origin.y, width: rightFinalFrame.width + widthDiff, height: initialFrame.height) let rightSnapshot = toVC.view.resizableSnapshotView(from: rightFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)! rightSnapshot.frame = rightInitialFrame containerView.addSubview(rightSnapshot) // setup snapshot to the bottom of selected cell image let bottomFinalFrameY = finalFrame.origin.y + finalFrame.height let bottomFinalFrame = CGRect(x: 0, y: bottomFinalFrameY, width: screenWidth, height: screenHeight - bottomFinalFrameY) let bottomInitialFrame = CGRect(x: 0, y: bottomFinalFrame.height, width: screenWidth, height: screenHeight) let bottomSnapshot = toVC.view.resizableSnapshotView(from: bottomFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)! bottomSnapshot.frame = bottomInitialFrame containerView.addSubview(bottomSnapshot) // setup snapshot to the top of selected cell image let topFinalFrame = CGRect(x: 0, y: 0, width: screenWidth, height: finalFrame.origin.y) let topInitialFrame = CGRect(x: 0, y: -topFinalFrame.height, width: topFinalFrame.width, height: topFinalFrame.height) let topSnapshot = toVC.view.resizableSnapshotView(from: topFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)! topSnapshot.frame = topInitialFrame containerView.addSubview(topSnapshot) // setup the bottom component of the origin view let fromVCBottomInitialFrameY = initialFrame.origin.y + initialFrame.height let fromVCBottomInitialFrame = CGRect(x: 0, y: fromVCBottomInitialFrameY, width: screenWidth, height: screenHeight - fromVCBottomInitialFrameY) let fromVCBottomFinalFrame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: fromVCBottomInitialFrame.height) let fromVCSnapshot = fromVC.view.resizableSnapshotView(from: fromVCBottomInitialFrame, afterScreenUpdates: false, withCapInsets: .zero)! fromVCSnapshot.frame = fromVCBottomInitialFrame containerView.addSubview(fromVCSnapshot) toVC.view.isHidden = true fromVC.view.isHidden = true let duration = transitionDuration(using: transitionContext) UIView.animate(withDuration: 0.3, animations: { //fromVCSnapshot.alpha = 0 fromVCSnapshot.frame = fromVCBottomFinalFrame }, completion: { _ in fromVCSnapshot.removeFromSuperview() }) UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: { snapshot.frame = finalFrame leftSnapshot.frame = leftFinalFrame rightSnapshot.frame = rightFinalFrame bottomSnapshot.frame = bottomFinalFrame topSnapshot.frame = topFinalFrame }, completion: { _ in toVC.view.isHidden = false fromVC.view.isHidden = false snapshot.removeFromSuperview() leftSnapshot.removeFromSuperview() rightSnapshot.removeFromSuperview() bottomSnapshot.removeFromSuperview() topSnapshot.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } }
59637970a9f6e989d374e2fc8581c83c
46.755906
151
0.694641
false
false
false
false
powerytg/Accented
refs/heads/master
Accented/UI/Common/Components/Drawer/DrawerOpenAnimator.swift
mit
1
// // DrawerOpenAnimator.swift // Accented // // Created by You, Tiangong on 6/16/16. // Copyright © 2016 Tiangong You. All rights reserved. // import UIKit class DrawerOpenAnimator: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning { private var animationContext : DrawerAnimationContext init(animationContext : DrawerAnimationContext) { self.animationContext = animationContext super.init() } // MARK: UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.2 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) let fromView = fromViewController?.view let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let duration = self.transitionDuration(using: transitionContext) let animationOptions : UIViewAnimationOptions = (animationContext.interactive ? .curveLinear : .curveEaseOut) UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { if fromView != nil { let scale = CGAffineTransform(scaleX: 0.94, y: 0.94) var translation : CGAffineTransform switch(self.animationContext.anchor) { case .bottom: translation = CGAffineTransform(translationX: 0, y: -25) case .left: translation = CGAffineTransform(translationX: 25, y: 0) case .right: translation = CGAffineTransform(translationX: -25, y: 0) } fromView!.transform = scale.concatenating(translation) } toView.transform = CGAffineTransform.identity }) { (finished) in let transitionCompleted = !transitionContext.transitionWasCancelled transitionContext.completeTransition(transitionCompleted) } } }
542d929e81de534e516c42f6b50e51cf
39.381818
117
0.656461
false
false
false
false
ColinConduff/BlocFit
refs/heads/master
BlocFit/Main Components/Map/MapController.swift
mit
1
// // MapController.swift // BlocFit // // Created by Colin Conduff on 1/8/17. // Copyright © 2017 Colin Conduff. All rights reserved. // import CoreData import GoogleMaps import HealthKit protocol MapNotificationDelegate: class { func blocMembersDidChange(_ blocMembers: [BlocMember]) func didPressActionButton() -> Bool func loadSavedRun(run: Run) } protocol MapControllerProtocol: class { var mapRunModel: MapRunModel { get } var authStatusIsAuthAlways: Bool { get } var cameraPosition: GMSCameraPosition { get } var paths: [Path] { get } var run: Run? { get } var seconds: Int { get } var mapRunModelDidChange: ((MapRunModel) -> ())? { get set } var authStatusDidChange: ((MapControllerProtocol) -> ())? { get set } var cameraPositionDidChange: ((MapControllerProtocol) -> ())? { get set } var pathsDidChange: ((MapControllerProtocol) -> ())? { get set } var secondsDidChange: ((MapControllerProtocol) -> ())? { get set } init(requestMainDataDelegate: RequestMainDataDelegate, scoreReporterDelegate: ScoreReporterDelegate, context: NSManagedObjectContext) func cameraPositionNeedsUpdate() } class MapController: NSObject, CLLocationManagerDelegate, MapControllerProtocol, MapNotificationDelegate { var mapRunModel: MapRunModel { didSet { self.mapRunModelDidChange?(mapRunModel) } } var authStatusIsAuthAlways = false { didSet { self.authStatusDidChange?(self) } } var cameraPosition: GMSCameraPosition { didSet { self.cameraPositionDidChange?(self) } } var paths = [Path]() { didSet { self.pathsDidChange?(self) } } var seconds = 0 { didSet { self.secondsDidChange?(self) } } var run: Run? { didSet { guard let run = run else { return } self.setDashboardModel(using: run) } } var mapRunModelDidChange: ((MapRunModel) -> ())? var authStatusDidChange: ((MapControllerProtocol) -> ())? var cameraPositionDidChange: ((MapControllerProtocol) -> ())? var pathsDidChange: ((MapControllerProtocol) -> ())? var secondsDidChange: ((MapControllerProtocol) -> ())? weak var requestMainDataDelegate: RequestMainDataDelegate! weak var scoreReporterDelegate: ScoreReporterDelegate! let locationManager = CLLocationManager() let context: NSManagedObjectContext let owner: Owner var currentlyRunning = false var timer = Timer() required init(requestMainDataDelegate: RequestMainDataDelegate, scoreReporterDelegate: ScoreReporterDelegate, context: NSManagedObjectContext) { self.requestMainDataDelegate = requestMainDataDelegate self.scoreReporterDelegate = scoreReporterDelegate self.context = context owner = try! Owner.get(context: context)! mapRunModel = MapRunModel(secondsElapsed: 0, score: 0, totalDistanceInMeters: 0, secondsPerMeter: 0) cameraPosition = GMSCameraPosition.camera(withLatitude: 37.35, longitude: -122.0, zoom: 18.0) authStatusIsAuthAlways = CLLocationManager.authorizationStatus() == .authorizedAlways super.init() initializeLocationManagement() HealthKitManager.authorize() } private func initializeLocationManagement() { locationManager.requestAlwaysAuthorization() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.activityType = .fitness locationManager.distanceFilter = 10 locationManager.allowsBackgroundLocationUpdates = true } // CLLocationManagerDelegate Methods func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { authStatusIsAuthAlways = (status == .authorizedAlways) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("location manager error") print(error) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var paths = [Path]() for location in locations { if location.horizontalAccuracy < 20 { let lastRunPoint = run?.runPoints?.lastObject as? RunPoint updateRun(currentLocation: location) let latitude = location.coordinate.latitude let longitude = location.coordinate.longitude if let lastLatitude = lastRunPoint?.latitude, let lastLongitude = lastRunPoint?.longitude { let path = Path(fromLat: lastLatitude, fromLong: lastLongitude, toLat: latitude, toLong: longitude) paths.append(path) } updateCameraPosition(latitude: latitude, longitude: longitude) } } self.paths = paths } func cameraPositionNeedsUpdate() { if let coordinate = locationManager.location?.coordinate { updateCameraPosition(latitude: coordinate.latitude, longitude: coordinate.longitude) } } private func updateCameraPosition(latitude: Double, longitude: Double) { let target = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) cameraPosition = GMSCameraPosition.camera(withTarget: target, zoom: 18.0) } // MapNotificationDelegate Method func loadSavedRun(run: Run) { self.run = run guard let runPoints = run.runPoints?.array as? [RunPoint] else { return } var paths = [Path]() var lastRunPoint: RunPoint? = nil for runPoint in runPoints { if let lastRunPoint = lastRunPoint { let path = Path(fromLat: lastRunPoint.latitude, fromLong: lastRunPoint.longitude, toLat: runPoint.latitude, toLong: runPoint.longitude) paths.append(path) } lastRunPoint = runPoint } self.paths = paths if let latitude = lastRunPoint?.latitude, let longitude = lastRunPoint?.longitude { updateCameraPosition(latitude: latitude, longitude: longitude) } } private func updateRun(currentLocation: CLLocation) { guard let run = run else { return } try? run.update(currentLocation: currentLocation) setDashboardModel(using: run) } private func setDashboardModel(using run: Run) { mapRunModel = MapRunModel(secondsElapsed: Double(run.secondsElapsed), score: Int(run.score), totalDistanceInMeters: run.totalDistanceInMeters, secondsPerMeter: run.secondsPerMeter) } // MapNotificationDelegate Method func blocMembersDidChange(_ blocMembers: [BlocMember]) { guard let run = run else { return } try? run.update(blocMembers: blocMembers) } // Logic for responding to action button click // // MapNotificationDelegate Method func didPressActionButton() -> Bool { if authStatusIsAuthAlways { if currentlyRunning { stopRunning() } else { startRunning() } currentlyRunning = !currentlyRunning } else { authStatusIsAuthAlways = false // trigger didSet } return authStatusIsAuthAlways } private func startRunning() { let blocMembers = requestMainDataDelegate.getCurrentBlocMembers() run = try! Run.create(owner: owner, blocMembers: blocMembers, context: context) startTrackingData() } private func startTrackingData() { locationManager.startUpdatingLocation() seconds = 0 timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in self.seconds += 1 } } private func stopRunning() { locationManager.stopUpdatingLocation() timer.invalidate() if let run = run { saveRunToHealthKit(run) scoreReporterDelegate.submitScore(run: run) scoreReporterDelegate.submitScore(owner: owner) } } private func saveRunToHealthKit(_ run: Run) { guard let start = run.startTime as? Date, let end = run.endTime as? Date else { return } HealthKitManager.save(meters: run.totalDistanceInMeters, start: start, end: end) } }
d61d65d85fef85ecc5ab85f3116b989e
34.942085
137
0.593834
false
false
false
false
thiagotmb/BEPiD-Challenges-2016
refs/heads/master
2016-04-06-Complications/TouristComplicationChallenge/TouristComplicationChallenge WatchKit Extension/ComplicationController.swift
mit
2
// // ComplicationController.swift // TouristComplicationChallenge WatchKit Extension // // Created by Thiago-Bernardes on 4/6/16. // Copyright © 2016 TB. All rights reserved. // import ClockKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Placeholder Templates func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached if complication.family == .UtilitarianLarge { let complicationTemplate = CLKComplicationTemplateUtilitarianLargeFlat() complicationTemplate.textProvider = CLKSimpleTextProvider(text: "05:50 - 😎") handler(complicationTemplate) } } // MARK: - Timeline Configuration func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) { handler([.Forward, .Backward]) } // MARK: - Timeline Population func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) { // Call the handler with the current timeline entry var emoji = "🤑" if TaskModel.completedTasks().count < 3 { emoji = "😐" } if complication.family == .UtilitarianLarge { let complicationTemplate = CLKComplicationTemplateUtilitarianLargeFlat() complicationTemplate.textProvider = CLKSimpleTextProvider(text: ("6:40" + emoji)) let complicationEntry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: complicationTemplate) handler(complicationEntry) } handler(nil) } func reloadData() { // 1 let server = CLKComplicationServer.sharedInstance() guard let complications = server.activeComplications where complications.count > 0 else { return } for complication in complications { server.reloadTimelineForComplication(complication) } } }
11d23c6d0d621b0223a3615f6fec9efc
29.688312
157
0.648752
false
false
false
false
sleekbyte/tailor
refs/heads/master
src/test/swift/com/sleekbyte/tailor/functional/RuleTest.swift
mit
1
import Foundation; import Cocoa let kMaximum = 42 let my_constant = 12 class SomeClass { // class definition goes here func timesTwo(myValue: Int) -> Int { let my_local_constant = 7 return my_local_constant + myValue } } enum someEnumeration { // enumeration definition goes here }; enum compassPoint { case North case South; case East case west } struct someStructure { // structure definition goes here } protocol someProtocol { // protocol definition goes here } // var airports = [("YYZ"): "Toronto"] var counter = (0) // // first line over max-file-length limit while (counter < 1) { counter++ } // missing trailing newline
ede75f826305c6328441b3aabfa58fe3
16.375
42
0.661383
false
false
false
false
himadrisj/SiriPay
refs/heads/dev
Client/SiriPay/ezPay-SiriIntent/IntentHandler.swift
mit
1
// // IntentHandler.swift // ezPay-SiriIntent // // Created by Himadri Sekhar Jyoti on 11/09/16. // Copyright // import Intents // As an example, this class is set up to handle Message intents. // You will want to replace this or add other intents as appropriate. // The intents you wish to handle must be declared in the extension's Info.plist. // You can test your example integration by saying things to Siri like: // "Send a message using <myApp>" // "<myApp> John saying hello" // "Search for messages in <myApp>" class IntentHandler: INExtension, INSendPaymentIntentHandling { override func handler(for intent: INIntent) -> Any { // This is the default implementation. If you want different objects to handle different intents, // you can override this and return the handler you want for that particular intent. return self } /*! @brief handling method @abstract Execute the task represented by the INSendPaymentIntent that's passed in @discussion This method is called to actually execute the intent. The app must return a response for this intent. @param sendPaymentIntent The input intent @param completion The response handling block takes a INSendPaymentIntentResponse containing the details of the result of having executed the intent @see INSendPaymentIntentResponse */ public func handle(sendPayment intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Swift.Void) { // Implement your application logic for payment here. var thePhoneNO = "9886957281" //"9711165687" //"9742048795" let defaults = UserDefaults(suiteName: "group.com.example.ezpay") if let contactDict = defaults?.object(forKey: contactsSharedKey) as? [String: String] { if let lowerCaseName = intent.payee?.displayName.lowercased() { if let phNo = contactDict[lowerCaseName] { thePhoneNO = phNo } } } // if(intent.payee?.displayName.caseInsensitiveCompare("Jatin") == .orderedSame) { // phoneNo = "9711165687" // } let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendPaymentIntent.self)) var response = INSendPaymentIntentResponse(code: .failure, userActivity: userActivity) if let intAmount = intent.currencyAmount?.amount?.intValue { var payInfo = [String:String]() payInfo["phone"] = thePhoneNO payInfo["amount"] = String(intAmount) let defaults = UserDefaults(suiteName: "group.com.example.ezpay") defaults?.set(payInfo, forKey: payInfoUserDefaultsKey) defaults?.synchronize() response = INSendPaymentIntentResponse(code: .success, userActivity: userActivity) response.paymentRecord = self.makePaymentRecord(for: intent) } completion(response) } /*! @brief Confirmation method @abstract Validate that this intent is ready for the next step (i.e. handling) @discussion These methods are called prior to asking the app to handle the intent. The app should return a response object that contains additional information about the intent, which may be relevant for the system to show the user prior to handling. If unimplemented, the system will assume the intent is valid following resolution, and will assume there is no additional information relevant to this intent. @param sendPaymentIntent The input intent @param completion The response block contains an INSendPaymentIntentResponse containing additional details about the intent that may be relevant for the system to show the user prior to handling. @see INSendPaymentIntentResponse */ public func confirm(sendPayment intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Swift.Void) { let response = INSendPaymentIntentResponse(code: .success, userActivity: nil) response.paymentRecord = self.makePaymentRecord(for: intent) completion(response) } func makePaymentRecord(for intent: INSendPaymentIntent, status: INPaymentStatus = .completed) -> INPaymentRecord? { let paymentMethod = INPaymentMethod(type: .unknown, name: "SimplePay", identificationHint: nil, icon: nil) let localCurrencyAmmount = INCurrencyAmount(amount: (intent.currencyAmount?.amount)!, currencyCode: "INR") return INPaymentRecord( payee: intent.payee, payer: nil, currencyAmount: localCurrencyAmmount, paymentMethod: paymentMethod, note: intent.note, status: status ) } /*! @brief Resolution methods @abstract Determine if this intent is ready for the next step (confirmation) @discussion These methods are called to make sure the app extension is capable of handling this intent in its current form. This method is for validating if the intent needs any further fleshing out. @param sendPaymentIntent The input intent @param completion The response block contains an INIntentResolutionResult for the parameter being resolved @see INIntentResolutionResult */ public func resolvePayee(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INPersonResolutionResult) -> Swift.Void) { guard let payee = intent.payee else { completion(INPersonResolutionResult.needsValue()) return } // if let type = payee.personHandle?.type { // if(type == .phoneNumber) { // completion(INPersonResolutionResult.success(with: payee)) // return // } // } let defaults = UserDefaults(suiteName: "group.com.example.ezpay") if let contactDict = defaults?.object(forKey: contactsSharedKey) as? [String: String] { if(contactDict[payee.displayName.lowercased()]?.characters.count == 10) { completion(INPersonResolutionResult.success(with: payee)) return } } // if (payee.displayName.caseInsensitiveCompare("om") == .orderedSame || payee.displayName.caseInsensitiveCompare("jatin") == .orderedSame) { // completion(INPersonResolutionResult.success(with: payee)) // } completion(INPersonResolutionResult.disambiguation(with: [payee])) } public func resolveCurrencyAmount(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INCurrencyAmountResolutionResult) -> Swift.Void) { guard let amount = intent.currencyAmount else { completion(INCurrencyAmountResolutionResult.needsValue()) return } guard amount.amount != nil else { completion(INCurrencyAmountResolutionResult.needsValue()) return } completion(INCurrencyAmountResolutionResult.success(with: amount)) } // public func resolveNote(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INStringResolutionResult) -> Swift.Void) { // // } // }
6a9ddd97d8a2b494afd43551d1e99ab0
40.527778
414
0.660602
false
false
false
false
kak-ios-codepath/everest
refs/heads/master
Everest/Everest/Controllers/TimeLine/TimelineViewController.swift
apache-2.0
1
// // TimelineViewController.swift // Everest // // Created by Kavita Gaitonde on 10/13/17. // Copyright © 2017 Kavita Gaitonde. All rights reserved. // import UIKit class TimelineViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, MomentCellDelegate { // MARK: -- outlets and properties @IBOutlet weak var timelineTableView: UITableView! private var timelineManager: TimeLineManager? private var moments : [Moment]? private var isMapView = false private var mapViewController : TimeLineMapViewController? private let refreshControl = UIRefreshControl() // MARK: -- Initialization codes required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) initialize() } func initialize() -> Void { timelineManager = TimeLineManager.init() moments = [Moment]() } // MARK: -- View controller lifecycle methods override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: "MomentCell", bundle: nil) self.timelineTableView.register(nib, forCellReuseIdentifier: "MomentCell") self.timelineTableView.estimatedRowHeight = 100//self.timelineTableView.rowHeight self.timelineTableView.rowHeight = UITableViewAutomaticDimension refreshControl.backgroundColor = UIColor.clear refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) self.timelineTableView.insertSubview(refreshControl, at: 0) self.mapViewController = TimeLineMapViewController(nibName: "TimeLineMapViewController", bundle: nil) self.mapViewController?.navController = self.navigationController NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "MomentCreated"), object: nil, queue: OperationQueue.main, using: {(Notification) -> () in self.loadData() }) self.loadData() //// -- TODO: Remove code after TESTING image uploads // guard let image = UIImage(named: "password") else { return } // //guard let imageData = UIImageJPEGRepresentation(image, 0.8) else { return } // // FireBaseManager.shared.uploadImage(image: image) { (path, url, error) in // if url != nil { // print("Image path: \(path)") // print("Uploaded image to: \(url!)") // FireBaseManager.shared.downloadImage(path: path, completion: { (url, error) in // if url != nil { // print("Downloaded image to: \(url!)") // } else { // print("Error Uploading image ") // } // }) // } else { // print("Error Uploadding image ") // } // } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.barTintColor = UIColor(red:0.94, green:0.71, blue:0.25, alpha:1.0) self.navigationController?.navigationBar.isTranslucent = false } @objc func refreshControlAction(_ refreshControl: UIRefreshControl) { loadData() } @IBAction func showMapAction(_ sender: Any) { if (isMapView) { self.timelineTableView.frame = self.view.bounds; //grab the view of a separate VC UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(1.0) UIView.setAnimationTransition(.flipFromLeft, for: (self.view)!, cache: true) self.mapViewController?.view.removeFromSuperview() self.view.addSubview(self.timelineTableView) UIView.commitAnimations() self.navigationItem.rightBarButtonItem?.title = "Map" } else { self.mapViewController?.view.frame = self.view.bounds; //grab the view of a separate VC UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(1.0) UIView.setAnimationTransition(.flipFromLeft, for: (self.view)!, cache: true) self.mapViewController?.view.removeFromSuperview() self.view.addSubview((self.mapViewController?.view)!) UIView.commitAnimations() self.mapViewController?.moments = self.moments self.navigationItem.rightBarButtonItem?.title = "List" } self.isMapView = self.isMapView ? false : true } func loadData() { self.timelineManager?.fetchPublicMomments(completion: { (moments:[Moment]?, error: Error?) in if((error) != nil) { // show the alert return } // for moment in moments! { // print("\(moment.title)") // } self.moments = moments?.sorted(by: { $0.timestamp > $1.timestamp }) DispatchQueue.main.async { self.refreshControl.endRefreshing() self.timelineTableView.reloadData() } }) } 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. } */ // MARK: -- Tableview data source and delegate methods @available(iOS 2.0, *) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MomentCell", for: indexPath) as! MomentCell if (self.moments?.count)!>0 { cell.momentCellDelegate = self cell.moment = self.moments?[indexPath.row] } return cell } @available(iOS 2.0, *) func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.moments?.count ?? 0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let momentsDetailVC = storyboard.instantiateViewController(withIdentifier: "MomentsViewController") as! MomentsViewController momentsDetailVC.momentId = self.moments?[indexPath.row].id momentsDetailVC.isUserMomentDetail = false self.navigationController?.pushViewController(momentsDetailVC, animated: true) } // MARK: -- MomentCell delegate methods func momentCell(cell: MomentCell, didTapOnUserIconForMoment moment: Moment) { let userProfileStoryboard = UIStoryboard(name: "UserProfile", bundle: nil) let userProfileVC = userProfileStoryboard.instantiateViewController(withIdentifier: "UserProfileViewController") as! UserProfileViewController //TODO: Add the user object property to the userprofile viewcontroller userProfileVC.userId = moment.userId self.navigationController?.pushViewController(userProfileVC, animated: true) } }
c37ff12b6975e9b146b3c8323de05aa7
37.227723
176
0.628335
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/ViewControllers/Import/ImportKeyViewController.swift
mit
1
// // StartImportViewController.swift // breadwallet // // Created by Adrian Corscadden on 2017-06-13. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit import WalletKit /** * Screen that allows the user to scan a QR code corresponding to a private key. * * It can be displayed in response to the "Redeem Private Key" menu item under Bitcoin * preferences or in response to the user scanning a private key using the Scan QR Code * item in the main menu. In the latter case, an initial QR code is passed to the init() method. */ class ImportKeyViewController: UIViewController, Subscriber { /** * Initializer * * walletManager - Bitcoin wallet manager * initialQRCode - a QR code that was previously scanned, causing this import view controller to * be displayed */ init(wallet: Wallet, initialQRCode: QRCode? = nil) { self.wallet = wallet self.initialQRCode = initialQRCode assert(wallet.currency.isBitcoin || wallet.currency.isBitcoinCash, "Importing only supports btc or bch") super.init(nibName: nil, bundle: nil) } private let wallet: Wallet private let header = RadialGradientView(backgroundColor: .blue, offset: 64.0) private let illustration = UIImageView(image: #imageLiteral(resourceName: "ImportIllustration")) private let message = UILabel.wrapping(font: .customBody(size: 16.0), color: .white) private let warning = UILabel.wrapping(font: .customBody(size: 16.0), color: .white) private let button = BRDButton(title: S.Import.scan, type: .primary) private let bullet = UIImageView(image: #imageLiteral(resourceName: "deletecircle")) private let leftCaption = UILabel.wrapping(font: .customMedium(size: 13.0), color: .darkText) private let rightCaption = UILabel.wrapping(font: .customMedium(size: 13.0), color: .darkText) private let balanceActivity = BRActivityViewController(message: S.Import.checking) private let importingActivity = BRActivityViewController(message: S.Import.importing) private let unlockingActivity = BRActivityViewController(message: S.Import.unlockingActivity) private var viewModel: TxViewModel? // Previously scanned QR code passed to init() private var initialQRCode: QRCode? override func viewDidLoad() { super.viewDidLoad() addSubviews() addConstraints() setInitialData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let code = initialQRCode { handleScanResult(code) // Set this nil so that if the user tries to can another QR code via the // Scan Private Key button we don't end up trying to process the initial // code again. viewWillAppear() will get called again when the scanner/camera // is dismissed. initialQRCode = nil } } deinit { wallet.unsubscribe(self) } private func addSubviews() { view.addSubview(header) header.addSubview(illustration) header.addSubview(leftCaption) header.addSubview(rightCaption) view.addSubview(message) view.addSubview(button) view.addSubview(bullet) view.addSubview(warning) } private func addConstraints() { header.constrainTopCorners(sidePadding: 0, topPadding: 0) header.constrain([ header.constraint(.height, constant: E.isIPhoneX ? 250.0 : 220.0) ]) illustration.constrain([ illustration.constraint(.width, constant: 64.0), illustration.constraint(.height, constant: 84.0), illustration.constraint(.centerX, toView: header, constant: 0.0), illustration.constraint(.centerY, toView: header, constant: E.isIPhoneX ? 4.0 : -C.padding[1]) ]) leftCaption.constrain([ leftCaption.topAnchor.constraint(equalTo: illustration.bottomAnchor, constant: C.padding[1]), leftCaption.trailingAnchor.constraint(equalTo: header.centerXAnchor, constant: -C.padding[2]), leftCaption.widthAnchor.constraint(equalToConstant: 80.0)]) rightCaption.constrain([ rightCaption.topAnchor.constraint(equalTo: illustration.bottomAnchor, constant: C.padding[1]), rightCaption.leadingAnchor.constraint(equalTo: header.centerXAnchor, constant: C.padding[2]), rightCaption.widthAnchor.constraint(equalToConstant: 80.0)]) message.constrain([ message.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[2]), message.topAnchor.constraint(equalTo: header.bottomAnchor, constant: C.padding[2]), message.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]) ]) bullet.constrain([ bullet.leadingAnchor.constraint(equalTo: message.leadingAnchor), bullet.topAnchor.constraint(equalTo: message.bottomAnchor, constant: C.padding[4]), bullet.widthAnchor.constraint(equalToConstant: 16.0), bullet.heightAnchor.constraint(equalToConstant: 16.0) ]) warning.constrain([ warning.leadingAnchor.constraint(equalTo: bullet.trailingAnchor, constant: C.padding[2]), warning.topAnchor.constraint(equalTo: bullet.topAnchor, constant: 0.0), warning.trailingAnchor.constraint(equalTo: message.trailingAnchor) ]) button.constrain([ button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[3]), button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -C.padding[4]), button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[3]), button.constraint(.height, constant: C.Sizes.buttonHeight) ]) } private func setInitialData() { view.backgroundColor = .darkBackground illustration.contentMode = .scaleAspectFill message.text = S.Import.importMessage leftCaption.text = S.Import.leftCaption leftCaption.textAlignment = .center rightCaption.text = S.Import.rightCaption rightCaption.textAlignment = .center warning.text = S.Import.importWarning // Set up the tap handler for the "Scan Private Key" button. button.tap = strongify(self) { myself in let scan = ScanViewController(forScanningPrivateKeysOnly: true) { result in guard let result = result else { return } myself.handleScanResult(result) } myself.parent?.present(scan, animated: true, completion: nil) } } private func handleScanResult(_ result: QRCode) { switch result { case .privateKey(let key): didReceiveAddress(key) case .gift(let key, let model): didReceiveAddress(key) self.viewModel = model default: break } } private func didReceiveAddress(_ address: String) { guard !Key.isProtected(asPrivate: address) else { return unlock(address: address) { self.createTransaction(withPrivKey: $0) } } guard let key = Key.createFromString(asPrivate: address) else { showErrorMessage(S.Import.Error.notValid) return } createTransaction(withPrivKey: key) } private func createTransaction(withPrivKey key: Key) { present(balanceActivity, animated: true, completion: nil) wallet.createSweeper(forKey: key) { result in DispatchQueue.main.async { self.balanceActivity.dismiss(animated: true) { switch result { case .success(let sweeper): self.importFrom(sweeper) case .failure(let error): self.handleError(error) } } } } } private func importFrom(_ sweeper: WalletSweeper) { guard let balance = sweeper.balance else { return self.showErrorMessage(S.Import.Error.empty) } let balanceAmount = Amount(cryptoAmount: balance, currency: wallet.currency) guard !balanceAmount.isZero else { return self.showErrorMessage(S.Import.Error.empty) } sweeper.estimate(fee: wallet.feeForLevel(level: .regular)) { result in DispatchQueue.main.async { switch result { case .success(let feeBasis): self.confirmImport(fromSweeper: sweeper, fee: feeBasis) case .failure(let error): self.handleEstimateFeeError(error) } } } } private func confirmImport(fromSweeper sweeper: WalletSweeper, fee: TransferFeeBasis) { let balanceAmount = Amount(cryptoAmount: sweeper.balance!, currency: wallet.currency) let feeAmount = Amount(cryptoAmount: fee.fee, currency: wallet.currency) let balanceText = "\(balanceAmount.fiatDescription) (\(balanceAmount.description))" let feeText = "\(feeAmount.fiatDescription)" let message = String(format: S.Import.confirm, balanceText, feeText) let alert = UIAlertController(title: S.Import.title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: S.Import.importButton, style: .default, handler: { _ in self.present(self.importingActivity, animated: true) self.submit(sweeper: sweeper, fee: fee) })) present(alert, animated: true) } private func submit(sweeper: WalletSweeper, fee: TransferFeeBasis) { guard let transfer = sweeper.submit(estimatedFeeBasis: fee) else { importingActivity.dismiss(animated: true) return showErrorMessage(S.Alerts.sendFailure) } wallet.subscribe(self) { event in guard case .transferSubmitted(let eventTransfer, let success) = event, eventTransfer.hash == transfer.hash else { return } DispatchQueue.main.async { self.importingActivity.dismiss(animated: true) { guard success else { return self.showErrorMessage(S.Import.Error.failedSubmit) } self.markAsReclaimed() self.showSuccess() } } } } private func markAsReclaimed() { guard let kvStore = Backend.kvStore else { return assertionFailure() } guard let viewModel = viewModel else { return assertionFailure() } guard let gift = viewModel.gift else { return assertionFailure() } let newGift = Gift(shared: gift.shared, claimed: gift.claimed, reclaimed: true, txnHash: gift.txnHash, keyData: gift.keyData, name: gift.name, rate: gift.rate, amount: gift.amount) viewModel.tx.updateGiftStatus(gift: newGift, kvStore: kvStore) if let hash = newGift.txnHash { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { Store.trigger(name: .txMetaDataUpdated(hash)) } } } private func handleError(_ error: WalletSweeperError) { switch error { case .unsupportedCurrency: showErrorMessage(S.Import.Error.unsupportedCurrency) case .invalidKey: showErrorMessage(S.Send.invalidAddressTitle) case .invalidSourceWallet: showErrorMessage(S.Send.invalidAddressTitle) case .insufficientFunds: showErrorMessage(S.Send.insufficientFunds) case .unableToSweep: showErrorMessage(S.Import.Error.sweepError) case .noTransfersFound: showErrorMessage(S.Import.Error.empty) case .unexpectedError: showErrorMessage(S.Alert.somethingWentWrong) case .queryError(let error): showErrorMessage(error.localizedDescription) } } private func handleEstimateFeeError(_ error: WalletKit.Wallet.FeeEstimationError) { switch error { case .InsufficientFunds: showErrorMessage(S.Send.insufficientFunds) case .ServiceError: showErrorMessage(S.Import.Error.serviceError) case .ServiceUnavailable: showErrorMessage(S.Import.Error.serviceUnavailable) } } private func unlock(address: String, callback: @escaping (Key) -> Void) { let alert = UIAlertController(title: S.Import.title, message: S.Import.password, preferredStyle: .alert) alert.addTextField(configurationHandler: { textField in textField.placeholder = S.Import.passwordPlaceholder textField.isSecureTextEntry = true textField.returnKeyType = .done }) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: S.Button.ok, style: .default, handler: { _ in self.unlock(alert: alert, address: address, callback: callback) })) present(alert, animated: true) } private func unlock(alert: UIAlertController, address: String, callback: @escaping (Key) -> Void) { present(self.unlockingActivity, animated: true, completion: { guard let password = alert.textFields?.first?.text, let key = Key.createFromString(asPrivate: address, withPassphrase: password) else { self.unlockingActivity.dismiss(animated: true, completion: { self.showErrorMessage(S.Import.wrongPassword) }) return } self.unlockingActivity.dismiss(animated: true, completion: { callback(key) }) }) } private func showSuccess() { Store.perform(action: Alert.Show(.sweepSuccess(callback: { [weak self] in guard let myself = self else { return } myself.dismiss(animated: true) }))) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
667027b1208286ad7f7fb3dc83167458
43.293939
112
0.635425
false
false
false
false
KenHeglund/Mustang
refs/heads/master
MustangApp/Mustang/Entity.swift
mit
1
/*=========================================================================== Entity.swift Mustang Copyright (c) 2020 OrderedBytes. All rights reserved. ===========================================================================*/ import Foundation enum Entity { /*==========================================================================*/ enum UsagePage { static let entityName = "UsagePageEntity" static let usagePageKey = "usagePage" static let nameKey = "name" static let usageNameFormatKey = "usageNameFormat" static let usagesKey = "usages" } /*==========================================================================*/ enum Usage { static let entityName = "UsageEntity" static let usageKey = "usage" static let nameKey = "name" static let usagePageKey = "usagePage" static let collectionTypeKey = "collectionType" } }
fa1f17d567a3364484f8154a683b7e93
29.75
79
0.465738
false
false
false
false
someoneAnyone/Nightscouter
refs/heads/dev
Common/Views/CompassControl.swift
mit
1
// // CompassView.swift // Nightscout Watch Face // // Created by Peter Ina on 4/30/15. // Copyright (c) 2015 Peter Ina. All rights reserved. // import UIKit @IBDesignable public class CompassControl: UIView { @IBInspectable open var sgvText:String = "---" { didSet{ setNeedsDisplay() } } @objc var angle: CGFloat = 0 @objc var isUncomputable = false @objc var isDoubleUp = false @objc var isArrowVisible = false @IBInspectable open var color: UIColor = NSAssetKit.predefinedNeutralColor { didSet { setNeedsDisplay() } } open override var intrinsicContentSize : CGSize { super.invalidateIntrinsicContentSize() let compactSize = CGSize(width: 156, height: 120) let midSize = CGSize(width: 156, height: 140) let fullSize = CGSize(width: 156, height: 200) switch direction { case .none, .NotComputable, .Not_Computable: return compactSize case .FortyFiveUp, .FortyFiveDown, .Flat: return compactSize case .SingleUp, .SingleDown: return midSize default: return fullSize } } @objc var animationValue: CGFloat = 0 @IBInspectable open var delta: String = "- --/--" { didSet{ setNeedsDisplay() } } open var direction: Direction = .none { didSet { switch direction { case .none: configireDrawRect(isArrowVisible: false) case .DoubleUp: configireDrawRect(true) case .SingleUp: configireDrawRect() case .FortyFiveUp: configireDrawRect(angle:-45) case .Flat: configireDrawRect(angle:-90) case .FortyFiveDown: configireDrawRect(angle:-120) case .SingleDown: configireDrawRect(angle:-180) case .DoubleDown: configireDrawRect(true, angle: -180) case .NotComputable, .Not_Computable: configireDrawRect(isArrowVisible: false, isUncomputable: true) case .RateOutOfRange: configireDrawRect(isArrowVisible: false, isUncomputable: true, sgvText: direction.description) } invalidateIntrinsicContentSize() setNeedsDisplay() } } } // MARK: - Lifecycle public extension CompassControl { override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.clear isAccessibilityElement = true setNeedsDisplay() } override func draw(_ rect: CGRect) { NSAssetKit.drawTextBlock(frame: rect, arrowTintColor: self.color, sgvText: self.sgvText, bg_delta: self.delta, textSizeForSgv: 39, textSizeForDelta: 12) if self.isUncomputable { NSAssetKit.drawUncomputedCircle(rect, arrowTintColor:self.color, isUncomputable: self.isUncomputable, computeAnimation: self.animationValue) } else { NSAssetKit.drawWatchFaceOnly(rect, arrowTintColor: self.color, angle: self.angle, isArrowVisible: self.isArrowVisible, doubleUp: self.isDoubleUp) } accessibilityHint = "Glucose Value of \(sgvText) with a delta of \(delta), with the following direction \(direction)" } } // MARK: - Methods public extension CompassControl { func configireDrawRect( _ isDoubleUp:Bool = false, isArrowVisible:Bool = true, isUncomputable:Bool = false, angle:CGFloat?=0, sgvText:String?=nil ){ self.isDoubleUp = isDoubleUp self.isArrowVisible = isArrowVisible self.isUncomputable = isUncomputable self.angle = angle! if (sgvText != nil) { self.sgvText = sgvText! } } @objc func takeSnapshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale) drawHierarchy(in: self.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } // MARK: - Delegate Methods public extension CompassControl { } // MARK: - Actions public extension CompassControl { }
40a65968009cfaf03779ff379155e80d
29.475862
160
0.602172
false
true
false
false
CodePath2017Group4/travel-app
refs/heads/master
RoadTripPlanner/TripDetailsViewController.swift
mit
1
// // TripsDetailsViewController.swift // RoadTripPlanner // // Created by Deepthy on 10/12/17. // Copyright © 2017 Deepthy. All rights reserved. // import UIKit import Parse import ParseUI import AFNetworking import MessageUI import MapKit class TripDetailsViewController: UIViewController { @IBOutlet weak var coverPhotoImageView: PFImageView! @IBOutlet weak var tripNameLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var profileImageView: PFImageView! @IBOutlet weak var tripDateLabel: UILabel! @IBOutlet weak var emailGroupImageView: UIImageView! @IBOutlet weak var editTableButton: UIButton! @IBOutlet weak var addStopButton: UIButton! @IBOutlet weak var addFriendsButton: UIButton! @IBOutlet weak var viewOnMapButton: UIButton! @IBOutlet weak var tripSettingsImageView: UIImageView! @IBOutlet weak var albumImageView: UIImageView! var trip: Trip? static func storyboardInstance() -> TripDetailsViewController? { let storyboard = UIStoryboard(name: String(describing: self), bundle: nil) return storyboard.instantiateInitialViewController() as? TripDetailsViewController } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 120 tableView.separatorStyle = .none profileImageView.layer.cornerRadius = profileImageView.frame.size.height / 2 profileImageView.clipsToBounds = true profileImageView.layer.borderColor = UIColor.white.cgColor profileImageView.layer.borderWidth = 3.0 // Make the navigation bar completely transparent. navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.isTranslucent = true navigationController?.navigationBar.tintColor = Constants.Colors.ColorPalette3314Color4 let textAttributes = [NSForegroundColorAttributeName:Constants.Colors.ColorPalette3314Color4] navigationController?.navigationBar.titleTextAttributes = textAttributes navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "md_settings"), style: .plain, target: self, action: #selector(tripSettingButtonPressed(_:))) navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "md_home"), style: .plain, target: self, action: #selector(homeButtonPressed(_:))) registerForNotifications() guard let trip = trip else { return } setUserInterfaceValues(trip: trip) } fileprivate func setUserInterfaceValues(trip: Trip) { let creator = trip.creator let tripDate = trip.date tripDateLabel.text = Utils.formatDate(date: tripDate) let avatarFile = creator.object(forKey: "avatar") as? PFFile if avatarFile != nil { profileImageView.file = avatarFile profileImageView.loadInBackground() } tripNameLabel.text = trip.name if let coverPhotoFile = trip.coverPhoto { coverPhotoImageView.file = coverPhotoFile coverPhotoImageView.loadInBackground() } tableView.reloadData() } fileprivate func registerForNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(TripDetailsViewController.tripWasModified(notification:)), name: Constants.NotificationNames.TripModifiedNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } func tripWasModified(notification: NSNotification) { let info = notification.userInfo let trip = info!["trip"] as! Trip setUserInterfaceValues(trip: trip) } fileprivate func loadLandmarkImageFromDesitination(location: CLLocation) { YelpFusionClient.sharedInstance.search(withLocation: location, term: "landmarks", completion: { (businesses, error) in if error == nil { guard let results = businesses else { return } log.verbose("num landmark results: \(results.count)") let randomIndex = Int(arc4random_uniform(UInt32(results.count))) let b = results[randomIndex] if let imageURL = b.imageURL { log.info(imageURL) let imageRequest = URLRequest(url: imageURL) self.coverPhotoImageView.setImageWith(imageRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) in if imageResponse != nil { self.coverPhotoImageView.alpha = 0.0 self.coverPhotoImageView.image = image let coverImageFile = Utils.imageToFile(image: image)! self.trip?.setCoverPhoto(file: coverImageFile) self.trip?.saveInBackground() UIView.animate(withDuration: 0.3, animations: { self.coverPhotoImageView.alpha = 0.8 }) } }, failure: { (request, response, error) in self.coverPhotoImageView.image = #imageLiteral(resourceName: "trip_placeholder") log.error(error) }) } } else { log.error(error ?? "unknown error occurred") self.coverPhotoImageView.image = #imageLiteral(resourceName: "trip_placeholder") } }) } fileprivate func setTripCoverPhoto() { let destination = trip?.segments?.last destination?.fetchInBackground(block: { (object, error) in if error == nil { let location = CLLocation(latitude: (destination?.geoPoint?.latitude)!, longitude: (destination?.geoPoint?.longitude)!) self.loadLandmarkImageFromDesitination(location: location) } else { log.error(error!) } }) } fileprivate func saveChanges() { guard let trip = self.trip else { return } trip.saveInBackground(block: { (success, error) in if error == nil { log.info("Trip save success: \(success)") } else { log.error("Error saving trip: \(error!)") } }) } // MARK: - IBAction methods @IBAction func editButtonPressed(_ sender: Any) { if tableView.isEditing { tableView.setEditing(false, animated: true) editTableButton.setTitle(" Edit", for: .normal) editTableButton.setTitleColor(UIColor.white, for: .normal) saveChanges() } else { tableView.setEditing(true, animated: true) editTableButton.setTitle(" Done", for: .normal) let doneColor = UIColor(red: 234/255.0, green: 76/255.0, blue: 28/255.0, alpha: 1) editTableButton.setTitleColor(doneColor, for: .normal) } // Disable other buttons if we are editing the table. addStopButton.isEnabled = !tableView.isEditing addFriendsButton.isEnabled = !tableView.isEditing viewOnMapButton.isEnabled = !tableView.isEditing } @IBAction func tripSettingButtonPressed(_ sender: Any) { showAlertController() } @IBAction func homeButtonPressed(_ sender: Any) { // Unwind to the root view controller. navigationController?.popToRootViewController(animated: true) } @IBAction func mapButtonPressed(_ sender: Any) { // Create a locations array from the trip segments. Locations array consists of tuples of UITextFields and MKMapItem objects. guard let trip = trip else { return } var locations: [(textField: UITextField?, mapItem: MKMapItem?)] = [] if let segments = trip.segments { for segment in segments { let address = segment.address let lat = segment.geoPoint?.latitude let lng = segment.geoPoint?.longitude let location = CLLocation(latitude: lat!, longitude: lng!) let placemark = MKPlacemark(coordinate: location.coordinate) let mapItem = MKMapItem(placemark: placemark) as MKMapItem? let textField = UITextField(frame: CGRect.zero) as UITextField? textField?.text = address let tuple = (textField: textField, mapItem: mapItem) locations.append(tuple) } } // Launch the map screen. let storyboard = UIStoryboard(name: "Main", bundle: nil) let routeMapViewController = storyboard.instantiateViewController(withIdentifier: "RouteMapView") as! RouteMapViewController routeMapViewController.trip = trip routeMapViewController.locationArray = locations routeMapViewController.termCategory = ["restaurant" : ["restaurant"]] routeMapViewController.loadTripOnMap = true navigationController?.pushViewController(routeMapViewController, animated: true) } @IBAction func addFriendsButtonPressed(_ sender: Any) { guard let friendsVC = FriendsListViewController.storyboardInstance() else { return } friendsVC.trip = trip navigationController?.pushViewController(friendsVC, animated: true) } @IBAction func addStopButtonPressed(_ sender: Any) { // Present the AddStopViewController modally. guard let addStopVC = AddStopViewController.storyboardInstance() else { return } addStopVC.trip = trip present(addStopVC, animated: true, completion: nil) } func emailImageTapped(_ sender: AnyObject) { let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.present(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setToRecipients([]) if #available(iOS 11.0, *) { let fromEmail = trip?.creator.email != nil ? "\((trip?.creator.email)!)" : "" mailComposerVC.setPreferredSendingEmailAddress("\(fromEmail)") } var emailSubject = User.currentUser?.userName != nil ? "\((User.currentUser?.userName)!)'s" :"" emailSubject += trip?.name != nil ? "\((trip?.name)!)" : "My Road Trip" mailComposerVC.setSubject("\(emailSubject) !") mailComposerVC.setMessageBody("\(Constants.PrefabricatedEmailMessage.TripInvitationEmail)", isHTML: true) return mailComposerVC } func showSendMailErrorAlert() { let alert = UIAlertController( title: "Could Not Send Email", message: "Your device could not send Email. Please check Email configuration and try again.", preferredStyle: .alert ) let okAction = UIAlertAction( title: "OK", style: .default, handler: nil ) alert.addAction(okAction) present( alert, animated: true, completion: nil ) } // MARK: - UIAlertController action sheet func showAlertController() { let alert = UIAlertController() alert.addAction(UIAlertAction(title: NSLocalizedString("Trip Settings", comment: "Default action"), style: .`default`, handler: { _ in log.verbose("Trip Settings selected") self.showSettings() })) // alert.addAction(UIAlertAction(title: "Write a Review", style: .default, handler: { _ in // log.verbose("Review selected") // })) alert.addAction(UIAlertAction(title: "Delete Trip", style: .destructive, handler: { _ in log.verbose("Delete Trip selected") self.deleteTrip() })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in log.verbose("Cancel selected") })) self.present(alert, animated: true, completion: nil) } // MARK: - Action sheet action handlers func showSettings() { guard let settingsVC = TripSettingsViewController.storyboardInstance() else { return } settingsVC.trip = trip navigationController?.pushViewController(settingsVC, animated: true) } func deleteTrip() { // Confirm they want the trip deleted. let alert = UIAlertController(title: "Delete Trip?", message: "Are you sure you would like to delete this trip?", preferredStyle: .alert) let noAction = UIAlertAction(title: "No", style: .default, handler: { _ in log.verbose("No selected") }) let confirmAction = UIAlertAction(title: "I'm Sure!", style: .default, handler: { _ in log.verbose("Delete confirmed") self.trip?.deleteInBackground(block: { (success, error) in if error == nil { log.info("Trip deletion success: \(success)") if success { // Post a notification that the trip has been deleted. NotificationCenter.default.post(name: Constants.NotificationNames.TripDeletedNotification, object: nil, userInfo: ["trip": self.trip!]) // Return to the previous screen. self.navigationController?.popViewController(animated: true) } } else { log.error("Error deleting trip: \(error!)") } }) }) alert.addAction(noAction) alert.addAction(confirmAction) alert.preferredAction = noAction self.present(alert, animated: true, completion: nil) } } // MARK: - UITableViewDelegate, UITableViewDataSource extension TripDetailsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let trip = self.trip else { return 0 } guard let segments = trip.segments else { return 0 } return segments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.ReuseableCellIdentifiers.TripSegmentCell, for: indexPath) as! TripSegmentCell cell.tripSegment = trip?.segments?[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 68 } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Let all cells be reordered. return true } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { guard let trip = self.trip else { return } guard var segments = trip.segments else { return } let tripSegmentToMove = segments[sourceIndexPath.row] segments.remove(at: sourceIndexPath.row) segments.insert(tripSegmentToMove, at: destinationIndexPath.row) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { guard let trip = self.trip else { return } if editingStyle == .delete { tableView.beginUpdates() // Remove the segment from the segments array. trip.deleteSegment(atIndex: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) tableView.endUpdates() saveChanges() // Post a notification that the trip has been modified NotificationCenter.default.post(name: Constants.NotificationNames.TripModifiedNotification, object: nil, userInfo: ["trip": trip]) } } } // MARK: - TripDetailsCellDelegate extension TripDetailsViewController: TripDetailsCellDelegate { func tripDetailsCell(tripDetailsCell: TripDetailsCell, didComment tripStopLabel: UILabel) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let compmentsViewController = storyboard.instantiateViewController(withIdentifier: "compose") as! CommentsViewController self.navigationController?.pushViewController(compmentsViewController, animated: true) } } extension TripDetailsViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } }
eff48d263b6f2e843cebee9661dbc6a3
38.624724
188
0.615209
false
false
false
false
mercadopago/px-ios
refs/heads/develop
MercadoPagoSDK/MercadoPagoSDK/LaytoutExtension/Dimension/AnchorDimension.swift
mit
1
import UIKit final class AnchorDimension: AnchorDimensionComposing { let anchor: NSLayoutDimension let type: AnchorType let root: AnchoringRoot init( anchor: NSLayoutDimension, root: AnchoringRoot, type: AnchorType ) { self.anchor = anchor self.type = type self.root = root self.root.translatesAutoresizingMaskIntoConstraints = false } @discardableResult func equalTo( _ otherConstraint: AnchorDimension, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { let constraint = anchor.constraint( equalTo: otherConstraint.anchor, multiplier: multiplier, constant: constant ) return prepare(constraint, with: priority) } @discardableResult func lessThanOrEqualTo( _ otherConstraint: AnchorDimension, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { let constraint = anchor.constraint( lessThanOrEqualTo: otherConstraint.anchor, multiplier: multiplier, constant: constant ) return prepare(constraint, with: priority) } @discardableResult func greaterThanOrEqualTo( _ otherConstraint: AnchorDimension, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { let constraint = anchor.constraint( greaterThanOrEqualTo: otherConstraint.anchor, multiplier: multiplier, constant: constant ) return prepare(constraint, with: priority) } @discardableResult func equalTo( constant: CGFloat, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { let constraint = anchor.constraint(equalToConstant: constant) return prepare(constraint, with: priority) } @discardableResult func lessThanOrEqualTo( constant: CGFloat, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { let constraint = anchor.constraint(lessThanOrEqualToConstant: constant) return prepare(constraint, with: priority) } @discardableResult func greaterThanOrEqualTo( constant: CGFloat, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { let constraint = anchor.constraint(greaterThanOrEqualToConstant: constant) return prepare(constraint, with: priority) } @discardableResult func equalTo( _ root: AnchoringRoot, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { equalTo( anchorFor(root: root), multiplier: multiplier, constant: constant, priority: priority ) } @discardableResult func lessThanOrEqualTo( _ root: AnchoringRoot, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { lessThanOrEqualTo( anchorFor(root: root), multiplier: multiplier, constant: constant, priority: priority ) } @discardableResult func greaterThanOrEqualTo( _ root: AnchoringRoot, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { greaterThanOrEqualTo( anchorFor(root: root), multiplier: multiplier, constant: constant, priority: priority ) } } private extension AnchorDimension { func anchorFor(root: AnchoringRoot) -> AnchorDimension { switch type { case .width: return root.width case .height: return root.height default: preconditionFailure("Could not resolve \(type) anchor for this root \(root)") } } func prepare( _ constraint: NSLayoutConstraint, with priority: UILayoutPriority ) -> NSLayoutConstraint { constraint.priority = priority constraint.isActive = true return constraint } }
5cfc4f18fbc0d29e82ee026a6adcd6b3
27.55414
89
0.611421
false
false
false
false
EmberTown/ember-hearth
refs/heads/master
Ember Hearth/Terminal.swift
mit
1
// // Terminal.swift // Ember Hearth // // Created by Thomas Sunde Nielsen on 29.03.15. // Copyright (c) 2015 Thomas Sunde Nielsen. All rights reserved. // import Cocoa enum InstallMethod: String { case Hearth = "Hearth" case NPM = "NPM" case Bower = "Bower" case Brew = "Homebrew" case Unknown = "Unknown" case NotInstalled = "Not installed" } public class Terminal { private var task: NSTask? private var output: NSPipe? public var workingDirectory: String? public init() { } func taskForCommand (command: String) -> NSTask { var task = NSTask() task.launchPath = "/bin/bash" task.arguments = ["-l", "-c", command] return task } public func runTerminalCommandSync (command: String) -> String? { var task = taskForCommand(command) var findOut = NSPipe() task.standardOutput = findOut task.launch() task.waitUntilExit() let outData = findOut.fileHandleForReading.readDataToEndOfFile() let result = NSString(data: outData, encoding: NSASCIIStringEncoding) if task.terminationStatus == 0 { return result as? String } return nil } public func runTerminalCommandAsync (command: String, completion: (result: String?) -> ()) -> NSTask? { return self.runTerminalCommandAsync(command, showOutput: true, completion: completion) } public func runTerminalCommandAsync (command: String, showOutput:Bool, completion: (result: String?) -> ()) -> NSTask? { self.task = taskForCommand(command) if self.workingDirectory != nil { self.task?.currentDirectoryPath = self.workingDirectory! } if showOutput { self.output = NSPipe() self.task?.standardOutput = self.output! } self.task?.terminationHandler = { (task: NSTask!) in if task.terminationStatus != 0 { completion(result: nil) } else { let outData = self.output?.fileHandleForReading.readDataToEndOfFile() var result: NSString = "" if outData != nil { if let string = NSString(data: outData!, encoding: NSASCIIStringEncoding) { result = string } } dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(result: result as String) }) } self.task = nil self.output = nil } self.task?.launch() return self.task } public func runTerminalCommandInTerminalApp(command:String, path:String) { NSAppleScript(source: "tell application \"Terminal\"\n" + " do script \"cd '\(path)' && \(command)\"\n" + " activate\n" + "end tell" )?.executeAndReturnError(nil) } }
d88880cc6f71907ae7002d2eecd86395
30.464646
124
0.54382
false
false
false
false
getwagit/Baya
refs/heads/master
Baya/layouts/BayaLinearLayout.swift
mit
1
// // Copyright (c) 2016-2017 wag it GmbH. // License: MIT // import Foundation import UIKit /** A simple layout that places children in a linear order. This Layout respects the margins of its children. */ public struct BayaLinearLayout: BayaLayout, BayaLayoutIterator { public var bayaMargins: UIEdgeInsets public var frame: CGRect var orientation: BayaLayoutOptions.Orientation var spacing: CGFloat private var elements: [BayaLayoutable] private var measures = [CGSize]() init( elements: [BayaLayoutable], orientation: BayaLayoutOptions.Orientation, spacing: CGFloat = 0, bayaMargins: UIEdgeInsets) { self.elements = elements self.orientation = orientation self.bayaMargins = bayaMargins self.spacing = spacing self.frame = CGRect() } mutating public func layoutWith(frame: CGRect) { self.frame = frame guard elements.count > 0 else { return } let measures = measureIfNecessary(&elements, cache: self.measures, size: frame.size) switch orientation { case .horizontal: iterate(&elements, measures) { e1, e2, e2s in let size = BayaLinearLayout.calculateSizeForLayout( withOrientation: .horizontal, forChild: e2, cachedSize: e2s, ownSize: frame.size) let origin: CGPoint if let e1 = e1 { origin = CGPoint( x: e1.frame.maxX + e1.bayaMargins.right + spacing + e2.bayaMargins.left, y: frame.minY + e2.bayaMargins.top) } else { origin = CGPoint( x: frame.minX + e2.bayaMargins.left, y: frame.minY + e2.bayaMargins.top) } return CGRect(origin: origin, size: size) } case .vertical: iterate(&elements, measures) { e1, e2, e2s in let size = BayaLinearLayout.calculateSizeForLayout( withOrientation: .vertical, forChild: e2, cachedSize: e2s, ownSize: frame.size) let origin: CGPoint if let e1 = e1 { origin = CGPoint( x: frame.minX + e2.bayaMargins.left, y: e1.frame.maxY + e1.bayaMargins.bottom + spacing + e2.bayaMargins.top) } else { origin = CGPoint( x: frame.minX + e2.bayaMargins.left, y: frame.minY + e2.bayaMargins.top) } return CGRect(origin: origin, size: size) } } } mutating public func sizeThatFits(_ size: CGSize) -> CGSize { measures = measure(&elements, size: size) var resultSize: CGSize = CGSize() switch orientation { case .horizontal: let elementCount = elements.count resultSize.width = elementCount > 1 ? (CGFloat(elementCount - 1) * spacing) : 0 for i in 0..<elements.count { let fit = measures[i] let element = elements[i] resultSize.width += fit.width + element.bayaMargins.left + element.bayaMargins.right resultSize.height = max( resultSize.height, fit.height + element.bayaMargins.top + element.bayaMargins.bottom) } case .vertical: let elementCount = elements.count resultSize.height = elementCount > 1 ? (CGFloat(elementCount - 1) * spacing) : 0 for i in 0..<elements.count { let fit = measures[i] let element = elements[i] resultSize.width = max( resultSize.width, fit.width + element.bayaMargins.left + element.bayaMargins.right) resultSize.height += fit.height + element.bayaMargins.top + element.bayaMargins.bottom } } return resultSize } private static func calculateSizeForLayout( withOrientation orientation: BayaLayoutOptions.Orientation, forChild element: BayaLayoutable, cachedSize: CGSize, ownSize availableSize: CGSize) -> CGSize { switch orientation { case .horizontal: guard element.bayaModes.height == .matchParent else { return cachedSize } return CGSize( width: cachedSize.width, height: availableSize.height - element.verticalMargins) case .vertical: guard element.bayaModes.width == .matchParent else { return cachedSize } return CGSize( width: availableSize.width - element.horizontalMargins, height: cachedSize.height) } } } public extension Sequence where Iterator.Element: BayaLayoutable { /// Aligns all elements in a single direction. /// - parameter orientation: Determines if the elements should be laid out in horizontal or vertical direction. /// - parameter spacing: The gap between the elements. /// - parameter bayaMargins: The layout's margins. /// - returns: A `BayaLinearLayout`. func layoutLinearly( orientation: BayaLayoutOptions.Orientation, spacing: CGFloat = 0, bayaMargins: UIEdgeInsets = UIEdgeInsets.zero) -> BayaLinearLayout { return BayaLinearLayout( elements: self.array(), orientation: orientation, spacing: spacing, bayaMargins: bayaMargins) } } public extension Sequence where Iterator.Element == BayaLayoutable { /// Aligns all elements in a single direction. /// - parameter orientation: Determines if the elements should be laid out in horizontal or vertical direction. /// - parameter spacing: The gap between the elements. /// - parameter bayaMargins: The layout's margins. /// - returns: A `BayaLinearLayout`. func layoutLinearly( orientation: BayaLayoutOptions.Orientation, spacing: CGFloat = 0, bayaMargins: UIEdgeInsets = UIEdgeInsets.zero) -> BayaLinearLayout { return BayaLinearLayout( elements: self.array(), orientation: orientation, spacing: spacing, bayaMargins: bayaMargins) } }
716f5567596b5bbf68efa4e01d127478
36.821229
115
0.553176
false
false
false
false
jessesquires/JSQCoreDataKit
refs/heads/main
Example/ExampleModel/ExampleModel/Employee.swift
mit
1
// // Created by Jesse Squires // https://www.jessesquires.com // // // Documentation // https://jessesquires.github.io/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015-present Jesse Squires // Released under an MIT license: https://opensource.org/licenses/MIT // import CoreData import Foundation import JSQCoreDataKit public final class Employee: NSManagedObject, CoreDataEntityProtocol { // MARK: CoreDataEntityProtocol public static let defaultSortDescriptors = [ NSSortDescriptor(key: "name", ascending: true) ] // MARK: Properties @NSManaged public var name: String @NSManaged public var birthDate: Date @NSManaged public var salary: NSDecimalNumber @NSManaged public var company: Company? // MARK: Init public init(context: NSManagedObjectContext, name: String, birthDate: Date, salary: NSDecimalNumber, company: Company? = nil) { super.init(entity: Self.entity(context: context), insertInto: context) self.name = name self.birthDate = birthDate self.salary = salary self.company = company } @objc override private init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { super.init(entity: entity, insertInto: context) } public static func newEmployee(_ context: NSManagedObjectContext, company: Company? = nil) -> Employee { let name = "Employee " + String(UUID().uuidString.split { $0 == "-" }.first!) return Employee(context: context, name: name, birthDate: Date.distantPast, salary: NSDecimalNumber(value: Int.random(in: 0...100_000)), company: company) } public static func fetchRequest(for company: Company) -> NSFetchRequest<Employee> { let fetch = self.fetchRequest fetch.predicate = NSPredicate(format: "company == %@", company) return fetch } }
89b8c410a18856647e22abae79cb4660
29.318841
108
0.639579
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Components/WalletBalanceView/WalletBalanceViewPresenter.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import ComposableArchitectureExtensions import PlatformKit import RxCocoa import RxRelay import RxSwift public final class WalletBalanceViewPresenter { typealias AccessibilityId = Accessibility.Identifier.Activity.WalletBalance public typealias PresentationState = LoadingState<WalletBalance> public struct WalletBalance { /// The balance in fiat public let fiatBalance: LabelContent /// The fiat currency code public let currencyCode: LabelContent /// Descriptors that allows customized content and style public struct Descriptors { let fiatFont: UIFont let fiatTextColor: UIColor let descriptionFont: UIFont let descriptionTextColor: UIColor public init( fiatFont: UIFont, fiatTextColor: UIColor, descriptionFont: UIFont, descriptionTextColor: UIColor ) { self.fiatFont = fiatFont self.fiatTextColor = fiatTextColor self.descriptionFont = descriptionFont self.descriptionTextColor = descriptionTextColor } } // MARK: - Setup public init( with value: WalletBalanceViewInteractor.WalletBalance, descriptors: Descriptors = .default ) { fiatBalance = LabelContent( text: value.fiatValue.displayString, font: descriptors.fiatFont, color: descriptors.fiatTextColor, accessibility: .id(AccessibilityId.fiatBalance) ) currencyCode = LabelContent( text: value.fiatCurrency.displayCode, font: descriptors.descriptionFont, color: descriptors.descriptionTextColor, accessibility: .id(AccessibilityId.currencyCode) ) } } // MARK: - Exposed Properties let accessibility: Accessibility = .id(AccessibilityId.view) public var state: Observable<PresentationState> { stateRelay .observe(on: MainScheduler.instance) } var alignment: Driver<UIStackView.Alignment> { alignmentRelay.asDriver() } // MARK: - Injected private let interactor: WalletBalanceViewInteractor // MARK: - Private Accessors private let alignmentRelay = BehaviorRelay<UIStackView.Alignment>(value: .fill) private let stateRelay = BehaviorRelay<PresentationState>(value: .loading) private let disposeBag = DisposeBag() // MARK: - Setup public init( alignment: UIStackView.Alignment = .trailing, interactor: WalletBalanceViewInteractor, descriptors: WalletBalanceViewPresenter.WalletBalance.Descriptors = .default ) { self.interactor = interactor alignmentRelay.accept(alignment) /// Map interaction state into presnetation state /// and bind it to `stateRelay` interactor.state .map { .init(with: $0, descriptors: descriptors) } .bindAndCatch(to: stateRelay) .disposed(by: disposeBag) } } extension WalletBalanceViewPresenter.WalletBalance.Descriptors { public typealias Descriptors = WalletBalanceViewPresenter.WalletBalance.Descriptors public static let `default` = Descriptors( fiatFont: .main(.semibold, 16.0), fiatTextColor: .textFieldText, descriptionFont: .main(.medium, 14.0), descriptionTextColor: .descriptionText ) } extension LoadingState where Content == WalletBalanceViewPresenter.WalletBalance { init( with state: LoadingState<WalletBalanceViewInteractor.WalletBalance>, descriptors: WalletBalanceViewPresenter.WalletBalance.Descriptors ) { switch state { case .loading: self = .loading case .loaded(next: let content): self = .loaded( next: .init( with: content, descriptors: descriptors ) ) } } }
499e39934ead610b7bf24131e3e6b9cc
30.598485
87
0.630065
false
false
false
false
pennlabs/penn-mobile-ios
refs/heads/main
PennMobile/GSR-Booking/Views/GSRGroups/GroupSettingsCell.swift
mit
1
// // GroupSettingsCell.swift // PennMobile // // Created by Rehaan Furniturewala on 10/20/19. // Copyright © 2019 PennLabs. All rights reserved. // import UIKit class GroupSettingsCell: UITableViewCell { static let cellHeight: CGFloat = 100 static let identifier = "gsrGroupSettingsCell" fileprivate var titleLabel: UILabel! fileprivate var descriptionLabel: UILabel! fileprivate var isEnabledSwitch: UISwitch! fileprivate var holderView: UIView! var delegate: GSRGroupIndividualSettingDelegate? var userSetting: GSRGroupIndividualSetting! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupCell(with userSetting: GSRGroupIndividualSetting) { self.userSetting = userSetting if titleLabel == nil || descriptionLabel == nil || isEnabledSwitch == nil { prepareUI() } titleLabel.text = userSetting.title descriptionLabel.text = userSetting.descr isEnabledSwitch.setOn(userSetting.isEnabled, animated: false) } @objc fileprivate func switchValueChanged() { if let delegate = delegate { userSetting.isEnabled = isEnabledSwitch.isOn delegate.updateSetting(setting: userSetting) } } } // MARK: - Setup UI extension GroupSettingsCell { fileprivate func prepareUI() { self.heightAnchor.constraint(equalToConstant: GroupSettingsCell.cellHeight).isActive = true prepareHolderView() prepareTitleLabel() prepareDescriptionLabel() prepareIsEnabledSwitch() titleLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -100).isActive = true // backgroundColor = .uiBackgroundSecondary } fileprivate func prepareHolderView() { holderView = UIView() addSubview(holderView) let inset: CGFloat = 14.0 _ = holderView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: inset, leftConstant: inset, bottomConstant: inset, rightConstant: inset, widthConstant: 0, heightConstant: 0) } fileprivate func prepareTitleLabel() { titleLabel = UILabel() holderView.addSubview(titleLabel) _ = titleLabel.anchor(holderView.topAnchor, left: holderView.leftAnchor, bottom: nil, right: holderView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 30) titleLabel.font = UIFont.systemFont(ofSize: 17.0, weight: .regular) } fileprivate func prepareDescriptionLabel() { descriptionLabel = UILabel() holderView.addSubview(descriptionLabel) _ = descriptionLabel.anchor(titleLabel.bottomAnchor, left: titleLabel.leftAnchor, bottom: holderView.bottomAnchor, right: titleLabel.rightAnchor, topConstant: 5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) descriptionLabel.numberOfLines = 3 descriptionLabel.textColor = UIColor.init(r: 153, g: 153, b: 153) descriptionLabel.font = UIFont.systemFont(ofSize: 14.0, weight: .light) } fileprivate func prepareIsEnabledSwitch() { isEnabledSwitch = UISwitch() holderView.addSubview(isEnabledSwitch) _ = isEnabledSwitch.anchor(titleLabel.topAnchor, left: nil, bottom: nil, right: holderView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 51, heightConstant: 0) isEnabledSwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) } }
ec04a857e1816db15dd4fdaa06a07853
38.479167
260
0.708443
false
false
false
false
ashare80/RVTTextScannerView
refs/heads/master
TextScanner/MyScanViewController.swift
bsd-3-clause
1
// // MyScanViewController.swift // PassportOCR // // Created by Edwin Vermeer on 9/7/15. // Copyright (c) 2015 mirabeau. All rights reserved. // import Foundation class MyScanViewController: UIViewController, RVTTextScannerViewDelegate { @IBOutlet weak var textScannerView: RVTTextScannerView! /// Delegate set by the calling controler so that we can pass on ProcessMRZ events. @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() self.textScannerView.delegate = self self.textScannerView.showCropView = true self.textScannerView.cropView?.edgeColor = UIColor.lightGrayColor() self.textScannerView.cropView?.progressColor = UIColor.redColor() self.textScannerView.startScan() } @IBAction func dismiss(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } override func prefersStatusBarHidden() -> Bool { return true } func scannerDidRecognizeText(scanner: RVTTextScannerView, textResult: RVTTextResult, image: UIImage?) { } func scannerDidFindCommontextResult(scanner: RVTTextScannerView, textResult: RVTTextResult, image: UIImage?) { self.label.text = textResult.lines.first self.imageView.image = image print(textResult.text, textResult.lines.first, textResult.whiteSpacedComponents) self.view.layoutIfNeeded() // self.textScannerView.stopScan() // self.dismissViewControllerAnimated(true, completion: nil) } }
5a4c54748dd04039ff592cb017b7be11
31.763636
114
0.694229
false
false
false
false
louisdh/lioness
refs/heads/master
Sources/Lioness/Standard Library/StdLib.swift
mit
1
// // StdLib.swift // Lioness // // Created by Louis D'hauwe on 11/12/2016. // Copyright © 2016 - 2017 Silver Fox. All rights reserved. // import Foundation public class StdLib { private let sources = ["Arithmetic", "Geometry", "Graphics"] public init() { } public func stdLibCode() throws -> String { var stdLib = "" #if SWIFT_PACKAGE // Swift packages don't currently have a resources folder var url = URL(fileURLWithPath: #file) url.deleteLastPathComponent() url.appendPathComponent("Sources") let resourcesPath = url.path #else let bundle = Bundle(for: type(of: self)) guard let resourcesPath = bundle.resourcePath else { throw StdLibError.resourceNotFound } #endif for sourceName in sources { let resourcePath = "\(resourcesPath)/\(sourceName).lion" let source = try String(contentsOfFile: resourcePath, encoding: .utf8) stdLib += source } return stdLib } enum StdLibError: Error { case resourceNotFound } }
c2fa72c22a90910d709ea23f448c36b5
16.305085
73
0.666014
false
false
false
false
merlos/iOS-Open-GPX-Tracker
refs/heads/master
OpenGpxTracker-Watch Extension/GPXFileTableInterfaceController.swift
gpl-3.0
1
// // GPXFileTableInterfaceController.swift // OpenGpxTracker-Watch Extension // // Created by Vincent on 7/2/19. // Copyright © 2019 TransitBox. All rights reserved. // import WatchKit import WatchConnectivity /// Text displayed when there are no GPX files in the folder. let kNoFiles = NSLocalizedString("NO_FILES", comment: "no comment") /// /// WKInterfaceTable that displays the list of files that have been saved in previous sessions. /// /// This interface controller allows users to manage their GPX Files. /// /// Currently the following actions with a file are supported /// /// 1. Send file to iOS App /// 3. Delete the file /// /// It also displays a back button to return to the main controls view. /// class GPXFileTableInterfaceController: WKInterfaceController { /// Main table that displays list of files @IBOutlet var fileTable: WKInterfaceTable! @IBOutlet var progressGroup: WKInterfaceGroup! @IBOutlet var progressTitle: WKInterfaceLabel! @IBOutlet var progressFileName: WKInterfaceLabel! @IBOutlet var progressImageView: WKInterfaceImage! /// List of strings with the filenames. var fileList: NSMutableArray = [kNoFiles] /// Is there any GPX file in the directory? var gpxFilesFound = false /// Temporary variable to manage var selectedRowIndex = -1 /// true if a gpx file will be sent. var willSendFile: Bool { return session?.outstandingFileTransfers.count != 0 } /// To ensure hide animation properly timed. var time = DispatchTime.now() /// Watch communication session private let session: WCSession? = WCSession.isSupported() ? WCSession.default: nil override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. } // MARK: Progress Indicators /// States of sending files enum SendingStatus { /// represents current state as sending case sending /// represents current state as successful case success /// represents current state as failure case failure } /// Hides progress indicator's group, such that group will not appear when not needed. func hideProgressIndicators() { self.progressGroup.setHidden(true) self.progressImageView.stopAnimating() self.progressFileName.setText("") self.progressTitle.setText("") } /// Animate hiding of progress indicator's group, when needed. func hideProgressIndicatorsWithAnimation() { DispatchQueue.main.asyncAfter(deadline: time + 3) { self.animate(withDuration: 1, animations: { self.progressGroup.setHeight(0) }) } // imageview do not have to be set with stop animating, // as image indicator should already have been set as successful or failure image, which is static. } /// Displays progress indicators. /// /// Details like status and filename should be updated accordingly using `updateProgressIndicators(status:fileName:)` func showProgressIndicators() { self.progressGroup.setHeight(30) self.progressGroup.setHidden(false) progressImageView.setImageNamed("Progress-") progressImageView.startAnimatingWithImages(in: NSRange(location: 0, length: 12), duration: 1, repeatCount: 0) } /// Updates progress indicators according to status when sending. /// /// If status is success or failure, method will hide and animate progress indicators when done func updateProgressIndicators(status: SendingStatus, fileName: String?) { switch status { case .sending: progressTitle.setText(NSLocalizedString("SENDING", comment: "no comment")) guard let fileName = fileName else { return } /// count of pending files, does not seem to include the current one let fileTransfersCount = session?.outstandingFileTransfers.count ?? 0 // if there are files pending for sending, filename will not be displayed with the name of file. if fileTransfersCount >= 1 { progressFileName.setText(String(format: NSLocalizedString("X_FILES", comment: "no comment"), fileTransfersCount + 1)) } else { progressFileName.setText(fileName) } case .success: progressImageView.stopAnimating() progressImageView.setImage(UIImage(named: "Progress-success")) progressTitle.setText(NSLocalizedString("SUCCESSFULLY_SENT", comment: "no comment")) hideProgressIndicatorsWithAnimation() case .failure: progressImageView.stopAnimating() progressImageView.setImage(UIImage(named: "Progress-failure")) progressTitle.setText(NSLocalizedString("FAILED_TO_SEND", comment: "no comment")) hideProgressIndicatorsWithAnimation() } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() print("GPXFileTableInterfaceController:: willActivate willSendFile: \(willSendFile)") self.setTitle(NSLocalizedString("YOUR_FILES", comment: "no comment")) session?.delegate = self if willSendFile == true { self.showProgressIndicators() } else { self.hideProgressIndicators() } // get gpx files let list: [GPXFileInfo] = GPXFileManager.fileList if list.count != 0 { self.fileList.removeAllObjects() self.fileList.addObjects(from: list) self.gpxFilesFound = true } loadTableData() } override func didAppear() { session?.delegate = self session?.activate() } override func willDisappear() { } /// Closes this view controller. @objc func closeGPXFilesTableViewController() { print("closeGPXFIlesTableViewController()") } /// Loads data on the table func loadTableData() { fileTable.setNumberOfRows(fileList.count, withRowType: "GPXFile") if gpxFilesFound { for index in 0..<fileTable.numberOfRows { guard let cell = fileTable.rowController(at: index) as? GPXFileTableRowController else { continue } // swiftlint:disable force_cast let gpxFileInfo = fileList.object(at: index) as! GPXFileInfo cell.fileLabel.setText(gpxFileInfo.fileName) } } else { guard let cell = fileTable.rowController(at: 0) as? GPXFileTableRowController else { return } cell.fileLabel.setText(kNoFiles) } } /// Invokes when one of the cells of the table is clicked. override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) { // required, if not, hide group animation will be faster than expected when display the next time. self.time = .now() /// checks if there is any files in directory if gpxFilesFound { /// Option lets user send selected file to iOS app let shareOption = WKAlertAction(title: NSLocalizedString("SEND_TO_IOS", comment: "no comment"), style: .default) { self.actionTransferFileAtIndex(rowIndex) } /// Option for users to cancel let cancelOption = WKAlertAction(title: NSLocalizedString("CANCEL", comment: "no comment"), style: .cancel) { self.actionSheetCancel() } /// Option to delete selected file let deleteOption = WKAlertAction(title: NSLocalizedString("DELETE", comment: "no comment"), style: .destructive) { self.actionDeleteFileAtIndex(rowIndex) self.loadTableData() } /// Array of all available options let options = [shareOption, cancelOption, deleteOption] presentAlert(withTitle: NSLocalizedString("FILE_SELECTED_TITLE", comment: "no comment"), message: NSLocalizedString("FILE_SELECTED_MESSAGE", comment: "no comment"), preferredStyle: .actionSheet, actions: options) } } // // MARK: Action Sheet - Actions // /// Attempts to transfer file to iOS app func actionTransferFileAtIndex(_ rowIndex: Int) { session?.activate() guard let fileURL: URL = (fileList.object(at: rowIndex) as? GPXFileInfo)?.fileURL else { print("GPXFileTableViewController:: actionTransferFileAtIndex: failed to get fileURL") self.hideProgressIndicators() return } // swiftlint:disable force_cast let gpxFileInfo = fileList.object(at: rowIndex) as! GPXFileInfo self.scroll(to: progressGroup, at: .top, animated: true) // scrolls to top when indicator is shown. self.updateProgressIndicators(status: .sending, fileName: gpxFileInfo.fileName) DispatchQueue.global().async { self.session?.transferFile(fileURL, metadata: ["fileName": "\(gpxFileInfo.fileName).gpx"]) } } // Cancel button is tapped. // // Does nothing, it only displays a log message internal func actionSheetCancel() { print("ActionSheet cancel") } /// Deletes from the disk storage the file of `fileList` at `rowIndex` internal func actionDeleteFileAtIndex(_ rowIndex: Int) { guard let fileURL: URL = (fileList.object(at: rowIndex) as? GPXFileInfo)?.fileURL else { print("GPXFileTableViewController:: actionDeleteFileAtIndex: failed to get fileURL") return } GPXFileManager.removeFileFromURL(fileURL) //Delete from list and Table fileList.removeObject(at: rowIndex) } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } } // MARK: WCSessionDelegate /// /// Handles all the file transfer to iOS app processes /// extension GPXFileTableInterfaceController: WCSessionDelegate { func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { let prefixText = "GPXFileTableInterfaceController:: activationDidCompleteWithActivationState:" switch activationState { case .activated: print("\(prefixText) session activated") case .inactive: print("\(prefixText) session inactive") case .notActivated: print("\(prefixText) session not activated, error:\(String(describing: error))") default: print("\(prefixText) default, error:\(String(describing: error))") } } func session(_ session: WCSession, didFinish fileTransfer: WCSessionFileTransfer, error: Error?) { let doneAction = WKAlertAction(title: NSLocalizedString("DONE", comment: "no comment"), style: .default) { } guard let error = error else { print("WCSession: didFinish fileTransfer: \(fileTransfer.file.fileURL.absoluteString)") // presenting success indicator to user if file is successfully transferred // will only present once all files are sent (if multiple in queue) if session.outstandingFileTransfers.count == 1 { self.updateProgressIndicators(status: .success, fileName: nil) } return } // presents indicator first, if file transfer failed, without error message self.updateProgressIndicators(status: .failure, fileName: nil) // presents alert after 1.5s, with error message // MARK: "as CVarArg" was suggested by XCode and my intruduce a bug... DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { self.presentAlert(withTitle: NSLocalizedString("ERROR_OCCURED_TITLE", comment: "no comment"), message: String(format: NSLocalizedString("ERROR_OCCURED_MESSAGE", comment: "no comment"), error as CVarArg), preferredStyle: .alert, actions: [doneAction]) } } }
75983e8d4d98327a1f4f8ee03ea27c32
38.512579
139
0.635018
false
false
false
false
phimage/MomXML
refs/heads/master
Sources/FromXML/MomAttribute+XMLObject.swift
mit
1
// Created by Eric Marchand on 07/06/2017. // Copyright © 2017 Eric Marchand. All rights reserved. // import Foundation extension MomAttribute: XMLObject { public init?(xml: XML) { guard let element = xml.element, element.name == "attribute" else { return nil } guard let name = element.attribute(by: "name")?.text, let attributeTypeString = element.attribute(by: "attributeType")?.text, let attributeType = AttributeType(rawValue: attributeTypeString) else { return nil } self.init(name: name, attributeType: attributeType) self.isOptional = element.attribute(by: "optional")?.text.fromXMLToBool ?? false self.usesScalarValueType = element.attribute(by: "usesScalarValueType")?.text.fromXMLToBool ?? false self.isIndexed = element.attribute(by: "indexed")?.text.fromXMLToBool ?? false self.isTransient = element.attribute(by: "transient")?.text.fromXMLToBool ?? false self.syncable = element.attribute(by: "syncable")?.text.fromXMLToBool ?? false self.isDerived = element.attribute(by: "derived")?.text.fromXMLToBool ?? false self.defaultValueString = element.attribute(by: "defaultValueString")?.text self.defaultDateTimeInterval = element.attribute(by: "defaultDateTimeInterval")?.text self.minValueString = element.attribute(by: "minValueString")?.text self.maxValueString = element.attribute(by: "maxValueString")?.text self.derivationExpression = element.attribute(by: "derivationExpression")?.text self.valueTransformerName = element.attribute(by: "valueTransformerName")?.text for xml in xml.children { if let object = MomUserInfo(xml: xml) { userInfo = object } else { MomXML.orphanCallback?(xml, MomUserInfo.self) } } } }
2d6074d0b4f7b1c869559de88f19fc37
43.395349
108
0.662127
false
false
false
false
5lucky2xiaobin0/PandaTV
refs/heads/master
PandaTV/PandaTV/Classes/Show/Controller/ShowXYanVC.swift
mit
1
// // ShowXYanVC.swift // PandaTV // // Created by 钟斌 on 2017/4/5. // Copyright © 2017年 xiaobin. All rights reserved. // import UIKit import MJRefresh class ShowXYanVC: ShowBasicVC { var showxyanvm : ShowXYanVM = ShowXYanVM() override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() showCollectionView.contentInset = UIEdgeInsets(top: cycleViewH, left: 0, bottom: 0, right: 0) } } extension ShowXYanVC { override func setUI(){ showCollectionView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadData)) showCollectionView.mj_header.ignoredScrollViewContentInsetTop = cycleViewH view.addSubview(showCollectionView) showCollectionView.addSubview(scrollImageView) } } extension ShowXYanVC { override func loadData() { showxyanvm.requestShowData { _ in self.showCollectionView.mj_header.endRefreshing() //判断是否有轮播图片 if self.self.showxyanvm.cycleImageArr.count == 0 { self.scrollImageView.isHidden = true self.showCollectionView.contentInset = UIEdgeInsets.zero self.showCollectionView.mj_header.ignoredScrollViewContentInsetTop = 0 }else { self.scrollImageView.isHidden = false self.showCollectionView.contentInset = UIEdgeInsets(top: cycleViewH, left: 0, bottom: 0, right: 0) self.showCollectionView.mj_header.ignoredScrollViewContentInsetTop = cycleViewH self.scrollImageView.items = self.self.showxyanvm.cycleImageArr } self.showCollectionView.reloadData() self.removeLoadImage() } } } extension ShowXYanVC { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: gameItemW, height: showItemH) } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.showxyanvm.showArr.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: showCell, for: indexPath) as! ShowCell cell.showItem = showxyanvm.showArr[indexPath.item] return cell } }
554d4ddc9b251ab5fbc4b134f547b065
33.849315
160
0.680031
false
false
false
false
EagleKing/SwiftStudy
refs/heads/master
闭包.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import Cocoa //闭包排序以及简化写法**************************************** let names = ["Chris","Alex","Ewa","Barry","Daniella"] func backwards(s1:String,s2:String) -> Bool { return s1 > s2 } var reversed = names.sort(backwards) reversed = names.sort( {(s1:String,s2:String) -> Bool in return s1 > s2 })//返回yes即在前面 reversed = names.sort( {s1,s2 in return s1 > s2}) reversed = names.sort( {s1,s2 in s1 > s2}) reversed = names.sort({$0 > $1}) reversed = names.sort(>) //*********************************************** //尾随闭包**************************************** reversed = names.sort(){$0>$1}//尾随闭包 reversed = names.sort{$0>$1}//尾随闭包省略括号() //尾随闭包应用 let digitNames = [ 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" ] let numbers = [16,58,510] let strings = numbers.map() { (var number) -> String in var output = "" while number > 0 { output = digitNames[number%10]! + output//取余 number /= 10 } return output } //捕获值************************************** func makeIncrementor(forIncrement amount:Int)->()->Int //注意,这里返回的是函数 { var runningTotal = 0 func incrementor()->Int { runningTotal += amount//捕获变量的引用 return runningTotal } return incrementor } let incrementByTen = makeIncrementor(forIncrement: 10) var a = incrementByTen(); a = incrementByTen(); a = incrementByTen(); a = incrementByTen(); let incermentBySeven = makeIncrementor(forIncrement: 7) var b = incermentBySeven() b = incermentBySeven() let alsoIncrementByTen = incrementByTen let c = alsoIncrementByTen() //非逃逸性闭包 //在参数前面加上@noescape //逃逸性闭包 var completionHandlers:[()-> Void] = [] func someFuncWithEscapingclosure( completionHandler:()-> Void) { completionHandlers.append(completionHandler) } func someFuncWithNoEscapingclosure(@noescape completionHandler:() -> Void) { completionHandler() } class SomeClass { var x = 10 func doSomething() { someFuncWithEscapingclosure {self.x = 100} someFuncWithNoEscapingclosure(){x = 200}//逃逸性闭包可以隐式引用self,尾随闭包 } } let instance = SomeClass() instance.doSomething() let aProperty = instance.x completionHandlers.first?()//逃逸性闭包延迟执行 print(instance.x) //自动闭包是一种自动创建的闭包,用来包装给函数作为参数的表达式 var customersInLine = ["chris","alex","ewa","barry","daniella"] print(customersInLine.count) let customerProvider = {customersInLine.removeAtIndex(0)}//此为自动闭包 print(customersInLine.count) print("Now serving \(customersInLine.removeAtIndex(0))") print(customersInLine.count) func serveCustomer(customerProvider:()->String) { print("Now serving \(customerProvider())!") } serveCustomer({customersInLine.removeAtIndex(0)}) //@autoclosures(escaping)允许闭包逃逸 var customerProviders:[()->String] = [] func collectCustomerProviders(@autoclosure(escaping) cutomerProvider:()->String) { customerProviders.append(customerProvider) } collectCustomerProviders(customersInLine.removeAtIndex(0)) collectCustomerProviders(customersInLine.removeAtIndex(0)) print("Collected \(customerProviders.count)closures.") for customerProvider in customerProviders { print("Now serving \(customerProvider())!") }
d2cd6a7938b1c9c5c49df53e53d60939
22.882353
80
0.663177
false
false
false
false
pozi119/VOVCManager.Swift
refs/heads/master
VOVCManager.Swift/VCManager/VCManager.swift
gpl-3.0
2
// // VCManager.swift // VOVCManagerDemo // // Created by Valo on 15/6/29. // Copyright (c) 2015年 Valo. All rights reserved. // import UIKit //MARK:调试开关 let VO_DEBUG = true //MARK:注册信息Key let VCName:String = "name" let VCController:String = "controller" let VCStoryBoard:String = "storyboard" let VCISPresent:String = "present" //MARK:全局方法 /** 设置指定对象的参数 :param: params 参数 :param: obj 指定对象 */ private func setParams(params:Dictionary<String,AnyObject>, forObject obj:AnyObject){ for (key,val) in params{ let sel:Selector? = Selector(key) if(sel != nil && obj.respondsToSelector(sel!)){ obj.setValue(val, forKey: key) } } } func swiftClassFromString(className: String) -> AnyClass! { if var appName: String? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String? { appName = appName?.stringByReplacingOccurrencesOfString(".", withString: "_", options: NSStringCompareOptions.LiteralSearch, range: nil) let classStringName = "\(appName!).\(className)" var cls: AnyClass? = NSClassFromString(classStringName) assert(cls != nil, "class notfound,please check className") return cls } return nil; } class VCRegistration: NSObject{ var name:String? var controller:String? var storyboard:String? var isPresent:Bool = false convenience init?(spec:Dictionary<String,AnyObject>?){ self.init() if(spec != nil){ setParams(spec!, forObject: self) } } } class VCManager: NSObject{ //MARK:私有属性 private var viewControllers = [UIViewController]() private var naviControllers = [UINavigationController]() private var registerList:Set<VCRegistration> = [] //MARK:公共属性 var curViewController:UIViewController?{ get{ return self.viewControllers.last } } var curNaviController:UINavigationController?{ get { var navi = self.viewControllers.last?.navigationController if(navi == nil){ navi = self.naviControllers.last } return navi } } //MARK:单例对象 /// 生成单例对象 class func sharedManager()->VCManager{ struct Singleton{ static var predicate:dispatch_once_t = 0 static var instance:VCManager? = nil } dispatch_once(&Singleton.predicate,{ Singleton.instance = VCManager() Singleton.instance?.commonInit() } ) return Singleton.instance! } //MARK:viewController管理 /** 将viewController添加到缓存列表 :param: viewController 要添加的viewController */ func addViewController(viewController:UIViewController){ if(viewController.isKindOfClass(UIViewController.classForCoder()) && NSStringFromClass(viewController.classForCoder) != "UIInputWindowController"){ self.viewControllers.append(viewController) self.printWithTag("Appear") } if(viewController.isKindOfClass(UINavigationController.classForCoder())){ self.naviControllers.append(viewController as! UINavigationController) } } /** 从保存的viewController列表中删除指定的viewController :param: viewController 要删除的viewController */ func removeViewController(viewController:UIViewController){ var index:Int = -1 for i in 0..<self.viewControllers.count{ let tmpVc = self.viewControllers[i] if(tmpVc == viewController){ index = i break } } if(index >= 0){ self.viewControllers.removeAtIndex(index) self.printWithTag("DisAppear") } index = -1 if(viewController.isKindOfClass(UINavigationController.classForCoder())){ for i in 0..<self.naviControllers.count{ let tmpVc = self.naviControllers[i] if(tmpVc == viewController){ index = i break } } if(index >= 0){ self.naviControllers.removeAtIndex(index) } } } //MARK: viewController生成 /** 根据ViewController名称和Storyboard名称生成ViewController,无参数 :param: aController 页面名称 :param: aStoryboard 故事版名称 :returns: viewController or nil */ func viewController(aController:String, storyboard aStoryboard:String?)->UIViewController?{ return self.viewController(aController, storyboard: aStoryboard, params: nil) } /** 根据ViewController名称和Storyboard名称生成ViewController :param: aController 页面名称 :param: aStoryboard 故事版名称 :param: params 页面参数 :returns: viewController or nil */ func viewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?)->UIViewController?{ let aClass:AnyClass? = swiftClassFromString(aController) if(aClass == nil){ return nil } var viewController:AnyObject? = nil if(aStoryboard?.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) > 0){ let storyboard:UIStoryboard? = UIStoryboard(name: aStoryboard!, bundle: nil) if(storyboard != nil){ viewController = storyboard?.instantiateViewControllerWithIdentifier(aController) } } if(viewController == nil){ let aControllerClass = aClass as! UIViewController.Type viewController = aControllerClass(nibName: aController, bundle: nil) if(viewController == nil){ viewController = aControllerClass() } } if(viewController != nil && params != nil){ setParams(params!, forObject: viewController!) } return viewController as? UIViewController } //MARK: 页面跳转 /** 页面跳转,push :param: aController 页面名称 :param: aStoryboard 故事版名称 */ func pushViewController(aController:String, storyboard aStoryboard:String?){ self.pushViewController(aController, storyboard: aStoryboard, params: nil, animated: true) } /** 页面跳转,push,指定是否有动画效果 :param: aController 页面名称 :param: aStoryboard 故事版名称 :param: animated 是否有动画效果 */ func pushViewController(aController:String, storyboard aStoryboard:String?, animated:Bool){ self.pushViewController(aController, storyboard: aStoryboard, params: nil, animated: animated) } /** 页面跳转,push,设置参数 :param: aController 页面名称 :param: aStoryboard 故事版名称 :param: params 页面参数 */ func pushViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?){ self.pushViewController(aController, storyboard: aStoryboard, params: params, animated: true) } /** 页面跳转,push,设置参数,并指定是否有动画效果 :param: aController 页面名称 :param: aStoryboard 故事版名称 :param: params 页面参数 :param: animated 是否有动画效果 */ func pushViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?, animated:Bool){ let viewController = self.viewController(aController, storyboard: aStoryboard, params: params) if(viewController == nil){ return } self.curNaviController?.pushViewController(viewController!, animated: animated) } /** 页面跳转,push,跳转至指定页面,并移除中间页面 :param: aController 页面名称 :param: aStoryboard 故事版名称 :param: params 页面参数 :param: animated 是否有动画效果 :param: removeControllers 要移除的页面名称数组 */ func pushViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?, animated:Bool, removeControllers:[String]?){ self.pushViewController(aController, storyboard: aStoryboard, params: params, animated:animated) if(removeControllers == nil || self.curNaviController == nil){ return } for removeController in removeControllers!{ if(removeController != aController){ var removeIndexes = [Int]() for i in 0..<self.curNaviController!.viewControllers.count{ let viewController:AnyObject = self.curNaviController!.viewControllers[i] if(viewController.type == removeController){ removeIndexes.append(i) } } for index in removeIndexes{ self.curNaviController?.viewControllers.removeAtIndex(index) } } } } //MARK: 页面出栈 /** 页面出栈,指定是否有动画效果 :param: animated 是否有动画效果 :returns: 出栈的页面 */ func popViewControllerAnimated(animated:Bool)->UIViewController?{ return self.curNaviController?.popViewControllerAnimated(animated) } /** 页面出栈,至根页面,指定是否有动画效果 :param: animated 指定是否有动画效果 :returns: 出栈的页面数组 */ func popToRootViewControllerAnimated(animated:Bool)->[AnyObject]?{ return self.curNaviController?.popToRootViewControllerAnimated(animated) } /** 页面出栈,至指定页面,设置参数,指定是否有动画效果 :param: aController 要显示的页面 :param: params 要显示页面的参数 :param: animated 是否有动画效果 :returns: 出栈的页面数组 */ func popToViewController(aController:String, params:Dictionary<String,AnyObject>?, animated:Bool)->[AnyObject]?{ if(self.curNaviController == nil){ return nil } var targetVC:UIViewController? = nil for viewController in self.curNaviController!.viewControllers{ if(viewController.type == aController){ targetVC = viewController as? UIViewController break; } } if(targetVC != nil){ if(params != nil){ setParams(params!, forObject: targetVC!) } return self.curNaviController?.popToViewController(targetVC!, animated: animated) } return nil; } //MARK:页面显示 /** 页面显示,present方式,设置参数,指定动画等 :param: aController 页面名称 :param: aStoryboard 故事版名称 :param: params 页面参数 :param: animated 是否有动画效果 :param: completion 显示完成后的操作 */ func presentViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?, animated:Bool, completion:(()->Void)?){ self.presentViewController(aController, storyboard: aStoryboard, params: params, animated: animated, isInNavi: false, completion: completion) } /** 页面显示,present方式,设置参数,指定动画,是否包含在导航页中 :param: aController 页面名称 :param: aStoryboard 故事版名称 :param: params 页面参数 :param: animated 是否有动画效果 :param: inNavi 是否包含在导航页中 :param: completion 显示完成后的操作 */ func presentViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?, animated:Bool,isInNavi inNavi:Bool, completion:(()->Void)?){ let viewController = self.viewController(aController, storyboard: aStoryboard, params: params) if(viewController == nil||self.curViewController == nil){ return } if(inNavi){ if(self.curNaviController == nil){ let navi = UINavigationController(rootViewController: viewController!) self.curViewController?.presentViewController(navi, animated: animated, completion: completion) } else{ self.curNaviController!.presentViewController(viewController!, animated: animated, completion: completion) } } else{ self.curViewController!.presentViewController(viewController!, animated: animated, completion: completion) } } /** 页面销毁 :param: animated 是否有动画效果 :param: completion 页面销毁后的操作 */ func dismissViewControllerAnimated(animated:Bool, completion:(()->Void)?){ if(self.curViewController == nil){ return } self.curViewController!.dismissViewControllerAnimated(animated, completion: completion) } //MARK:页面URL管理 /** 注册页面 :param: spec 页面特征参数 */ func registerWithSpec(spec:Dictionary<String,AnyObject>){ let vcReg:VCRegistration? = VCRegistration(spec: spec) if(vcReg != nil){ self.addRegistration(vcReg!) } } /** 注册页面 :param: name 页面注册名 :param: aController 页面名称 :param: aStoryboard 故事版名称 :param: isPresent 是否present方式显示,是-present,否-push */ func registerName(name:String,forViewController aController:String, storyboard aStoryboard:String?, isPresent:Bool){ let vcReg = VCRegistration() vcReg.name = name vcReg.controller = aController vcReg.storyboard = aStoryboard vcReg.isPresent = isPresent self.addRegistration(vcReg) } /** 取消注册页面 :param: name 页面注册名 */ func cancelRegisterName(name:String){ var removeVcReg:VCRegistration? = nil for vcReg in self.registerList{ vcReg.name == name removeVcReg = vcReg break } if(removeVcReg != nil){ self.registerList.remove(removeVcReg!) } } /** 处理URL :param: url 以AppScheme开始的URL :returns: 是否成功处理 */ func handleURL(url:NSURL)->Bool{ /** 1.检查scheme是否匹配 */ let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: true) let urlTypes:[Dictionary<String, AnyObject>]? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleURLTypes") as? [Dictionary<String, AnyObject>] var schemes = [String]() if(urlTypes == nil){ return false } for dic in urlTypes!{ let tmpArray:[String]? = dic["CFBundleURLSchemes"] as? [String] if(tmpArray != nil){ schemes += tmpArray! } } var match:Bool = false for scheme in schemes{ if(scheme == components?.scheme){ match = true } } if(!match){ return false } /** 2.获取页面名 */ let name = (components?.path?.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) == 0) ? components?.host : components?.path?.lastPathComponent /** 3.获取页面参数 */ var params:Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() let tmpArray = components?.query?.componentsSeparatedByString("&") if(tmpArray == nil){ return false } for paramStr in tmpArray!{ let range = paramStr.rangeOfString("=", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) if(range != nil){ let key = paramStr.substringToIndex(range!.startIndex) let val = paramStr.substringFromIndex(range!.endIndex) params[key] = val } } /** 4.打开对应页面 */ self.showViewControllerWithRegisterName(name!, params: params) return true } /** 显示指定页面 :param: name 页面注册名 :param: params 页面参数 */ func showViewControllerWithRegisterName(name:String, params:Dictionary<String, AnyObject>){ /** 1.检查是否注册,若注册,则获取相应的参数 */ var registration:VCRegistration? = nil for tmpReg in self.registerList{ if(tmpReg.name == name){ registration = tmpReg break } } if(registration == nil || registration?.controller == nil){ return } /** 2.打开指定页面 */ if(registration!.isPresent){ self.presentViewController(registration!.controller!, storyboard: registration!.storyboard, params: params, animated: true, completion: nil) } else{ self.pushViewController(registration!.controller!, storyboard: registration!.storyboard, params: params) } } //MARK:私有函数 private func commonInit(){ UIViewController.record() } /** 打印viewController层级信息 :param: tag 打印标签 */ private func printWithTag(tag:String){ if(VO_DEBUG){ var paddingItems:String = "" for tmpVc in self.viewControllers{ paddingItems = paddingItems + "--" } println("\(tag):\(paddingItems)>\(self.viewControllers.last?.description)") } } /** 添加注册信息 :param: registration 注册信息 :returns: 是否添加成功 */ private func addRegistration(registration:VCRegistration)->Bool{ for vcReg in self.registerList{ if(vcReg.name == registration.name){ return false } } self.registerList.insert(registration) return true } }
32f3ff2853886c0ce335a53cae8dd492
30.483456
181
0.607089
false
false
false
false
verticon/VerticonsToolbox
refs/heads/master
VerticonsToolbox/NumericType.swift
mit
1
// // NumericType.swift // VerticonsToolbox // // Created by Robert Vaessen on 6/9/17. // Copyright © 2017 Verticon. All rights reserved. // import Foundation public enum NumericType : CustomStringConvertible { case int8 case uint8 case int16 case uint16 case int32 case uint32 case int64 case uint64 case float case double public static let all: [NumericType] = [.int8, .uint8, .int16, .uint16, .int32, .uint32, .int64, .uint64, .float, .double] public var description: String { return self.name } public var name: String { switch self { case .int8: return "\(Int8.self)" case .uint8: return "\(UInt8.self)" case .int16: return "\(Int16.self)" case .uint16: return "\(UInt16.self)" case .int32: return "\(Int32.self)" case .uint32: return "\(UInt32.self)" case .int64: return "\(Int64.self)" case .uint64: return "\(UInt64.self)" case .float: return "\(Float.self)" case .double: return "\(Double.self)" } } /// The index of this numeric type in the NumericType.all array public var index: Int { return NumericType.all.firstIndex { self == $0 }! } public func valueToData(value: String) -> Data? { switch self { case .int8: return Int8(value)?.data case .uint8: return UInt8(value)?.data case .int16: return Int16(value)?.data case .uint16: return UInt16(value)?.data case .int32: return Int32(value)?.data case .uint32: return UInt32(value)?.data case .int64: return Int64(value)?.data case .uint64: return UInt64(value)?.data case .float: return Float(value)?.data case .double: return Double(value)?.data } } public func valueFromData(data: Data, hex: Bool) -> String? { switch self { case .int8: guard let number = Int8(data: data) else { return nil } return String(format: hex ? "%02hhX" : "%hhd", number) case .uint8: guard let number = UInt8(data: data) else { return nil } return String(format: hex ? "%02hhX" : "%hhu", number) case .int16: guard let number = Int16(data: data) else { return nil } return String(format: hex ? "%04hX " : "%hd ", number) case .uint16: guard let number = UInt16(data: data) else { return nil } return String(format: hex ? "%04hX " : "%hu ", number) case .int32: guard let number = Int32(data: data) else { return nil } return String(format: hex ? "%08X " : "%d ", number) case .uint32: guard let number = UInt32(data: data) else { return nil } return String(format: hex ? "%08X " : "%u ", number) case .int64: guard let number = Int64(data: data) else { return nil } return String(format: hex ? "%016X " : "%ld ", number) case .uint64: guard let number = UInt64(data: data) else { return nil } return String(format: hex ? "%016X " : "%lu ", number) case .float: guard let number = Float(data: data) else { return nil } return String(format: "%f ", number) case .double: guard let number = Double(data: data) else { return nil } return String(format: "%f ", number) } } }
0b9724ceb123a0975632c9ca45416d86
28.906977
126
0.506739
false
false
false
false
Desgard/Calendouer-iOS
refs/heads/master
Calendouer/Calendouer/App/Model/WeatherObject.swift
mit
1
// // WeatherObject.swift // Calendouer // // Created by 段昊宇 on 2017/3/8. // Copyright © 2017年 Desgard_Duan. All rights reserved. // import UIKit class WeatherObject: NSObject, NSCoding { var id: String = "" var name: String = "" var country: String = "" var path: String = "" var timezone: String = "" var timezone_offset: String = "" var date: String = "" var text_day: String = "" var code_day: String = "" var text_night: String = "" var code_night: String = "" var high: String = "" var low: String = "" var precip: String = "" var wind_direction: String = "" var wind_direction_degree: String = "" var wind_speed: String = "" var wind_scale: String = "" var last_update: String = "" var city: String = "" init(Dictionary dic: [String: String]) { super.init() if let id = dic["id"] { self.id = id } if let name = dic["name"] { self.name = name } if let country = dic["country"] { self.country = country } if let path = dic["path"] { self.path = path } if let timezone = dic["timezone"] { self.timezone = timezone } if let timezone_offset = dic["timezone_offset"] { self.timezone_offset = timezone_offset } if let date = dic["date"] { self.date = date } if let text_day = dic["text_day"] { self.text_day = text_day } if let code_day = dic["code_day"] { self.code_day = code_day } if let code_night = dic["code_night"] { self.code_night = code_night } if let text_night = dic["text_night"] { self.text_night = text_night } if let high = dic["high"] { self.high = high } if let low = dic["low"] { self.low = low } if let precip = dic["precip"] { self.precip = precip } if let wind_direction = dic["wind_direction"] { self.wind_direction = wind_direction } if let wind_direction_degree = dic["wind_direction_degree"] { self.wind_direction_degree = wind_direction_degree } if let wind_speed = dic["wind_speed"] { self.wind_speed = wind_speed } if let wind_scale = dic["wind_scale"] { self.wind_scale = wind_scale } if let last_update = dic["last_update"] { if last_update.characters.count != 0 { self.last_update = (last_update as NSString).substring(to: 10) } } if let city = dic["city"] { self.city = city } } public func getWeatherIcon() -> String { let time: DayObject = DayObject() var judgeCode = "" if time.hour >= 5 && time.hour <= 18 { judgeCode = code_day } else { judgeCode = code_night } switch judgeCode { case "0": return "sunny"// 晴天 case "1": return "sunny" case "2": return "sunny" case "3": return "sunny" case "4": return "cloudy" case "5": return "partly_cloudy_day" case "6": return "partly_cloudy_day" case "7": return "mostly_cloudy_day" case "8": return "mostly_cloudy_day" case "9": return "mostly_cloudy_day" case "10": return "shower" case "11": return "thunder_shower" case "12": return "thunder_shower" case "13": return "light_rain" case "14": return "moderate_rain" case "15": return "heavy_rain" case "16": return "heavy_rain" case "17": return "heavy_rain" case "18": return "heavy_rain" case "19": return "ice_rain" case "20": return "heavy_rain" case "21": return "snow" case "22": return "snow" case "23": return "snow" case "24": return "snow" case "25": return "snow" case "26": return "mist" case "27": return "mist" case "28": return "mist" case "29": return "mist" case "30": return "mist" case "31": return "mist" case "32": return "wind" case "33": return "wind" case "34": return "wind" case "35": return "wind" case "36": return "wind" case "37": return "wind" case "38": return "sunny" default: return "sunny" } } required override init() { } // MARK: - NSCoding - private struct WeatherObjectCodingKey { static let kCodingID = "id" static let kCodingName = "name" static let kCodingCountry = "country" static let kCodingPath = "path" static let kCodingTimezone = "timezone" static let kCodingTimezone_offset = "timezone_offset" static let kCodingDate = "date" static let kCodingText_day = "text_day" static let kCodingCode_day = "code_day" static let kCodingText_night = "text_night" static let kCodingCode_night = "code_night" static let kCodingHigh = "high" static let kCodingLow = "low" static let kCodingPrecip = "precip" static let kCodingWind_direction = "wind_direction" static let kCodingWind_direction_degree = "wind_direction_degree" static let kCodingWind_speed = "wind_speed" static let kCodingWind_scale = "wind_scale" static let kCodingLast_update = "last_update" static let kCodingCity = "city" } required init?(coder aDecoder: NSCoder) { self.id = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingID) as! String self.name = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingName) as! String self.country = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingCountry) as! String self.path = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingPath) as! String self.timezone = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingTimezone) as! String self.timezone_offset = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingTimezone_offset) as! String self.date = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingDate) as! String self.text_day = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingText_day) as! String self.code_day = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingCode_day) as! String self.text_night = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingText_night) as! String self.code_night = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingCode_night) as! String self.high = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingHigh) as! String self.low = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingLow) as! String self.precip = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingPrecip) as! String self.wind_direction = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingWind_direction) as! String self.wind_direction_degree = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingWind_direction_degree) as! String self.wind_speed = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingWind_speed) as! String self.wind_scale = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingWind_scale) as! String self.last_update = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingLast_update) as! String self.city = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingCity) as! String } func encode(with aCoder: NSCoder) { aCoder.encode(self.id, forKey: WeatherObjectCodingKey.kCodingID) aCoder.encode(self.name, forKey: WeatherObjectCodingKey.kCodingName) aCoder.encode(self.country, forKey: WeatherObjectCodingKey.kCodingCountry) aCoder.encode(self.path, forKey: WeatherObjectCodingKey.kCodingPath) aCoder.encode(self.timezone, forKey: WeatherObjectCodingKey.kCodingTimezone) aCoder.encode(self.timezone_offset, forKey: WeatherObjectCodingKey.kCodingTimezone_offset) aCoder.encode(self.date, forKey: WeatherObjectCodingKey.kCodingDate) aCoder.encode(self.text_day, forKey: WeatherObjectCodingKey.kCodingText_day) aCoder.encode(self.code_day, forKey: WeatherObjectCodingKey.kCodingCode_day) aCoder.encode(self.text_night, forKey: WeatherObjectCodingKey.kCodingText_night) aCoder.encode(self.code_night, forKey: WeatherObjectCodingKey.kCodingCode_night) aCoder.encode(self.high, forKey: WeatherObjectCodingKey.kCodingHigh) aCoder.encode(self.low, forKey: WeatherObjectCodingKey.kCodingLow) aCoder.encode(self.precip, forKey: WeatherObjectCodingKey.kCodingPrecip) aCoder.encode(self.wind_direction, forKey: WeatherObjectCodingKey.kCodingWind_direction) aCoder.encode(self.wind_direction_degree, forKey: WeatherObjectCodingKey.kCodingWind_direction_degree) aCoder.encode(self.wind_speed, forKey: WeatherObjectCodingKey.kCodingWind_speed) aCoder.encode(self.wind_scale, forKey: WeatherObjectCodingKey.kCodingWind_scale) aCoder.encode(self.last_update, forKey: WeatherObjectCodingKey.kCodingLast_update) aCoder.encode(self.city, forKey: WeatherObjectCodingKey.kCodingCity) } }
c2c7093c70e4d4fc141a73db1369ff1a
45.084444
130
0.580577
false
false
false
false
nearspeak/iOS-SDK
refs/heads/master
NearspeakKit/NSKManager.swift
lgpl-3.0
1
// // NSKManager.swift // NearspeakKit // // Created by Patrick Steiner on 27.01.15. // Copyright (c) 2015 Nearspeak. All rights reserved. // import UIKit import CoreLocation import CoreBluetooth private let _NSKManagerSharedInstance = NSKManager() /** Nearspeak Manager class. */ public class NSKManager: NSObject { /** Get the singelton object of this class. */ public class var sharedInstance: NSKManager { return _NSKManagerSharedInstance } private let tagQueue = dispatch_queue_create("at.nearspeak.manager.tagQueue", DISPATCH_QUEUE_CONCURRENT) private var _nearbyTags = [NSKTag]() private var activeUUIDs = Set<NSUUID>() private var unkownTagID = -1 /** Array of all currently nearby Nearspeak tags. */ public var nearbyTags: [NSKTag] { var nearbyTagsCopy = [NSKTag]() var tags = [NSKTag]() dispatch_sync(tagQueue) { nearbyTagsCopy = self._nearbyTags } if showUnassingedBeacons { return nearbyTagsCopy } else { for tag in nearbyTagsCopy { if let _ = tag.tagIdentifier { tags.append(tag) } } } return tags } public var unassignedTags: [NSKTag] { var nearbyTagsCopy = [NSKTag]() var unassingedTags = [NSKTag]() dispatch_sync(tagQueue) { nearbyTagsCopy = self._nearbyTags } // remove assigend tags for tag in nearbyTagsCopy { if tag.tagIdentifier == nil { unassingedTags.append(tag) } } return unassingedTags } private var api = NSKApi(devMode: false) private var beaconManager: NSKBeaconManager? private var showUnassingedBeacons = false // Current beacons private var beacons = [CLBeacon]() /** The standard constructor. */ public override init() { super.init() setupBeaconManager() } // MARK: - NearbyBeacons - public /** Check if the device has all necessary features enabled to support beacons. :return: True if all necessary features are enabled, else false. */ public func checkForBeaconSupport() -> Bool { if let bManager = beaconManager { return bManager.checkForBeaconSupport() } return false } /** Add a custom UUID for monitoring. */ public func addCustomUUID(uuid: String) { if let uuid = NSUUID(UUIDString: uuid) { var uuids = Set<NSUUID>() uuids.insert(uuid) beaconManager?.addUUIDs(uuids) activeUUIDs.insert(uuid) } } /** Add the UUIDs from the Nearspeak server. */ public func addServerUUIDs() { getActiveUUIDs() } /** Start monitoring for iBeacons. */ public func startBeaconMonitoring() { if let beaconManager = beaconManager { beaconManager.startMonitoringForNearspeakBeacons() } } /** Stop monitoring for iBeacons. */ public func stopBeaconMonitoring() { if let beaconManager = beaconManager { beaconManager.stopMonitoringForNearspeakBeacons() } } /** Start the Nearspeak beacon discovery / ranging. - parameter showUnassingedBeacons: True if unassinged Nearspeak beacons should also be shown. */ public func startBeaconDiscovery(showUnassingedBeacons: Bool) { if let bManager = beaconManager { bManager.startRangingForNearspeakBeacons() } self.showUnassingedBeacons = showUnassingedBeacons } /** Stop the Nearspeak beacon discovery. */ public func stopBeaconDiscovery() { if let bManager = beaconManager { bManager.stopRangingForNearspeakBeacons() } } /** Get a Nearspeak tag object from the nearby beacons array. - parameter index: The index of the Nearspeak tag object. */ public func getTagAtIndex(index: Int) -> NSKTag? { return _nearbyTags[index] } /** Show or hide unassigned Nearspeak tags. - parameter show: True if unassinged Nearspeak beacons should als be show. */ public func showUnassingedBeacons(show: Bool) { if show != showUnassingedBeacons { showUnassingedBeacons = show self.reset() } } /** Add a demo tag for the simulator. */ public func addDemoTag(hardwareIdentifier: String, majorId: String, minorId: String) { self.api.getTagByHardwareId(hardwareIdentifier: hardwareIdentifier, beaconMajorId: majorId, beaconMinorId: minorId) { (succeeded, tag) -> () in if succeeded { if let tag = tag { self.addTag(tag) } } } } /** Reset the NSKManager. */ public func reset() { self.removeAllTags() self.removeAllBeacons() } // MARK: - private private func getActiveUUIDs() { api.getSupportedBeaconsUUIDs { (succeeded, uuids) -> () in if succeeded { var newUUIDS = Set<NSUUID>() for uuid in uuids { if newUUIDS.count < NSKApiUtils.maximalBeaconUUIDs { if let id = NSKApiUtils.hardwareIdToUUID(uuid) { newUUIDS.insert(id) self.activeUUIDs.insert(id) } } } if let beaconManager = self.beaconManager { beaconManager.addUUIDs(newUUIDS) } } } } private func setupBeaconManager() { beaconManager = NSKBeaconManager(uuids: activeUUIDs) beaconManager!.delegate = self } // MARK: - NearbyBeacons - private private func addTagWithBeacon(beacon: CLBeacon) { // check if this beacon currently gets added for addedBeacon in beacons { if beaconsAreTheSame(beaconOne: addedBeacon, beaconTwo: beacon) { // beacon is already in the beacon array, update the current tag updateTagWithBeacon(beacon) return } } // add the new beacon to the waiting array beacons.append(beacon) self.api.getTagByHardwareId(hardwareIdentifier: beacon.proximityUUID.UUIDString, beaconMajorId: beacon.major.stringValue, beaconMinorId: beacon.minor.stringValue) { (succeeded, tag) -> () in if succeeded { if let currentTag = tag { // set the discovered beacon as hardware beacon on the new tag currentTag.hardwareBeacon = beacon self.addTag(currentTag) } else { // beacon is not assigned to a tag in the system self.addUnknownTagWithBeacon(beacon) } } else { // beacon is not assigned to a tag in the system self.addUnknownTagWithBeacon(beacon) } } } private func addUnknownTagWithBeacon(beacon: CLBeacon) { let tag = NSKTag(id: unkownTagID) tag.name = "Unassigned Tag: \(beacon.major) - \(beacon.minor)" tag.hardwareBeacon = beacon self.addTag(tag) unkownTagID -= 1 } private func addTag(tag: NSKTag) { dispatch_barrier_async(tagQueue, { () -> Void in self._nearbyTags.append(tag) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.postContentUpdateNotification() }) }) } private func removeTagWithId(id: Int) { var index = 0 for tag in _nearbyTags { if tag.id.integerValue == id { dispatch_barrier_sync(tagQueue, { () -> Void in self._nearbyTags.removeAtIndex(index) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.postContentUpdateNotification() }) }) // also remove the beacon from the beacons array if let beacon = tag.hardwareBeacon { removeBeacon(beacon) } } index += 1 } } private func removeBeacon(beacon: CLBeacon) { var index = 0 for currentBeacon in beacons { if beaconsAreTheSame(beaconOne: beacon, beaconTwo: currentBeacon) { self.beacons.removeAtIndex(index) } index += 1 } } private func removeAllTags() { dispatch_barrier_async(tagQueue, { () -> Void in self._nearbyTags = [] dispatch_async(dispatch_get_main_queue(), { () -> Void in self.postContentUpdateNotification() }) }) } private func removeAllBeacons() { self.beacons = [] } private func beaconsAreTheSame(beaconOne beaconOne: CLBeacon, beaconTwo: CLBeacon) -> Bool { if beaconOne.proximityUUID.UUIDString == beaconTwo.proximityUUID.UUIDString { if beaconOne.major.longLongValue == beaconTwo.major.longLongValue { if beaconOne.minor.longLongValue == beaconTwo.minor.longLongValue { return true } } } return false } private func getTagByBeacon(beacon: CLBeacon) -> NSKTag? { for tag in self._nearbyTags { if let hwBeacon = tag.hardwareBeacon { if beaconsAreTheSame(beaconOne: hwBeacon, beaconTwo: beacon) { return tag } } } return nil } private func updateTagWithBeacon(beacon: CLBeacon) { if let tag = getTagByBeacon(beacon) { tag.hardwareBeacon = beacon postContentUpdateNotification() } } private func processFoundBeacons(beacons: [CLBeacon]) { // add or update tags for beacon in beacons { addTagWithBeacon(beacon) } var tagsToRemove = Set<Int>() // remove old tags for tag in _nearbyTags { var isNewBeacon = false if let hwBeacon = tag.hardwareBeacon { for beacon in beacons { // if the beacon is not found. remove the tag if self.beaconsAreTheSame(beaconOne: beacon, beaconTwo: hwBeacon) { isNewBeacon = true } } } if !isNewBeacon { tagsToRemove.insert(tag.id.integerValue) } } for tagId in tagsToRemove { removeTagWithId(tagId) } } private func postContentUpdateNotification() { NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationNearbyTagsUpdatedKey, object: nil) } } // MARK: - NSKBeaconManagerDelegate extension NSKManager: NSKBeaconManagerDelegate { /** Delegate method which gets called, when new beacons are found. */ public func beaconManager(manager: NSKBeaconManager!, foundBeacons: [CLBeacon]) { self.processFoundBeacons(foundBeacons) } /** Delegate method which gets called, when the bluetooth state changed. */ public func beaconManager(manager: NSKBeaconManager!, bluetoothStateDidChange bluetoothState: CBCentralManagerState) { switch bluetoothState { case .PoweredOn: NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationBluetoothOkKey, object: nil) default: NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationBluetoothErrorKey, object: nil) } } /** Delegate method which gets called, when the location state changed. */ public func beaconManager(manager: NSKBeaconManager!, locationStateDidChange locationState: CLAuthorizationStatus) { switch locationState { case .AuthorizedAlways: NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationLocationAlwaysOnKey, object: nil) case .AuthorizedWhenInUse: NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationLocationWhenInUseOnKey, object: nil) default: NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationLocationErrorKey, object: nil) } } /** Delegate method which gets called, when a region is entered. */ public func beaconManager(manager: NSKBeaconManager, didEnterRegion region: CLRegion) { NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationRegionEnterKey, object: region, userInfo: ["region" : region]) } /** Delegate method which gets called, when a region is exited. */ public func beaconManager(manager: NSKBeaconManager, didExitRegion region: CLRegion) { NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationRegionExitKey, object: nil, userInfo: ["region" : region]) } /** Delegate method which gets called, when new regions are added from the Nearspeak server. */ public func newRegionsAdded(manager: NSKBeaconManager) { NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationNewRegionAddedKey, object: nil) } }
ab4ab5ef3be40165f1aef980bab184cf
29.833333
198
0.5755
false
false
false
false
donileo/RMessage
refs/heads/master
Sources/RMessage/Animators/SlideAnimator.swift
mit
1
// // SlideAnimator.swift // // Created by Adonis Peralta on 8/6/18. // Copyright © 2018 None. All rights reserved. // import Foundation import UIKit private enum Constants { enum KVC { static let safeAreaInsets = "view.safeAreaInsets" } } /// Implements an animator that slides the message from the top to target position or /// bottom to target position. This animator handles the layout of its managed view in the managed /// view's superview. class SlideAnimator: NSObject, RMAnimator { /// Animator delegate. weak var delegate: RMessageAnimatorDelegate? // MARK: - Start the customizable animation properties /// The amount of time to perform the presentation animation in. var presentationDuration = 0.5 /// The amount of time to perform the dismiss animation in. var dismissalDuration = 0.3 /// The alpha value the view should have prior to starting animations. var animationStartAlpha: CGFloat = 0 /// The alpha value the view should have at the end of animations. var animationEndAlpha: CGFloat = 1 /// A custom vertical offset to apply to the animation. positive values move the view upward, /// negative values move it downward. var verticalOffset = CGFloat(0) /// Enables/disables the use animation padding so as to prevent a visual white gap from appearing when /// animating with a spring animation. var disableAnimationPadding = false private let superview: UIView @objc private let view: UIView private let contentView: UIView private let targetPosition: RMessagePosition /** The starting animation constraint for the view */ private var viewStartConstraint: NSLayoutConstraint? /** The ending animation constraint for the view */ private var viewEndConstraint: NSLayoutConstraint? private var contentViewSafeAreaGuideConstraint: NSLayoutConstraint? /** The amount of vertical padding/height to add to RMessage's height so as to perform a spring animation without visually showing an empty gap due to the spring animation overbounce. This value changes dynamically due to iOS changing the overbounce dynamically according to view size. */ private var springAnimationPadding = CGFloat(0) private var springAnimationPaddingCalculated = false private var isPresenting = false private var isDismissing = false private var hasPresented = false private var hasDismissed = true private var kvcContext = 0 init(targetPosition: RMessagePosition, view: UIView, superview: UIView, contentView: UIView) { self.targetPosition = targetPosition self.superview = superview self.contentView = contentView self.view = view super.init() // Sign up to be notified for when the safe area of our view changes addObserver(self, forKeyPath: Constants.KVC.safeAreaInsets, options: [.new], context: &kvcContext) } /// Ask the animator to present the view with animation. This call may or may not succeed depending on whether /// the animator was already previously asked to animate or where in the presentation cycle the animator is. /// In cases when the animator refuses to present this method returns false, otherwise it returns true. /// /// - Note: Your implementation of this method must allow for this method to be called multiple times by ignoring /// subsequent requests. /// - Parameter completion: A completion closure to execute after presentation is complete. /// - Returns: A boolean value indicating if the animator executed your instruction to present. func present(withCompletion completion: (() -> Void)?) -> Bool { // Guard against being called under the following conditions: // 1. If currently presenting or dismissing // 2. If already presented or have not yet dismissed guard !isPresenting && !hasPresented && hasDismissed else { return false } layoutView() setupFinalAnimationConstraints() setupStartingAnimationConstraints() delegate?.animatorWillAnimatePresentation?(self) animatePresentation(withCompletion: completion) return true } /// Ask the animator to dismiss the view with animation. This call may or may not succeed depending on whether /// the animator was already previously asked to animate or where in the presentation cycle the animator is. /// In cases when the animator refuses to dismiss this method returns false, otherwise it returns true. /// /// - Note: Your implementation of this method must allow for this method to be called multiple times by ignoring /// subsequent requests. /// - Parameter completion: A completion closure to execute after presentation is complete. /// - Returns: A boolean value indicating if the animator executed your instruction to dismiss. func dismiss(withCompletion completion: (() -> Void)?) -> Bool { // Guard against being called under the following conditions: // 1. If currently presenting or dismissing // 2. If already dismissed or have not yet presented guard !isDismissing && hasDismissed && hasPresented else { return false } delegate?.animatorWillAnimateDismissal?(self) animateDismissal(withCompletion: completion) return true } private func animatePresentation(withCompletion completion: (() -> Void)?) { guard let viewSuper = view.superview else { assertionFailure("view must have superview by this point") return } guard let viewStartConstraint = viewStartConstraint, let viewEndConstraint = viewEndConstraint else { return } isPresenting = true viewStartConstraint.isActive = true DispatchQueue.main.async { viewSuper.layoutIfNeeded() self.view.alpha = self.animationStartAlpha // For now lets be safe and not call this code inside the animation block. Though there may be some slight timing // issue in notifying exactly when the animator is animating it should be fine. self.delegate?.animatorIsAnimatingPresentation?(self) UIView.animate( withDuration: self.presentationDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.curveEaseInOut, .beginFromCurrentState, .allowUserInteraction], animations: { viewStartConstraint.isActive = false viewEndConstraint.isActive = true self.contentViewSafeAreaGuideConstraint?.isActive = true self.delegate?.animationBlockForPresentation?(self) self.view.alpha = self.animationEndAlpha viewSuper.layoutIfNeeded() }, completion: { finished in self.isPresenting = false self.hasPresented = true self.delegate?.animatorDidPresent?(self) if finished { completion?() } } ) } } /** Dismiss the view with a completion block */ private func animateDismissal(withCompletion completion: (() -> Void)?) { guard let viewSuper = view.superview else { assertionFailure("view must have superview by this point") return } guard let viewStartConstraint = viewStartConstraint, let viewEndConstraint = viewEndConstraint else { return } isDismissing = true DispatchQueue.main.async { viewSuper.layoutIfNeeded() // For now lets be safe and not call this code inside the animation block. Though there may be some slight timing // issue in notifying exactly when the animator is animating it should be fine. self.delegate?.animatorIsAnimatingDismissal?(self) UIView.animate( withDuration: self.dismissalDuration, animations: { viewEndConstraint.isActive = false self.contentViewSafeAreaGuideConstraint?.isActive = false viewStartConstraint.isActive = true self.delegate?.animationBlockForDismissal?(self) self.view.alpha = self.animationStartAlpha viewSuper.layoutIfNeeded() }, completion: { finished in self.isDismissing = false self.hasPresented = false self.hasDismissed = true self.view.removeFromSuperview() self.delegate?.animatorDidDismiss?(self) if finished { completion?() } } ) } } // MARK: - View notifications override func observeValue( forKeyPath keyPath: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer? ) { if keyPath == Constants.KVC.safeAreaInsets { safeAreaInsetsDidChange(forView: view) } } private func safeAreaInsetsDidChange(forView view: UIView) { var constant = CGFloat(0) if targetPosition == .bottom { constant = springAnimationPadding + view.safeAreaInsets.bottom } else { constant = -springAnimationPadding - view.safeAreaInsets.top } viewEndConstraint?.constant = constant } // MARK: - Layout /// Lay's out the view in its superview for presentation private func layoutView() { setupContentViewLayoutGuideConstraint() // Add RMessage to superview and prepare the ending constraints if view.superview == nil { superview.addSubview(view) } view.translatesAutoresizingMaskIntoConstraints = false delegate?.animatorDidAddToSuperview?(self) NSLayoutConstraint.activate([ view.centerXAnchor.constraint(equalTo: superview.centerXAnchor), view.leadingAnchor.constraint(equalTo: superview.leadingAnchor), view.trailingAnchor.constraint(equalTo: superview.trailingAnchor) ]) delegate?.animatorDidLayout?(self) calculateSpringAnimationPadding() } private func setupContentViewLayoutGuideConstraint() { // Install a constraint that guarantees the title subtitle container view is properly spaced from the top layout // guide when animating from top or the bottom layout guide when animating from bottom let safeAreaLayoutGuide = superview.safeAreaLayoutGuide switch targetPosition { case .top, .navBarOverlay: contentViewSafeAreaGuideConstraint = contentView.topAnchor.constraint( equalTo: safeAreaLayoutGuide.topAnchor, constant: 10 ) case .bottom: contentViewSafeAreaGuideConstraint = contentView.bottomAnchor.constraint( equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -10 ) } } private func setupStartingAnimationConstraints() { guard let viewSuper = view.superview else { assertionFailure("view must have superview by this point") return } if targetPosition != .bottom { viewStartConstraint = view.bottomAnchor.constraint(equalTo: viewSuper.topAnchor) } else { viewStartConstraint = view.topAnchor.constraint(equalTo: viewSuper.bottomAnchor) } } private func setupFinalAnimationConstraints() { assert(springAnimationPaddingCalculated, "spring animation padding must have been calculated by now!") guard let viewSuper = view.superview else { assertionFailure("view must have superview by this point") return } var viewAttribute: NSLayoutAttribute var layoutGuideAttribute: NSLayoutAttribute var constant = CGFloat(0) view.layoutIfNeeded() if targetPosition == .bottom { viewAttribute = .bottom layoutGuideAttribute = .bottom constant = springAnimationPadding + viewSuper.safeAreaInsets.bottom } else { viewAttribute = .top layoutGuideAttribute = .top constant = -springAnimationPadding - viewSuper.safeAreaInsets.top } viewEndConstraint = NSLayoutConstraint( item: view, attribute: viewAttribute, relatedBy: .equal, toItem: viewSuper.safeAreaLayoutGuide, attribute: layoutGuideAttribute, multiplier: 1, constant: constant ) viewEndConstraint?.constant += verticalOffset } // Calculate the padding after the view has had a chance to perform its own custom layout changes via the delegate // call to animatorWillLayout, animatorDidLayout private func calculateSpringAnimationPadding() { guard !disableAnimationPadding else { springAnimationPadding = CGFloat(0) springAnimationPaddingCalculated = true return } // Tell the view to layout so that we may properly calculate the spring padding view.layoutIfNeeded() // Base the spring animation padding on an estimated height considering we need the spring animation padding itself // to truly calculate the height of the view. springAnimationPadding = (view.bounds.size.height / 120.0).rounded(.up) * 5 springAnimationPaddingCalculated = true } deinit { removeObserver(self, forKeyPath: Constants.KVC.safeAreaInsets) } }
3c85a68da43e01c0565a749a5923e259
36.176991
119
0.723161
false
false
false
false
BlinkOCR/blinkocr-ios
refs/heads/master
Samples/FieldByField-sample-Swift/FieldByField-sample-Swift/ViewController.swift
apache-2.0
2
// // ViewController.swift // FieldByField-sample-Swift // // Created by Jura Skrlec on 10/05/2018. // Copyright © 2018 Jura Skrlec. All rights reserved. // import UIKit import BlinkInput class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func startScanTapped(_ sender: Any) { // Create MBIFieldByFieldOverlaySettings let settings = MBIFieldByFieldOverlaySettings(scanElements: MBGenericPreset.getPreset()!) // Create field by field VC let fieldByFieldVC = MBIFieldByFieldOverlayViewController(settings: settings, delegate: self) // Create scanning VC let recognizerRunnerViewController: (UIViewController & MBIRecognizerRunnerViewController)? = MBIViewControllerFactory.recognizerRunnerViewController(withOverlayViewController: fieldByFieldVC) // Present VC self.present(recognizerRunnerViewController!, animated: true, completion: nil) } } extension ViewController : MBIFieldByFieldOverlayViewControllerDelegate { func field(_ fieldByFieldOverlayViewController: MBIFieldByFieldOverlayViewController, didFinishScanningWith scanElements: [MBIScanElement]) { fieldByFieldOverlayViewController.recognizerRunnerViewController?.pauseScanning() var dict = [String: String]() for element: MBIScanElement in scanElements { if (element.scanned) { dict[element.identifier] = element.value } } var description : String = "" for (key, value) in dict { description += "\(key): \(value)\n" } let alert = UIAlertController(title: "Field by field Result", message: "\(description)", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in self.dismiss(animated: true, completion: nil) })) fieldByFieldOverlayViewController.present(alert, animated: true, completion: nil) } func field(byFieldOverlayViewControllerWillClose fieldByFieldOverlayViewController: MBIFieldByFieldOverlayViewController) { self.dismiss(animated: true, completion: nil) } }
d380d99faaa8f3c3d27c502cf99cfb5d
35.485714
200
0.682067
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Cliqz/Frontend/Browser/Settings/LimitMobileDataUsageTableViewController.swift
mpl-2.0
2
// // LimitMobileDataUsageTableViewController.swift // Client // // Created by Mahmoud Adam on 5/9/17. // Copyright © 2017 Mozilla. All rights reserved. // import UIKit class LimitMobileDataUsageTableViewController: SubSettingsTableViewController { private let toggleTitles = [ NSLocalizedString("Limit Mobile Data Usage", tableName: "Cliqz", comment: "[Settings] Limit Mobile Data Usage") ] private let sectionFooters = [ NSLocalizedString("Download videos on Wi-Fi Only", tableName: "Cliqz", comment: "[Settings -> Limit Mobile Data Usage] toogle footer") ] private lazy var toggles: [Bool] = { return [SettingsPrefs.shared.getLimitMobileDataUsagePref()] }() override func getSectionFooter(section: Int) -> String { guard section < sectionFooters.count else { return "" } return sectionFooters[section] } override func getViewName() -> String { return "limit_mobile_data_usage" } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = getUITableViewCell() cell.textLabel?.text = toggleTitles[indexPath.row] let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = toggles[indexPath.row] cell.accessoryView = control cell.selectionStyle = .none cell.isUserInteractionEnabled = true cell.textLabel?.textColor = UIColor.black control.isEnabled = true return cell } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return super.tableView(tableView, heightForHeaderInSection: section) } @objc func switchValueChanged(_ toggle: UISwitch) { self.toggles[toggle.tag] = toggle.isOn saveToggles() self.tableView.reloadData() // log telemetry signal let state = toggle.isOn == true ? "off" : "on" // we log old value let valueChangedSignal = TelemetryLogEventType.Settings(getViewName(), "click", "enable", state, nil) TelemetryLogger.sharedInstance.logEvent(valueChangedSignal) } private func saveToggles() { SettingsPrefs.shared.updateLimitMobileDataUsagePref(self.toggles[0]) } }
7a07e70b7950ce0f9b6aa8a6f21b63de
33.325
142
0.658776
false
false
false
false
Coderian/SwiftedKML
refs/heads/master
SwiftedKML/Elements/ViewVolume.swift
mit
1
// // ViewVolume.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML ViewVolume /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="ViewVolume" type="kml:ViewVolumeType" substitutionGroup="kml:AbstractObjectGroup"/> public class ViewVolume :SPXMLElement, AbstractObjectGroup ,HasXMLElementValue { public static var elementName: String = "ViewVolume" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as PhotoOverlay: v.value.viewVolume = self default: break } } } } public var value : ViewVolumeType public required init(attributes:[String:String]){ self.value = ViewVolumeType(attributes: attributes) super.init(attributes: attributes) } public var abstractObject : AbstractObjectType { return self.value } } /// KML ViewVolumeType /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <complexType name="ViewVolumeType" final="#all"> /// <complexContent> /// <extension base="kml:AbstractObjectType"> /// <sequence> /// <element ref="kml:leftFov" minOccurs="0"/> /// <element ref="kml:rightFov" minOccurs="0"/> /// <element ref="kml:bottomFov" minOccurs="0"/> /// <element ref="kml:topFov" minOccurs="0"/> /// <element ref="kml:near" minOccurs="0"/> /// <element ref="kml:ViewVolumeSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// <element ref="kml:ViewVolumeObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// </sequence> /// </extension> /// </complexContent> /// </complexType> /// <element name="ViewVolumeSimpleExtensionGroup" abstract="true" type="anySimpleType"/> /// <element name="ViewVolumeObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/> public class ViewVolumeType: AbstractObjectType { public var leftFov: LeftFov! // = 0.0 public var rightFov: RightFov! // = 0.0 public var bottomFov: BottomFov! // = 0.0 public var topFov: TopFov! // = 0.0 public var near: Near! // = 0.0 public var viewVolumeSimpleExtensionGroup: [AnyObject] = [] public var viewVolumeObjectExtensionGroup: [AbstractObjectGroup] = [] }
853540d89f2e673f07443fa49480042c
37.848485
116
0.650936
false
false
false
false
iceman201/NZAirQuality
refs/heads/master
Classes/Plots/DotPlot.swift
mit
4
import UIKit open class DotPlot : Plot { // Customisation // ############# /// The shape to draw for each data point. open var dataPointType = ScrollableGraphViewDataPointType.circle /// The size of the shape to draw for each data point. open var dataPointSize: CGFloat = 5 /// The colour with which to fill the shape. open var dataPointFillColor: UIColor = UIColor.black /// If dataPointType is set to .Custom then you,can provide a closure to create any kind of shape you would like to be displayed instead of just a circle or square. The closure takes a CGPoint which is the centre of the shape and it should return a complete UIBezierPath. open var customDataPointPath: ((_ centre: CGPoint) -> UIBezierPath)? // Private State // ############# private var dataPointLayer: DotDrawingLayer? public init(identifier: String) { super.init() self.identifier = identifier } override func layers(forViewport viewport: CGRect) -> [ScrollableGraphViewDrawingLayer?] { createLayers(viewport: viewport) return [dataPointLayer] } private func createLayers(viewport: CGRect) { dataPointLayer = DotDrawingLayer( frame: viewport, fillColor: dataPointFillColor, dataPointType: dataPointType, dataPointSize: dataPointSize, customDataPointPath: customDataPointPath) dataPointLayer?.owner = self } } @objc public enum ScrollableGraphViewDataPointType : Int { case circle case square case custom }
4add75844111c2ace56b6bf5842371a7
31.959184
275
0.663158
false
false
false
false
finder39/Swimgur
refs/heads/master
SWNetworking/Comment.swift
mit
1
// // Comment.swift // Swimgur // // Created by Joseph Neuman on 11/2/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import Foundation public class Comment { public var id: Int! public var imageID: String? public var comment: String? public var author: String? public var authorID: String? public var onAlbum: Bool? public var albumCover: String? public var ups: Int? public var downs: Int? public var points: Int? public var datetime: Int = 0 public var parentID: String? public var deleted: Bool? public var vote: String? public var children: [Comment] = [] // expansion management in table public var expanded = false public var depth = 0 public init(dictionary:Dictionary<String, AnyObject>, depth theDepth:Int) { id = dictionary["id"] as AnyObject! as Int! imageID = dictionary["image_id"] as AnyObject? as? String comment = dictionary["comment"] as AnyObject? as? String author = dictionary["author"] as AnyObject? as? String authorID = dictionary["author_id"] as AnyObject? as? String onAlbum = dictionary["on_album"] as AnyObject? as? Bool albumCover = dictionary["album_cover"] as AnyObject? as? String ups = dictionary["ups"] as AnyObject? as? Int downs = dictionary["downs"] as AnyObject? as? Int points = dictionary["points"] as AnyObject? as? Int datetime = dictionary["datetime"] as AnyObject! as Int! parentID = dictionary["parent_id"] as AnyObject? as? String deleted = dictionary["deleted"] as AnyObject? as? Bool vote = dictionary["vote"] as AnyObject? as? String depth = theDepth if let children = (dictionary["children"] as AnyObject?) as? [Dictionary<String, AnyObject>] { for child in children { self.children.append(Comment(dictionary: child, depth:depth+1)) } } } public convenience init(dictionary:Dictionary<String, AnyObject>) { self.init(dictionary: dictionary, depth:0) } }
efa9fb59ed2a84fdfc0f69a216b63706
32.033333
98
0.684503
false
false
false
false
PimCoumans/Foil
refs/heads/master
Foil/Animation/AnimationCurve.swift
mit
2
// // Interpolatable.swift // Foil // // Created by Pim Coumans on 25/01/17. // Copyright © 2017 pixelrock. All rights reserved. // import CoreGraphics protocol Lerpable: Equatable { mutating func lerp(to: Self, t: Double) func lerped(to: Self, t: Double) -> Self static func + (lhs: Self, rhs: Self) -> Self } extension Lerpable { func lerped(to: Self, t: Double) -> Self { var value = self value.lerp(to: to, t: t) return value } } extension CGFloat: Lerpable { mutating internal func lerp(to: CGFloat, t: Double) { self += (to - self) * CGFloat(t) } } protocol AnimationCurve { func value(for progress: Double) -> Double } struct Linear: AnimationCurve { func value(for progress: Double) -> Double { return progress } } struct EaseIn: AnimationCurve { func value(for progress: Double) -> Double { return progress * progress } } struct EaseOut: AnimationCurve { func value(for progress: Double) -> Double { return -(progress * (progress - 2)); } } struct ElasticIn: AnimationCurve { func value(for p: Double) -> Double { return sin(13 * (Double.pi / 2) * p) * pow(2, 10 * (p - 1)); } } struct ElasticOut: AnimationCurve { func value(for p: Double) -> Double { return sin(-13 * (Double.pi / 2) * (p + 1)) * pow(2, -10 * p) + 1; } } struct Spring: AnimationCurve { var damping: Double var mass: Double var stiffness: Double var velocity: Double = 0 func value(for progress: Double) -> Double { if damping <= 0.0 || stiffness <= 0.0 || mass <= 0.0 { fatalError("Incorrect animation values") } let beta = damping / (2 * mass) let omega0 = sqrt(stiffness / mass) let omega1 = sqrt((omega0 * omega0) - (beta * beta)) let omega2 = sqrt((beta * beta) - (omega0 * omega0)) let x0: Double = -1 let oscillation: (Double) -> Double if beta < omega0 { // Underdamped oscillation = {t in let envelope = exp(-beta * t) let part2 = x0 * cos(omega1 * t) let part3 = ((beta * x0 + self.velocity) / omega1) * sin(omega1 * t) return -x0 + envelope * (part2 + part3) } } else if beta == omega0 { // Critically damped oscillation = {t in let envelope = exp(-beta * t) return -x0 + envelope * (x0 + (beta * x0 + self.velocity) * t) } } else { // Overdamped oscillation = {t in let envelope = exp(-beta * t) let part2 = x0 * cosh(omega2 * t) let part3 = ((beta * x0 + self.velocity) / omega2) * sinh(omega2 * t) return -x0 + envelope * (part2 + part3) } } return oscillation(progress) } }
d35b3d227651170b91e140453236c647
25.60177
85
0.52495
false
false
false
false
IAskWind/IAWExtensionTool
refs/heads/master
IAWExtensionTool/IAWExtensionTool/Classes/RatingBar/RatingBar.swift
mit
1
// // RatingBar.swift // Stareal // // Created by Nino on 16/9/1. // Copyright © 2016年 mirroon. All rights reserved. // import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } public protocol RatingBarDelegate { func ratingChanged(_ ratingBar:RatingBar,newRating:Float) } open class RatingBar: UIView { var delegate:RatingBarDelegate? open var starRating:Float? open var lastRating:Float? var starWidth:CGFloat? var starHeight:CGFloat? var unSelectedImage:UIImage? var halfSelectedImage:UIImage? var fullSelectedImage:UIImage? var s1:UIImageView? var s2:UIImageView? var s3:UIImageView? var s4:UIImageView? var s5:UIImageView? //是否是指示器 默认 true,表示用来显示,不用来打分 open var isIndicator:Bool = true //默认支持半颗星 open var supportHalfStar:Bool = true /**设置星星显示状态 deselectedName 满星图片名 halfSelectedName 半星图片名 fullSelectedName 空星图片名 starSideLength 星星边长 */ open func setSeletedState(_ deselectedName:String?,halfSelectedName:String?,fullSelectedName:String?,starSideLength:CGFloat, delegate:RatingBarDelegate){ self.delegate = delegate unSelectedImage = UIImage(named: deselectedName!) fullSelectedImage = UIImage(named: fullSelectedName!) halfSelectedImage = halfSelectedName == nil ? fullSelectedImage:UIImage(named: halfSelectedName!) starWidth = 0 starHeight = 0 if (starHeight < starSideLength) { starHeight = starSideLength } if (starWidth < starSideLength) { starWidth = starSideLength } //控件宽度适配 var frame = self.frame var viewWidth:CGFloat = starWidth! * 5 if (frame.size.width) > viewWidth { viewWidth = frame.size.width } frame.size.width = viewWidth self.frame = frame starRating = 0 lastRating = 0 s1 = UIImageView(image: unSelectedImage) s2 = UIImageView(image: unSelectedImage) s3 = UIImageView(image: unSelectedImage) s4 = UIImageView(image: unSelectedImage) s5 = UIImageView(image: unSelectedImage) //星星间距 let space:CGFloat = (viewWidth - starWidth!*5)/6 var starX = space let starY = (frame.height - starHeight!)/2 s1?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!) starX = starX + starWidth! + space s2?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!) starX = starX + starWidth! + space s3?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!) starX = starX + starWidth! + space s4?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!) starX = starX + starWidth! + space s5?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!) starX = starX + starWidth! + space s1?.isUserInteractionEnabled = false s2?.isUserInteractionEnabled = false s3?.isUserInteractionEnabled = false s4?.isUserInteractionEnabled = false s5?.isUserInteractionEnabled = false self.addSubview(s1!) self.addSubview(s2!) self.addSubview(s3!) self.addSubview(s4!) self.addSubview(s5!) } //设置评分值 open func displayRating(_ rating:Float){ s1?.image = unSelectedImage s2?.image = unSelectedImage s3?.image = unSelectedImage s4?.image = unSelectedImage s5?.image = unSelectedImage if (rating >= 1) { s1?.image = halfSelectedImage } if (rating >= 2) { s1?.image = fullSelectedImage } if (rating >= 3) { s2?.image = halfSelectedImage } if (rating >= 4) { s2?.image = fullSelectedImage } if (rating >= 5) { s3?.image = halfSelectedImage } if (rating >= 6) { s3?.image = fullSelectedImage } if (rating >= 7) { s4?.image = halfSelectedImage } if (rating >= 8) { s4?.image = fullSelectedImage } if (rating >= 9) { s5?.image = halfSelectedImage } if (rating >= 10) { s5?.image = fullSelectedImage } starRating = rating lastRating = rating delegate?.ratingChanged(self, newRating: rating) } open func rating() -> Float{ return starRating! } //手势 override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) self.touchesRating(touches as NSSet) } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) self.touchesRating(touches as NSSet) } //触发 open func touchesRating(_ touches:NSSet){ if(self.isIndicator == true){ return } let point:CGPoint = (touches.anyObject()! as AnyObject).location(in: self) let space:CGFloat = (self.frame.size.width - starWidth!*5)/6 //这里为10分制 可根据逻辑改为五分制 var newRating:Float = 0 if (point.x >= 0 && point.x <= self.frame.size.width) { if (point.x <= space+starWidth!*0.5) { if supportHalfStar{ newRating = 1; }else{ newRating = 2; } }else if (point.x < space*2+starWidth!){ newRating = 2; }else if (point.x < space*2+starWidth!*1.5){ if supportHalfStar{ newRating = 3; }else{ newRating = 4; } }else if (point.x <= 3*space+2*starWidth!){ newRating = 4; }else if (point.x <= 3*space+2.5*starWidth!){ if supportHalfStar{ newRating = 5; }else{ newRating = 6; } }else if (point.x <= 4*space+3*starWidth!){ newRating = 6; }else if (point.x <= 4*space+3.5*starWidth!){ if supportHalfStar{ newRating = 7; }else{ newRating = 8; } }else if (point.x <= 5*space+4*starWidth!){ newRating = 8; }else if (point.x <= 5*space+4.5*starWidth!){ if supportHalfStar{ newRating = 9; }else{ newRating = 10; } }else { newRating = 10; } } if (newRating != lastRating){ self.displayRating(newRating) } } }
aa0b60d8af3c3eda1fda4e256c3c2f6b
28.703252
157
0.538251
false
false
false
false
JohnEstropia/Animo
refs/heads/master
AnimoDemo/AnimoDemo/ViewController.swift
mit
2
// // ViewController.swift // AnimoDemo // // Copyright © 2016 eureka, 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 UIKit import Animo // MARK: - ViewController final class ViewController: UIViewController { // MARK: UIViewController override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.startSqureView1() self.startSquareView2() let fromPoint = CGPoint(x: 0, y: 0) let toPoint = CGPoint(x: 20, y: 20) let fromColor = UIColor.red let toColor = UIColor.blue let someView = UIView() let positionAnimation = CABasicAnimation(keyPath: "position") positionAnimation.duration = 1 positionAnimation.fromValue = NSValue(cgPoint: fromPoint) positionAnimation.toValue = NSValue(cgPoint: toPoint) let colorAnimation = CABasicAnimation(keyPath: "backgroundColor") colorAnimation.duration = 1 colorAnimation.fromValue = fromColor.cgColor colorAnimation.toValue = toColor.cgColor let animationGroup = CAAnimationGroup() animationGroup.animations = [positionAnimation, colorAnimation] animationGroup.fillMode = kCAFillModeForwards animationGroup.isRemovedOnCompletion = false animationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) someView.layer.add(animationGroup, forKey: "animationGroup") _ = someView.layer.runAnimation( Animo.group( Animo.move(from: fromPoint, to: toPoint, duration: 1), Animo.keyPath("backgroundColor", from: fromColor, to: toColor, duration: 1), timingMode: .easeInOut, options: Options(fillMode: .forwards) ) ) } // MARK: Private @IBOutlet private dynamic weak var squareView1: UIView? @IBOutlet private dynamic weak var squareView2: UIView? private func startSqureView1() { _ = self.squareView1?.layer.runAnimation( Animo.replayForever( Animo.group( Animo.autoreverse( Animo.rotateDegrees( by: 360, duration: 1.5, timingMode: .easeInOutSine ) ), Animo.sequence( Animo.wait(1), Animo.autoreverse( Animo.move( to: CGPoint(x: 200, y: 100), duration: 1, timingMode: .easeInOutSine ) ) ), Animo.autoreverse( Animo.keyPath( "cornerRadius", to: self.squareView1?.layer.bounds.width ?? 0, duration: 1.5, timingMode: .easeInOutSine ) ), Animo.autoreverse( Animo.keyPath( "borderWidth", to: 2, duration: 1.5 ) ), Animo.sequence( Animo.keyPath( "backgroundColor", from: UIColor.red, to: UIColor.blue, duration: 1, timingMode: .easeInOut ), Animo.keyPath( "backgroundColor", to: UIColor.yellow, duration: 1, timingMode: .easeInOut ), Animo.keyPath( "backgroundColor", to: UIColor.red, duration: 1, timingMode: .easeInOut ) ) ) ) ) } private func startSquareView2() { _ = self.squareView2?.layer.runAnimation( Animo.sequence( Animo.wait(1), Animo.replayForever( Animo.sequence( Animo.move( by: CGPoint(x: 100, y: 200), duration: 2, timingMode: .easeInOutBack ), Animo.rotateDegrees( by: -180, duration: 1, timingMode: .easeInOutBack ), Animo.group( Animo.scaleX( by: 2, duration: 1, timingMode: .easeInOutBack ), Animo.scaleY( by: 0.5, duration: 1, timingMode: .easeInOutBack ) ), Animo.wait(1), Animo.move( by: CGPoint(x: -100, y: -200), duration: 2, timingMode: .easeInOutBack ), Animo.rotateDegrees( by: 180, duration: 1, timingMode: .easeInOutBack ), Animo.group( Animo.scaleX( to: 1, duration: 1, timingMode: .easeInOutBack ), Animo.scaleY( to: 1, duration: 1, timingMode: .easeInOutBack ) ) ) ) ) ) } }
c4c30245de6ea3444b62a75b23b8cd47
35.404762
104
0.431524
false
false
false
false
machelix/Swift-SpriteKit-Analog-Stick
refs/heads/master
AnalogStick Demo/AnalogStick Demo/AnalogStick/AnalogStick.swift
mit
1
// // AnalogStick.swift // Joystick // // Created by Dmitriy Mitrophanskiy on 28.09.14. // // import SpriteKit public typealias AnalogStickMoveHandler = (AnalogStick) -> () public struct AnalogStickData: CustomStringConvertible { var velocity: CGPoint = CGPointZero var angular: CGFloat = 0 public var description: String { return "velocity: \(velocity), angular: \(angular)" } } let kStickOfSubstrateWidthPercent: CGFloat = 0.5 // [0..1] public class AnalogStick: SKNode { let stickNode = SKSpriteNode() let substrateNode = SKSpriteNode() private var tracking = false private var velocityLoop: CADisplayLink? var data = AnalogStickData() var trackingHandler: AnalogStickMoveHandler? private var _stickColor = UIColor.lightGrayColor() private var _substrateColor = UIColor.darkGrayColor() var stickColor: UIColor { get { return _stickColor } set(newColor) { stickImage = UIImage.circleWithRadius(diameter * kStickOfSubstrateWidthPercent, color: newColor) _stickColor = newColor } } var substrateColor: UIColor { get { return _substrateColor } set(newColor) { substrateImage = UIImage.circleWithRadius(diameter, color: newColor, borderWidth: 5, borderColor: UIColor.blackColor()) _substrateColor = newColor } } var stickImage: UIImage? { didSet { guard let newImage = stickImage else { stickColor = _stickColor return } stickNode.texture = SKTexture(image: newImage) } } var substrateImage: UIImage? { didSet { guard let newImage = substrateImage else { substrateColor = _substrateColor return } substrateNode.texture = SKTexture(image: newImage) } } var diameter: CGFloat { get { return max(substrateNode.size.width, substrateNode.size.height) } set { substrateNode.size = CGSizeMake(newValue, newValue) stickNode.size = CGSizeMake(newValue * kStickOfSubstrateWidthPercent, newValue * kStickOfSubstrateWidthPercent) } } func listen() { guard tracking else { return } trackingHandler?(self) } let kThumbSpringBackDuration: NSTimeInterval = 0.15 // action duration var anchorPointInPoints = CGPointZero init(diameter: CGFloat, substrateImage: UIImage? = nil, stickImage: UIImage? = nil) { super.init() userInteractionEnabled = true; self.diameter = diameter self.stickImage = stickImage self.substrateImage = substrateImage addChild(substrateNode) addChild(stickNode) velocityLoop = CADisplayLink(target: self, selector: Selector("listen")) velocityLoop!.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) } convenience init(diameter: CGFloat, substrateImage: UIImage?) { self.init(diameter: diameter, substrateImage: substrateImage, stickImage: nil) } convenience init(diameter: CGFloat, stickImage: UIImage?) { self.init(diameter: diameter, substrateImage: nil, stickImage: stickImage) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func resetStick() { tracking = false data.velocity = CGPointZero data.angular = 0 let easeOut = SKAction.moveTo(anchorPointInPoints, duration: kThumbSpringBackDuration) easeOut.timingMode = .EaseOut stickNode.runAction(easeOut) } //MARK: - Overrides public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) for touch in touches { let touchedNode = nodeAtPoint(touch.locationInNode(self)) guard self.stickNode == touchedNode && !tracking else { return } tracking = true } } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event); for touch: AnyObject in touches { let location = touch.locationInNode(self); let xDistance: Float = Float(location.x - self.stickNode.position.x) let yDistance: Float = Float(location.y - self.stickNode.position.y) guard tracking && sqrtf(powf(xDistance, 2) + powf(yDistance, 2)) <= Float(diameter * 2) else { return } let xAnchorDistance: CGFloat = (location.x - anchorPointInPoints.x) let yAnchorDistance: CGFloat = (location.y - anchorPointInPoints.y) if sqrt(pow(xAnchorDistance, 2) + pow(yAnchorDistance, 2)) <= self.stickNode.size.width { let moveDifference: CGPoint = CGPointMake(xAnchorDistance , yAnchorDistance) stickNode.position = CGPointMake(anchorPointInPoints.x + moveDifference.x, anchorPointInPoints.y + moveDifference.y) } else { let magV = sqrt(xAnchorDistance * xAnchorDistance + yAnchorDistance * yAnchorDistance) let aX = anchorPointInPoints.x + xAnchorDistance / magV * stickNode.size.width let aY = anchorPointInPoints.y + yAnchorDistance / magV * stickNode.size.width stickNode.position = CGPointMake(aX, aY) } let tNAnchPoinXDiff = stickNode.position.x - anchorPointInPoints.x; let tNAnchPoinYDiff = stickNode.position.y - anchorPointInPoints.y data = AnalogStickData(velocity: CGPointMake(tNAnchPoinXDiff, tNAnchPoinYDiff), angular: CGFloat(-atan2f(Float(tNAnchPoinXDiff), Float(tNAnchPoinYDiff)))) } } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) resetStick() } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) resetStick() } } extension UIImage { static func circleWithRadius(radius: CGFloat, color: UIColor, borderWidth: CGFloat = 0, borderColor: UIColor? = nil) -> UIImage { let diametr = radius * 2 UIGraphicsBeginImageContextWithOptions(CGSizeMake(diametr + borderWidth * 2, diametr + borderWidth * 2), false, 0) let bPath = UIBezierPath(ovalInRect: CGRect(origin: CGPoint(x: borderWidth, y: borderWidth), size: CGSizeMake(diametr, diametr))) if let bC = borderColor { bC.setStroke() bPath.lineWidth = borderWidth bPath.stroke() } color.setFill() bPath.fill() let rImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return rImage } }
fdf61ef217f9e245b439a519fe12cdd0
31.590517
166
0.598995
false
false
false
false
JohnDuxbury/xcode
refs/heads/master
Fingers/Fingers/ViewController.swift
apache-2.0
1
// // ViewController.swift // Fingers // // Created by JD on 09/05/2015. // Copyright (c) 2015 JDuxbury.me. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var guessResult: UILabel! @IBOutlet weak var guessEntry: UITextField! @IBAction func guessButton(sender: AnyObject) { var randomNumber = arc4random_uniform(6) var guessInt = guessEntry.text.toInt() guessResult.text=toString(randomNumber) if guessInt != nil { if Int(randomNumber) == guessInt { guessResult.text="Good Guess!" } else { guessResult.text="Sorry - the correct number was \(randomNumber)!" } }else{ guessResult.text="Please enter a number between 1 - 5!" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
52bdcf03e1923f0f6626de871ecad89e
21.375
82
0.557861
false
false
false
false
BrettRToomey/brett-xml
refs/heads/master
Sources/BML.swift
mit
1
import Core import Node public typealias XML = BML public final class BML { var _name: Bytes var _value: Bytes? var nameCache: String? var valueCache: String? public var name: String { if let nameCache = nameCache { return nameCache } else { let result = _name.fasterString nameCache = result return result } } public var value: String? { guard _value != nil else { return nil } if let valueCache = valueCache { return valueCache } else { let result = _value!.fasterString valueCache = result return result } } public var attributes: [BML] public var children: [BML] public weak var parent: BML? init( name: Bytes, value: Bytes? = nil, attributes: [BML] = [], children: [BML] = [], parent: BML? = nil ) { _name = name _value = value self.attributes = attributes self.children = children self.parent = parent } convenience init( name: String, value: String? = nil, attributes: [BML] = [], children: [BML] = [], parent: BML? = nil ) { self.init( name: name.bytes, value: value?.bytes, attributes: attributes, children: children, parent: parent ) } } extension BML { func addChild(key: Bytes, value: Bytes) { let sighting = BML(name: key, value: value, parent: self) add(child: sighting) } func addAttribute(key: Bytes, value: Bytes) { let sighting = BML(name: key, value: value, parent: self) add(attribute: sighting) } func add(child: BML) { child.parent = self children.append(child) } func add(attribute: BML) { attributes.append(attribute) } } extension BML { public func children(named name: String) -> [BML] { let name = name.bytes return children.filter { $0._name == name } } public func firstChild(named name: String) -> BML? { let name = name.bytes for child in children { if child._name == name { return child } } return nil } public func attributes(named name: String) -> [BML] { let name = name.bytes return children.filter { $0._name == name } } public func firstAttribute(named name: String) -> BML? { let name = name.bytes for attribute in attributes { if attribute._name == name { return attribute } } return nil } } extension BML { public subscript(_ name: String) -> BML? { return firstChild(named: name) } } extension BML { /*func makeNode() -> Node { // String if let text = text?.fasterString, children.count == 0 { return .string(text) } // Array if children.count == 1, text == nil, children[0].value.count > 1 { return .array( children[0].value.map { $0.makeNode() } ) } // Object var object = Node.object([:]) if let text = text?.fasterString { object["text"] = .string(text) } children.forEach { let subObject: Node if $0.value.count == 1 { subObject = $0.value[0].makeNode() } else { subObject = .array( $0.value.map { $0.makeNode() } ) } object[$0.key.fasterString] = subObject } return object }*/ }
8fdd0395a15b6680a823acbe7df50780
21.539326
74
0.472333
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Media/StockPhotos/StockPhotosDataLoader.swift
gpl-2.0
2
/// Implementations of this protocol will be notified when data is loaded from the StockPhotosService protocol StockPhotosDataLoaderDelegate: AnyObject { func didLoad(media: [StockPhotosMedia], reset: Bool) } /// Uses the StockPhotosService to load stock photos, handling pagination final class StockPhotosDataLoader { private let service: StockPhotosService private weak var delegate: StockPhotosDataLoaderDelegate? private var request: StockPhotosSearchParams? fileprivate enum State { case loading case idle } fileprivate var state: State = .idle init(service: StockPhotosService, delegate: StockPhotosDataLoaderDelegate) { self.service = service self.delegate = delegate } func search(_ params: StockPhotosSearchParams) { request = params let isFirstPage = request?.pageable?.pageIndex == StockPhotosPageable.defaultPageIndex state = .loading DispatchQueue.main.async { [weak self] in WPAnalytics.track(.stockMediaSearched) self?.service.search(params: params) { resultsPage in self?.state = .idle self?.request = StockPhotosSearchParams(text: self?.request?.text, pageable: resultsPage.nextPageable()) if let content = resultsPage.content() { self?.delegate?.didLoad(media: content, reset: isFirstPage) } } } } func loadNextPage() { // Bail out if there is another active request guard state == .idle else { return } // Bail out if we are not aware of the pagination status guard let request = request else { return } // Bail out if we do not expect more pages of data guard request.pageable?.next() != nil else { return } search(request) } }
8c04b9bb5b889a9e0b724c5d67d24caa
31.525424
120
0.633663
false
false
false
false
clwm01/RCTools
refs/heads/master
RCToolsDemo/RCToolsDemo/AudioStreamViewController.swift
mit
2
// // AudioStreamViewController.swift // // // Created by Rex Tsao on 3/14/16. // // import UIKit class AudioStreamViewController: UIViewController { private let adds = ["http://www.bu-chou-la.com/uploadfile/24Vi.mp3", "http://120.24.165.30/ShadoPan_A_Hero.mp3"] private let titles = ["24Vi.mp3", "ShadoPan_A_Hero.mp3"] private var queue: AFSoundQueue? private lazy var items = [AFSoundItem]() private var player: RTAudioPlayback? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.whiteColor() let startButton = UIButton() startButton.setTitle("start", forState: .Normal) startButton.sizeToFit() startButton.addTarget(self, action: #selector(AudioStreamViewController.start), forControlEvents: .TouchUpInside) startButton.frame.origin = CGPointMake(10, 64) startButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) self.view.addSubview(startButton) let stopButton = UIButton() stopButton.setTitle("pause", forState: .Normal) stopButton.sizeToFit() stopButton.addTarget(self, action: #selector(AudioStreamViewController.pause), forControlEvents: .TouchUpInside) stopButton.frame.origin = CGPointMake(startButton.frame.origin.x + startButton.frame.width + 10, 64) stopButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) self.view.addSubview(stopButton) let tableView = UITableView(frame: CGRectMake(0, stopButton.frame.origin.y + stopButton.frame.height + 10, self.view.bounds.width, self.view.bounds.height - stopButton.frame.height - 10)) tableView.delegate = self tableView.dataSource = self tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "music") self.view.addSubview(tableView) // AFSoundManager let item1 = AFSoundItem(streamingURL: NSURL(string: self.adds[0])) let item2 = AFSoundItem(streamingURL: NSURL(string: self.adds[1])) self.items.append(item1) self.items.append(item2) self.queue = AFSoundQueue(items: items) // self.queue?.playCurrentItem() self.queue?.listenFeedbackUpdatesWithBlock({ item in RTPrint.shareInstance().prt("Item duration: \(item.duration) - time elapsed: \(item.timePlayed)") }, andFinishedBlock: { nextItem in if nextItem != nil { RTPrint.shareInstance().prt("Finished item, next one is \(nextItem.title)") } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.queue?.clearQueue() } func start() { RTPrint.shareInstance().prt("[AudioStreamViewController:start] You touched the start button.") self.queue?.playCurrentItem() self.player?.restart() } func pause() { self.queue?.pause() self.player?.pause() } } extension AudioStreamViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("music")! as UITableViewCell cell.textLabel!.text = self.titles[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.queue?.playItem(self.items[indexPath.row]) tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } }
976852156eff59499d3f6375a04442ea
37.811321
195
0.663588
false
false
false
false
anzfactory/TwitterClientCLI
refs/heads/master
Sources/TwitterClientCore/TwitterClient.swift
mit
1
import AppKit import Foundation import Dispatch import APIKit import Swiftline import Rainbow public final class Client { let oauth: TwitterOAuth = TwitterOAuth( consumerKey: Keys.consumerKey, consumerSecret: Keys.consumerSecret, oauthToken: UserDefaults.standard.string(forKey: "oauthtoken"), oauthTokenSecret: UserDefaults.standard.string(forKey: "oauthtokensecret") ) public init() { } } extension Client { public func auth() { let request = RequestTokenType(oauth: self.oauth) Session.send(request) { [weak self] result in switch result { case .success(let requestToken): self?.oauth.update(by: requestToken) NSWorkspace.shared.open(URL(string: TwitterOAuth.URLs.authorize(oauthToken: requestToken.oauthToken).string)!) let pinCode = ask("Enter PIN") self?.getAccessToken(pinCode: pinCode) case .failure(let error): print(error.localizedDescription.red) exit(0) } } dispatchMain() } public func logout() { UserDefaults.standard.removeObject(forKey: "oauthtoken") UserDefaults.standard.removeObject(forKey: "oauthtokensecret") print("アクセストークンをクリアしました\nアプリ連携の解除は忘れずに行って下さい".blue) } public func tweet(_ message: String, replyId: Int, path: String) { if message.isEmpty && path.isEmpty { print("message and path is empty...".red) return } self.getTweet(tweetId: replyId) { tweet in var msg = message if let tweet = tweet { msg = "@\(tweet.user.screenName) \(message)" } self.uploadMedia(path: path, callback: { mediaId in let request = TweetType(oauth: self.oauth, message: msg, replyId: replyId, mediaId: mediaId) Session.send(request) { [weak self] result in switch result { case .success(let tweet): print("-- done --".blue) self?.output(items: [tweet]) case .failure(let error): print(error.localizedDescription.red) } exit(0) } }) } dispatchMain() } public func retweet(_ tweetId: Int) { let request = RetweetType(oauth: self.oauth, tweetId: tweetId) Session.send(request) { [weak self] result in switch result { case .success(let tweet): print("-- retweeted --".blue) self?.output(items: [tweet]) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func unretweet(_ tweetId: Int) { let request = UnRetweetType(oauth: self.oauth, tweetId: tweetId) Session.send(request) { [weak self] result in switch result { case .success(let tweet): print("-- unretweeted --".blue) self?.output(items: [tweet]) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func favorites(count: Int = 30) { let request = FavoritesType(oauth: self.oauth, count: count) Session.send(request) { [weak self] result in switch result { case .success(let tweets): self?.output(items: tweets.list) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func favorite(_ tweetId: Int) { let request = FavoriteType(oauth: self.oauth, tweetId: tweetId) Session.send(request) { [weak self] result in switch result { case .success(let tweet): print("-- favorited --".blue) self?.output(items: [tweet]) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func unfavorite(_ tweetId: Int) { let request = UnFavoriteType(oauth: self.oauth, tweetId: tweetId) Session.send(request) { [weak self] result in switch result { case .success(let tweet): print("-- unfavorited --".blue) self?.output(items: [tweet]) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func love(_ tweetId: Int) { let request = FavoriteType(oauth: self.oauth, tweetId: tweetId) Session.send(request) { switch $0 { case .success(_): let retweetRequest = RetweetType(oauth: self.oauth, tweetId: tweetId) Session.send(retweetRequest) { [weak self] result in switch result { case .success(let tweet): print("-- retweeted & favorited --".blue) self?.output(items: [tweet]) case .failure(let error): print(error.localizedDescription.red) } exit(0) } case .failure(let error): print(error.localizedDescription.red) exit(0) } } dispatchMain() } public func timeline(count: Int = 30, sinceId: Int = 0, maxId: Int = 0) { var count = count if count <= 0 { print("invalid count...".red) return } else if count > 200 { count = 200 } let request = TimelineType(oauth: self.oauth, count: count, sinceId: sinceId, maxId: maxId) Session.send(request) { [weak self] result in switch result { case .success(let tweets): self?.output(items: tweets.list) case.failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func userTimeline(_ screenName: String, count: Int = 30, sinceId: Int = 0, maxId: Int = 0) { var count = count if count <= 0 { print("invalid count...".red) return } else if count > 200 { count = 200 } let request = UserTimelineType(oauth: self.oauth, screenName: screenName, count: count, sinceId: sinceId, maxId: maxId) Session.send(request) { [weak self] result in switch result { case .success(let tweets): self?.output(items: tweets.list) case.failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func searchTweet(_ q: String, count: Int = 30, sinceId: Int, maxId: Int) { var count = count if count <= 0 { print("invalid count...".red) return } else if count > 200 { count = 200 } let request = SearchTweetType(oauth: self.oauth, q: q, count: count, sinceId: sinceId, maxId: maxId) Session.send(request) { [weak self] result in switch result { case .success(let tweets): self?.output(items: tweets.list) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func searchUser(_ q: String, count: Int = 30) { var count = count if count <= 0 { print("invalid count...".red) return } else if count > 200 { count = 200 } let request = SearchUserType(oauth: self.oauth, q: q, count: count) Session.send(request) { [weak self] result in switch result { case .success(let users): self?.output(items: users.list) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func follow(userId: Int, screenName: String) { let request = FollowType(oauth: self.oauth, userId: userId, screenName: screenName) Session.send(request) { switch $0 { case .success(let user): print("follow: @\(user.screenName)(\(user.id))".blue) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func unfollow(userId: Int, screenName: String) { let request = UnFollowType(oauth: self.oauth, userId: userId, screenName: screenName) Session.send(request) { switch $0 { case .success(let user): print("unfollow: @\(user.screenName)(\(user.id))".blue) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func me() { let request = AccountSettingsType(oauth: self.oauth) Session.send(request) { [weak self] result in switch result { case .success(let settings): self?.output(items: [settings]) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } public func rateLimit() { let request = RateLimitType(oauth: self.oauth) Session.send(request) { [weak self] result in switch result { case .success(let rateLimit): self?.output(items: [rateLimit]) case .failure(let error): print(error.localizedDescription.red) } exit(0) } dispatchMain() } } extension Client { fileprivate func getAccessToken(pinCode: String) { let request = AccessTokenType(oauth: self.oauth, pinCode: pinCode) Session.send(request) { [weak self] result in switch result { case .success(let accessToken): UserDefaults.standard.set(accessToken.oauthToken, forKey: "oauthtoken") UserDefaults.standard.set(accessToken.oauthTokenSecret, forKey: "oauthtokensecret") self?.oauth.update(by: accessToken) print("Hello \(accessToken.userName)".blue) case .failure(let error): print(error.localizedDescription.red) } exit(0) } } fileprivate func uploadMedia(path: String, callback: @escaping (Int?) -> Void) { if path.isEmpty { callback(nil) return } let request = MediaUploadType(oauth: self.oauth, url: URL(fileURLWithPath: path)) Session.send(request) { switch $0 { case .success(let media): callback(media.id) case .failure(_): callback(nil) } } } fileprivate func getTweet(tweetId: Int, callback: @escaping (Tweet?) -> Void) { if 0 >= tweetId { callback(nil) return } let request = ShowTweetType(oauth: self.oauth, tweetId: tweetId) Session.send(request) { switch $0 { case .success(let tweet): callback(tweet) case .failure(let error): print(error) callback(nil) } } } fileprivate func output(items: [Outputable]) { for item in items { print(item.output()) print("") } } }
3cc918243d1c960e369bce168f1ec818
31.471204
127
0.510158
false
false
false
false
premefeed/premefeed-ios
refs/heads/master
PremeFeed-iOS/PremeFeedAPI.swift
mit
1
// // PremeFeedAPI.swift // PremeFeed-iOS // // Created by Cryptoc1 on 12/20/15. // Copyright © 2015 Cryptoc1. All rights reserved. // import Foundation class PremeFeedAPI { // Default api url (NOTE: no ending slash) let apiURL: String = "https://premefeed.herokuapp.com/api/v1" init() { // Empty } /* * * The folloiwing functions make requests to the api endpoint on the heroku app, they're pretty straightfoward. * Because NSURLSession is asynchronous, we have to use callbacks * */ func getItemById(id: String, callback: (SupremeItem) -> Void) { self.makeRequest(NSURL(string: "\(self.apiURL)/item/id?id=\(id)")!, callback: { (json) -> Void in callback(SupremeItem(json: json)) return }) } func getItemByLink(link: String, callback: (SupremeItem) -> Void) { self.makeRequest(NSURL(string: "\(self.apiURL)/item/link?link=\(link.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!)")!, callback: { (json) -> Void in callback(SupremeItem(json: json)) return }) } func getItemsByTitle(title: String, callback: (Array<SupremeItem>) -> Void) { self.makeRequest(NSURL(string: "\(self.apiURL)/items/title?title=\(title.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!)")!, callback: { (json) -> Void in var ret = [SupremeItem]() for (i, _) in json["items"].enumerate() { ret.append(SupremeItem(json: json["items"][i])) } callback(ret) return }) } func getItemsByAvailability(availability: String, callback: (Array<SupremeItem>) -> Void) { self.makeRequest(NSURL(string: "\(self.apiURL)/items/availability?availability=\(availability.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()))")!, callback: { (json) -> Void in var ret = [SupremeItem]() for (i, _) in json["items"].enumerate() { ret.append(SupremeItem(json: json["items"][i])) } callback(ret) return }) } func getAllItems(callback: (Array<SupremeItem>) -> Void) { self.makeRequest(NSURL(string: "\(self.apiURL)/items/all")!, callback: { (json) -> Void in var ret = [SupremeItem]() for (i, _) in json["items"].enumerate() { ret.append(SupremeItem(json: json["items"][i])) } callback(ret) }) } private func makeRequest(url: NSURL, callback: (JSON) -> Void) { let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in callback(JSON(data: data!)); } task.resume() } } // Converts JSON to a native object class SupremeItem { var id: String? var title: String? var style: String? var link: String? var description: String? var price: Int? var images: Array<String>? var image: String? var availability: String? var results: Bool init(json: JSON) { if (json.stringValue == "No Results") { self.results = false } else { self.results = true self.id = json["id"].stringValue self.title = json["title"].stringValue self.style = json["style"].stringValue self.link = json["link"].stringValue self.description = json["description"].stringValue self.price = json["price"].intValue self.images = [String]() for (i, _) in json["images"].enumerate() { self.images!.append(json["images"][i].stringValue) } self.image = json["image"].stringValue self.availability = json["availability"].stringValue } } }
b60770d1e1d4fb23c07ce1b21ac64648
33.605263
218
0.580629
false
false
false
false
saagarjha/iina
refs/heads/develop
iina/GuideWindowController.swift
gpl-3.0
1
// // GuideWindowController.swift // iina // // Created by Collider LI on 26/8/2020. // Copyright © 2020 lhc. All rights reserved. // import Cocoa import WebKit fileprivate let highlightsLink = "https://iina.io/highlights" class GuideWindowController: NSWindowController { override var windowNibName: NSNib.Name { return NSNib.Name("GuideWindowController") } enum Page { case highlights } private var page = 0 var highlightsWebView: WKWebView? @IBOutlet weak var highlightsContainerView: NSView! @IBOutlet weak var highlightsLoadingIndicator: NSProgressIndicator! @IBOutlet weak var highlightsLoadingFailedBox: NSBox! override func windowDidLoad() { super.windowDidLoad() } func show(pages: [Page]) { loadHighlightsPage() showWindow(self) } private func loadHighlightsPage() { window?.title = NSLocalizedString("guide.highlights", comment: "Highlights") let webView = WKWebView() highlightsWebView = webView webView.isHidden = true webView.translatesAutoresizingMaskIntoConstraints = false webView.navigationDelegate = self highlightsContainerView.addSubview(webView, positioned: .below, relativeTo: nil) Utility.quickConstraints(["H:|-0-[v]-0-|", "V:|-0-[v]-0-|"], ["v": webView]) let (version, _) = Utility.iinaVersion() webView.load(URLRequest(url: URL(string: "\(highlightsLink)/\(version.split(separator: "-").first!)/")!)) highlightsLoadingIndicator.startAnimation(nil) } @IBAction func continueBtnAction(_ sender: Any) { window?.close() } @IBAction func visitIINAWebsite(_ sender: Any) { NSWorkspace.shared.open(URL(string: AppData.websiteLink)!) } } extension GuideWindowController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.url { if url.absoluteString.starts(with: "https://iina.io/highlights/") { decisionHandler(.allow) return } else { NSWorkspace.shared.open(url) } } decisionHandler(.cancel) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { highlightsLoadingIndicator.stopAnimation(nil) highlightsLoadingIndicator.isHidden = true highlightsLoadingFailedBox.isHidden = false } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { highlightsLoadingIndicator.stopAnimation(nil) highlightsLoadingIndicator.isHidden = true highlightsLoadingFailedBox.isHidden = false } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { highlightsLoadingIndicator.stopAnimation(nil) highlightsLoadingIndicator.isHidden = true highlightsWebView?.isHidden = false } } class GuideWindowButtonCell: NSButtonCell { override func awakeFromNib() { self.attributedTitle = NSAttributedString( string: title, attributes: [NSAttributedString.Key.foregroundColor: NSColor.white] ) } override func drawBezel(withFrame frame: NSRect, in controlView: NSView) { NSGraphicsContext.saveGraphicsState() let rectPath = NSBezierPath( roundedRect: NSRect(x: 2, y: 2, width: frame.width - 4, height: frame.height - 4), xRadius: 4, yRadius: 4 ) let shadow = NSShadow() shadow.shadowOffset = NSSize(width: 0, height: 0) shadow.shadowBlurRadius = 1 shadow.shadowColor = NSColor.black.withAlphaComponent(0.5) shadow.set() if isHighlighted { NSColor.systemBlue.highlight(withLevel: 0.1)?.setFill() } else { NSColor.systemBlue.setFill() } rectPath.fill() NSGraphicsContext.restoreGraphicsState() } }
6c164ee1f8f5d3d2bcea7b71c0ba547c
29.766129
155
0.718742
false
false
false
false
u10int/Kinetic
refs/heads/master
Pod/Classes/Animation.swift
mit
1
// // Animation.swift // Kinetic // // Created by Nicholas Shipes on 12/31/15. // Copyright © 2015 Urban10 Interactive, LLC. All rights reserved. // import UIKit public class Animation: Animatable, TimeScalable, Repeatable, Reversable, Subscriber { fileprivate static var counter: UInt32 = 0 public var hashValue: Int { return Unmanaged.passUnretained(self).toOpaque().hashValue } public init() { Animation.counter += 1 self.id = Animation.counter self.updated.observe { [weak self] (animation) in self?.onUpdate() } } deinit { kill() } // MARK: Animatable public var state: AnimationState = .idle { willSet { guard newValue != state else { return } if newValue == .running && (state == .completed || state == .cancelled) { reset() } } didSet { guard oldValue != state else { return } switch state { case .pending: if canSubscribe() { Scheduler.shared.add(self) } break case .running: started.trigger(self) // started.close(self) case .idle: break case .cancelled: kill() cancelled.trigger(self) break case .completed: // kill() Scheduler.shared.remove(self) completed.trigger(self) // completed.close(self) print("animation \(id) done") break } } } public var duration: TimeInterval = 1.0 { didSet { if duration == 0 { duration = 0.001 } } } public var delay: TimeInterval = 0 public var progress: Double { get { return min(Double(elapsed / (delay + duration)), 1.0) } set { seek(duration * TimeInterval(newValue)) } } public var totalProgress: Double { get { return Double(min(Float(totalTime / totalDuration), Float(1.0))) } set { seek(totalDuration * TimeInterval(newValue)) } } private var hasPlayed = false public var startTime: TimeInterval = 0 public var endTime: TimeInterval { return startTime + totalDuration } public var totalDuration: TimeInterval { return (duration * TimeInterval(repeatCount + 1)) + (repeatDelay * TimeInterval(repeatCount)) } public var totalTime: TimeInterval { return min(runningTime, totalDuration) } internal(set) public var elapsed: TimeInterval = 0 public var time: TimeInterval { return (elapsed - delay) } internal var runningTime: TimeInterval = 0 internal(set) public var timingFunction: TimingFunction = Linear().timingFunction internal(set) public var spring: Spring? @discardableResult public func duration(_ duration: TimeInterval) -> Self { self.duration = duration return self } @discardableResult public func delay(_ delay: TimeInterval) -> Self { self.delay = delay return self } @discardableResult public func ease(_ easing: EasingType) -> Self { timingFunction = easing.timingFunction return self } @discardableResult public func spring(tension: Double, friction: Double = 3) -> Self { spring = Spring(tension: tension, friction: friction) return self } public func play() { // if animation is currently paused, reset it since play() starts from the beginning if hasPlayed && state == .idle { stop() } else if state == .completed { reset() } if state != .running && state != .pending { state = .pending hasPlayed = true } } public func stop() { if state == .running || state == .pending || isPaused() { state = .cancelled } else { reset() } } public func pause() { if state == .running || state == .pending { state = .idle } } public func resume() { if state == .idle { state = .running } } @discardableResult public func seek(_ offset: TimeInterval) -> Self { guard offset != elapsed else { return self } pause() state = .idle if (offset > 0 && offset < totalDuration) { } let time = delay + elapsedTimeFromSeekTime(offset) // print("\(self).\(self.id).seek - offset: \(offset), time: \(time), elapsed: \(elapsed), duration: \(duration)") render(time: time) return self } @discardableResult public func forward() -> Self { direction = .forward return self } @discardableResult public func reverse() -> Self { direction = .reversed return self } public func restart(_ includeDelay: Bool = false) { reset() elapsed = includeDelay ? 0 : delay play() } internal func reset() { seek(0) runningTime = 0 cycle = 0 progress = 0 state = .idle direction = .forward updated.trigger(self) } var started = Event<Animation>() var updated = Event<Animation>() var completed = Event<Animation>() var cancelled = Event<Animation>() var repeated = Event<Animation>() // MARK: TimeScalable public var timeScale: Double = 1.0 // MARK: Repeatable private(set) public var cycle: Int = 0 private(set) public var repeatCount: Int = 0 private(set) public var repeatDelay: TimeInterval = 0.0 private(set) public var repeatForever: Bool = false @discardableResult public func repeatCount(_ count: Int) -> Self { repeatCount = count return self } @discardableResult public func repeatDelay(_ delay: TimeInterval) -> Self { repeatDelay = delay return self } @discardableResult public func forever() -> Self { repeatForever = true return self } // MARK: Reversable public var direction: Direction = .forward private(set) public var reverseOnComplete: Bool = false @discardableResult public func yoyo() -> Self { reverseOnComplete = true return self } // MARK: TimeRenderable internal func render(time: TimeInterval, advance: TimeInterval = 0) { elapsed = time updated.trigger(self) } // MARK: - Subscriber internal var id: UInt32 = 0 internal var updatesStateOnAdvance = true internal func kill() { reset() Scheduler.shared.remove(self) } internal func advance(_ time: Double) { guard shouldAdvance() else { return } let end = delay + duration let multiplier: TimeInterval = direction == .reversed ? -timeScale : timeScale elapsed = max(0, min(elapsed + (time * multiplier), end)) runningTime += time // if animation doesn't repeat forever, cap elapsed time to endTime if !repeatForever { elapsed = min(elapsed, (delay + endTime)) } if state == .pending && elapsed >= delay { state = .running } // print("\(self).advance - id: \(id), state: \(state), time: \(time), elapsed: \(elapsed), end: \(end), duration: \(duration), progress: \(progress), cycle: \(cycle)") render(time: elapsed, advance: time) } internal func canSubscribe() -> Bool { return true } internal func shouldAdvance() -> Bool { return state == .pending || state == .running || !isPaused() } internal func isAnimationComplete() -> Bool { return true } // MARK: Event Handlers @discardableResult public func on(_ event: Animation.EventType, observer: @escaping Event<Animation>.Observer) -> Self { switch event { case .started: started.observe(observer) case .updated: updated.observe(observer) case .completed: completed.observe(observer) case .repeated: repeated.observe(observer) case .cancelled: cancelled.observe(observer) } return self } private func onUpdate() { let end = delay + duration let shouldRepeat = (repeatForever || (repeatCount > 0 && cycle < repeatCount)) if state == .running && ((direction == .forward && elapsed >= end) || (direction == .reversed && elapsed == 0)) && updatesStateOnAdvance { if shouldRepeat { print("\(self) completed - repeating, reverseOnComplete: \(reverseOnComplete), reversed: \(direction == .reversed), repeat count \(cycle) of \(repeatCount)") cycle += 1 if reverseOnComplete { direction = (direction == .forward) ? .reversed : .forward } else { // restart() elapsed = 0 } repeated.trigger(self) } else { if isAnimationComplete() && state == .running { state = .completed } } } else if state == .idle && elapsed >= end { state = .completed } } // MARK: Internal Methods func isPaused() -> Bool { return (state == .idle && Scheduler.shared.contains(self)) } func elapsedTimeFromSeekTime(_ time: TimeInterval) -> TimeInterval { var adjustedTime = time var adjustedCycle = cycle // seek time must be restricted to the duration of the timeline minus repeats and repeatDelays // so if the provided time is greater than the timeline's duration, we need to adjust the seek time first if adjustedTime > duration { if repeatCount > 0 && fmod(adjustedTime, duration) != 0.0 { // determine which repeat cycle the seek time will be in for the specified time adjustedCycle = Int(adjustedTime / duration) adjustedTime -= (duration * TimeInterval(adjustedCycle)) } else { adjustedTime = duration } } else { adjustedCycle = 0 } // determine if we should reverse the direction of the timeline based on calculated adjustedCycle let shouldReverse = adjustedCycle != cycle && reverseOnComplete if shouldReverse { if direction == .forward { reverse() } else { forward() } } // if direction is reversed, then adjusted time needs to start from end of animation duration instead of 0 if direction == .reversed { adjustedTime = duration - adjustedTime } cycle = adjustedCycle return adjustedTime } } public func ==(lhs: Animation, rhs: Animation) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } extension Animation { public enum EventType { case started case updated case cancelled case completed case repeated } }
90ac84bfc6093e0317129efaa4a1f20d
22.150121
169
0.665307
false
false
false
false
TonnyTao/Acornote
refs/heads/master
Acornote_iOS/Acornote/View/TextView.swift
apache-2.0
1
// // TextView.swift // Acornote // // Created by Tonny on 09/11/2016. // Copyright © 2016 Tonny&Sunm. All rights reserved. // import UIKit class TextView: UITextView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) textContainerInset = .zero textContainer.lineFragmentPadding = 0 } override var textColor: UIColor? { didSet { if let old = attributedText?.string, let color = textColor { let style:NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle style.lineSpacing = 2 let att = NSAttributedString(string: old, attributes: [.font : ItemTableViewCell.titleFont, .paragraphStyle:style, .foregroundColor: color]) attributedText = att } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if touches.count == 1 && touches.first?.tapCount == 1 { superview?.touchesBegan(touches, with: event) return } super.touchesBegan(touches, with: event) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if touches.count == 1 && touches.first?.tapCount == 1 { superview?.touchesEnded(touches, with: event) return } super.touchesEnded(touches, with: event) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if touches.count == 1 && touches.first?.tapCount == 1 { superview?.touchesMoved(touches, with: event) return } super.touchesMoved(touches, with: event) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { if touches.count == 1 && touches.first?.tapCount == 1 { superview?.touchesCancelled(touches, with: event) return } super.touchesCancelled(touches, with: event) } }
0c725ce02717db1088399265de3a91dc
31.515625
156
0.590581
false
false
false
false
SteveKChiu/CoreDataMonk
refs/heads/master
CoreDataMonk/CollectionViewDataProvider.swift
mit
1
// // https://github.com/SteveKChiu/CoreDataMonk // // Copyright 2015, Steve K. Chiu <[email protected]> // // The MIT License (http://www.opensource.org/licenses/mit-license.php) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import UIKit import CoreData //--------------------------------------------------------------------------- private class CollectionViewDataBridge<EntityType: NSManagedObject> : NSObject, UICollectionViewDataSource, NSFetchedResultsControllerDelegate { weak var provider: CollectionViewDataProvider<EntityType>? var pendingActions: [() -> Void] = [] var updatedIndexPaths: Set<IndexPath> = [] var shouldReloadData = false var isFiltering = false var semaphore: DispatchSemaphore var collectionView: UICollectionView? { return self.provider?.collectionView } init(provider: CollectionViewDataProvider<EntityType>) { self.provider = provider self.semaphore = DispatchSemaphore(value: 1) } @objc func numberOfSections(in collectionView: UICollectionView) -> Int { return self.provider?.numberOfSections() ?? 0 } @objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.provider?.numberOfObjectsInSection(section) ?? 0 } @objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let object = self.provider?.objectAtIndexPath(indexPath), let cell = self.provider?.onGetCell?(object, indexPath) { return cell } return UICollectionViewCell() } @objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if let view = self.provider?.onGetSupplementary?(kind, indexPath) { return view } return UICollectionReusableView() } private func ensureIndexPath(_ indexPath: IndexPath) -> Bool { if self.isFiltering || self.shouldReloadData { return false } else if self.updatedIndexPaths.contains(indexPath) { self.updatedIndexPaths.removeAll() self.pendingActions.removeAll() self.shouldReloadData = true return false } else { self.updatedIndexPaths.insert(indexPath) return true } } @objc func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.pendingActions.removeAll() self.updatedIndexPaths.removeAll() self.shouldReloadData = false self.isFiltering = self.provider?.objectFilter != nil } @objc func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: if ensureIndexPath(newIndexPath!) { self.pendingActions.append() { [weak self] in self?.collectionView?.insertItems(at: [ newIndexPath! ]) } } case .delete: if ensureIndexPath(indexPath!) { self.pendingActions.append() { [weak self] in self?.collectionView?.deleteItems(at: [ indexPath! ]) } } case .move: if ensureIndexPath(indexPath!) && ensureIndexPath(newIndexPath!) { self.pendingActions.append() { [weak self] in self?.collectionView?.moveItem(at: indexPath!, to: newIndexPath!) } } case .update: if ensureIndexPath(indexPath!) { self.pendingActions.append() { [weak self] in self?.collectionView?.reloadItems(at: [ indexPath! ]) } } } } @objc func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { if self.isFiltering || self.shouldReloadData { return } switch type { case .insert: self.pendingActions.append() { [weak self] in self?.collectionView?.insertSections(IndexSet(integer: sectionIndex)) self?.collectionView?.collectionViewLayout.invalidateLayout() } case .delete: self.pendingActions.append() { [weak self] in self?.collectionView?.deleteSections(IndexSet(integer: sectionIndex)) self?.collectionView?.collectionViewLayout.invalidateLayout() } default: break } } @objc func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { if self.isFiltering { self.provider?.filter() self.provider?.onDataChanged?() return } if self.shouldReloadData || self.collectionView?.window == nil { self.pendingActions.removeAll() self.updatedIndexPaths.removeAll() self.collectionView?.reloadData() self.provider?.onDataChanged?() return } guard let collectionView = self.collectionView else { return } // make sure batch update animation is not overlapped let semaphore = self.semaphore _ = semaphore.wait(timeout: DispatchTime.now() + Double(Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)) self.updatedIndexPaths.removeAll() collectionView.performBatchUpdates({ [weak self] in if let actions = self?.pendingActions, !actions.isEmpty { self?.pendingActions.removeAll() for action in actions { action() } } }, completion: { [weak self] _ in self?.provider?.onDataChanged?() semaphore.signal() }) } } //--------------------------------------------------------------------------- open class CollectionViewDataProvider<EntityType: NSManagedObject> : ViewDataProvider<EntityType> { public let context: CoreDataMainContext private var bridge: CollectionViewDataBridge<EntityType>! public typealias OnGetCell = (EntityType, IndexPath) -> UICollectionViewCell? public typealias OnGetSupplementary = (String, IndexPath) -> UICollectionReusableView? public typealias OnDataChanged = () -> Void public var onGetCell: OnGetCell? public var onGetSupplementary: OnGetSupplementary? public var onDataChanged: OnDataChanged? public weak var collectionView: UICollectionView? { willSet { if self.collectionView?.dataSource === self.bridge { self.collectionView?.dataSource = nil } } didSet { self.collectionView?.dataSource = self.bridge } } open override var fetchedResultsController: NSFetchedResultsController<EntityType>? { get { return super.fetchedResultsController } set { super.fetchedResultsController?.delegate = nil super.fetchedResultsController = newValue newValue?.delegate = self.bridge } } public init(context: CoreDataMainContext) { self.context = context super.init() self.bridge = CollectionViewDataBridge<EntityType>(provider: self) } public func bind(_ collectionView: UICollectionView, onGetCell: @escaping OnGetCell) { self.onGetCell = onGetCell self.collectionView = collectionView } public func load(_ query: CoreDataQuery? = nil, orderBy: CoreDataOrderBy, sectionBy: CoreDataQueryKey? = nil, options: CoreDataQueryOptions? = nil) throws { self.fetchedResultsController = try self.context.fetchResults(EntityType.self, query, orderBy: orderBy, sectionBy: sectionBy, options: options) try reload() } open override func filter() { super.filter() self.collectionView?.reloadData() } }
106b07b5b097797b4e620f6b4a59b6ca
37.278884
215
0.623335
false
false
false
false
Bing0/ThroughWall
refs/heads/master
ChiselLogViewer/CoreDataController.swift
gpl-3.0
1
// // CoreDataController.swift // ChiselLogViewer // // Created by Bingo on 09/07/2017. // Copyright © 2017 Wu Bin. All rights reserved. // import Cocoa class CoreDataController: NSObject { var databaseURL: URL? init(withBaseURL url: URL) { let databaseURL = url.appendingPathComponent(databaseFileName) self.databaseURL = databaseURL } // 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: "ThroughWall") if let _databaseURL = self.databaseURL { container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: _databaseURL)] } container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error { // 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)") } }) return container }() func getContext() -> NSManagedObjectContext { return persistentContainer.viewContext } }
f3721c247a0e7328a415fcabadb84865
40.185185
199
0.640737
false
false
false
false
hironytic/HNTask
refs/heads/master
HNTaskTests/HNTaskTests.swift
mit
1
// // HNTaskTests.swift // // Copyright (c) 2014 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import XCTest class HNTaskTests: XCTestCase { struct MyError { let message: String } 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 testContinuationShouldRun() { let expectation = expectationWithDescription("finish task"); let task = HNTask.resolve(nil) task.continueWith { context in expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testContinuationShouldRunWhenRejected() { let expectation = expectationWithDescription("finish task"); let task = HNTask.reject(MyError(message: "error")) task.continueWith { context in expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testResultShouldBePassed() { let expectation = expectationWithDescription("finish task"); let task = HNTask.resolve(10) task.continueWith { context in if let value = context.result as? Int { XCTAssertEqual(value, 10, "previous result should be passed.") } else { XCTFail("previous result should be Int.") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testReturnValueShouldBeResult() { let expectation = expectationWithDescription("finish task"); let task = HNTask.resolve(nil) task.continueWith { context in return ("result", nil) }.continueWith { context in if let value = context.result as? String { XCTAssertEqual(value, "result", "previous return value should be result.") } else { XCTFail("previous result should be String.") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testRejectShouldCauseError() { let expectation = expectationWithDescription("finish task"); let task = HNTask.reject(MyError(message: "error")) task.continueWith { context in XCTAssertTrue(context.isError(), "error should be occured.") expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testErrorValueShouldBePassed() { let expectation = expectationWithDescription("finish task"); let task = HNTask.reject(MyError(message: "error")) task.continueWith { context in if let error = context.error { if let myError = error as? MyError { XCTAssertEqual(myError.message, "error", "error value should be passed.") } else { XCTFail("error value should be type of MyError.") } } else { XCTFail("error value should be exist.") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testThreadShouldSwitchedByExecutor() { let myQueue = dispatch_queue_create("com.hironytic.hntasktests", nil) class MyExecutor: HNExecutor { let queue: dispatch_queue_t init(queue: dispatch_queue_t) { self.queue = queue } func execute(callback: () -> Void) { dispatch_async(queue) { callback() } } } let testThread = NSThread.currentThread() let expectation = expectationWithDescription("finish task"); let task = HNTask.resolve(nil) task.continueWith(MyExecutor(queue: myQueue)) { context in XCTAssertFalse(testThread.isEqual(NSThread.currentThread()), "thread should be switched") expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testResolvedTask() { let expectation = expectationWithDescription("finish task"); let task = HNTask.resolve(20) XCTAssertTrue(task.isCompleted(), "task should be completed.") task.continueWith { context in if let value = context.result as? Int { XCTAssertEqual(value, 20, "resolved value should be passed.") } else { XCTFail("resolved value should be Int.") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testRejectedTask() { let expectation = expectationWithDescription("finish task"); let task = HNTask.reject(MyError(message: "rejected")) XCTAssertTrue(task.isCompleted(), "task should be completed.") task.continueWith { context in XCTAssertTrue(context.isError(), "task should be in error state.") if let error = context.error { if let myError = error as? MyError { XCTAssertEqual(myError.message, "rejected", "error message should be 'rejected'") } else { XCTFail("error value should be MyError.") } } else { XCTFail("error value should be exist.") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testThenShouldRunWhenSucceeded() { let expectation = expectationWithDescription("finish task"); HNTask.resolve(30).then { value in if let intValue = value as? Int { XCTAssertEqual(intValue, 30, "previous value should be passed.") } else { XCTFail("previous value should be Int.") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testThenShouldNotRunWhenError() { let expectation = expectationWithDescription("finish task"); var ran = false HNTask.reject(MyError(message: "myError")).then { value in ran = true return nil }.finally { expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) XCTAssertFalse(ran, "then closure should not run.") } func testTypeCheckThenShouldRunWhenSucceeded() { let expectation = expectationWithDescription("finish task"); HNTask.resolve(30).then { (value: Int) in XCTAssertEqual(value, 30, "previous value should be passed.") expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testTypeCheckThenShouldNotRunWhenError() { let expectation = expectationWithDescription("finish task"); var ran = false HNTask.reject(MyError(message: "myError")).then { (value: Int) in ran = true return nil }.finally { expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) XCTAssertFalse(ran, "then closure should not run.") } func testTypeCheckThenShouldNotRunWhenTypeMismatch() { let expectation = expectationWithDescription("finish task"); var ran = false HNTask.resolve(40).then { (value: String) in ran = true return nil }.finally { expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) XCTAssertFalse(ran, "then closure should not run.") } func testTypeCheckThenShouldMakeError() { let expectation = expectationWithDescription("finish task"); HNTask.resolve(40).then { (value: String) in return nil }.catch { error in if let typeError = error as? HNTaskTypeError { if let errorValue = typeError.value as? Int { XCTAssertEqual(errorValue, 40, "error value shoule be 40.") } else { XCTFail("error value shoule be Int") } } else { XCTFail("error shoule be kind of HNTaskTypeError") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testCatchShouldNotRunWhenSucceeded() { let expectation = expectationWithDescription("finish task"); var ran = false HNTask.resolve(30).catch { error in ran = true return nil }.finally { expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) XCTAssertFalse(ran, "catch closure should not run.") } func testCatchShouldRunWhenError() { let expectation = expectationWithDescription("finish task"); HNTask.reject(MyError(message: "myError")).catch { error in if let myError = error as? MyError { XCTAssertEqual(myError.message, "myError", "error message should be 'myError'") } else { XCTFail("error value should be MyError.") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testCatchShouldConsumeError() { let expectation = expectationWithDescription("finish task"); HNTask.reject(MyError(message: "myError")).catch { error in return 100 }.continueWith { context in XCTAssertFalse(context.isError(), "error should be consumed.") if let intValue = context.result as? Int { XCTAssertEqual(intValue, 100, "previous value should be passed.") } else { XCTFail("previous value should be Int.") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testFinallyShouldRunWhenSucceeded() { let expectation = expectationWithDescription("finish task"); HNTask.resolve(30).finally { expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testFinallyShouldRunWhenFailed() { let expectation = expectationWithDescription("finish task"); HNTask.reject(MyError(message: "myError")).finally { expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testFinallyShouldCompleteAfterReturnedTasksCompletion() { let expectation = expectationWithDescription("finish task"); var v = 0 HNTask.resolve(30).finally { return self.delayAsync(100) { v = 100 } }.then { value in XCTAssertEqual(v, 100, "called after the task returnd from finally()") expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testFinallyShouldNotChangeResultValue() { let expectation = expectationWithDescription("finish task"); HNTask.resolve(30).finally { return nil }.continueWith { context in XCTAssertFalse(context.isError(), "error should not occured") if let value = context.result as? Int { XCTAssertEqual(value, 30, "result value should not change") } else { XCTFail("result value shoule be Int") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testFinallyShouldNotChangeErrorValue() { let expectation = expectationWithDescription("finish task"); HNTask.reject(MyError(message: "error1")).finally { return nil }.continueWith { context in XCTAssertTrue(context.isError(), "error should remain") if let error = context.error as? MyError { XCTAssertEqual(error.message, "error1", "error value should not change") } else { XCTFail("error value shoule be MyError") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testFinallyShouldNotChangeResultValueAfterReturnedTasksCompletion() { let expectation = expectationWithDescription("finish task"); HNTask.resolve(30).finally { return self.delayAsync(100) { } }.continueWith { context in XCTAssertFalse(context.isError(), "error should not occured") if let value = context.result as? Int { XCTAssertEqual(value, 30, "result value should not change") } else { XCTFail("result value shoule be Int") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func testFinallyShouldNotChangeErrorValueAfterReturnedTasksCompletion() { let expectation = expectationWithDescription("finish task"); HNTask.reject(MyError(message: "error1")).finally { return self.delayAsync(100) { } }.continueWith { context in XCTAssertTrue(context.isError(), "error should remain") if let error = context.error as? MyError { XCTAssertEqual(error.message, "error1", "error value should not change") } else { XCTFail("error value shoule be MyError") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func makeStringAsync(str: String) -> HNTask { let task = HNTask.resolve(str + "s") return task } func testExecutionOrder() { let expectation = expectationWithDescription("finish task"); HNTask.resolve("").then { value in if let str = value as? String { return str + "a" } else { return HNTask.reject(MyError(message: "error")) } }.then { value in if var str = value as? String { str += "b" return self.makeStringAsync(str) } else { return HNTask.reject(MyError(message: "error")) } }.then { value in if let str = value as? String { return str + "c" } else { return HNTask.reject(MyError(message: "error")) } }.continueWith { context in XCTAssertFalse(context.isError(), "error should not occured") if let str = context.result as? String { XCTAssertEqual(str, "absc", "check order") } else { XCTFail("result value should be String") } expectation.fulfill() return (nil, nil) } waitForExpectationsWithTimeout(5.0, handler: nil) } func delayAsync(milliseconds: Int, callback: () -> Void) -> HNTask { let task = HNTask { (resolve, reject) in let delta: Int64 = Int64(milliseconds) * Int64(NSEC_PER_MSEC) let time = dispatch_time(DISPATCH_TIME_NOW, delta); dispatch_after(time, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { callback() resolve(milliseconds) } } return task } func timeoutAsync(milliseconds: Int) -> HNTask { let task = HNTask { (resolve, reject) in let delta: Int64 = Int64(milliseconds) * Int64(NSEC_PER_MSEC) let time = dispatch_time(DISPATCH_TIME_NOW, delta); dispatch_after(time, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { reject(MyError(message: "timeout")) } } return task } func testThenShouldBeCalledAfterAllTasksAreCompleted() { let expectation = expectationWithDescription("finish task"); var value = 0 let task1 = delayAsync(100, callback:{ value += 100 }) let task2 = delayAsync(300, callback:{ value += 300 }) let task3 = delayAsync(200, callback:{ value += 200 }) HNTask.all([task1, task2, task3]).then { values in XCTAssertEqual(value, 600, "all task shoule be completed") if let results = values as? Array<Any?> { let v1 = results[0] as Int let v2 = results[1] as Int let v3 = results[2] as Int XCTAssertEqual(v1, 100, "task1 should return 100") XCTAssertEqual(v2, 300, "task1 should return 300") XCTAssertEqual(v3, 200, "task1 should return 200") } else { XCTFail("values should be a type of Array") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testCatchAfterAllShouleBeCalledWhenTaskReturnsError() { let expectation = expectationWithDescription("finish task"); var value = 0 let task1 = delayAsync(100, callback:{ value += 100 }) let task2 = timeoutAsync(150) let task3 = delayAsync(200, callback:{ value += 200 }) HNTask.all([task1, task2, task3]).then { values in return nil }.catch { error in if let err = error as? MyError { XCTAssertEqual(err.message, "timeout") } else { XCTFail("error should be a type of MyError") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testThenShouldBeCalledAfterOneTaskInRaceIsCompleted() { let expectation = expectationWithDescription("finish task"); let task1 = delayAsync(100, callback:{ }) let task2 = delayAsync(700, callback:{ }) let task3 = delayAsync(500, callback:{ }) HNTask.race([task1, task2, task3]).then { value in if let result = value as? Int { XCTAssertEqual(result, 100, "first task should pass the result") } else { XCTFail("result should be a type of Int") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testCatchAfterRaceShouleBeCalledWhenTaskReturnsError() { let expectation = expectationWithDescription("finish task"); var value = 0 let task1 = delayAsync(500, callback:{ }) let task2 = timeoutAsync(150) let task3 = delayAsync(700, callback:{ }) HNTask.race([task1, task2, task3]).then { values in return nil }.catch { error in if let err = error as? MyError { XCTAssertEqual(err.message, "timeout") } else { XCTFail("error should be a type of MyError") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testThenShouldBeCalledAfterAllTasksAreSettled() { let expectation = expectationWithDescription("finish task"); var value = 0 let task1 = delayAsync(100, callback:{ value += 100 }) let task2 = delayAsync(300, callback:{ value += 300 }) let task3 = delayAsync(200, callback:{ value += 200 }) HNTask.allSettled([task1, task2, task3]).then { values in XCTAssertEqual(value, 600, "all task shoule be completed") if let results = values as? Array<Any?> { let v1 = results[0] as Int let v2 = results[1] as Int let v3 = results[2] as Int XCTAssertEqual(v1, 100, "task1 should return 100") XCTAssertEqual(v2, 300, "task1 should return 300") XCTAssertEqual(v3, 200, "task1 should return 200") } else { XCTFail("values should be a type of Array") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testThenShouldBeCalledAfterAllTasksAreSettledEvenIfOneOfThemIsRejected() { let expectation = expectationWithDescription("finish task"); var value = 0 let task1 = delayAsync(100, callback:{ value += 100 }) let task2 = timeoutAsync(150) let task3 = delayAsync(200, callback:{ value += 200 }) HNTask.allSettled([task1, task2, task3]).then { values in XCTAssertTrue(task1.isCompleted(), "task1 should be completed") XCTAssertTrue(task2.isCompleted(), "task2 should be completed") XCTAssertTrue(task3.isCompleted(), "task3 should be completed") if let results = values as? Array<Any?> { let v1 = results[0] as Int let v3 = results[2] as Int XCTAssertEqual(v1, 100, "task1 should return 100") XCTAssertEqual(v3, 200, "task1 should return 200") if let v2 = results[1] as? MyError { XCTAssertEqual(v2.message, "timeout", "task2 should be timeout.") } else { XCTFail("values[1] should be a type of MyError.") } } else { XCTFail("values should be a type of Array.") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } func testAsyncExecutorsRunAsync() { let expectation = expectationWithDescription("finish task"); HNAsyncExecutor.sharedExecutor.runAsync { return "ran" }.then { value in if let result = value as? String { XCTAssertEqual(result, "ran", "return value should be passed.") } else { XCTFail("result should be a type of String") } expectation.fulfill() return nil } waitForExpectationsWithTimeout(5.0, handler: nil) } }
15db04b5554f9bddf3defea404012040
37.284144
111
0.577152
false
true
false
false
apple/swift-nio-ssl
refs/heads/main
Sources/NIOSSL/String+unsafeUninitializedCapacity.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// extension String { /// This is a backport of `String.init(unsafeUninitializedCapacity:initializingUTF8With:)` /// that allows writing directly into an uninitialized String's backing memory. /// /// As this API does not exist on older Apple platforms, we fake it out with a pointer and accept the extra copy. init( customUnsafeUninitializedCapacity capacity: Int, initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer<UInt8>) throws -> Int ) rethrows { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) { try self.init(unsafeUninitializedCapacity: capacity, initializingUTF8With: initializer) } else { try self.init(backportUnsafeUninitializedCapacity: capacity, initializingUTF8With: initializer) } } private init( backportUnsafeUninitializedCapacity capacity: Int, initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer<UInt8>) throws -> Int ) rethrows { let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: capacity) defer { buffer.deallocate() } let initializedCount = try initializer(buffer) precondition(initializedCount <= capacity, "Overran buffer in initializer!") self = String(decoding: UnsafeMutableBufferPointer(start: buffer.baseAddress!, count: initializedCount), as: UTF8.self) } }
d721e2a69e148cb8bbf1e02f62f52160
41.26087
127
0.644033
false
false
false
false
doctorn/hac-website
refs/heads/master
Sources/HaCWebsiteLib/Events/WorkshopEvent.swift
mit
1
import Foundation struct WorkshopEvent : Event { let title : String let time : DateInterval let tagLine : String let eventDescription : Text let color : String let hypePeriod : DateInterval let tags : [String] let workshop : Workshop let imageURL : String? let location : Location? let facebookEventID : String? var shouldShowAsUpdate: Bool { get { return self.hypePeriod.contains(Date()) } } var postCardRepresentation : PostCard { return PostCard( title: self.title, category: .workshop, description: self.tagLine, backgroundColor: self.color, //TODO imageURL: self.imageURL ) } init(title: String, time: DateInterval, tagLine : String, description: Text, color: String, hypePeriod: DateInterval, tags: [String], workshop: Workshop, imageURL: String? = nil, location: Location? = nil, facebookEventID : String? = nil) { self.title = title self.time = time self.tagLine = tagLine self.eventDescription = description self.color = color self.hypePeriod = hypePeriod self.tags = tags self.workshop = workshop self.imageURL = imageURL self.location = location self.facebookEventID = facebookEventID } }
0feb6b08ce747b03165bc9cf78aa36f0
28.652174
95
0.620968
false
false
false
false
vivint/Woody
refs/heads/master
Sources/Woody.swift
apache-2.0
1
// // Woody.swift // Vivint.SmartHome // // Created by Kaden Wilkinson on 9/1/17. // Copyright © 2017 Vivint.SmartHome. All rights reserved. // import Foundation @objc public protocol WoodyDelegate: class { @objc optional func verbose(_ msg: String, filepath: String, function: String, line: Int) @objc optional func debug(_ msg: String, filepath: String, function: String, line: Int) @objc optional func info(_ msg: String, filepath: String, function: String, line: Int) @objc optional func warning(_ msg: String, filepath: String, function: String, line: Int) @objc optional func error(_ msg: String, filepath: String, function: String, line: Int) } @objcMembers public class Woody: NSObject { @objc public enum Level: Int { case verbose case debug case info case warning case error } /// This should never be set by a framework @objc public static var delegate: WoodyDelegate? /// This is used when the delegate hasn't been set yet /// Keep internal for now until we know API is stable @objc static var defaultLogger: (String) -> Void = { message in NSLog(message) } @objc(logVerbose:filepath:function:line:) public static func verbose(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) { guard let d = delegate else { defaultLogger("[VERBOSE] \(filename(from: filepath)).\(function): \(line) - \(message)") return } d.verbose?(message, filepath: filepath, function: function, line: line) } @objc(logDebug:filepath:function:line:) public static func debug(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) { guard let d = delegate else { defaultLogger("[DEBUG] \(filename(from: filepath)).\(function): \(line) - \(message)") return } d.debug?(message, filepath: filepath, function: function, line: line) } @objc(logInfo:filepath:function:line:) public static func info(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) { guard let d = delegate else { defaultLogger("[INFO] \(filename(from: filepath)).\(function): \(line) - \(message)") return } d.info?(message, filepath: filepath, function: function, line: line) } @objc(logWarning:filepath:function:line:) public static func warning(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) { guard let d = delegate else { defaultLogger("[WARNING] \(filename(from: filepath)).\(function): \(line) - \(message)") return } d.warning?(message, filepath: filepath, function: function, line: line) } @objc(logError:filepath:function:line:) public static func error(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) { guard let d = delegate else { defaultLogger("[ERROR] \(filename(from: filepath)).\(function): \(line) - \(message)") return } d.error?(message, filepath: filepath, function: function, line: line) } private static func filename(from path: String, extensionIncluded: Bool = false) -> String { let filename = (path as NSString).lastPathComponent if !extensionIncluded { let fileNameComponents = filename.components(separatedBy: ".") if let firstComponent = fileNameComponents.first { return firstComponent } return filename } return filename } }
9a31efdd4e7b96ead1a59df20333f220
38.808511
126
0.627205
false
false
false
false
fengxinsen/ReadX
refs/heads/master
ReadX/BaseWindowController.swift
mit
1
// // BaseWindowController.swift // ReadX // // Created by video on 2017/2/24. // Copyright © 2017年 Von. All rights reserved. // import Cocoa class BaseWindowController: NSWindowController { open var index = 0 override var windowNibName: String? { return "BaseWindowController" } override func windowDidLoad() { super.windowDidLoad() } } extension BaseWindowController { //隐藏zoomButton func hiddenZoomButton() { self.window?.standardWindowButton(.zoomButton)?.isHidden = true } func hiddenTitleVisibility() { self.window?.titleVisibility = .hidden } func titleBackgroundColor(color: NSColor) { let titleView = self.window?.standardWindowButton(.closeButton)?.superview titleView?.backgroundColor = color // titleView?.wantsLayer = true // titleView?.layer?.backgroundColor = NSColor.brown.cgColor } func center() { self.window?.center() } func mAppDelegate() -> AppDelegate { return NSApplication.shared().delegate as! AppDelegate } }
9c4e6c24622605f92e4ece22428f993a
21.66
82
0.634598
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS Tests/RequestPasswordViewControllerSnapshotTests.swift
gpl-3.0
1
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire final class RequestPasswordControllerSnapshotTests: XCTestCase, CoreDataFixtureTestHelper { var coreDataFixture: CoreDataFixture! var sut: RequestPasswordController! var fingerprint: Data! override func setUp() { super.setUp() coreDataFixture = CoreDataFixture() fingerprint = coreDataFixture.mockUserClient(fingerprintString: "102030405060708090a0b0c0d0e0f0708090102030405060708090").fingerprint! } override func tearDown() { fingerprint = nil sut = nil coreDataFixture = nil super.tearDown() } func testForRemoveDeviceContextPasswordEntered() { sut = RequestPasswordController(context: .removeDevice, callback: {_ in }) sut.passwordTextField?.text = "12345678" sut.passwordTextFieldChanged(sut.passwordTextField!) verify(matching: sut.alertController) } func testForRemoveDeviceContext() { sut = RequestPasswordController(context: .removeDevice, callback: {_ in }) verify(matching: sut.alertController) } }
82e92d808f106a2e5eb1af43d3b2bad2
30.614035
142
0.718091
false
true
false
false
gitkong/FLTableViewComponent
refs/heads/master
FLComponentDemo/FLComponentDemo/FLCollectionViewFlowLayout.swift
mit
2
// // FLCollectionViewFlowLayout.swift // FLComponentDemo // // Created by gitKong on 2017/5/18. // Copyright © 2017年 gitKong. All rights reserved. // import UIKit typealias LayoutAttributesArray = Array<UICollectionViewLayoutAttributes>? typealias LayoutAttributesDict = Dictionary<FLIdentifierType , LayoutAttributesArray>? @objc enum FLCollectionViewFlowLayoutStyle : NSInteger{ case System = 0// System style, Both ends of the same spacing, the middle spacing is not equal, alignment is center case Custom = 1// Both ends of spacing is not equal, the middle spacing is equal, alignment is top } class FLCollectionViewFlowLayout: UICollectionViewFlowLayout { weak var delegate : UICollectionViewDelegateFlowLayout? private var sectionAttributes : Array<LayoutAttributesDict> = [] var flowLayoutStyle : FLCollectionViewFlowLayoutStyle?{ didSet { // reset verticalTotalItemMaxY = 0 } } var verticalTotalItemMaxY : CGFloat = 0 var sectionInsetArray : Array<UIEdgeInsets> = [] var minimumInteritemSpacingArray : Array<CGFloat> = [] var minimumLineSpacingArray : Array<CGFloat> = [] convenience init(with flowLayoutStyle : FLCollectionViewFlowLayoutStyle = .System) { self.init() self.flowLayoutStyle = flowLayoutStyle } override init() { super.init() self.scrollDirection = .vertical } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepare() { super.prepare() if flowLayoutStyle == .System { return } guard self.collectionView != nil , let sections = self.collectionView?.numberOfSections , self.delegate != nil else { return } sectionAttributes.removeAll() var currentInset : UIEdgeInsets = sectionInsetArray[0] var currentMinimumInteritemSpacing : CGFloat = minimumInteritemSpacingArray[0] var currentMinimumLineSpacing : CGFloat = minimumLineSpacingArray[0] var offsetX : CGFloat = currentInset.left var nextOffsetX : CGFloat = currentInset.left var offsetY : CGFloat = currentInset.top var currentRowMaxItemHeight : CGFloat = 0 var lastHeaderAttributeSize : CGSize = CGSize.zero var lastFooterAttributeSize : CGSize = CGSize.zero for section in 0 ..< sections { var itemAttributes : LayoutAttributesArray = [] var attributeDict : LayoutAttributesDict = [FLIdentifierType.Cell : itemAttributes] if let items = self.collectionView?.numberOfItems(inSection: section) { let headerAttributeSize : CGSize = (self.delegate?.collectionView!(self.collectionView!, layout: self, referenceSizeForHeaderInSection: section))! let headerAttribute = UICollectionViewLayoutAttributes.init(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, with: IndexPath.init(item: 0, section: section)) headerAttribute.frame = CGRect.init(origin: CGPoint.init(x: 0, y: verticalTotalItemMaxY), size: headerAttributeSize) verticalTotalItemMaxY = 0 let footerAttribute = UICollectionViewLayoutAttributes.init(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, with: IndexPath.init(item: 0, section: section)) //print("----- section (\(section)) ------") for item in 0 ..< items { let indexPath = IndexPath.init(item: item, section: section) let attribute = UICollectionViewLayoutAttributes.init(forCellWith: indexPath) if let itemSize = self.delegate?.collectionView!(self.collectionView!, layout: self, sizeForItemAt: indexPath) { nextOffsetX = nextOffsetX + currentMinimumInteritemSpacing + itemSize.width if nextOffsetX > self.collectionView!.bounds.size.width{ offsetX = currentInset.left nextOffsetX = currentInset.left + currentMinimumInteritemSpacing + itemSize.width offsetY = offsetY + currentRowMaxItemHeight + currentMinimumLineSpacing //print("max item height = \(currentRowMaxItemHeight)") // next row , compare with last itemSize currentRowMaxItemHeight = itemSize.height } else { //print("compare : \(currentRowMaxItemHeight) - \(itemSize.height)") currentRowMaxItemHeight = max(currentRowMaxItemHeight, itemSize.height) offsetX = nextOffsetX - (currentMinimumInteritemSpacing + itemSize.width) } attribute.frame = CGRect.init(x: offsetX, y: offsetY + headerAttribute.frame.size.height, width: itemSize.width, height: itemSize.height) if item == items - 1 { //print("last attribute frame : \(attribute.frame)") verticalTotalItemMaxY = currentRowMaxItemHeight + attribute.frame.origin.y + currentInset.bottom lastHeaderAttributeSize = headerAttribute.frame.size } } itemAttributes!.append(attribute) } if let footerAttributeSize = self.delegate?.collectionView!(self.collectionView!, layout: self, referenceSizeForFooterInSection: section) { if footerAttributeSize.height != 0 , footerAttributeSize.width != 0 { //print("section : \(section), footerHeight : \(footerAttributeSize.height), verticalTotalItemMaxY : \(verticalTotalItemMaxY)") footerAttribute.frame = CGRect.init(origin: CGPoint.init(x: 0, y: verticalTotalItemMaxY), size: footerAttributeSize) verticalTotalItemMaxY = verticalTotalItemMaxY + footerAttribute.frame.size.height if headerAttributeSize.height != 0 , headerAttributeSize.width != 0 { //print("footer and header exist at section-\(section)") } else { //print("footer exist at section-\(section), but header not") } offsetY = verticalTotalItemMaxY - lastHeaderAttributeSize.height + headerAttribute.frame.size.height + currentMinimumLineSpacing lastFooterAttributeSize = footerAttribute.frame.size } else { //print("section : \(section), headerAttribute : \(headerAttribute.size) verticalTotalItemMaxY : \(verticalTotalItemMaxY)") offsetY = verticalTotalItemMaxY - lastHeaderAttributeSize.height + headerAttribute.frame.size.height + currentMinimumLineSpacing if headerAttributeSize.height != 0 , headerAttributeSize.width != 0 { //print("header exist at section-\(section), but footer not") } else { //print("header and footer NOT exist at section-\(section)") offsetY = offsetY + currentMinimumLineSpacing } } } else { offsetY = verticalTotalItemMaxY - lastHeaderAttributeSize.height + headerAttribute.frame.size.height + currentMinimumLineSpacing } // if current header and last footer exist , just need to add minimumLineSpacing once if lastFooterAttributeSize.height == 0 , headerAttributeSize.height == 0 { offsetY = offsetY - currentMinimumLineSpacing } // reset // next section, you should subtract the last section minimumLineSpacing offsetY = offsetY - currentMinimumLineSpacing if section < sections - 1 { currentInset = sectionInsetArray[section + 1] currentMinimumInteritemSpacing = minimumInteritemSpacingArray[section + 1] currentMinimumLineSpacing = minimumLineSpacingArray[section + 1] } // add currentInset.top for next section offsetY offsetY = offsetY + currentInset.top offsetX = currentInset.left nextOffsetX = offsetX currentRowMaxItemHeight = 0 lastHeaderAttributeSize = CGSize.zero lastFooterAttributeSize = CGSize.zero attributeDict = [FLIdentifierType.Header : [headerAttribute], FLIdentifierType.Cell : itemAttributes, FLIdentifierType.Footer : [footerAttribute]] } sectionAttributes.append(attributeDict) } } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if flowLayoutStyle == .System { return super.layoutAttributesForItem(at: indexPath) } guard let attributeDict = sectionAttributes[indexPath.section] else { return nil } guard let itemAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Cell] else { return nil } return itemAttributes?[indexPath.item] } override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if flowLayoutStyle == .System { return super.layoutAttributesForSupplementaryView(ofKind: elementKind, at:indexPath) } guard let attributeDict = sectionAttributes[indexPath.section] else { return nil } if elementKind == UICollectionElementKindSectionHeader { guard let headerAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Header] else { return nil } return headerAttributes?.first } else { guard let footerAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Footer] else { return nil } return footerAttributes?.first } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if flowLayoutStyle == .System { return super.layoutAttributesForElements(in: rect) } var totalAttributes : LayoutAttributesArray = [] for attributeDict in sectionAttributes { if let attributeDict = attributeDict { if let headerAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Header] { totalAttributes = totalAttributes! + headerAttributes! } if let itemAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Cell] { totalAttributes = totalAttributes! + itemAttributes! } if let footerAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Footer] { totalAttributes = totalAttributes! + footerAttributes! } } } return totalAttributes?.filter({ (attribute) -> Bool in return CGRect.intersects(rect)(attribute.frame) }) } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { if flowLayoutStyle == .System { return super.shouldInvalidateLayout(forBoundsChange: newBounds) } return false } override var collectionViewContentSize: CGSize { if flowLayoutStyle == .System { return super.collectionViewContentSize } if verticalTotalItemMaxY == 0 { return CGSize.zero } return CGSize.init(width: (self.collectionView?.frame.size.width)!, height: verticalTotalItemMaxY) } }
8e9db163504e0137ef086e16919d682a
46.360294
190
0.586555
false
false
false
false
Bunn/firefox-ios
refs/heads/master
Storage/Rust/RustLogins.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @_exported import MozillaAppServices private let log = Logger.syncLogger public extension LoginRecord { convenience init(credentials: URLCredential, protectionSpace: URLProtectionSpace) { let hostname: String if let _ = protectionSpace.`protocol` { hostname = protectionSpace.urlString() } else { hostname = protectionSpace.host } let httpRealm = protectionSpace.realm let username = credentials.user let password = credentials.password self.init(fromJSONDict: [ "hostname": hostname, "httpRealm": httpRealm as Any, "username": username ?? "", "password": password ?? "" ]) } var credentials: URLCredential { return URLCredential(user: username ?? "", password: password, persistence: .forSession) } var protectionSpace: URLProtectionSpace { return URLProtectionSpace.fromOrigin(hostname) } var hasMalformedHostname: Bool { let hostnameURL = hostname.asURL guard let _ = hostnameURL?.host else { return true } return false } var isValid: Maybe<()> { // Referenced from https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginManager.js?rev=f76692f0fcf8&mark=280-281#271 // Logins with empty hostnames are not valid. if hostname.isEmpty { return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty hostname.")) } // Logins with empty passwords are not valid. if password.isEmpty { return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty password.")) } // Logins with both a formSubmitURL and httpRealm are not valid. if let _ = formSubmitURL, let _ = httpRealm { return Maybe(failure: LoginRecordError(description: "Can't add a login with both a httpRealm and formSubmitURL.")) } // Login must have at least a formSubmitURL or httpRealm. if (formSubmitURL == nil) && (httpRealm == nil) { return Maybe(failure: LoginRecordError(description: "Can't add a login without a httpRealm or formSubmitURL.")) } // All good. return Maybe(success: ()) } } public class LoginRecordError: MaybeErrorType { public let description: String public init(description: String) { self.description = description } } public class RustLogins { let databasePath: String let encryptionKey: String let queue: DispatchQueue let storage: LoginsStorage fileprivate(set) var isOpen: Bool = false private var didAttemptToMoveToBackup = false public init(databasePath: String, encryptionKey: String) { self.databasePath = databasePath self.encryptionKey = encryptionKey self.queue = DispatchQueue(label: "RustLogins queue: \(databasePath)", attributes: []) self.storage = LoginsStorage(databasePath: databasePath) } private func open() -> NSError? { do { try storage.unlock(withEncryptionKey: encryptionKey) isOpen = true return nil } catch let err as NSError { if let loginsStoreError = err as? LoginsStoreError { switch loginsStoreError { // The encryption key is incorrect, or the `databasePath` // specified is not a valid database. This is an unrecoverable // state unless we can move the existing file to a backup // location and start over. case .invalidKey(let message): log.error(message) if !didAttemptToMoveToBackup { RustShared.moveDatabaseFileToBackupLocation(databasePath: databasePath) didAttemptToMoveToBackup = true return open() } case .panic(let message): Sentry.shared.sendWithStacktrace(message: "Panicked when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: message) default: Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription) } } else { Sentry.shared.sendWithStacktrace(message: "Unknown error when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription) } return err } } private func close() -> NSError? { do { try storage.lock() isOpen = false return nil } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "Unknown error when closing Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription) return err } } public func reopenIfClosed() -> NSError? { var error: NSError? queue.sync { guard !isOpen else { return } error = open() } return error } public func forceClose() -> NSError? { var error: NSError? do { try storage.interrupt() } catch let err as NSError { error = err Sentry.shared.sendWithStacktrace(message: "Error interrupting Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription) } queue.sync { guard isOpen else { return } error = close() } return error } public func sync(unlockInfo: SyncUnlockInfo) -> Success { let deferred = Success() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { try self.storage.sync(unlockInfo: unlockInfo) deferred.fill(Maybe(success: ())) } catch let err as NSError { if let loginsStoreError = err as? LoginsStoreError { switch loginsStoreError { case .panic(let message): Sentry.shared.sendWithStacktrace(message: "Panicked when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: message) default: Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription) } } deferred.fill(Maybe(failure: err)) } } return deferred } public func get(id: String) -> Deferred<Maybe<LoginRecord?>> { let deferred = Deferred<Maybe<LoginRecord?>>() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { let record = try self.storage.get(id: id) deferred.fill(Maybe(success: record)) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<LoginRecord>>> { return list().bind({ result in if let error = result.failureValue { return deferMaybe(error) } guard let records = result.successValue else { return deferMaybe(ArrayCursor(data: [])) } guard let query = query?.lowercased(), !query.isEmpty else { return deferMaybe(ArrayCursor(data: records)) } let filteredRecords = records.filter({ $0.hostname.lowercased().contains(query) || ($0.username?.lowercased() ?? "").contains(query) }) return deferMaybe(ArrayCursor(data: filteredRecords)) }) } public func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String? = nil) -> Deferred<Maybe<Cursor<LoginRecord>>> { return list().bind({ result in if let error = result.failureValue { return deferMaybe(error) } guard let records = result.successValue else { return deferMaybe(ArrayCursor(data: [])) } let filteredRecords: [LoginRecord] if let username = username { filteredRecords = records.filter({ $0.username == username && ( $0.hostname == protectionSpace.urlString() || $0.hostname == protectionSpace.host ) }) } else { filteredRecords = records.filter({ $0.hostname == protectionSpace.urlString() || $0.hostname == protectionSpace.host }) } return deferMaybe(ArrayCursor(data: filteredRecords)) }) } public func hasSyncedLogins() -> Deferred<Maybe<Bool>> { return list().bind({ result in if let error = result.failureValue { return deferMaybe(error) } return deferMaybe((result.successValue?.count ?? 0) > 0) }) } public func list() -> Deferred<Maybe<[LoginRecord]>> { let deferred = Deferred<Maybe<[LoginRecord]>>() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { let records = try self.storage.list() deferred.fill(Maybe(success: records)) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func add(login: LoginRecord) -> Deferred<Maybe<String>> { let deferred = Deferred<Maybe<String>>() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { let id = try self.storage.add(login: login) deferred.fill(Maybe(success: id)) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func use(login: LoginRecord) -> Success { login.timesUsed += 1 login.timeLastUsed = Int64(Date.nowMicroseconds()) return update(login: login) } public func update(login: LoginRecord) -> Success { let deferred = Success() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { try self.storage.update(login: login) deferred.fill(Maybe(success: ())) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func delete(ids: [String]) -> Deferred<[Maybe<Bool>]> { return all(ids.map({ delete(id: $0) })) } public func delete(id: String) -> Deferred<Maybe<Bool>> { let deferred = Deferred<Maybe<Bool>>() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { let existed = try self.storage.delete(id: id) deferred.fill(Maybe(success: existed)) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func reset() -> Success { let deferred = Success() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { try self.storage.reset() deferred.fill(Maybe(success: ())) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func wipeLocal() -> Success { let deferred = Success() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { try self.storage.wipeLocal() deferred.fill(Maybe(success: ())) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } }
667ef6c58313f16438812ff47b9186f7
32.391101
222
0.563193
false
false
false
false
windaddict/ARFun
refs/heads/master
ARFun.playground/Pages/Waypoint.xcplaygroundpage/Contents.swift
mit
1
/* * Copyright 2017 John M. P. Knox * Licensed under the MIT License - see license file */ import UIKit import ARKit import PlaygroundSupport import MapKit /** * A starting point for placing AR content at real world coordinates in Swift Playgrounds 2 * Note since location services don't work in Playgrounds, the user has to manually pick * their starting location and the AR location on a map before starting. If the compass isn't * calibrated, the AR content won't place accurately. */ class WaypointNavigator: NSObject{ let mapView = MKMapView() let debugView = ARDebugView() ///0: no locations, 1: start location marked, 2: destination marked var mapState = 0 var start: CLLocationCoordinate2D? = nil var destination: CLLocationCoordinate2D? = nil var arDisplay: WayPointDisplay? override init(){ super.init() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gestureRecognizer:))) mapView.addGestureRecognizer(tapGestureRecognizer) debugView.translatesAutoresizingMaskIntoConstraints = false //add the debug view mapView.addSubview(debugView) mapView.leadingAnchor.constraint(equalTo: debugView.leadingAnchor) mapView.topAnchor.constraint(equalTo: debugView.topAnchor) PlaygroundPage.current.liveView = mapView } @objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){ let tapPoint = gestureRecognizer.location(in: mapView) let tapLocation = mapView.convert(tapPoint, toCoordinateFrom: mapView) debugView.log("tapped: \(tapLocation)") switch mapState{ case 0: //wait for the user to tap their starting location start = tapLocation mapState = 1 case 1: //wait for the user to tap their destination destination = tapLocation mapState = 2 case 2: //calculate the distances between the start and destination, show the ar display guard let start = start, let destination = destination else { debugView.log("Error: either start or destination didn't exist") return } let (distanceSouth, distanceEast) = distances(start: start, destination: destination) let display = WayPointDisplay() arDisplay = display PlaygroundPage.current.liveView = display.view display.distanceSouth = distanceSouth display.distanceEast = distanceEast mapState = 0 //return to initial state default : mapState = 0 debugView.log("Error: hit default case") } } ///an approximation that returns the number of meters south and east the destination is from the start func distances(start: CLLocationCoordinate2D, destination: CLLocationCoordinate2D)->(Double, Double){ //east / longitude let lonStart = CLLocation(latitude: start.latitude, longitude: start.longitude) let lonDest = CLLocation(latitude: start.latitude, longitude: destination.longitude) var distanceEast = lonStart.distance(from: lonDest) let directionMultiplier = destination.longitude >= start.longitude ? 1.0 : -1.0 distanceEast = distanceEast * directionMultiplier //south / latitude let latDest = CLLocation(latitude: destination.latitude, longitude: start.longitude) var distanceSouth = lonStart.distance(from: latDest) let latMultiplier = destination.latitude >= start.latitude ? -1.0 : 1.0 distanceSouth = latMultiplier * distanceSouth return (distanceSouth, distanceEast) } } class WayPointDisplay: NSObject, ARSCNViewDelegate { ///the distance south of the world origin to place the waypoint var distanceSouth: Double = 0.0 ///the distance east of the world origin to place the waypoint var distanceEast: Double = 0.0 ///maps ARAnchors to SCNNodes var nodeDict = [UUID:SCNNode]() //mark: ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { if let node = nodeDict[anchor.identifier] { return node } return nil } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { [weak self] in self?.debugView.log("updated node") } } let arSessionConfig = ARWorldTrackingConfiguration() let debugView = ARDebugView() var view:ARSCNView? = nil let scene = SCNScene() let useScenekit = true override init(){ super.init() let frame = CGRect(x: 0.0, y: 0, width: 100, height: 100) let arView = ARSCNView(frame: frame) //configure the ARSCNView arView.debugOptions = [ ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints, // SCNDebugOptions.showLightInfluences, // SCNDebugOptions.showWireframe ] arView.showsStatistics = true arView.automaticallyUpdatesLighting = true debugView.translatesAutoresizingMaskIntoConstraints = false //add the debug view arView.addSubview(debugView) arView.leadingAnchor.constraint(equalTo: debugView.leadingAnchor) arView.topAnchor.constraint(equalTo: debugView.topAnchor) view = arView arView.scene = scene //setup session config if !ARWorldTrackingConfiguration.isSupported { return } arSessionConfig.planeDetection = .horizontal arSessionConfig.worldAlignment = .gravityAndHeading //y-axis points UP, x points E (longitude), z points S (latitude) arSessionConfig.isLightEstimationEnabled = true arView.session.run(arSessionConfig, options: [.resetTracking, .removeExistingAnchors]) arView.delegate = self let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gestureRecognizer:))) view?.addGestureRecognizer(gestureRecognizer) } let shouldAddAnchorsForNodes = true func addNode(node: SCNNode, worldTransform: matrix_float4x4) { let anchor = ARAnchor(transform: worldTransform) let position = vectorFrom(transform: worldTransform) node.position = position node.rotation = SCNVector4(x: 1, y: 1, z: 0, w: 0) nodeDict[anchor.identifier] = node if shouldAddAnchorsForNodes { view?.session.add(anchor: anchor) } else { scene.rootNode.addChildNode(node) } } ///adds a 200M high cylinder at worldTransform func addAntenna(worldTransform: matrix_float4x4 = matrix_identity_float4x4) { let height = 200 as Float let cylinder = SCNCylinder(radius: 0.5, height: CGFloat(height)) cylinder.firstMaterial?.diffuse.contents = UIColor(red: 0.4, green: 0, blue: 0, alpha: 1) cylinder.firstMaterial?.specular.contents = UIColor.white //raise the cylinder so the base is positioned at the worldTransform var transform = matrix_identity_float4x4 transform.columns.3.y = height / 2 let finalTransform = matrix_multiply(worldTransform, transform) let cylinderNode = SCNNode(geometry:cylinder) addNode(node: cylinderNode, worldTransform: finalTransform) } ///when the user taps, add a waypoint antenna at distanceEast, distanceSouth from the origin @objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){ debugView.log("DE: \(distanceEast) DS: \(distanceSouth)") var transform = matrix_identity_float4x4 transform.columns.3.x = Float(distanceEast) transform.columns.3.z = Float(distanceSouth) addAntenna(worldTransform: transform) } ///convert a transform matrix_float4x4 to a SCNVector3 func vectorFrom(transform: matrix_float4x4) -> SCNVector3 { return SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z) } } let mapper = WaypointNavigator() PlaygroundPage.current.needsIndefiniteExecution = true
fd95d144dcb9fcc65decb3ba044dad82
40.954774
125
0.669421
false
false
false
false
szk-atmosphere/MartyJunior
refs/heads/master
MartyJunior/MJTableViewTopCell.swift
mit
1
// // MJTableViewTopCell.swift // MartyJunior // // Created by 鈴木大貴 on 2015/11/26. // Copyright © 2015年 Taiki Suzuki. All rights reserved. // import UIKit import MisterFusion class MJTableViewTopCell: UITableViewCell { static let ReuseIdentifier: String = "MJTableViewTopCell" weak var mainContentView: MJContentView? { didSet { guard let mainContentView = mainContentView else { return } contentView.addLayoutSubview(mainContentView, andConstraints: mainContentView.top, mainContentView.left, mainContentView.right, mainContentView.height |==| mainContentView.currentHeight ) } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initialize() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initialize() { selectionStyle = .none } }
4d6fc27df902348936c247a23f96dedc
26.1
74
0.639299
false
false
false
false
kaushaldeo/Olympics
refs/heads/master
Olympics/Views/KDRankingCell.swift
apache-2.0
1
// // KDRankingCell.swift // Olympics // // Created by Kaushal Deo on 7/25/16. // Copyright © 2016 Scorpion Inc. All rights reserved. // import UIKit class KDRankingCell: UITableViewCell { @IBOutlet weak var tableView: UITableView! var competitors = [Competitor]() { didSet { self.tableView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: - Table view data source func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.competitors.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Configure the cell... let cell = tableView.dequeueReusableCellWithIdentifier("Rank", forIndexPath: indexPath) as! KDResultViewCell let competitor = self.competitors[indexPath.row] cell.nameLabel.text = competitor.name() if let text = competitor.iconName() { cell.iconView.image = UIImage(named: "Images/\(text).png") } cell.rankLabel.text = competitor.rank ?? "-" if let string = competitor.resultValue { cell.resultLabel.text = string } else if let unit = competitor.unit { let status = unit.statusValue() if status != "closed" && status != "progress" { cell.resultLabel.text = competitor.unit?.startDate?.time() } else if let string = competitor.resultType { cell.resultLabel.text = string == "irm" ? "DNF" : "" } } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let competitor = self.competitors[indexPath.row] var height = CGFloat(0) let string = competitor.resultValue ?? "" let width = string.size(UIFont.systemFontOfSize(14), width: (CGRectGetWidth(tableView.frame) - 80)).width + 80.0 if let text = competitor.name() { height += text.size(UIFont.systemFontOfSize(14), width:CGRectGetWidth(tableView.frame) - width).height + 24 } return height } }
69582111169e25e5bb7d979c8fd1f878
30.924051
124
0.603489
false
false
false
false
garygriswold/Bible.js
refs/heads/master
SafeBible2/SafeBible_ios/SafeBible/Adapters/BiblePageModel.swift
mit
1
// // BiblePageModel.swift // Settings // // Created by Gary Griswold on 10/25/18. // Copyright © 2018 ShortSands. All rights reserved. // // Bible.objectKey contains codes that define String replacements // %I := Id in last part of s3KeyPrefix // %O := ordinal 1 is GEN, 70 is MAT, not zero filled // %o := 3 char ordinal A01 is GEN, zero filled // %B := USFM 3 char book code // %b := 2 char book code // %C := chapter number, not zero filled // %c := chapter number, zero filled, 2 char, 3 Psalms // import AWS import WebKit struct BiblePageModel { func loadPage(reference: Reference, webView: WKWebView, controller: UIViewController) { self.getChapter(reference: reference, view: webView, complete: { html in if html != nil { let page = DynamicCSS.shared.wrapHTML(html: html!, reference: reference) webView.loadHTMLString(page, baseURL: nil) } else { // Usually an error occurs because the book does not exist in this Bible TOCBooksViewController.push(controller: controller) } }) } func loadCompareVerseCell(reference: Reference, startVerse: Int, endVerse: Int, cell: CompareVerseCell, table: UITableView, indexPath: IndexPath) { self.getChapter(reference: reference, view: cell.contentView, complete: { html in if html != nil { cell.verse.text = self.parse(html: html!, reference: reference, startVerse: startVerse, endVerse: endVerse) table.reloadRows(at: [indexPath], with: .automatic) } }) } /** * I guess the correct way to pass back a string is to pass in a Writable Key Path, but I don't understand it. */ func loadLabel(reference: Reference, verse: Int, label: UILabel) { self.getChapter(reference: reference, view: nil, complete: { html in if html != nil { var result = self.parse(html: html!, reference: reference, startVerse: verse, endVerse: verse) result = result.replacingOccurrences(of: String(verse), with: "") label.text = result.trimmingCharacters(in: .whitespacesAndNewlines) } }) } /** Used by HTMLVerseParserTest */ func testParse(reference: Reference, lastVerse: Int, complete: @escaping () -> Void) { self.getChapter(reference: reference, view: nil, complete: { html in for verse in 1..<(lastVerse + 1) { let result = self.parse(html: html!, reference: reference, startVerse: verse, endVerse: verse) if result.count < 5 { print("PARSE ERROR \(reference):\(verse) |\(result)|") } } complete() }) } private func parse(html: String, reference: Reference, startVerse: Int, endVerse: Int) -> String { if reference.isDownloaded { return BibleDB.shared.getBibleVerses(reference: reference, startVerse: startVerse, endVerse: endVerse) } else if reference.isShortsands { let parser = HTMLVerseParserSS(html: html, startVerse: startVerse, endVerse: endVerse) return parser.parseVerses() } else { let parser = HTMLVerseParserDBP(html: html, startVerse: startVerse, endVerse: endVerse) return parser.parseVerses() } } private func getChapter(reference: Reference, view: UIView?, complete: @escaping (_ data:String?) -> Void) { let start = CFAbsoluteTimeGetCurrent() let html = BibleDB.shared.getBiblePage(reference: reference) if html == nil { let progress = self.addProgressIndicator(view: view) let s3Key = self.generateKey(reference: reference) let s3 = (reference.isShortsands) ? AwsS3Manager.findSS() : AwsS3Manager.findDbp() s3.downloadText(s3Bucket: reference.bible.textBucket, s3Key: s3Key, complete: { error, data in self.removeProgressIndicator(indicator: progress) if let err = error { print("ERROR: \(err)") complete(nil) } else if let data1 = data { complete(data1) print("AWS Load \(reference.toString())") _ = BibleDB.shared.storeBiblePage(reference: reference, html: data1) print("*** BiblePageModel.getChapter duration \((CFAbsoluteTimeGetCurrent() - start) * 1000) ms") } }) } else { complete(html) print("DB Load \(reference.toString())") } } private func addProgressIndicator(view: UIView?) -> UIActivityIndicatorView? { if view != nil { let style: UIActivityIndicatorView.Style = AppFont.nightMode ? .white : .gray let progress = UIActivityIndicatorView(style: style) progress.frame = CGRect(x: 40, y: 40, width: 0, height: 0) view!.addSubview(progress) progress.startAnimating() return progress } else { return nil } } private func removeProgressIndicator(indicator: UIActivityIndicatorView?) { if indicator != nil { indicator!.stopAnimating() indicator!.removeFromSuperview() } } private func generateKey(reference: Reference) -> String { var result = [String]() var inItem = false for char: Character in reference.s3TextTemplate { if char == "%" { inItem = true } else if !inItem { result.append(String(char)) } else { inItem = false switch char { case "I": // Id is last part of s3KeyPrefix let parts = reference.s3TextPrefix.split(separator: "/") result.append(String(parts[parts.count - 1])) case "O": // ordinal 1 is GEN, 70 is MAT, not zero filled if let seq = bookMap[reference.bookId]?.seq { result.append(seq) } case "o": // 3 char ordinal A01 is GEN, zero filled if let seq3 = bookMap[reference.bookId]?.seq3 { result.append(seq3) } case "B": // USFM 3 char book code result.append(reference.bookId) case "b": // 2 char book code if let id2 = bookMap[reference.bookId]?.id2 { result.append(id2) } case "C": // chapter number, not zero filled if reference.chapter > 0 { result.append(String(reference.chapter)) } else { result.removeLast() // remove the underscore that would preceed chapter } case "d": // chapter number, 2 char zero filled, Psalms 3 char var chapStr = String(reference.chapter) if chapStr.count == 1 { chapStr = "0" + chapStr } if chapStr.count == 2 && reference.bookId == "PSA" { chapStr = "0" + chapStr } result.append(chapStr) default: print("ERROR: Unknown format char %\(char)") } } } return reference.s3TextPrefix + "/" + result.joined() } struct BookData { let seq: String let seq3: String let id2: String } let bookMap: [String: BookData] = [ "FRT": BookData(seq: "0", seq3: "?", id2: "?"), "GEN": BookData(seq: "2", seq3: "A01", id2: "GN"), "EXO": BookData(seq: "3", seq3: "A02", id2: "EX"), "LEV": BookData(seq: "4", seq3: "A03", id2: "LV"), "NUM": BookData(seq: "5", seq3: "A04", id2: "NU"), "DEU": BookData(seq: "6", seq3: "A05", id2: "DT"), "JOS": BookData(seq: "7", seq3: "A06", id2: "JS"), "JDG": BookData(seq: "8", seq3: "A07", id2: "JG"), "RUT": BookData(seq: "9", seq3: "A08", id2: "RT"), "1SA": BookData(seq: "10", seq3: "A09", id2: "S1"), "2SA": BookData(seq: "11", seq3: "A10", id2: "S2"), "1KI": BookData(seq: "12", seq3: "A11", id2: "K1"), "2KI": BookData(seq: "13", seq3: "A12", id2: "K2"), "1CH": BookData(seq: "14", seq3: "A13", id2: "R1"), "2CH": BookData(seq: "15", seq3: "A14", id2: "R2"), "EZR": BookData(seq: "16", seq3: "A15", id2: "ER"), "NEH": BookData(seq: "17", seq3: "A16", id2: "NH"), "EST": BookData(seq: "18", seq3: "A17", id2: "ET"), "JOB": BookData(seq: "19", seq3: "A18", id2: "JB"), "PSA": BookData(seq: "20", seq3: "A19", id2: "PS"), "PRO": BookData(seq: "21", seq3: "A20", id2: "PR"), "ECC": BookData(seq: "22", seq3: "A21", id2: "EC"), "SNG": BookData(seq: "23", seq3: "A22", id2: "SS"), "ISA": BookData(seq: "24", seq3: "A23", id2: "IS"), "JER": BookData(seq: "25", seq3: "A24", id2: "JR"), "LAM": BookData(seq: "26", seq3: "A25", id2: "LM"), "EZK": BookData(seq: "27", seq3: "A26", id2: "EK"), "DAN": BookData(seq: "28", seq3: "A27", id2: "DN"), "HOS": BookData(seq: "29", seq3: "A28", id2: "HS"), "JOL": BookData(seq: "30", seq3: "A29", id2: "JL"), "AMO": BookData(seq: "31", seq3: "A30", id2: "AM"), "OBA": BookData(seq: "32", seq3: "A31", id2: "OB"), "JON": BookData(seq: "33", seq3: "A32", id2: "JH"), "MIC": BookData(seq: "34", seq3: "A33", id2: "MC"), "NAM": BookData(seq: "35", seq3: "A34", id2: "NM"), "HAB": BookData(seq: "36", seq3: "A35", id2: "HK"), "ZEP": BookData(seq: "37", seq3: "A36", id2: "ZP"), "HAG": BookData(seq: "38", seq3: "A37", id2: "HG"), "ZEC": BookData(seq: "39", seq3: "A38", id2: "ZC"), "MAL": BookData(seq: "40", seq3: "A39", id2: "ML"), "TOB": BookData(seq: "41", seq3: "?", id2: "?"), "JDT": BookData(seq: "42", seq3: "?", id2: "?"), "ESG": BookData(seq: "43", seq3: "?", id2: "?"), "WIS": BookData(seq: "45", seq3: "?", id2: "?"), "SIR": BookData(seq: "46", seq3: "?", id2: "?"), "BAR": BookData(seq: "47", seq3: "?", id2: "?"), "LJE": BookData(seq: "48", seq3: "?", id2: "?"), "S3Y": BookData(seq: "49", seq3: "?", id2: "?"), "SUS": BookData(seq: "50", seq3: "?", id2: "?"), "BEL": BookData(seq: "51", seq3: "?", id2: "?"), "1MA": BookData(seq: "52", seq3: "?", id2: "?"), "2MA": BookData(seq: "53", seq3: "?", id2: "?"), "1ES": BookData(seq: "54", seq3: "?", id2: "?"), "MAN": BookData(seq: "55", seq3: "?", id2: "?"), "3MA": BookData(seq: "57", seq3: "?", id2: "?"), "4MA": BookData(seq: "59", seq3: "?", id2: "?"), "MAT": BookData(seq: "70", seq3: "B01", id2: "MT"), "MRK": BookData(seq: "71", seq3: "B02", id2: "MK"), "LUK": BookData(seq: "72", seq3: "B03", id2: "LK"), "JHN": BookData(seq: "73", seq3: "B04", id2: "JN"), "ACT": BookData(seq: "74", seq3: "B05", id2: "AC"), "ROM": BookData(seq: "75", seq3: "B06", id2: "RM"), "1CO": BookData(seq: "76", seq3: "B07", id2: "C1"), "2CO": BookData(seq: "77", seq3: "B08", id2: "C2"), "GAL": BookData(seq: "78", seq3: "B09", id2: "GL"), "EPH": BookData(seq: "79", seq3: "B10", id2: "EP"), "PHP": BookData(seq: "80", seq3: "B11", id2: "PP"), "COL": BookData(seq: "81", seq3: "B12", id2: "CL"), "1TH": BookData(seq: "82", seq3: "B13", id2: "H1"), "2TH": BookData(seq: "83", seq3: "B14", id2: "H2"), "1TI": BookData(seq: "84", seq3: "B15", id2: "T1"), "2TI": BookData(seq: "85", seq3: "B16", id2: "T2"), "TIT": BookData(seq: "86", seq3: "B17", id2: "TT"), "PHM": BookData(seq: "87", seq3: "B18", id2: "PM"), "HEB": BookData(seq: "88", seq3: "B19", id2: "HB"), "JAS": BookData(seq: "89", seq3: "B20", id2: "JM"), "1PE": BookData(seq: "90", seq3: "B21", id2: "P1"), "2PE": BookData(seq: "91", seq3: "B22", id2: "P2"), "1JN": BookData(seq: "92", seq3: "B23", id2: "J1"), "2JN": BookData(seq: "93", seq3: "B24", id2: "J2"), "3JN": BookData(seq: "94", seq3: "B25", id2: "J3"), "JUD": BookData(seq: "95", seq3: "B26", id2: "JD"), "REV": BookData(seq: "96", seq3: "B27", id2: "RV"), "BAK": BookData(seq: "97", seq3: "?", id2: "?"), "GLO": BookData(seq: "106", seq3: "?", id2: "?") ] }
8b67847252f463900986c4adbc6641b7
45.902527
117
0.504233
false
false
false
false
ZENTRALALEX/LeafEditor
refs/heads/master
Sources/App/main.swift
mit
1
import Vapor import Foundation let drop = Droplet() var nodes = [Node(["one": "One", "two": "Two", "three": Node(["one": "One", "sub": "Two"])])] drop.post("leaf/save") { request in guard let leaf = request.data["leaf"]?.string else { return try JSON(node: ["error": "Failed to find leaf string.", "description": nil]) } do { try leaf.write(toFile: drop.resourcesDir + "/Views/written.leaf", atomically: false, encoding: String.Encoding.utf8) } catch { print("could not write leaf") } return try JSON(node: ["error": nil, "description": "Successfully wrote .leaf file."]) } drop.get { req in do { let directoryContents = try FileManager.default.contentsOfDirectory(atPath: drop.resourcesDir + "/Views/") let node = try directoryContents.makeNode() let editorContent = try drop.view.make("written").makeBytes() let file = try String(contentsOfFile: drop.resourcesDir + "/Views/written.leaf", encoding: String.Encoding.utf8) print(directoryContents); return try drop.view.make("written", [ "messages": node, "editorContent" : file ]) } catch { print("failed to read leaf files or written.leaf") } return try drop.view.make("welcome", [ "message": Node([]) ]) } drop.resource("posts", PostController()) drop.run()
f0ff13aad21ce7e7e9c2000026e3c3dd
27.921569
124
0.581695
false
false
false
false
ianrahman/HackerRankChallenges
refs/heads/master
Swift/Data Structures/Arrays/dynamic-array.swift
mit
1
import Foundation // define initial values var lastAns = 0 let params = readLine()!.components(separatedBy: " ").map{ Int($0)! } let sequencesCount = params[0] let queriesCount = params[1] var seqList = [[Int]]() // create necessary number of empty sequences for _ in 0..<sequencesCount { seqList.append([Int]()) } // define query types enum QueryType: Int { case type1 = 1, type2 } // read each query for _ in 0..<queriesCount { // define temp values let query = readLine()!.components(separatedBy: " ").map{ Int($0)! } let x = query[1] let y = query[2] let xor = x ^ lastAns let index = (x ^ lastAns) % sequencesCount // perform query if let type = QueryType(rawValue: query[0]) { switch type { case .type1: seqList[index].append(y) case .type2: let size = seqList[index].count let value = seqList[index][y % size] lastAns = value print(lastAns) } } }
e280a15e3c602cc584d569a1a8f2615e
22.714286
72
0.591365
false
false
false
false
santosli/100-Days-of-Swift-3
refs/heads/master
Project 19/Project 19/ViewController.swift
apache-2.0
1
// // ViewController.swift // Project 19 // // Created by Santos on 23/11/2016. // Copyright © 2016 santos. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var demoTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //add left and right navigation button self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil) //init color self.navigationItem.title = "New Entry" self.navigationController?.navigationBar.barTintColor = UIColor(red:0.93, green:0.98, blue:0.96, alpha:1.00) self.navigationController?.navigationBar.tintColor = UIColor(red:0.00, green:0.73, blue:0.58, alpha:1.00) //add toolbar above keyboard let keyboardToolbar = UIToolbar() keyboardToolbar.sizeToFit() keyboardToolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default) keyboardToolbar.setShadowImage(UIImage(), forToolbarPosition: .any) let cameraButton = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: nil) cameraButton.tintColor = UIColor(red:0.46, green:0.84, blue:0.74, alpha:1.00) let locationButton = UIBarButtonItem.init(image: #imageLiteral(resourceName: "location"), style: .plain, target: nil, action: nil) locationButton.tintColor = UIColor(red:0.46, green:0.84, blue:0.74, alpha:1.00) keyboardToolbar.items = [cameraButton, locationButton] demoTextView.inputAccessoryView = keyboardToolbar } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
d34ea9eadd8508db7459d27486ed842d
37.45283
138
0.678606
false
false
false
false
YevhenHerasymenko/SwiftGroup1
refs/heads/master
FirstGetRequest/FirstGetRequest/Controllers/ViewController.swift
apache-2.0
1
// // ViewController.swift // FirstGetRequest // // Created by Yevhen Herasymenko on 22/07/2016. // Copyright © 2016 Yevhen Herasymenko. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var userAvatar: UIImageView! var user: User? = nil { didSet { let operation = NSBlockOperation { self.updateUI() } NSOperationQueue.mainQueue().addOperation(operation) } } override func viewDidLoad() { super.viewDidLoad() NetworkManager.getUser {[weak self] (answer) in switch answer { case .Success(let user): guard let strongSelf = self else { return } strongSelf.user = user case .Failure(let error): print(error) } } } func updateUI() { if let avatar = user?.avatarUrl, let avatarUrl = NSURL(string: avatar), let photoData = NSData(contentsOfURL: avatarUrl) { let image = UIImage(data: photoData) userAvatar.image = image } } }
32140d58e3e4535cfcf308dd2801b5a0
24.888889
64
0.551931
false
false
false
false
sora0077/QiitaKit
refs/heads/master
QiitaKit/src/Endpoint/Tagging/CreateTagging.swift
mit
1
// // CreateTagging.swift // QiitaKit // // Created on 2015/06/08. // Copyright (c) 2015年 林達也. All rights reserved. // import Foundation import APIKit import Result /** * 投稿にタグを追加します。Qiita:Teamでのみ有効です。 */ public struct CreateTagging { public let id: Item.Identifier /// タグを特定するための一意な名前 /// example: qiita /// public let name: String /// /// example: ["0.0.1"] /// public let versions: Array<String> public init(id: Item.Identifier, name: String, versions: Array<String>) { self.id = id self.name = name self.versions = versions } } extension CreateTagging: QiitaRequestToken { public typealias Response = Tagging public typealias SerializedObject = [String: AnyObject] public var method: HTTPMethod { return .POST } public var path: String { return "/api/v2/items/\(id)/taggings" } public var parameters: [String: AnyObject]? { return [ "name": name, "versions": versions ] } public var encoding: RequestEncoding { return .JSON } } public extension CreateTagging { func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { return _Tagging(object) } }
88e28e3bc36f8fba690f5ab50d54cce6
18.925373
119
0.610487
false
false
false
false
codefellows/sea-b19-ios
refs/heads/master
Projects/FlappyBirdSwift/FlappyBirdSwift/GameScene.swift
gpl-2.0
1
// // GameScene.swift // FlappyBirdSwift // // Created by Bradley Johnson on 9/1/14. // Copyright (c) 2014 learnswift. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var flappy = SKSpriteNode(imageNamed: "flappy") var pipes = [PipeNode]() var firstAvailable : PipeNode! var flappyIsDead = false var deltaTime = 0.0 var nextPipeTime = 2.0 var previousTime = 0.0 var timeSinceLastPipe = 0.0 //categories let flappyCategory = 0x1 << 0 let pipeCategory = 0x1 << 1 let bottomPipeLowerBounds = -300 let pipeHeight = 530 override func didMoveToView(view: SKView) { /* Setup your scene here */ //creating our main character //setup scrollingbackground self.setupBackground() println(self.frame) self.physicsWorld.contactDelegate = self //setup pipes list self.setupPipes() //setup flappy self.flappy.position = CGPoint(x: 100, y: 300) self.addChild(self.flappy) //adding physics to flappy self.flappy.physicsBody = SKPhysicsBody(rectangleOfSize: self.flappy.size) self.flappy.physicsBody.dynamic = true self.flappy.physicsBody.mass = 0.02 self.flappy.physicsBody.categoryBitMask = UInt32(self.flappyCategory) self.flappy.physicsBody.contactTestBitMask = UInt32(self.pipeCategory) self.flappy.physicsBody.collisionBitMask = 0 } func setupPipes() { for (var i = 0; i < 10;i++) { //pipe setup var pipeNode = PipeNode() pipeNode.pipe.position = CGPointMake(1100, 0) pipeNode.pipe.anchorPoint = CGPointZero pipeNode.pipe.physicsBody = SKPhysicsBody(rectangleOfSize: pipeNode.pipe.size) pipeNode.pipe.physicsBody.affectedByGravity = false pipeNode.pipe.physicsBody.dynamic = false pipeNode.pipe.physicsBody.categoryBitMask = UInt32(self.pipeCategory) pipeNode.pipe.physicsBody.contactTestBitMask = UInt32(self.flappyCategory) //pipeNode.pipe.hidden = true self.addChild(pipeNode.pipe) //insert pipe into array, assign next pointer for linked list self.pipes.insert(pipeNode, atIndex: 0) if self.pipes.count > 1 { pipeNode.nextNode = self.pipes[1] } } self.firstAvailable = self.pipes[0] } func fetchFirstAvailablePipe () -> PipeNode { var firstPipe = self.firstAvailable //replace current head with head's next if self.firstAvailable.nextNode != nil { self.firstAvailable = self.firstAvailable.nextNode } //firstPipe.pipe.hidden = false return firstPipe } func doneWithPipe(pipeNode : PipeNode) { //pipeNode.pipe.hidden = true pipeNode.nextNode = self.firstAvailable self.firstAvailable = pipeNode println("done with pipe") } func setupBackground() { //this creates 2 backgrounds for (var i = 0; i < 2;i++) { var bg = SKSpriteNode(imageNamed: "space.jpg") var newI = CGFloat(i) bg.anchorPoint = CGPointZero bg.position = CGPointMake(newI * bg.size.width, 90) bg.name = "background" self.addChild(bg) } } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { /* Called when a touch begins */ println("touches began") if flappyIsDead == false { self.flappy.physicsBody.velocity = CGVectorMake(0, 0) self.flappy.physicsBody.applyImpulse(CGVectorMake(0, 7)) } } func movePipe(pipeNode : PipeNode, location : CGPoint){ var moveAction = SKAction.moveTo(location, duration: 3) var completionAction = SKAction.runBlock({ self.doneWithPipe(pipeNode) }) var sequence = SKAction.sequence([moveAction,completionAction]) pipeNode.pipe.runAction(sequence) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ //figuring our delta time, aka time since last update: self.deltaTime = currentTime - self.previousTime self.previousTime = currentTime self.timeSinceLastPipe += self.deltaTime if self.timeSinceLastPipe > self.nextPipeTime { println("spawning pipe") //generate random number between 0 and -300 var y = Int(arc4random_uniform(UInt32(300))) var randomY = CGFloat(y * -1) //its time to create a pipe var pipeNode = self.fetchFirstAvailablePipe() println("height of pipe : \(pipeNode.pipe.size.height)") pipeNode.pipe.position = CGPointMake(1100, randomY) //create location to tell pipe to move to with an action var location = CGPointMake(-70, randomY) self.movePipe(pipeNode, location: location) // var topY = CGFloat(self.pipeHeight) + 450 + randomY //// spawn top pipe // var topPipe = self.fetchFirstAvailablePipe() // var rotate = SKAction.rotateByAngle(CGFloat(M_PI), duration: 0.0) // topPipe.pipe.runAction(rotate) // // topPipe.pipe.position = CGPointMake(1100, topY) // var nextLocation = CGPointMake(-70, topY) // self.movePipe(topPipe, location: nextLocation) // // reset timesincelastpipe to 0, since we just created a pipe self.timeSinceLastPipe = 0 } //enumerate through our background nodes self.enumerateChildNodesWithName("background", usingBlock: { (node, stop) -> Void in if let bg = node as? SKSpriteNode { //move the background to the left bg.position = CGPointMake(bg.position.x - 5, bg.position.y) //if background is completely off screen to left, move it to the right so it can be scrolled back on screen if bg.position.x <= bg.size.width * -1 { bg.position = CGPointMake(bg.position.x + bg.size.width * 2, bg.position.y) } } }) } func didBeginContact(contact: SKPhysicsContact!) { println("contact!") self.flappyIsDead = true var bird = contact.bodyB.node var slightUp = CGPointMake(bird.position.x, bird.position.y + 20) var moveUp = SKAction.moveTo(slightUp, duration: 0.1) var drop = CGPointMake(bird.position.x, 0) var moveDown = SKAction.moveTo(drop, duration: 0.5) var sequence = SKAction.sequence([moveUp,moveDown]) bird.runAction(sequence) } }
015fe12f3d8c5f0ab392d6cadf02e074
32.251163
115
0.586096
false
false
false
false
mxcl/PromiseKit
refs/heads/v6
Tests/JS-A+/JSUtils.swift
mit
1
// // JSUtils.swift // PMKJSA+Tests // // Created by Lois Di Qual on 3/2/18. // import Foundation import JavaScriptCore enum JSUtils { class JSError: Error { let reason: JSValue init(reason: JSValue) { self.reason = reason } } static let sharedContext: JSContext = { guard let context = JSContext() else { fatalError("Couldn't create JS context") } return context }() static var undefined: JSValue { guard let undefined = JSValue(undefinedIn: JSUtils.sharedContext) else { fatalError("Couldn't create `undefined` value") } return undefined } static func typeError(message: String) -> JSValue { let message = message.replacingOccurrences(of: "\"", with: "\\\"") let script = "new TypeError(\"\(message)\")" guard let result = sharedContext.evaluateScript(script) else { fatalError("Couldn't create TypeError") } return result } // @warning: relies on lodash to be present static func isFunction(value: JSValue) -> Bool { guard let context = value.context else { return false } guard let lodash = context.objectForKeyedSubscript("_") else { fatalError("Couldn't get lodash in JS context") } guard let result = lodash.invokeMethod("isFunction", withArguments: [value]) else { fatalError("Couldn't invoke _.isFunction") } return result.toBool() } // Calls a JS function using `Function.prototype.call` and throws any potential exception wrapped in a JSError static func call(function: JSValue, arguments: [JSValue]) throws -> JSValue? { let context = JSUtils.sharedContext // Create a new exception handler that will store a potential exception // thrown in the handler. Save the value of the old handler. var caughtException: JSValue? let savedExceptionHandler = context.exceptionHandler context.exceptionHandler = { context, exception in caughtException = exception } // Call the handler let returnValue = function.invokeMethod("call", withArguments: arguments) context.exceptionHandler = savedExceptionHandler // If an exception was caught, throw it if let exception = caughtException { throw JSError(reason: exception) } return returnValue } static func printCurrentStackTrace() { guard let exception = JSUtils.sharedContext.evaluateScript("new Error()") else { return print("Couldn't get current stack trace") } printStackTrace(exception: exception, includeExceptionDescription: false) } static func printStackTrace(exception: JSValue, includeExceptionDescription: Bool) { guard let lineNumber = exception.objectForKeyedSubscript("line"), let column = exception.objectForKeyedSubscript("column"), let message = exception.objectForKeyedSubscript("message"), let stacktrace = exception.objectForKeyedSubscript("stack")?.toString() else { return print("Couldn't print stack trace") } if includeExceptionDescription { print("JS Exception at \(lineNumber):\(column): \(message)") } let lines = stacktrace.split(separator: "\n").map { "\t> \($0)" }.joined(separator: "\n") print(lines) } } #if !swift(>=3.2) extension String { func split(separator: Character, omittingEmptySubsequences: Bool = true) -> [String] { return characters.split(separator: separator, omittingEmptySubsequences: omittingEmptySubsequences).map(String.init) } var first: Character? { return characters.first } } #endif
16d87ca5d537eccd627d97184c78f7c6
32.974138
124
0.618371
false
false
false
false
andreamazz/BubbleTransition
refs/heads/master
Source/BubbleTransition.swift
mit
1
// // BubbleTransition.swift // BubbleTransition // // Created by Andrea Mazzini on 04/04/15. // Copyright (c) 2015-2018 Fancy Pixel. All rights reserved. // import UIKit /** A custom modal transition that presents and dismiss a controller with an expanding bubble effect. - Prepare the transition: ```swift override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let controller = segue.destination controller.transitioningDelegate = self controller.modalPresentationStyle = .custom } ``` - Implement UIViewControllerTransitioningDelegate: ```swift func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.transitionMode = .present transition.startingPoint = someButton.center transition.bubbleColor = someButton.backgroundColor! return transition } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.transitionMode = .dismiss transition.startingPoint = someButton.center transition.bubbleColor = someButton.backgroundColor! return transition } ``` */ open class BubbleTransition: NSObject { /** The point that originates the bubble. The bubble starts from this point and shrinks to it on dismiss */ @objc open var startingPoint = CGPoint.zero { didSet { bubble.center = startingPoint } } /** The transition duration. The same value is used in both the Present or Dismiss actions Defaults to `0.5` */ @objc open var duration = 0.5 /** The transition direction. Possible values `.present`, `.dismiss` or `.pop` Defaults to `.Present` */ @objc open var transitionMode: BubbleTransitionMode = .present /** The color of the bubble. Make sure that it matches the destination controller's background color. */ @objc open var bubbleColor: UIColor = .white open fileprivate(set) var bubble = UIView() /** The possible directions of the transition. - Present: For presenting a new modal controller - Dismiss: For dismissing the current controller - Pop: For a pop animation in a navigation controller */ @objc public enum BubbleTransitionMode: Int { case present, dismiss, pop } } /// The interactive swipe direction /// /// - up: swipe up /// - down: swipe down public enum BubbleInteractiveTransitionSwipeDirection: CGFloat { case up = -1 case down = 1 } /** Handles the interactive dismissal of the presented controller via swipe - Prepare the interactive transaction: ```swift let interactiveTransition = BubbleInteractiveTransition() override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let controller = segue.destination controller.transitioningDelegate = self controller.modalPresentationStyle = .custom interactiveTransition.attach(to: controller) } ``` and implement the appropriate delegate method: ```swift func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition } ``` */ open class BubbleInteractiveTransition: UIPercentDrivenInteractiveTransition { fileprivate var interactionStarted = false fileprivate var interactionShouldFinish = false fileprivate var controller: UIViewController? /// The threshold that grants the dismissal of the controller. Values from 0 to 1 open var interactionThreshold: CGFloat = 0.3 /// The swipe direction open var swipeDirection: BubbleInteractiveTransitionSwipeDirection = .down /// Attach the swipe gesture to a controller /// /// - Parameter to: the target controller open func attach(to: UIViewController) { controller = to controller?.view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(BubbleInteractiveTransition.handlePan(gesture:)))) if #available(iOS 10.0, *) { wantsInteractiveStart = false } } @objc func handlePan(gesture: UIPanGestureRecognizer) { guard let controller = controller, let view = controller.view else { return } let translation = gesture.translation(in: controller.view.superview) let delta = swipeDirection.rawValue * (translation.y / view.bounds.height) let movement = fmaxf(Float(delta), 0.0) let percent = fminf(movement, 1.0) let progress = CGFloat(percent) switch gesture.state { case .began: interactionStarted = true controller.dismiss(animated: true, completion: nil) case .changed: interactionShouldFinish = progress > interactionThreshold update(progress) case .cancelled: interactionShouldFinish = false fallthrough case .ended: interactionStarted = false interactionShouldFinish ? finish() : cancel() default: break } } } extension BubbleTransition: UIViewControllerAnimatedTransitioning { // MARK: - UIViewControllerAnimatedTransitioning /** Required by UIViewControllerAnimatedTransitioning */ public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } /** Required by UIViewControllerAnimatedTransitioning */ public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView let fromViewController = transitionContext.viewController(forKey: .from) let toViewController = transitionContext.viewController(forKey: .to) if transitionMode == .present { fromViewController?.beginAppearanceTransition(false, animated: true) if toViewController?.modalPresentationStyle == .custom { toViewController?.beginAppearanceTransition(true, animated: true) } let presentedControllerView = transitionContext.view(forKey: .to)! let originalCenter = presentedControllerView.center let originalSize = presentedControllerView.frame.size bubble = UIView() bubble.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint) bubble.layer.cornerRadius = bubble.frame.size.height / 2 bubble.center = startingPoint bubble.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) bubble.backgroundColor = bubbleColor containerView.addSubview(bubble) presentedControllerView.center = startingPoint presentedControllerView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) presentedControllerView.alpha = 0 containerView.addSubview(presentedControllerView) UIView.animate(withDuration: duration, animations: { self.bubble.transform = CGAffineTransform.identity presentedControllerView.transform = CGAffineTransform.identity presentedControllerView.alpha = 1 presentedControllerView.center = originalCenter }, completion: { (_) in transitionContext.completeTransition(true) self.bubble.isHidden = true if toViewController?.modalPresentationStyle == .custom { toViewController?.endAppearanceTransition() } fromViewController?.endAppearanceTransition() }) } else { if fromViewController?.modalPresentationStyle == .custom { fromViewController?.beginAppearanceTransition(false, animated: true) } toViewController?.beginAppearanceTransition(true, animated: true) let key: UITransitionContextViewKey = (transitionMode == .pop) ? .to : .from let returningControllerView = transitionContext.view(forKey: key)! let originalCenter = returningControllerView.center let originalSize = returningControllerView.frame.size bubble.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint) bubble.layer.cornerRadius = bubble.frame.size.height / 2 bubble.backgroundColor = bubbleColor bubble.center = startingPoint bubble.isHidden = false UIView.animate(withDuration: duration, animations: { self.bubble.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) returningControllerView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) returningControllerView.center = self.startingPoint returningControllerView.alpha = 0 if self.transitionMode == .pop { containerView.insertSubview(returningControllerView, belowSubview: returningControllerView) containerView.insertSubview(self.bubble, belowSubview: returningControllerView) } }, completion: { (completed) in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) if !transitionContext.transitionWasCancelled { returningControllerView.center = originalCenter returningControllerView.removeFromSuperview() self.bubble.removeFromSuperview() if fromViewController?.modalPresentationStyle == .custom { fromViewController?.endAppearanceTransition() } toViewController?.endAppearanceTransition() } }) } } } private extension BubbleTransition { func frameForBubble(_ originalCenter: CGPoint, size originalSize: CGSize, start: CGPoint) -> CGRect { let lengthX = fmax(start.x, originalSize.width - start.x) let lengthY = fmax(start.y, originalSize.height - start.y) let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2 let size = CGSize(width: offset, height: offset) return CGRect(origin: CGPoint.zero, size: size) } }
be9b1fb686557413e4be0ad8f2635ca8
34.151625
169
0.723529
false
false
false
false
nielstj/GLChat
refs/heads/master
GLChat/Model/ChatObject.swift
mit
1
// // ChatObject.swift // GLChat // // Created by Daniel on 16/8/17. // Copyright © 2017 Holmusk. All rights reserved. // import Foundation import UIKit public enum ChatObjectCellType: Int { case incoming case outgoing case options case information } public protocol ChatObjectType { var id: String { get } var type: ChatObjectCellType { get } var sender: AvatarType { get } var message: String { get } var images: [UIImage]? { get } var timestamp: Date { get } } public struct ChatObject: ChatObjectType { public var id: String public var type: ChatObjectCellType public var sender: AvatarType public var message: String public var images : [UIImage]? public var timestamp: Date public init(id: String, type: ChatObjectCellType, sender: AvatarType, message: String, images: [UIImage]?, timestamp: Date) { self.id = id self.type = type self.sender = sender self.message = message self.images = images self.timestamp = timestamp } }
359008be329a35c48094c288ec32f12d
21.92
50
0.609948
false
false
false
false
apegroup/APEReactiveNetworking
refs/heads/master
Example/fastlane/SnapshotHelper.swift
mit
1
// // SnapshotHelper.swift // // // Created by Felix Krause on 10/8/15. // Copyright © 2015 Felix Krause. All rights reserved. // import Foundation import XCTest var deviceLanguage = "" @available(*, deprecated, message="use setupSnapshot: instead") func setLanguage(app: XCUIApplication) { setupSnapshot(app) } func setupSnapshot(app: XCUIApplication) { Snapshot.setupSnapshot(app) } func snapshot(name: String, waitForLoadingIndicator: Bool = false) { Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator) } class Snapshot: NSObject { class func setupSnapshot(app: XCUIApplication) { setLanguage(app) setLaunchArguments(app) } class func setLanguage(app: XCUIApplication) { let path = "/tmp/language.txt" do { let locale = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String deviceLanguage = locale.substringToIndex(locale.startIndex.advancedBy(2, limit:locale.endIndex)) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))", "-AppleLocale", "\"\(locale)\"", "-ui_testing"] } catch { print("Couldn't detect/set language...") } } class func setLaunchArguments(app: XCUIApplication) { let path = "/tmp/snapshot-launch_arguments.txt" app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES"] do { let launchArguments = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matchesInString(launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count)) let results = matches.map { result -> String in (launchArguments as NSString).substringWithRange(result.range) } app.launchArguments += results } catch { print("Couldn't detect/set launch_arguments...") } } class func snapshot(name: String, waitForLoadingIndicator: Bool = false) { if waitForLoadingIndicator { waitForLoadingIndicatorToDisappear() } print("snapshot: \(name)") // more information about this, check out https://github.com/krausefx/snapshot sleep(1) // Waiting for the animation to be finished (kind of) XCUIDevice.sharedDevice().orientation = .Unknown } class func waitForLoadingIndicatorToDisappear() { let query = XCUIApplication().statusBars.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Other) while query.count > 4 { sleep(1) print("Number of Elements in Status Bar: \(query.count)... waiting for status bar to disappear") } } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [[1.0]]
fb6d6d96f0d0502674211fdb600d69a6
33.333333
146
0.655842
false
false
false
false
PokeMapCommunity/PokeMap-iOS
refs/heads/master
PokeMap/Helpers/LocationHelper.swift
mit
1
// // LocationHelper.swift // PokeMap // // Created by Ivan Bruel on 20/07/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import UIKit import CoreLocation import RxCocoa import RxOptional import RxSwift class LocationHelper { static let sharedInstance = LocationHelper() private lazy var locationManager: CLLocationManager = { let locationManager = CLLocationManager() locationManager.distanceFilter = 5 return locationManager }() private var disposeBag = DisposeBag() private var notifiedPokemons = [Pokemon]() func start() { locationManager.startMonitoringSignificantLocationChanges() locationManager.rx_didUpdateLocations .map { $0.first } .filterNil() .flatMap { location in LocationHelper.loadPokemons(location.coordinate.latitude, longitude: location.coordinate.longitude).retry(2) } .filter { $0.count > 0 } .subscribeNext { pokemons in self.notifiedPokemons = self.notifiedPokemons.unique.filter { !$0.expired } let watchlistedPokemons = pokemons.filter { Globals.watchlist.contains(($0.pokemonId as NSNumber).stringValue) && !self.notifiedPokemons.contains($0) } self.notifiedPokemons = self.notifiedPokemons .arrayByAppendingContentsOf(watchlistedPokemons) .unique guard watchlistedPokemons.count > 0 else { return } self.notifyPokemons(watchlistedPokemons) }.addDisposableTo(disposeBag) } func stop() { locationManager.stopUpdatingLocation() disposeBag = DisposeBag() } private func notifyPokemons(pokemons: [Pokemon]) { if pokemons.count == 1 { showNotification(pokemons[0]) } else { //pokemons.forEach { showNotification($0) } showNotification(pokemons.count) } } private func showNotification(pokemon: Pokemon) { let notification = UILocalNotification() notification.alertBody = "\(pokemon.name) is nearby for another \(pokemon.expirationTime.shortTimeAgoSinceNow())" notification.fireDate = NSDate(timeIntervalSinceNow: 1) notification.timeZone = NSTimeZone.defaultTimeZone() UIApplication.sharedApplication().scheduleLocalNotification(notification) } private func showNotification(numberOfPokemon: Int) { let notification = UILocalNotification() notification.alertBody = "\(numberOfPokemon) Rare pokemons nearby!" notification.fireDate = NSDate(timeIntervalSinceNow: 1) notification.timeZone = NSTimeZone.defaultTimeZone() UIApplication.sharedApplication().scheduleLocalNotification(notification) } private static func loadPokemons(latitude: Double, longitude: Double) -> Observable<[Pokemon]> { return Network.request(API.Pokemons(latitude: latitude, longitude: longitude, jobId: nil)) .mapArray(Pokemon.self, key: "pokemon") } }
d16a029511e571b7a0b1a3718464d83c
31.055556
115
0.713345
false
false
false
false
blg-andreasbraun/Operations
refs/heads/development
Sources/Testing/TestProcedure.swift
mit
2
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation import ProcedureKit public struct TestError: Error, Equatable { public static func == (lhs: TestError, rhs: TestError) -> Bool { return lhs.uuid == rhs.uuid } public static func verify(errors: [Error], count: Int = 1, contains error: TestError) -> Bool { return (errors.count == count) && errors.contains { ($0 as? TestError) ?? TestError() == error } } let uuid = UUID() public init() { } } open class TestProcedure: Procedure, InputProcedure, OutputProcedure { public let delay: TimeInterval public let error: Error? public let producedOperation: Operation? public var input: Pending<Void> = pendingVoid public var output: Pending<ProcedureResult<String>> = .ready(.success("Hello World")) public private(set) var executedAt: CFAbsoluteTime = 0 public private(set) var didExecute = false public private(set) var procedureWillFinishCalled = false public private(set) var procedureDidFinishCalled = false public private(set) var procedureWillCancelCalled = false public private(set) var procedureDidCancelCalled = false public init(name: String = "TestProcedure", delay: TimeInterval = 0.000_001, error: Error? = .none, produced: Operation? = .none) { self.delay = delay self.error = error self.producedOperation = produced super.init() self.name = name } open override func execute() { executedAt = CFAbsoluteTimeGetCurrent() if let operation = producedOperation { DispatchQueue.main.asyncAfter(deadline: .now() + (delay / 2.0)) { try! self.produce(operation: operation) // swiftlint:disable:this force_try } } DispatchQueue.main.asyncAfter(deadline: .now() + delay) { self.didExecute = true self.finish(withError: self.error) } } open override func procedureWillCancel(withErrors: [Error]) { procedureWillCancelCalled = true } open override func procedureDidCancel(withErrors: [Error]) { procedureDidCancelCalled = true } open override func procedureWillFinish(withErrors: [Error]) { procedureWillFinishCalled = true } open override func procedureDidFinish(withErrors: [Error]) { procedureDidFinishCalled = true } }
8055655f586affd677a895837a0580f9
31.118421
135
0.661614
false
true
false
false
gtcode/GTMetronome
refs/heads/master
GTMetronome/AppDelegate.swift
mit
1
// // AppDelegate.swift // GTMetronome // // Created by Paul Lowndes on 8/3/17. // Copyright © 2017 Paul Lowndes. All rights reserved. // import UIKit import CoreData import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // per: https://github.com/gtcode/Learning-AV-Foundation-Swift/blob/master/Chapter%202/AudioLooper/AudioLooper/AppDelegate.swift let audioSession = AVAudioSession.sharedInstance() do { // https://developer.apple.com/documentation/avfoundation/avaudiosession/audio_session_categories try audioSession.setCategory( AVAudioSessionCategoryPlayback , mode: AVAudioSessionModeDefault , options: [ AVAudioSessionCategoryOptions.mixWithOthers ] ) try audioSession.setActive( true ) } catch let error as NSError { print("AVAudioSession configuration error: \(error.localizedDescription)") } 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: "GTMetronome") 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)") } } } }
27ad96a8e81e533d48768fca3dbf2411
44.504587
281
0.726008
false
false
false
false
koogawa/iSensorSwift
refs/heads/master
iSensorSwift/Controller/BrightnessViewController.swift
mit
1
// // BrightnessViewController.swift // iSensorSwift // // Created by koogawa on 2016/03/21. // Copyright © 2016 koogawa. All rights reserved. // import UIKit class BrightnessViewController: UIViewController { @IBOutlet weak var brightnessLabel: UILabel! @IBOutlet weak var brightStepper: UIStepper! override func viewDidLoad() { super.viewDidLoad() // Setup UIStepper let screen = UIScreen.main self.brightStepper.value = Double(screen.brightness) self.updateBrightnessLabel() // Observe screen brightness NotificationCenter.default.addObserver(self, selector: #selector(screenBrightnessDidChange(_:)), name: NSNotification.Name.UIScreenBrightnessDidChange, object: nil) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // Finish observation NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIScreenBrightnessDidChange, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Internal methods func updateBrightnessLabel() { let screen = UIScreen.main self.brightnessLabel.text = "".appendingFormat("%.2f", screen.brightness) } @objc func screenBrightnessDidChange(_ notification: Notification) { if let screen = notification.object { self.brightnessLabel.text = "".appendingFormat("%.2f", (screen as AnyObject).brightness) } } // MARK: - Action methods @IBAction func stepperDidTap(_ stepper: UIStepper) { UIScreen.main.brightness = CGFloat(stepper.value) self.updateBrightnessLabel() } }
09019a0cf5f70b6b0133a9ec79d450c3
30.984615
114
0.589707
false
false
false
false