repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
AckeeCZ/ACKategories
ACKategoriesCore/Base/ViewModel.swift
1
1148
// // BaseViewModel.swift // ProjectTemplate // // Created by Jan Misar on 16.08.18. // import Foundation import os.log extension Base { /// Turn on/off logging of init/deinit of all VMs /// ⚠️ Has no effect when Base.memoryLoggingEnabled is true public static var viewModelMemoryLoggingEnabled: Bool = true /// Base class for all view models open class ViewModel { public init() { if Base.memoryLoggingEnabled && Base.viewModelMemoryLoggingEnabled { if #available(iOS 10.0, macOS 10.12, *) { os_log("🧠 👶 %@", log: Logger.lifecycleLog(), type: .info, "\(self)") } else { NSLog("🧠 👶 \(self)") } } } deinit { if Base.memoryLoggingEnabled && Base.viewModelMemoryLoggingEnabled { if #available(iOS 10.0, macOS 10.12, *) { os_log("🧠 ⚰️ %@", log: Logger.lifecycleLog(), type: .info, "\(self)") } else { NSLog("🧠 ⚰️ \(self)") } } } } }
mit
Minecodecraft/50DaysOfSwift
Day 4 - TabBarCenterButton/TabBarCenterButton/TabBarCenterButton/MCBaseViewController.swift
1
301
// // MCBaseViewController.swift // TabBarCenterButton // // Created by Minecode on 2017/7/14. // Copyright © 2017年 Minecode. All rights reserved. // import UIKit class MCBaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
mit
morizotter/BrightFutures
BrightFutures/AsyncType.swift
1
1712
// // Async.swift // BrightFutures // // Created by Thomas Visser on 09/07/15. // Copyright © 2015 Thomas Visser. All rights reserved. // import Foundation public protocol AsyncType { typealias Value var value: Value? { get } init() init(value: Value) init(value: Value, delay: NSTimeInterval) init<A: AsyncType where A.Value == Value>(other: A) func onComplete(context c: ExecutionContext, callback: Value -> Void) -> Self func map<U>(context: ExecutionContext, transform: Value -> U) -> Async<U>; } public extension AsyncType { /// `true` if the future completed (either `isSuccess` or `isFailure` will be `true`) public var isCompleted: Bool { return self.value != nil } /// See `map<U>(context c: ExecutionContext, f: T -> U) -> Async<U>` /// The given closure is executed according to the default threading model (see README.md) public func map<U>(transform: Value -> U) -> Async<U> { return self.map(DefaultThreadingModel(), transform: transform) } /// Returns an Async that succeeds with the value returned from the given closure when it is invoked with the success value /// from this future. If this Async fails, the returned future fails with the same error. /// The closure is executed on the given context. If no context is given, the behavior is defined by the default threading model (see README.md) public func map<U>(context: ExecutionContext, transform: Value -> U) -> Async<U> { let res = Async<U>() onComplete(context: context) { value in try! res.complete(transform(value)) } return res } }
mit
yuhao-ios/DouYuTVForSwift
DouYuTVForSwift/DouYuTVForSwift/Home/Controller/AmuseVC.swift
1
1363
// // AmuseVC.swift // DouYuTVForSwift // // Created by t4 on 17/5/22. // Copyright © 2017年 t4. All rights reserved. // import UIKit fileprivate let kMenuViewHeight : CGFloat = 200 class AmuseVC: BaseAnchorViewController { fileprivate lazy var amuseVM : AmuseVM = AmuseVM() fileprivate lazy var amuseMenuView : AmuseMenuView = { let menuView = AmuseMenuView.amuseMenuView() menuView.frame = CGRect(x: 0, y: -kMenuViewHeight, width: kMainWidth, height: kMenuViewHeight) menuView.backgroundColor = UIColor.white return menuView }() } extension AmuseVC { //加载界面 override func loadUI() { super.loadUI() //添加菜单View collectionView.addSubview(amuseMenuView) collectionView.contentInset = UIEdgeInsets(top: kMenuViewHeight, left: 0, bottom: 0, right: 0) } //加载数据 override func loadData () { super.loadData() //1.将数据model赋值父类 baseAnchorVm = amuseVM amuseVM.loadAmuseAllData { //2.刷新界面 self.collectionView.reloadData() self.amuseMenuView.groups = self.amuseVM.anchorGroups //3.数据加载完成 展示内容 self.showContentView() } } }
mit
mownier/photostream
Photostream/Modules/Post Like/View/PostLikeScene.swift
1
609
// // PostLikeScene.swift // Photostream // // Created by Mounir Ybanez on 20/01/2017. // Copyright © 2017 Mounir Ybanez. All rights reserved. // protocol PostLikeScene: BaseModuleView { var presenter: PostLikeModuleInterface! { set get } var isEmptyViewHidden: Bool { set get } var isLoadingViewHidden: Bool { set get } var isRefreshingViewHidden: Bool { set get } func reload() func reload(at index: Int) func didRefresh(error: String?) func didLoadMore(error: String?) func didFollow(error: String?) func didUnfollow(error: String?) }
mit
podaenur/SberTech_test
SberTech_test/SberTech_test/ScreensFactory.swift
1
410
// // ScreensFactory.swift // SberTech_test // // Created by Evgeniy Akhmerov on 07/09/2017. // Copyright © 2017 Evgeniy Akhmerov. All rights reserved. // import UIKit struct ScreensFactory { static func mainScreen(context: Any?) -> MainController { let model = MainViewModel(context: context) let controller = MainController(viewModel: model) return controller } }
mit
taqun/TodoEver
TodoEverTests/Tests/Model/TDEMNoteTests.swift
1
3496
// // TDEMNoteTests.swift // TodoEver // // Created by taqun on 2015/06/09. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit import XCTest import MagicalRecord class TDEMNoteTests: XCTestCase { override func setUp() { super.setUp() MagicalRecord.setupCoreDataStackWithInMemoryStore() } override func tearDown() { MagicalRecord.cleanUp() super.tearDown() } /* * Private Method */ private func createNote() -> (TDEMNote) { let context = NSManagedObjectContext.MR_defaultContext() let entity = NSEntityDescription.entityForName("TDEMNote", inManagedObjectContext: context)! let note = TDEMNote(entity: entity, insertIntoManagedObjectContext: context) return note } private func createTask() -> (TDEMTask) { let context = NSManagedObjectContext.MR_defaultContext() let entity = NSEntityDescription.entityForName("TDEMTask", inManagedObjectContext: context)! let task = TDEMTask(entity: entity, insertIntoManagedObjectContext: context) return task } private func createTasks() -> ([TDEMTask]) { var tasks: [TDEMTask] = [] var task1 = self.createTask() task1.index = 2 task1.title = "Task3" task1.isChecked = false tasks.append(task1) var task2 = self.createTask() task2.index = 1 task2.title = "Task2" task2.isChecked = true tasks.append(task2) var task3 = self.createTask() task3.index = 0 task3.title = "Task1" task3.isChecked = true tasks.append(task3) return tasks } /* * Tests */ func testCreateEntity() { let note = self.createNote() XCTAssertNotNil(note) } func testParseMetaData() { let metaData = EDAMNoteMetadata() metaData.title = "note title" metaData.guid = "note guid" metaData.updateSequenceNum = 123 let note = self.createNote() note.parseMetaData(metaData) XCTAssertEqual(note.title, "note title") XCTAssertEqual(note.guid, "note guid") XCTAssertEqual(note.usn, 123) } func testAppendTasks() { let tasks = self.createTasks() // [2, 1, 0] let note = self.createNote() note.appendTasks(tasks) // [0, 1, 2] XCTAssertEqual(note.orderedTasks[0], tasks[2]) XCTAssertEqual(note.orderedTasks[1], tasks[1]) XCTAssertEqual(note.orderedTasks[2], tasks[0]) } func testAddTask() { let tasks = self.createTasks() let note = self.createNote() note.appendTasks(tasks) var task4 = self.createTask() task4.index = 3 task4.title = "Task4" task4.isChecked = false note.addTask(task4) XCTAssertEqual(note.orderedTasks[3], task4) } func testRemoveTask() { let tasks = self.createTasks() // [2, 1, 0] let note = self.createNote() note.appendTasks(tasks) // [0, 1, 2] note.removeTask(1) // [0, 2] XCTAssertEqual(note.orderedTasks[0], tasks[2]) XCTAssertEqual(note.orderedTasks[1], tasks[0]) } }
mit
moozzyk/SignalR-Client-Swift
Tests/SignalRClientTests/ServerInvocationHandlerTests.swift
1
10144
// // ServerInvocationHandlerTests.swift // SignalRClientTests // // Created by Pawel Kadluczka on 2/25/18. // Copyright © 2018 Pawel Kadluczka. All rights reserved. // import XCTest @testable import SignalRClient class InvocationHandlerTests: XCTestCase { private let callbackQueue = DispatchQueue(label: "SignalR.tests") func testThatInvocationHandlerCreatesInvocationMessage() { let invocationHandler = InvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, invocationDidComplete: { result, error in }) let invocationMessage = invocationHandler.createInvocationMessage(invocationId: "42", method: "testMethod", arguments: [1, "abc"], streamIds: ["1", "2"]) as? ServerInvocationMessage XCTAssertNotNil(invocationMessage) XCTAssertEqual(MessageType.Invocation, invocationMessage!.type) XCTAssertEqual("42", invocationMessage!.invocationId) XCTAssertEqual("testMethod", invocationMessage!.target) XCTAssertEqual(2, invocationMessage!.arguments.count) XCTAssertEqual(1, invocationMessage!.arguments[0] as? Int) XCTAssertEqual("abc", invocationMessage!.arguments[1] as? String) XCTAssertEqual(2, invocationMessage!.streamIds?.count ?? 0) XCTAssertEqual("1", invocationMessage!.streamIds![0]) XCTAssertEqual("2", invocationMessage!.streamIds![1]) } func testThatInvocationHandlerReturnsErrorForStreamItem() { let invocationHandler = InvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, invocationDidComplete: { result, error in }) let messagePayload = "{ \"type\": 2, \"invocationId\": \"42\", \"item\": \"abc\" }".data(using: .utf8)! let streamItemMessage = try! JSONDecoder().decode(StreamItemMessage.self, from: messagePayload) if let error = invocationHandler.processStreamItem(streamItemMessage: streamItemMessage) as? SignalRError { switch error { case SignalRError.protocolViolation: break default: XCTFail() } } else { XCTFail() } } func testThatInvocationHandlerPassesErrorForErrorCompletionMessage() { let invocationHandler = InvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, invocationDidComplete: { result, error in XCTAssertNil(result) XCTAssertNotNil(error) XCTAssertEqual(String(describing: error as! SignalRError), String(describing: SignalRError.hubInvocationError(message: "Error occurred!"))) }) let messagePayload = "{ \"type\": 3, \"invocationId\": \"12\", \"error\": \"Error occurred!\" }".data(using: .utf8)! let completionMessage = try! JSONDecoder().decode(CompletionMessage.self, from: messagePayload) invocationHandler.processCompletion(completionMessage: completionMessage) } func testThatInvocationHandlerPassesNilAsResultForVoidCompletionMessage() { let invocationHandler = InvocationHandler<DecodableVoid>(logger: NullLogger(), callbackQueue: callbackQueue, invocationDidComplete: { result, error in XCTAssertNil(error) XCTAssertNil(result) }) let messagePayload = "{ \"type\": 3, \"invocationId\": \"12\" }".data(using: .utf8)! let completionMessage = try! JSONDecoder().decode(CompletionMessage.self, from: messagePayload) invocationHandler.processCompletion(completionMessage: completionMessage) } func testThatInvocationHandlerPassesValueForResultCompletionMessage() { let invocationHandler = InvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, invocationDidComplete: { result, error in XCTAssertNil(error) XCTAssertEqual(42, result) }) let messagePayload = "{ \"type\": 3, \"invocationId\": \"12\", \"result\": 42 }".data(using: .utf8)! let completionMessage = try! JSONDecoder().decode(CompletionMessage.self, from: messagePayload) invocationHandler.processCompletion(completionMessage: completionMessage) } func testThatInvocationHandlerPassesErrorIfResultConversionFails() { let invocationHandler = InvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, invocationDidComplete: { result, error in XCTAssertNil(result) switch (error as! SignalRError) { case SignalRError.serializationError: break default: XCTFail() } }) let messagePayload = "{ \"type\": 3, \"invocationId\": \"12\", \"result\": \"abc\" }".data(using: .utf8)! let completionMessage = try! JSONDecoder().decode(CompletionMessage.self, from: messagePayload) invocationHandler.processCompletion(completionMessage: completionMessage) } func testThatRaiseErrorPassesError() { let invocationHandler = InvocationHandler<String>(logger: NullLogger(), callbackQueue: callbackQueue, invocationDidComplete: { result, error in XCTAssertNil(result) XCTAssertNotNil(error) XCTAssertEqual(String(describing: error!), String(describing: SignalRError.hubInvocationCancelled)) }) invocationHandler.raiseError(error: SignalRError.hubInvocationCancelled) } } class StreamInvocationHandlerTests: XCTestCase { private let callbackQueue = DispatchQueue(label: "SignalR.tests") func testThatInvocationHandlerCreatesInvocationMessage() { let invocationHandler = StreamInvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, streamItemReceived: { item in }, invocationDidComplete: { error in }) let invocationMessage = invocationHandler.createInvocationMessage(invocationId: "42", method: "testMethod", arguments: [1, "abc"], streamIds: ["1", "2"]) as? StreamInvocationMessage XCTAssertNotNil(invocationMessage) XCTAssertEqual(MessageType.StreamInvocation, invocationMessage!.type) XCTAssertEqual("42", invocationMessage!.invocationId) XCTAssertEqual("testMethod", invocationMessage!.target) XCTAssertEqual(2, invocationMessage!.arguments.count) XCTAssertEqual(1, invocationMessage!.arguments[0] as? Int) XCTAssertEqual("abc", invocationMessage!.arguments[1] as? String) XCTAssertEqual(2, invocationMessage!.streamIds?.count ?? 0) XCTAssertEqual("1", invocationMessage!.streamIds![0]) XCTAssertEqual("2", invocationMessage!.streamIds![1]) } func testThatInvocationInvokesCallbackForStreamItem() { let streamItemReceivedExpectation = expectation(description: "stream item received") var receivedItem = -1 let invocationHandler = StreamInvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, streamItemReceived: { item in receivedItem = 7 streamItemReceivedExpectation.fulfill() }, invocationDidComplete: { error in XCTFail()}) let messagePayload = "{ \"type\": 2, \"invocationId\": \"42\", \"item\": 7 }".data(using: .utf8)! let streamItemMessage = try! JSONDecoder().decode(StreamItemMessage.self, from: messagePayload) let error = invocationHandler.processStreamItem(streamItemMessage: streamItemMessage) as? SignalRError waitForExpectations(timeout: 5 /*seconds*/) XCTAssertNil(error) XCTAssertEqual(7, receivedItem) } func testThatInvocationReturnsErrorIfProcessingStreamItemFails() { let invocationHandler = StreamInvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, streamItemReceived: { item in XCTFail()}, invocationDidComplete: { error in XCTFail()}) let messagePayload = "{ \"type\": 2, \"invocationId\": \"42\", \"item\": \"abc\" }".data(using: .utf8)! let streamItemMessage = try! JSONDecoder().decode(StreamItemMessage.self, from: messagePayload) if let error = invocationHandler.processStreamItem(streamItemMessage: streamItemMessage) as? SignalRError { switch (error) { case SignalRError.serializationError: break default: XCTFail() } } else { XCTFail() } } func testThatInvocationHandlerPassesErrorForErrorCompletionMessage() { let streamInvocationHandler = StreamInvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, streamItemReceived: { item in }, invocationDidComplete: { error in XCTAssertEqual(String(describing: error as! SignalRError), String(describing: SignalRError.hubInvocationError(message: "Error occurred!"))) }) let messagePayload = "{ \"type\": 3, \"invocationId\": \"12\", \"error\": \"Error occurred!\" }".data(using: .utf8)! let completionMessage = try! JSONDecoder().decode(CompletionMessage.self, from: messagePayload) streamInvocationHandler.processCompletion(completionMessage: completionMessage) } func testThatInvocationHandlerPassesNilAsResultForVoidCompletionMessage() { let streamInvocationHandler = StreamInvocationHandler<Int>(logger: NullLogger(), callbackQueue: callbackQueue, streamItemReceived: { item in }, invocationDidComplete: { error in XCTAssertNil(error) }) let messagePayload = "{ \"type\": 3, \"invocationId\": \"12\" }".data(using: .utf8)! let completionMessage = try! JSONDecoder().decode(CompletionMessage.self, from: messagePayload) streamInvocationHandler.processCompletion(completionMessage: completionMessage) } func testThatRaiseErrorPassesError() { let streamInvocationHandler = StreamInvocationHandler<String>(logger: NullLogger(), callbackQueue: callbackQueue, streamItemReceived: { item in }, invocationDidComplete: { error in XCTAssertNotNil(error) XCTAssertEqual(String(describing: error!), String(describing: SignalRError.hubInvocationCancelled)) }) streamInvocationHandler.raiseError(error: SignalRError.hubInvocationCancelled) } }
mit
peggyrayzis/react-native-create-bridge
templates/ui-components/ios-swift/TemplateManager.swift
1
434
// Created by react-native-create-bridge import Foundation import UIKit @objc({{template}}) class {{template}}Manager : RCTViewManager { // Return the native view that represents your React component override func view() -> UIView! { return {{template}}View() } // Export constants to use in your native module override func constantsToExport() -> [String : Any]! { return ["EXAMPLE_CONSTANT": "example"] } }
mit
benlangmuir/swift
validation-test/stdlib/Collection/DefaultedMutableRangeReplaceableRandomAccessCollection.swift
32
2261
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // rdar://problem/46878013 // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var CollectionTests = TestSuite("Collection") // Test collections using value types as elements. do { var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap CollectionTests.addRangeReplaceableRandomAccessCollectionTests( makeCollection: { (elements: [OpaqueValue<Int>]) in return DefaultedMutableRangeReplaceableRandomAccessCollection(elements: elements) }, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in return DefaultedMutableRangeReplaceableRandomAccessCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks ) CollectionTests.addMutableRandomAccessCollectionTests( makeCollection: { (elements: [OpaqueValue<Int>]) in return DefaultedMutableRangeReplaceableRandomAccessCollection(elements: elements) }, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in return DefaultedMutableRangeReplaceableRandomAccessCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in return DefaultedMutableRangeReplaceableRandomAccessCollection(elements: elements) }, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) } runAllTests()
apache-2.0
mobgeek/swift
Swift em 4 Semanas/App Lista/Lista Semana 2/Lista/AdicionarItemViewController.swift
3
892
// // AdicionarItemViewController.swift // Lista // // Created by Fabio Santos on 11/3/14. // Copyright (c) 2014 Fabio Santos. All rights reserved. // import UIKit class AdicionarItemViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
squiffy/AlienKit
Example/Pods/p2.OAuth2/Sources/Base/OAuth2Base.swift
1
10927
// // OAuth2Base.swift // OAuth2 // // Created by Pascal Pfiffner on 6/2/15. // Copyright 2015 Pascal Pfiffner // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// Typealias to ease working with JSON dictionaries. public typealias OAuth2JSON = [String: AnyObject] /// Typealias to work with dictionaries full of strings. public typealias OAuth2StringDict = [String: String] /** Abstract base class for OAuth2 authorization as well as client registration classes. */ public class OAuth2Base { /// Server-side settings, as set upon initialization. final let settings: OAuth2JSON /// Set to `true` to log all the things. `false` by default. Use `"verbose": bool` in settings. public var verbose = false /// If set to `true` (the default) will use system keychain to store tokens. Use `"keychain": bool` in settings. public var useKeychain = true { didSet { if useKeychain { updateFromKeychain() } } } /// Defaults to `kSecAttrAccessibleWhenUnlocked` public internal(set) var keychainAccessMode = kSecAttrAccessibleWhenUnlocked /** Base initializer. Looks at the `keychain`, `keychain_access_mode` and `verbose` keys in the _settings_ dict. Everything else is handled by subclasses. */ public init(settings: OAuth2JSON) { self.settings = settings // client settings if let keychain = settings["keychain"] as? Bool { useKeychain = keychain } if let accessMode = settings["keychain_access_mode"] as? String { keychainAccessMode = accessMode } if let verb = settings["verbose"] as? Bool { verbose = verb } // init from keychain if useKeychain { updateFromKeychain() } logIfVerbose("Initialization finished") } // MARK: - Keychain Integration /** The service key under which to store keychain items. Returns "http://localhost", subclasses override to return the authorize URL. */ public func keychainServiceName() -> String { return "http://localhost" } /** Queries the keychain for tokens stored for the receiver's authorize URL, and updates the token properties accordingly. */ private func updateFromKeychain() { logIfVerbose("Looking for items in keychain") do { var creds = OAuth2KeychainAccount(oauth2: self, account: OAuth2KeychainTokenKey) let creds_data = try creds.fetchedFromKeychain() updateFromKeychainItems(creds_data) } catch { logIfVerbose("Failed to load client credentials from keychain: \(error)") } do { var toks = OAuth2KeychainAccount(oauth2: self, account: OAuth2KeychainCredentialsKey) let toks_data = try toks.fetchedFromKeychain() updateFromKeychainItems(toks_data) } catch { logIfVerbose("Failed to load tokens from keychain: \(error)") } } /** Updates instance properties according to the items found in the given dictionary, which was found in the keychain. */ func updateFromKeychainItems(items: [String: NSCoding]) { } /** Items that should be stored when storing client credentials. */ func storableCredentialItems() -> [String: NSCoding]? { return nil } /** Stores our client credentials in the keychain. */ internal func storeClientToKeychain() { if let items = storableCredentialItems() { logIfVerbose("Storing client credentials to keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: OAuth2KeychainTokenKey, data: items) do { try keychain.saveInKeychain() } catch { logIfVerbose("Failed to store client credentials to keychain: \(error)") } } } /** Items that should be stored when tokens are stored to the keychain. */ func storableTokenItems() -> [String: NSCoding]? { return nil } /** Stores our current token(s) in the keychain. */ internal func storeTokensToKeychain() { if let items = storableTokenItems() { logIfVerbose("Storing tokens to keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: OAuth2KeychainCredentialsKey, data: items) do { try keychain.saveInKeychain() } catch { logIfVerbose("Failed to store tokens to keychain: \(error)") } } } /** Unsets the client credentials and deletes them from the keychain. */ public func forgetClient() { logIfVerbose("Forgetting client credentials and removing them from keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: OAuth2KeychainTokenKey) do { try keychain.removeFromKeychain() } catch { logIfVerbose("Failed to delete credentials from keychain: \(error)") } } /** Unsets the tokens and deletes them from the keychain. */ public func forgetTokens() { logIfVerbose("Forgetting tokens and removing them from keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: OAuth2KeychainCredentialsKey) do { try keychain.removeFromKeychain() } catch { logIfVerbose("Failed to delete tokens from keychain: \(error)") } } // MARK: - Requests /// The instance's current session, creating one by the book if necessary. public var session: NSURLSession { if nil == _session { if let delegate = sessionDelegate { let config = sessionConfiguration ?? NSURLSessionConfiguration.defaultSessionConfiguration() _session = NSURLSession(configuration: config, delegate: delegate, delegateQueue: nil) } else if let config = sessionConfiguration { _session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil) } else { _session = NSURLSession.sharedSession() } } return _session! } /// The backing store for `session`. private var _session: NSURLSession? /// The configuration to use when creating `session`. Uses `sharedSession` or one with `defaultSessionConfiguration` if nil. public var sessionConfiguration: NSURLSessionConfiguration? { didSet { _session = nil } } /// URL session delegate that should be used for the `NSURLSession` the instance uses for requests. public var sessionDelegate: NSURLSessionDelegate? { didSet { _session = nil } } /** Perform the supplied request and call the callback with the response JSON dict or an error. This implementation uses the shared `NSURLSession` and executes a data task. If the server responds with an error, this will be converted into an error according to information supplied in the response JSON (if availale). - parameter request: The request to execute - parameter callback: The callback to call when the request completes/fails; data and error are mutually exclusive */ public func performRequest(request: NSURLRequest, callback: ((data: NSData?, status: Int?, error: ErrorType?) -> Void)) { let task = session.dataTaskWithRequest(request) { sessData, sessResponse, error in self.abortableTask = nil if let error = error { if NSURLErrorDomain == error.domain && -999 == error.code { // request was cancelled callback(data: nil, status: nil, error: OAuth2Error.RequestCancelled) } else { callback(data: nil, status: nil, error: error) } } else if let data = sessData, let http = sessResponse as? NSHTTPURLResponse { callback(data: data, status: http.statusCode, error: nil) } else { let error = OAuth2Error.Generic("Unknown response \(sessResponse) with data “\(NSString(data: sessData!, encoding: NSUTF8StringEncoding))”") callback(data: nil, status: nil, error: error) } } abortableTask = task task.resume() } /// Currently running abortable session task. private var abortableTask: NSURLSessionTask? /** Can be called to immediately abort the currently running authorization request, if it was started by `performRequest()`. - returns: A bool indicating whether a task was aborted or not */ func abortTask() -> Bool { guard let task = abortableTask else { return false } logIfVerbose("Aborting request") task.cancel() return true } // MARK: - Response Verification /** Handles access token error response. - parameter params: The URL parameters returned from the server - parameter fallback: The message string to use in case no error description is found in the parameters - returns: An OAuth2Error */ public func assureNoErrorInResponse(params: OAuth2JSON, fallback: String? = nil) throws { // "error_description" is optional, we prefer it if it's present if let err_msg = params["error_description"] as? String { throw OAuth2Error.ResponseError(err_msg) } // the "error" response is required for error responses, so it should be present if let err_code = params["error"] as? String { throw OAuth2Error.fromResponseError(err_code, fallback: fallback) } } // MARK: - Utilities /** Parse string-only JSON from NSData. - parameter data: NSData returned from the call, assumed to be JSON with string-values only. - returns: An OAuth2JSON instance */ func parseJSON(data: NSData) throws -> OAuth2JSON { if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? OAuth2JSON { return json } if let str = NSString(data: data, encoding: NSUTF8StringEncoding) { logIfVerbose("Unparsable JSON was: \(str)") } throw OAuth2Error.JSONParserError } /** Parse a query string into a dictionary of String: String pairs. If you're retrieving a query or fragment from NSURLComponents, use the `percentEncoded##` variant as the others automatically perform percent decoding, potentially messing with your query string. - parameter query: The query string you want to have parsed - returns: A dictionary full of strings with the key-value pairs found in the query */ public final class func paramsFromQuery(query: String) -> OAuth2StringDict { let parts = query.characters.split() { $0 == "&" }.map() { String($0) } var params = OAuth2StringDict(minimumCapacity: parts.count) for part in parts { let subparts = part.characters.split() { $0 == "=" }.map() { String($0) } if 2 == subparts.count { params[subparts[0]] = subparts[1].wwwFormURLDecodedString } } return params } /** Debug logging, will only log if `verbose` is YES. */ public func logIfVerbose(log: String) { if verbose { print("OAuth2: \(log)") } } } /** Helper function to ensure that the callback is executed on the main thread. */ func callOnMainThread(callback: (Void -> Void)) { if NSThread.isMainThread() { callback() } else { dispatch_sync(dispatch_get_main_queue(), callback) } }
mit
The-iPocalypse/BA-iOS-Application
src/Annotation.swift
1
697
// // Annotation.swift // BA-iOS-Application // // Created by Samuel Bellerose on 2016-02-13. // Copyright © 2016 Samuel Bellerose. All rights reserved. // import MapKit class Annotation: NSObject, MKAnnotation { let title: String? let locationName: String let discipline: String let coordinate: CLLocationCoordinate2D init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) { self.title = title self.locationName = locationName self.discipline = discipline self.coordinate = coordinate super.init() } var subtitle: String? { return locationName } }
mit
Tombio/Trafalert
iOS Client/Trafalert/DataFetcher.swift
1
2925
// // DataFetcher.swift // Trafalert // // Created by Tomi Lahtinen on 02/02/16. // Copyright © 2016 Tomi Lahtinen. All rights reserved. // import Foundation import Alamofire import ObjectMapper class DataFetcher { //static let server = "http://localhost:8080" static let server = "https://trafalert.herokuapp.com" static let infoEndPoint = "/info" // get weather + warnings static let weatherEndPoint = "/weather" // get weather only static let warningEndPoint = "/warning" // get warnings only static let stationMetaEndPoint = "/meta/station" func updateWeatherInfo(station: Int, callback: (WeatherStationData) -> Void) { let address = String(format: "%@%@/%d", arguments:[DataFetcher.server, DataFetcher.infoEndPoint, station]) debugPrint("Address \(address)") Alamofire.request(.POST, address, parameters: nil, headers: ["API_KEY": DataFetcher.apiKey]).responseJSON() { (response) in if let json = response.result.value { if let weather = Mapper<WeatherStationData>().map(json) { callback(weather) } } else { debugPrint("Failed to update info \(address) => \(response.result.error)") } } } func updateWarningStations(callback: (Array<WarningInfo>) -> Void){ let address = String(format: "%@%@", arguments:[DataFetcher.server, DataFetcher.warningEndPoint]) Alamofire.request(.POST, address, parameters: nil, headers: ["API_KEY": DataFetcher.apiKey]).responseJSON() { (response) in if let warnings = Mapper<WarningInfo>().mapArray(response.result.value) { callback(warnings) } } } func fetchStationMetaData(callback: (Array<WeatherStationGroup>) -> Void) { let address = String(format: "%@%@", arguments:[DataFetcher.server, DataFetcher.stationMetaEndPoint]) Alamofire.request(.POST, address, parameters: nil, headers: ["API_KEY": DataFetcher.apiKey]).responseJSON() { (response) in if let stations = Mapper<WeatherStationGroup>().mapArray(response.result.value) { debugPrint("Stations \(stations.count)") callback(stations) } else { fatalError("Station fetching failed") } } } static var apiKey: String { if let path = NSBundle.mainBundle().pathForResource("properties", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] { if let apiKey = dict["API_KEY"] { return apiKey as! String } } fatalError("Unable to read API key from properties.plist") } }
mit
joshdholtz/fastlane
fastlane/swift/Deliverfile.swift
1
729
// This class is automatically included in FastlaneRunner during build // This autogenerated file will be overwritten or replaced during build time, or when you initialize `deliver` // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // class Deliverfile: DeliverfileProtocol { // If you want to enable `deliver`, run `fastlane deliver init` // After, this file will be replaced with a custom implementation that contains values you supplied // during the `init` process, and you won't see this message } // Generated with fastlane 2.138.0
mit
tatsuyamoriguchi/PoliPoli
View Controller/LoginViewController.swift
1
12014
// // LoginViewController.swift // Poli // // Created by Tatsuya Moriguchi on 8/4/18. // Copyright © 2018 Becko's Inc. All rights reserved. // import UIKit import QuartzCore // Keychain Configuration struct KeychainConfiguration { static let serviceName = "Poli" static let accessGroup: String? = nil } class LoginViewController: UIViewController, UITextFieldDelegate, CAAnimationDelegate, CALayerDelegate { @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var createLogin: UIButton! @IBOutlet weak var createInfoLabel: UILabel! @IBOutlet weak var touchIDButton: UIButton! var passwordItems: [KeychainPasswordItem] = [] // MARK: - ANIMATION // Declare a layer variable for animation var mask: CALayer? // MARK: - LOGIN VIEW // Variables var userName: String = "" var userPassword: String = "" var isOpening: Bool = true // Create a reference to BiometricIDAuth let touchMe = BiometricIDAuth() // Properties @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBAction func registerPressed(_ sender: UIButton) { userName = userNameTextField.text! userPassword = passwordTextField.text! // User login account already exists alert if (UserDefaults.standard.object(forKey: "userName") as? String) != nil { let NSL_alertTitle_001 = NSLocalizedString("NSL_alertTitle_001", value: "User Already Exists", comment: "") let NSL_alertMessage_001 = NSLocalizedString("NSL_alertMessage_001", value: "This App already has a user. To change your user info, login Poli and go to Settings.", comment: " ") AlertNotification().alert(title: NSL_alertTitle_001, message: NSL_alertMessage_001, sender: self) // If any of user info is missing, display an alert. } else if userNameTextField.text == "" || passwordTextField.text == "" { // no enough input entry alert let NSL_alertTitle_002 = NSLocalizedString("NSL_alertTitle_002", value: "Need More Information", comment: " ") let NSL_alertMessage_002 = NSLocalizedString("NSL_alertMessage_002", value: "Fill both information: User Name and Password", comment: " ") AlertNotification().alert(title: NSL_alertTitle_002, message: NSL_alertMessage_002, sender: self) } else { // Create a KeychainPasswordItem with the service Name, newAccountName(username) and accessGroup. Using Swift's error handling, you try to save the password. The catch is there if something goes wrong. do { // This is a new account, create a new keychain item with the account name. let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: userName, accessGroup: KeychainConfiguration.accessGroup) // Save the password for the new item. try passwordItem.savePassword(userPassword) }catch { fatalError("Error updating keychain = \(error)") } // Set a user login account UserDefaults.standard.set(userName, forKey: "userName") //UserDefaults.standard.set(userPassword, forKey: "userPassword") userNameTextField.text = "" passwordTextField.text = "" let NSL_alertTitle_003 = NSLocalizedString("NSL_NSL_alertTitle_003", value: "User Account Created", comment: " ") let NSL_alertMessage_003 = NSLocalizedString("NSL_alertMessage_003", value: "Please use the user name and password just created to login Poli.", comment: " ") AlertNotification().alert(title: NSL_alertTitle_003, message: NSL_alertMessage_003, sender: self) } } @IBAction func loginPressed(_ sender: UIButton) { userName = userNameTextField.text! userPassword = passwordTextField.text! let storedUserName = UserDefaults.standard.object(forKey: "userName") as? String //let storedPassword = UserDefaults.standard.object(forKey: "userPassword") as? String if (storedUserName == nil) { let NSL_alertTitle_004 = NSLocalizedString("NSL_alertTitle_004", value: "No Account", comment: " ") let NSL_alertMessage_004 = NSLocalizedString("NSL_alertMessage_004", value: "No account is registered yet. Please create an account.", comment: " ") AlertNotification().alert(title: NSL_alertTitle_004, message: NSL_alertMessage_004, sender: self) } //else if userName == storedUserName && userPassword == storedPassword { // If the user is logging in, call checkLogin to verify the user-provided credentials; if they match then you dismiss the login view. else if checkLogin(username: userName, password: userPassword) { UserDefaults.standard.set(true, forKey: "isLoggedIn") UserDefaults.standard.synchronize() performSegue(withIdentifier: "loginSegue", sender: self) } else { let NSL_alertTitle_005 = NSLocalizedString("NSL_alertTitle_005", value: "Authentification Failed", comment: " ") let NSL_alertMessage_005 = NSLocalizedString("NSL_alertMessage_005", value: "Data you entered didn't match with user information.", comment: " ") AlertNotification().alert(title: NSL_alertTitle_005, message: NSL_alertMessage_005, sender: self) } } @IBAction func touchIDLoginAction() { /* touchMe.authenticateUser() { [weak self] inrr self?.performSegue(withIdentifier: "loginSegue", sender: self) } */ // 1 Update the trailing closure to accept an optional message. // If biometric ID works, no message. touchMe.authenticateUser() { [weak self] message in // 2 Unwrap the message and display it with an alert. if (UserDefaults.standard.object(forKey: "userName") as? String) == nil { AlertNotification().alert(title: "Error", message: "No User Name found", sender: self!) } else if let message = message { // if the completion is not nil show an alert let alertView = UIAlertController(title: "Error", message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "Darn!", style: .default) alertView.addAction(okAction) self?.present(alertView, animated: true) } else { UserDefaults.standard.set(true, forKey: "isLoggedIn") UserDefaults.standard.synchronize() // 3 if no message, dismiss the Login view. self?.performSegue(withIdentifier: "loginSegue", sender: self) } } } func checkLogin(username: String, password: String) -> Bool { guard username == UserDefaults.standard.value(forKey: "userName") as? String else { return false } do { let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: username, accessGroup: KeychainConfiguration.accessGroup) let keychainPassword = try passwordItem.readPassword() return password == keychainPassword } catch { fatalError("Error reading passwod from keychain - \(error)") } } override func viewDidLoad() { super.viewDidLoad() // Opening Animation maskView() animate() // Opening Sound if isOpening != false { PlayAudio.sharedInstance.playClick(fileName: "bigdog", fileExt: ".wav") isOpening = false } userNameTextField.delegate = self passwordTextField.delegate = self // Find whether the device can implement biometric authentication // If so, show the Touch ID button. touchIDButton.isHidden = !touchMe.canEvaluatePolicy() // Fix the button's icon switch touchMe.biometricType() { case .faceID: touchIDButton.setImage(UIImage(named: "FaceIcon"), for: .normal) default: touchIDButton.setImage(UIImage(named: "Touch-icon-lg"), for: .normal) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let touchBool = touchMe.canEvaluatePolicy() if touchBool { touchIDLoginAction() } } // Create a layer func maskView() { self.mask = CALayer() self.mask!.contents = UIImage(named: "dogpow")!.cgImage self.mask!.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) self.mask!.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.mask!.position = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height/2) view.layer.mask = mask } // Do Animation func animate() { let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds") keyFrameAnimation.delegate = self keyFrameAnimation.beginTime = CACurrentMediaTime() + 1 keyFrameAnimation.duration = 2 keyFrameAnimation.timingFunctions = [CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut), CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)] let initialBounds = NSValue(cgRect: mask!.bounds) let secondBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 60, height: 60)) let finalBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 1500, height: 1500)) keyFrameAnimation.values = [initialBounds, secondBounds, finalBounds] keyFrameAnimation.keyTimes = [0, 0.3, 1] self.mask!.add(keyFrameAnimation, forKey: "bounds") } // Remove sublayer after animation is done to expose login view func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { mask?.removeFromSuperlayer() } // To dismiss a keyboard func textFieldShouldReturn(_ textField: UITextField) -> Bool { userNameTextField.resignFirstResponder() passwordTextField.resignFirstResponder() return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // Refactoring alert message // Learn how to pass action to handler func alert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } */ // 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. if segue.identifier == "loginSegue" { let destVC = segue.destination as! UINavigationController let targetVC = destVC.topViewController as! GoalTableViewController targetVC.userName = userName } // Pass the selected object to the new view controller. } }
gpl-3.0
IamAlchemist/DemoAnimations
Animations/DraggableView.swift
2
1389
// // DraggableView.swift // DemoAnimations // // Created by wizard on 5/4/16. // Copyright © 2016 Alchemist. All rights reserved. // import UIKit protocol DraggableViewDelegate : class { func draggableView(view: DraggableView, draggingEndedWithVelocity velocity: CGPoint) func draggableViewBeganDraggin(view: DraggableView) } class DraggableView : UIView { weak var delegate : DraggableViewDelegate? override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { let recognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:))) addGestureRecognizer(recognizer) } func didPan(recognizer : UIPanGestureRecognizer) { let point = recognizer.translationInView(superview) center = CGPoint(x: center.x, y: center.y + point.y) recognizer.setTranslation(CGPointZero, inView: superview) if case .Ended = recognizer.state { var velocity = recognizer.velocityInView(superview) velocity.x = 0 delegate?.draggableView(self, draggingEndedWithVelocity: velocity) } else if case .Began = recognizer.state { delegate?.draggableViewBeganDraggin(self) } } }
mit
natecook1000/swift-compiler-crashes
crashes-fuzzing/27938-swift-arrayexpr-create.swift
3
199
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {{func a{struct Q<f:f.a}} [t}
mit
below/NavTest
NavTest/AppDelegate.swift
1
2159
// // AppDelegate.swift // NavTest // // Created by Alexander v. Below on 05.11.14. // Copyright (c) 2014 Alexander von Below. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
unlicense
karyjan/KMediaPlayer
KMediaPlayer/Button.swift
1
1465
// // Button.swift // MobilePlayer // // Created by Baris Sencan on 9/16/15. // Copyright (c) 2015 MovieLaLa. All rights reserved. // import UIKit class Button: UIButton { let config: ButtonConfig init(config: ButtonConfig = ButtonConfig()) { self.config = config super.init(frame: CGRectZero) accessibilityLabel = accessibilityLabel ?? config.identifier tintColor = config.tintColor setImage(config.image, forState: .Normal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sizeThatFits(size: CGSize) -> CGSize { let superSize = super.sizeThatFits(size) return CGSize( width: (config.widthCalculation == .AsDefined) ? config.width : superSize.width, height: config.height) } override func setImage(image: UIImage?, forState state: UIControlState) { let tintedImage = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) super.setImage(tintedImage, forState: state) } } // MARK: - Element extension Button: Element { var type: ElementType { return config.type } var identifier: String? { return config.identifier } var widthCalculation: ElementWidthCalculation { return config.widthCalculation } var width: CGFloat { return config.width } var marginLeft: CGFloat { return config.marginLeft } var marginRight: CGFloat { return config.marginRight } var view: UIView { return self } }
apache-2.0
natecook1000/swift-compiler-crashes
crashes-duplicates/13855-no-stacktrace.swift
11
249
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { struct A { enum S { let a { class A { let start = [ e( { class case ,
mit
oddpanda/SegmentControl
segmentControl.swift
1
2066
// // segmentControl.swift // Edinburgh Mums // // Created by Shaun Gillon on 27/08/2015. // Copyright (c) 2015 Odd Panda Design Ltd. All rights reserved. // import UIKit class segmentControlView: UISegmentedControl { var borderView: UIView! var segBackgroundColor : UIColor = UIColor.whiteColor() //border Variables var borderColor : UIColor = UIColor.greenColor() var borderHeight :CGFloat = 2 //Font Variables var fontColour = UIColor(red: 102.0/255, green: 145.0/255, blue: 142.0/255, alpha: 1.0) var selectedFontColour = UIColor(red: 102.0/255, green: 145.0/255, blue: 142.0/255, alpha: 1.0) var fontType = UIFont(name: "AvenirNext-Regular", size: 14.0) override func drawRect(rect: CGRect) { self.setTitleTextAttributes([NSForegroundColorAttributeName: fontColour, NSFontAttributeName : fontType!], forState: .Normal) self.setTitleTextAttributes([NSForegroundColorAttributeName: selectedFontColour, NSFontAttributeName : fontType!], forState: .Selected) self.backgroundColor = segBackgroundColor self.tintColor = UIColor.clearColor() let segmentCount = self.numberOfSegments let width = self.frame.width let height = self.frame.height - 5 let border = width/CGFloat(segmentCount) self.borderView = UIView(frame: CGRectMake(0, height, border, borderHeight)) self.borderView.backgroundColor = borderColor self.addSubview(borderView) } func animateBorderToSegment(segment : Int){ UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: nil, animations: { let segmentCount = self.numberOfSegments let width = self.frame.width let border = width/CGFloat(segmentCount) let difference = CGFloat(segment) * border self.borderView.frame.origin.x = difference }, completion: nil) } }
gpl-2.0
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01327-resolvetypedecl.swift
1
218
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum A class a<T where B : start extension A : a
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/02133-resolvetypedecl.swift
12
232
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class b<T where B : AnyObject if true { { } { } struct Q<T : b
mit
lukesutton/hekk
Sources/Node+Update.swift
1
1077
extension Node { public func remove(match: Query) -> Node? { return execute(match: match, node: self) { _ in nil } } public func update(match: Query, closure: (Node) -> Node) -> Node? { return execute(match: match, node: self, closure: closure) } private func execute(match: Query, node: Node, closure: (Node) -> Node?) -> Node? { if match.run(node: node) { return closure(node) } switch node { case let .regular(name, attrs, children, state): return .regular(name: name, attributes: attrs, children: reduce(match: match, children: children, closure: closure), state: state) case let .fragment(children): return .fragment(reduce(match: match, children: children, closure: closure)) default: return node } } private func reduce(match: Query, children: [Node], closure: (Node) -> Node?) -> [Node] { return children.reduce([]) { memo, child in if let node = execute(match: match, node: child, closure: closure) { return memo + [node] } else { return memo } } } }
mit
Yurssoft/QuickFile
QuickFile/ViewModels/YSPlaylistViewModel.swift
1
4479
// // YSPlaylistViewModel.swift // YSGGP // // Created by Yurii Boiko on 12/6/16. // Copyright © 2016 Yurii Boiko. All rights reserved. // import Foundation class YSPlaylistViewModel: YSPlaylistViewModelProtocol { func viewIsLoadedAndReadyToDisplay(_ completion: @escaping CompletionHandler) { getFiles { (_) in completion() } } var model: YSPlaylistAndPlayerModelProtocol? fileprivate var files = [YSDriveFileProtocol]() { didSet { folders = selectFolders() } } var folders = [YSDriveFileProtocol]() weak var viewDelegate: YSPlaylistViewModelViewDelegate? weak var coordinatorDelegate: YSPlaylistViewModelCoordinatorDelegate? func numberOfFiles(in folder: Int) -> Int { guard folders.count > folder else { return 0 } let folderFile = folders[folder] let filesInFolder = files.filter { $0.folder.folderID == folderFile.id && $0.isAudio } return filesInFolder.count } var numberOfFolders: Int { return folders.count } func selectFolders() -> [YSDriveFileProtocol] { let folders = files.filter { let folderFile = $0 if !folderFile.isAudio { let filesInFolder = files.filter { $0.folder.folderID == folderFile.id && $0.isAudio } return filesInFolder.count > 0 } else { return false } } return folders } var error: YSErrorProtocol = YSError() { didSet { if !error.isEmpty() { viewDelegate?.errorDidChange(viewModel: self, error: error) } } } func file(at index: Int, folderIndex: Int) -> YSDriveFileProtocol? { guard folders.count > folderIndex else { return nil } let folderFile = folders[folderIndex] let filesInFolder = files.filter { $0.folder.folderID == folderFile.id && $0.isAudio } guard filesInFolder.count > index else { return nil } let file = filesInFolder[index] return file } func folder(at index: Int) -> YSDriveFileProtocol? { guard folders.count > index else { return nil } let folderFile = folders[index] return folderFile } func useFile(at folder: Int, file: Int) { let audio = self.file(at: file, folderIndex: folder) coordinatorDelegate?.playlistViewModelDidSelectFile(self, file: audio!) } func removeDownloads() { } func getFiles(completion: @escaping ErrorCH) { files = [] model?.allFiles { (files, currentPlayingFile, error) in defer { } self.files = files if let error = error { self.error = error } DispatchQueue.main.async { completion(error) } if let currentPlayingFile = currentPlayingFile { let indexPathOfCurrentPlaying = self.indexPath(of: currentPlayingFile) if !files.isEmpty { self.viewDelegate?.scrollToCurrentlyPlayingFile(at: indexPathOfCurrentPlaying) } } } } func indexPath(of file: YSDriveFileProtocol) -> IndexPath { let fileFolderIndex = folders.index(where: { $0.id == file.folder.folderID }) let filesInFolder = files.filter { $0.folder.folderID == file.folder.folderID && $0.isAudio } let fileIndex = filesInFolder.index(where: { $0.id == file.id }) let indexPath = IndexPath.init(row: fileIndex ?? 0, section: fileFolderIndex ?? 0) return indexPath } } extension YSPlaylistViewModel: YSUpdatingDelegate { func downloadDidChange(_ download: YSDownloadProtocol, _ error: YSErrorProtocol?) { getFiles { (_) in self.viewDelegate?.filesDidChange(viewModel: self) } } func filesDidChange() { getFiles { (_) in self.viewDelegate?.filesDidChange(viewModel: self) } } } extension YSPlaylistViewModel: YSPlayerDelegate { func fileDidChange(file: YSDriveFileProtocol) { let indexOfUpdatingFile = files.index(where: { $0.id == file.id }) if let indexOfUpdatingFile = indexOfUpdatingFile, files.indices.contains(indexOfUpdatingFile) { files[indexOfUpdatingFile] = file } viewDelegate?.fileDidChange(viewModel: self) } }
mit
MrAlek/Swift-NSFetchedResultsController-Trickery
CoreDataTrickerySwift/ToDoSection.swift
1
677
// // ToDoSection.swift // CoreDataTrickerySwift // // Created by Alek Åström on 2015-09-13. // Copyright © 2015 Apps and Wonders. All rights reserved. // import Foundation enum ToDoSection: String { case ToDo = "10" case HighPriority = "11" case MediumPriority = "12" case LowPriority = "13" case Done = "20" var title: String { switch self { case .ToDo: return "Left to do" case .Done: return "Done" case .HighPriority: return "High priority" case .MediumPriority: return "Medium priority" case .LowPriority: return "Low priority" } } }
mit
cp3hnu/Bricking
Bricking/Source/Collapse.swift
1
7052
// // Collapse.swift // Bricking // // Created by CP3 on 17/4/12. // Copyright © 2017年 CP3. All rights reserved. // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif extension View { private struct AssociatedKeys { static var previousConstraint = "previousConstraint" static var nextConstraint = "nextConstraint" static var currentConstraint = "currentConstraint" static var isBottomSpaceReserved = "isBottomSpaceReserved" static var isRightSpaceReserved = "isRightSpaceReserved" } private var previousConstraint: NSLayoutConstraint? { get { return objc_getAssociatedObject(self, &AssociatedKeys.previousConstraint) as? NSLayoutConstraint } set { objc_setAssociatedObject(self, &AssociatedKeys.previousConstraint, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var nextConstraint: NSLayoutConstraint? { get { return objc_getAssociatedObject(self, &AssociatedKeys.nextConstraint) as? NSLayoutConstraint } set { objc_setAssociatedObject(self, &AssociatedKeys.nextConstraint, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var currentConstraint: NSLayoutConstraint? { get { return objc_getAssociatedObject(self, &AssociatedKeys.currentConstraint) as? NSLayoutConstraint } set { objc_setAssociatedObject(self, &AssociatedKeys.currentConstraint, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var isBottomSpaceReserved: Bool? { get { return objc_getAssociatedObject(self, &AssociatedKeys.isBottomSpaceReserved) as? Bool } set { objc_setAssociatedObject(self, &AssociatedKeys.isBottomSpaceReserved, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) } } public var isRightSpaceReserved: Bool? { get { return objc_getAssociatedObject(self, &AssociatedKeys.isRightSpaceReserved) as? Bool } set { objc_setAssociatedObject(self, &AssociatedKeys.isRightSpaceReserved, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) } } public var collapseVertically: Bool { get { return isHidden } set { isHidden = newValue if newValue { changeVerticalConstraint() } else { self.currentConstraint?.isActive = false self.previousConstraint?.isActive = true self.nextConstraint?.isActive = true } } } public var collapseHorizontally: Bool { get { return isHidden } set { isHidden = newValue if newValue { changeHorizontalConstraint() } else { self.currentConstraint?.isActive = false self.previousConstraint?.isActive = true self.nextConstraint?.isActive = true } } } private func changeVerticalConstraint() { let (pView, pConstraint, pAttribute, pConstant) = constraintFor(.top) let (nView, nConstraint, nAttribute, nConstant) = constraintFor(.bottom) guard let preView = pView, let nextView = nView, let preConstraint = pConstraint, let nextConstraint = nConstraint, let preAttribute = pAttribute, let nextAttribute = nAttribute else { return } preConstraint.isActive = false nextConstraint.isActive = false self.previousConstraint = preConstraint self.nextConstraint = nextConstraint var constant = pConstant if let isBottom = self.isBottomSpaceReserved, isBottom == true { constant = nConstant } self.currentConstraint = NSLayoutConstraint(item: preView, attribute: preAttribute, relatedBy: .equal, toItem: nextView, attribute: nextAttribute, multiplier: 1.0, constant: constant) self.currentConstraint!.isActive = true } private func changeHorizontalConstraint() { let (pView, pConstraint, pAttribute, pConstant) = constraintFor(.leading) let (nView, nConstraint, nAttribute, nConstant) = constraintFor(.trailing) guard let preView = pView, let nextView = nView, let preConstraint = pConstraint, let nextConstraint = nConstraint, let preAttribute = pAttribute, let nextAttribute = nAttribute else { return } preConstraint.isActive = false nextConstraint.isActive = false self.previousConstraint = preConstraint self.nextConstraint = nextConstraint var constant = pConstant if let isRight = self.isRightSpaceReserved, isRight == true { constant = nConstant } self.currentConstraint = NSLayoutConstraint(item: preView, attribute: preAttribute, relatedBy: .equal, toItem: nextView, attribute: nextAttribute, multiplier: 1.0, constant: constant) self.currentConstraint!.isActive = true } private func constraintFor(_ attribute: LayoutAttribute) -> (View?, NSLayoutConstraint?, LayoutAttribute?, constant: CGFloat) { if let spv = superview { for c in spv.constraints { if let fi = c.firstItem as? View, fi == self && c.firstAttribute == attribute { var constant = c.constant if attribute == LayoutAttribute.leading || attribute == LayoutAttribute.top { constant = -c.constant } return (c.secondItem as? View, c, c.secondAttribute, constant) } if let si = c.secondItem as? View, si == self && c.secondAttribute == attribute { var constant = c.constant if attribute == LayoutAttribute.trailing || attribute == LayoutAttribute.bottom { constant = -c.constant } return (c.firstItem as? View, c, c.firstAttribute, constant) } } } return (nil, nil, nil, 0) } }
mit
buyiyang/iosstar
iOSStar/General/Extension/QiniuTool.swift
3
4870
// // QiniuTool.swift // iOSStar // // Created by mu on 2017/8/19. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import Alamofire import Kingfisher import Qiniu class QiniuTool: NSObject { static let tool = QiniuTool() class func shared() -> QiniuTool{ return tool } func getIPAdrees() { Alamofire.request(AppConst.ipUrl).responseString { (response) in if let value = response.result.value { if let ipValue = value.components(separatedBy: ",").first{ print(ipValue) let ipString = (ipValue as NSString).substring(with: NSRange.init(location: 6, length: ipValue.length() - 7)) self.getIPInfoAdrees(ipString) } } } } func getIPInfoAdrees(_ ipString: String) { Alamofire.request(AppConst.ipInfoUrl).responseJSON { (response) in if let value = response.result.value as? NSDictionary{ if let dataDic = value.value(forKey: "data") as? NSDictionary{ if let area = dataDic.value(forKey: "area") as? String{ ShareDataModel.share().netInfo.area = area self.getQiniuHeader(area) } if let areaId = dataDic.value(forKey: "area_id") as? NSString{ ShareDataModel.share().netInfo.area_id = Int((areaId).intValue) } if let isp = dataDic.value(forKey: "isp") as? String{ ShareDataModel.share().netInfo.isp = isp } if let isp_id = dataDic.value(forKey: "isp_id") as? NSString{ ShareDataModel.share().netInfo.isp_id = Int((isp_id).intValue) } } } } } func getQiniuHeader(_ area: String) { AppAPIHelper.login().qiniuHttpHeader(complete: { (result) in if let model = result as? QinniuModel{ if area == "华南"{ ShareDataModel.share().qiniuHeader = model.QINIU_URL_HUANAN return } if area == "华北"{ ShareDataModel.share().qiniuHeader = model.QINIU_URL_HUABEI return } if area == "华东"{ ShareDataModel.share().qiniuHeader = model.QINIU_URL_HUADONG return } } }, error: nil) } func upload(_ path : URL, _ type : Bool){ //获取 token } //上传图片 class func qiniuUploadImage(image: UIImage,imageName: String, complete: CompleteBlock?, error: ErrorBlock?) { let filePath = UIImage.cacheImage(image, imageName: imageName) let timestamp = NSDate().timeIntervalSince1970 let key = "\(imageName)\(Int(timestamp)).png" uploadResource(filePath: filePath, key: key, complete: complete, error: error) } //上传视频 class func qiniuUploadVideo(filePath: String,videoName: String, complete: CompleteBlock?, error: ErrorBlock?) { let timestamp = NSDate().timeIntervalSince1970 let key = "\(videoName)\(Int(timestamp)).mp4" uploadResource(filePath: filePath, key: key, complete: complete, error: error) } //上传声音 class func qiniuUploadVoice(filePath: String,voiceName: String, complete: CompleteBlock?, error: ErrorBlock?) { let timestamp = NSDate().timeIntervalSince1970 let key = "\(voiceName)\(Int(timestamp)).mp3" uploadResource(filePath: filePath, key: key, complete: complete, error: error) } class func uploadResource(filePath : String, key : String, complete: CompleteBlock?, error: ErrorBlock?){ AppAPIHelper.user().uploadimg(complete: { (result) in if let response = result as? UploadTokenModel{ let qiniuManager = QNUploadManager() qiniuManager?.putFile(filePath, key: key, token: response.uptoken, complete: { (info, key, resp) in if complete == nil{ return } if resp == nil { complete!(nil) return } //3,返回URL let respDic: NSDictionary? = resp as NSDictionary? let value:String? = respDic!.value(forKey: "key") as? String let imageUrl = value! complete!(imageUrl as AnyObject?) }, option: nil) } }) { (error ) in } } }
gpl-3.0
SASAbus/SASAbus-ios
SASAbus Watch Extension/Controller/MainInterfaceController.swift
1
2192
import WatchKit import Foundation import Realm import RealmSwift class MainInterfaceController: WKInterfaceController { let color = UIColor(hue: 0.08, saturation: 0.85, brightness: 0.90, alpha: 1) @IBOutlet var nearbyButton: WKInterfaceButton! @IBOutlet var recentButton: WKInterfaceButton! @IBOutlet var favoritesButton: WKInterfaceButton! @IBOutlet var searchButton: WKInterfaceButton! @IBOutlet var nearbyIcon: WKInterfaceImage! @IBOutlet var recentIcon: WKInterfaceImage! @IBOutlet var favoritesIcon: WKInterfaceImage! @IBOutlet var searchIcon: WKInterfaceImage! override func awake(withContext context: Any?) { super.awake(withContext: context) nearbyIcon.setTintColor(color) recentIcon.setTintColor(color) favoritesIcon.setTintColor(color) searchIcon.setTintColor(color) } @IBAction func onSearchButtonPress() { displaySearch() } private func displaySearch() { var defaults = [String]() let realm = Realm.busStops() var filterChain = "" for id in SearchInterfaceController.defaultBusStopsIds { filterChain += "family == \(id) OR " } filterChain = filterChain.substring(to: filterChain.index(filterChain.endIndex, offsetBy: -4)) let busStops = realm.objects(BusStop.self).filter(filterChain) for busStop in busStops { defaults.append(busStop.name()) } // Filter out duplicate bus stops defaults = defaults.uniques().sorted() presentTextInputController(withSuggestions: defaults, allowedInputMode: .plain, completion: {(results) -> Void in guard let results = results, !results.isEmpty else { Log.warning("No results returned") self.popToRootController() return } let busStop = results[0] as! String Log.info("Searched for '\(busStop)'") self.pushController(withName: "SearchInterfaceController", context: busStop) }) } }
gpl-3.0
moppymopperson/HeartView
HeartView/HeartView/HeartView.swift
1
2896
// // HeartView.swift // HeartView // // Created by Erik Hornberger on 2017/01/23. // Copyright © 2017年 EExT. All rights reserved. // import Foundation import UIKit /** A heart shaped view that mimicking the one in Apple's CareKit, but built with .xib file instead, and made to render properly in IB. */ @IBDesignable class HeartView: RenderableView { /** This is used as the outline of the heart when it is not full */ @IBOutlet private weak var outlineView: UIImageView! /** A second copy of the outline image, but this time with the rendering mode set to template so that all non-transparent pixels are made the tint color of the view */ @IBOutlet private weak var filledHeartImage: UIImageView! /** This is resized to hide the top part of the heart view and create the illusion of the heart filling up. */ @IBOutlet private weak var clippingView: UIView! /** The distance from the top of the view to the top of the clipping view (effectively the top of the fill) */ @IBOutlet private weak var topConstraint: NSLayoutConstraint! /** Set this to between 0 and 1 to adjust the percent of the heart that is filled. */ @IBInspectable var value:CGFloat = 1.0 { didSet { updateHeight(animated: true) } } /** Sets the fill color of the heart. Actually just a mapping of tint. */ @IBInspectable var fillColor:UIColor { get { return tintColor } set { tintColor = newValue } } /** Additional setup can be performed here. Essentially equivalent to 'viewDidLoad' */ override func setup() { layoutIfNeeded() filledHeartImage.image = outlineView.image?.withRenderingMode(.alwaysTemplate) fillColor = .red } /** Play a fill animation */ private func updateHeight(animated: Bool) { if !animated { topConstraint.constant = self.frame.height * (1 - self.value) layoutIfNeeded() return } // fill UIView.animate(withDuration: 1.0) { self.layoutIfNeeded() self.topConstraint.constant = self.frame.height * (1 - self.value) self.layoutIfNeeded() } // beat let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeOut) { self.transform = CGAffineTransform.init(scaleX: 1.2, y: 1.2) } animator.addCompletion { (position) in UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: { self.transform = CGAffineTransform.identity }, completion: nil) } animator.startAnimation() } }
mit
dreamsxin/swift
validation-test/compiler_crashers_fixed/26542-swift-typechecker-validatedecl.swift
11
435
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse if{struct Q<h{class a{class A:a{protocol A
apache-2.0
liuxiangdong3721/Swift
swiftLearning/swiftLearningTests/swiftLearningTests.swift
1
916
// // swiftLearningTests.swift // swiftLearningTests // // Created by Elvis on 15/4/22. // Copyright (c) 2015年 liuxiangdong. All rights reserved. // import UIKit import XCTest class swiftLearningTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
emilstahl/swift
validation-test/compiler_crashers/27547-swift-constraints-constraintsystem-getalternativeliteraltypes.swift
9
294
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T where g:n{ struct c<b{ class B class B var _=true{ } let a=B
apache-2.0
CodeEagle/Animate
Source/BasicProperties.swift
1
17071
// // BasicProperties.swift // Pods // // Created by LawLincoln on 15/6/24. // // import Foundation import pop public class BasicProperties: NSObject { // MARK: - UIView public var alpha: CGFloat!{ didSet { if let value = alpha { let anim = animator(kPOPViewAlpha) anim.toGenericValue(value,type) addAnimate(anim) } } } public var center: CGPoint!{ didSet { if let value = center { let anim = animator(kPOPViewCenter) anim.toGenericValue(NSValue(CGPoint:value),type) addAnimate(anim) } } } public var frame: CGRect! { didSet{ if let value = frame { let anim = animator(kPOPViewFrame) anim.toGenericValue(NSValue(CGRect:value),type) addAnimate(anim) } } } public var tintColor: UIColor!{ didSet { if let value = tintColor { if self.type != .Decay { let anim = animator(kPOPViewTintColor) anim.toValue = value addAnimate(anim) } } } } // MARK: - Common public var backgroundColor: UIColor!{ didSet { if let value = backgroundColor { var key = kPOPLayerBackgroundColor if self.target is UIView { key = kPOPViewBackgroundColor } let anim = animator(key) anim.toGenericValue(value,type) addAnimate(anim) } } } public var bounds: CGRect!{ didSet { if let value = bounds { var key = kPOPLayerBounds if self.target is UIView { key = kPOPViewBounds } let anim = animator(key) anim.toGenericValue(NSValue(CGRect:value),type) addAnimate(anim) } } } public var scaleX: CGFloat!{ didSet { if let value = scaleX { var key = kPOPLayerScaleX if self.target is UIView { key = kPOPViewScaleX } let anim = animator(key) anim.toGenericValue(value,type) addAnimate(anim) } } } public var scaleXY: CGSize!{ didSet { if let value = scaleXY { var key = kPOPLayerScaleXY if self.target is UIView { key = kPOPViewScaleXY } let anim = animator(key) anim.toGenericValue(NSValue(CGSize:value),type) addAnimate(anim) } } } public var scaleY: CGFloat!{ didSet { if let value = scaleY { var key = kPOPLayerScaleY if self.target is UIView { key = kPOPViewScaleY } let anim = animator(key) anim.toGenericValue(value,type) addAnimate(anim) } } } public var size: CGSize!{ didSet { if let value = size { var key = kPOPLayerSize if self.target is UIView { key = kPOPViewSize } let anim = animator(key) anim.toGenericValue(NSValue(CGSize:value),type) addAnimate(anim) } } } // MARK: - CALayer public var cornerRadius: CGFloat!{ didSet { if let value = cornerRadius { let anim = animator(kPOPLayerCornerRadius) anim.toGenericValue(value,type) addAnimate(anim) } } } public var borderWidth: CGFloat!{ didSet { if let value = borderWidth { let anim = animator(kPOPLayerBorderWidth) anim.toGenericValue(value,type) addAnimate(anim) } } } public var borderColor: UIColor!{ didSet { if let value = borderColor { let anim = animator(kPOPLayerBorderColor) anim.toGenericValue(value,type) addAnimate(anim) } } } public var opacity: CGFloat!{ didSet { if let value = opacity { let anim = animator(kPOPLayerOpacity) anim.toGenericValue(value,type) addAnimate(anim) } } } public var position: CGPoint!{ didSet { if let value = position { let anim = animator(kPOPLayerPosition) anim.toGenericValue(NSValue(CGPoint:value),type) addAnimate(anim) } } } public var positionX: CGFloat!{ didSet { if let value = positionX { let anim = animator(kPOPLayerPositionX) anim.toGenericValue(value,type) addAnimate(anim) } } } public var positionY: CGFloat!{ didSet { if let value = positionY { let anim = animator(kPOPLayerPositionY) anim.toGenericValue(value,type) addAnimate(anim) } } } public var rotation: CGFloat!{ didSet { if let value = rotation { let anim = animator(kPOPLayerRotation) anim.toGenericValue(value,type) addAnimate(anim) } } } public var rotationX: CGFloat!{ didSet { if let value = rotationX { let anim = animator(kPOPLayerRotationX) anim.toGenericValue(value,type) addAnimate(anim) } } } public var rotationY: CGFloat!{ didSet { if let value = rotationY { let anim = animator(kPOPLayerRotationY) anim.toGenericValue(value,type) addAnimate(anim) } } } public var subscaleXY: CGSize!{ didSet { if let value = subscaleXY { let anim = animator(kPOPLayerSubscaleXY) anim.toGenericValue(NSValue(CGSize:value),type) addAnimate(anim) } } } public var subtranslationX: CGFloat!{ didSet { if let value = subtranslationX { let anim = animator(kPOPLayerSubtranslationX) anim.toGenericValue(value,type) addAnimate(anim) } } } public var subtranslationXY: CGSize!{ didSet { if let value = subtranslationXY { let anim = animator(kPOPLayerSubtranslationXY) anim.toGenericValue(NSValue(CGSize:value),type) addAnimate(anim) } } } public var subtranslationY: CGFloat!{ didSet { if let value = subtranslationY { let anim = animator(kPOPLayerSubtranslationY) anim.toGenericValue(value,type) addAnimate(anim) } } } public var subtranslationZ: CGFloat!{ didSet { if let value = subtranslationZ { let anim = animator(kPOPLayerSubtranslationZ) anim.toGenericValue(value,type) addAnimate(anim) } } } public var translationX: CGFloat!{ didSet { if let value = translationX { let anim = animator(kPOPLayerTranslationX) anim.toGenericValue(value,type) addAnimate(anim) } } } public var translationXY: CGSize!{ didSet { if let value = translationXY { let anim = animator(kPOPLayerTranslationXY) anim.toGenericValue(NSValue(CGSize:value),type) addAnimate(anim) } } } public var translationY: CGFloat!{ didSet { if let value = translationY { let anim = animator(kPOPLayerTranslationY) anim.toGenericValue(value,type) addAnimate(anim) } } } public var translationZ: CGFloat!{ didSet { if let value = translationZ { let anim = animator(kPOPLayerTranslationZ) anim.toGenericValue(value,type) addAnimate(anim) } } } public var zPosition: CGPoint!{ didSet { if let value = zPosition { let anim = animator(kPOPLayerZPosition) anim.toGenericValue(NSValue(CGPoint:value),type) addAnimate(anim) } } } public var shadowColor: UIColor!{ didSet { if let value = shadowColor { let anim = animator(kPOPLayerShadowColor) anim.toGenericValue(value,type) addAnimate(anim) } } } public var shadowOffset: CGSize!{ didSet { if let value = shadowOffset { let anim = animator(kPOPLayerShadowOffset) anim.toGenericValue(NSValue(CGSize:value),type) addAnimate(anim) } } } public var shadowOpacity: CGFloat!{ didSet { if let value = shadowOpacity { let anim = animator(kPOPLayerShadowOpacity) anim.toGenericValue(value,type) addAnimate(anim) } } } public var shadowRadius: CGFloat!{ didSet { if let value = shadowRadius { let anim = animator(kPOPLayerShadowRadius) anim.toGenericValue(value,type) addAnimate(anim) } } } typealias ApplyToProtocol = (AnyObject)->Void var applyToBlock: ApplyToProtocol! var doneBlock: NextAnimtionBlock! // MARK: - private var animateWhenSet: Bool = false var animating: Bool = false var animates = [AnyObject]() var animatesQueue = [AnyObject]() var delayTime: Double = 0 var type: AnimateType = .Spring weak var target: NSObject!{ didSet{ self.associate() } } var doneCount: Int = 0 func addAnimate(obj:AnyObject){ if animating && !animateWhenSet{ animatesQueue.insert(obj, atIndex: 0) }else{ animates.append(obj) if animateWhenSet{ if self.target != nil { applyToBlock?(self.target) } } } } } // MARK: - Setter extension BasicProperties { // MARK: - Common public func setAnimateBackgroundColor(value:UIColor){ backgroundColor = value } public func setAnimateBounds(value:NSValue){ bounds = value.CGRectValue() } public func setAnimateScaleX(value:CGFloat){ scaleX = value } public func setAnimateScaleXY(value:CGSize){ scaleXY = value } public func setAnimateScaleY(value:CGFloat){ scaleY = value } public func setAnimateSize(value:CGSize){ size = value } // MARK: - UIView public func setAnimateAlpha(value:CGFloat){ alpha = value } public func setAnimateTintColor(value:UIColor){ tintColor = value } public func setAnimateFrame(value:NSValue){ frame = value.CGRectValue() } public func setAnimateCenter(value:NSValue){ center = value.CGPointValue() } // MARK: - CALayer public func setAnimateCornerRadius(value:CGFloat){ cornerRadius = value } public func setAnimateBorderWidth(value:CGFloat){ borderWidth = value } public func setAnimateBorderColor(value:UIColor){ borderColor = value } public func setAnimateOpacity(value:CGFloat){ opacity = value } public func setAnimatePosition(value:CGPoint){ position = value } public func setAnimatePositionX(value:CGFloat){ positionX = value } public func setAnimatePositionY(value:CGFloat){ positionY = value } public func setAnimateRotation(value:CGFloat){ rotation = value } public func setAnimateRotationX(value:CGFloat){ rotationX = value } public func setAnimateRotationY(value:CGFloat){ rotationY = value } public func setAnimateSubscaleXY(value:CGSize){ subscaleXY = value } public func setAnimateSubtranslationX(value:CGFloat){ subtranslationX = value } public func setAnimateSubtranslationXY(value:CGSize){ subtranslationXY = value } public func setAnimateSubtranslationY(value:CGFloat){ subtranslationY = value } public func setAnimateSubtranslationZ(value:CGFloat){ subtranslationZ = value } public func setAnimateTranslationX(value:CGFloat){ translationX = value } public func setAnimateTranslationXY(value:CGSize){ translationXY = value } public func setAnimateTranslationY(value:CGFloat){ translationY = value } public func setAnimateTranslationZ(value:CGFloat){ translationZ = value } public func setAnimateZPosition(value:CGPoint){ zPosition = value } public func setAnimateShadowColor(value:UIColor){ shadowColor = value } public func setAnimateShadowOffset(value:CGSize){ shadowOffset = value } public func setAnimateShadowOpacity(value:CGFloat){ shadowOpacity = value } public func setAnimateShadowRadius(value:CGFloat){ shadowRadius = value } } // MARK: - Private Function extension BasicProperties: POPAnimationDelegate { private func associate(){ if !self.target { objc_setAssociatedObject(self.target, &AnimateAssociatedKeys.SelfRetain, self, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private func animator(name:String!)->POPPropertyAnimation{ var anim: POPPropertyAnimation = POPSpringAnimation(propertyNamed: name) switch type { case .Basic: anim = POPBasicAnimation(propertyNamed: name) break case .Decay: anim = POPDecayAnimation(propertyNamed: name) break default: break } return anim } func playNext(){ // debugPrint("play", appendNewline: true) if animateWhenSet { if self.animatesQueue.count > 0 { let anim: AnyObject = self.animatesQueue.removeLast() addAnimate(anim) } }else{ // debugPrint("delay:\(self.delayTime)", appendNewline: true) if self.delayTime > 0 { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(self.delayTime * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.play() } }else{ play() } } } private func play(){ // debugPrint("next", appendNewline: true) if self.target.AnimatePopQueue.count > 0 { self.target.AnimatePopQueue.removeLastObject() if self.target.AnimatePopQueue.count > 0 { if let block = self.target.AnimatePopQueue.lastObject as? NSBlockOperation { block.start() } } }else{ !doneBlock ? doneBlock() : (debugPrint("no more animate")) } } // MARK: - POPAnimationDelegate public func pop_animationDidStop(anim: POPAnimation!, finished: Bool) { self.animateStop(anim, finished: finished) } func animateStop(anim: POPAnimation!, finished: Bool) { anim.delegate = nil doneCount++ if doneCount == self.animates.count { animating = false if animateWhenSet { self.animates.removeAll(keepCapacity: true) } doneCount = 0 self.playNext() } } } // MARK: - Public Function public extension BasicProperties { public func delay(delay:Double)->BasicProperties{ self.delayTime = delay return self } public func done(done:NextAnimtionBlock){ self.doneBlock = done } }
mit
ben-ng/swift
test/stdlib/RuntimeObjC.swift
2
25574
// RUN: rm -rf %t && mkdir -p %t // // RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g // RUN: %target-build-swift -parse-stdlib -Xfrontend -disable-access-control -module-name a -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o %s -o %t.out // RUN: %target-run %t.out // REQUIRES: executable_test // REQUIRES: objc_interop import Swift import StdlibUnittest import Foundation import CoreGraphics import SwiftShims import MirrorObjC var nsObjectCanaryCount = 0 @objc class NSObjectCanary : NSObject { override init() { nsObjectCanaryCount += 1 } deinit { nsObjectCanaryCount -= 1 } } struct NSObjectCanaryStruct { var ref = NSObjectCanary() } var swiftObjectCanaryCount = 0 class SwiftObjectCanary { init() { swiftObjectCanaryCount += 1 } deinit { swiftObjectCanaryCount -= 1 } } struct SwiftObjectCanaryStruct { var ref = SwiftObjectCanary() } @objc class ClassA { init(value: Int) { self.value = value } var value: Int } struct BridgedValueType : _ObjectiveCBridgeable { init(value: Int) { self.value = value } func _bridgeToObjectiveC() -> ClassA { return ClassA(value: value) } static func _forceBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedValueType? ) { assert(x.value % 2 == 0, "not bridged to Objective-C") result = BridgedValueType(value: x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedValueType? ) -> Bool { if x.value % 2 == 0 { result = BridgedValueType(value: x.value) return true } result = nil return false } static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?) -> BridgedValueType { var result: BridgedValueType? _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int var canaryRef = SwiftObjectCanary() } struct BridgedLargeValueType : _ObjectiveCBridgeable { init(value: Int) { value0 = value value1 = value value2 = value value3 = value value4 = value value5 = value value6 = value value7 = value } func _bridgeToObjectiveC() -> ClassA { assert(value == value0) return ClassA(value: value0) } static func _forceBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedLargeValueType? ) { assert(x.value % 2 == 0, "not bridged to Objective-C") result = BridgedLargeValueType(value: x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedLargeValueType? ) -> Bool { if x.value % 2 == 0 { result = BridgedLargeValueType(value: x.value) return true } result = nil return false } static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?) -> BridgedLargeValueType { var result: BridgedLargeValueType? _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int { let x = value0 assert(value0 == x && value1 == x && value2 == x && value3 == x && value4 == x && value5 == x && value6 == x && value7 == x) return x } var (value0, value1, value2, value3): (Int, Int, Int, Int) var (value4, value5, value6, value7): (Int, Int, Int, Int) var canaryRef = SwiftObjectCanary() } class BridgedVerbatimRefType { var value: Int = 42 var canaryRef = SwiftObjectCanary() } func withSwiftObjectCanary<T>( _ createValue: () -> T, _ check: (T) -> Void, file: String = #file, line: UInt = #line ) { let stackTrace = SourceLocStack(SourceLoc(file, line)) swiftObjectCanaryCount = 0 autoreleasepool { var valueWithCanary = createValue() expectEqual(1, swiftObjectCanaryCount, stackTrace: stackTrace) check(valueWithCanary) } expectEqual(0, swiftObjectCanaryCount, stackTrace: stackTrace) } var Runtime = TestSuite("Runtime") func _isClassOrObjCExistential_Opaque<T>(_ x: T.Type) -> Bool { return _isClassOrObjCExistential(_opaqueIdentity(x)) } Runtime.test("_isClassOrObjCExistential") { expectTrue(_isClassOrObjCExistential(NSObjectCanary.self)) expectTrue(_isClassOrObjCExistential_Opaque(NSObjectCanary.self)) expectFalse(_isClassOrObjCExistential(NSObjectCanaryStruct.self)) expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanaryStruct.self)) expectTrue(_isClassOrObjCExistential(SwiftObjectCanary.self)) expectTrue(_isClassOrObjCExistential_Opaque(SwiftObjectCanary.self)) expectFalse(_isClassOrObjCExistential(SwiftObjectCanaryStruct.self)) expectFalse(_isClassOrObjCExistential_Opaque(SwiftObjectCanaryStruct.self)) typealias SwiftClosure = () -> () expectFalse(_isClassOrObjCExistential(SwiftClosure.self)) expectFalse(_isClassOrObjCExistential_Opaque(SwiftClosure.self)) typealias ObjCClosure = @convention(block) () -> () expectTrue(_isClassOrObjCExistential(ObjCClosure.self)) expectTrue(_isClassOrObjCExistential_Opaque(ObjCClosure.self)) expectTrue(_isClassOrObjCExistential(CFArray.self)) expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self)) expectTrue(_isClassOrObjCExistential(CFArray.self)) expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self)) expectTrue(_isClassOrObjCExistential(AnyObject.self)) expectTrue(_isClassOrObjCExistential_Opaque(AnyObject.self)) // AnyClass == AnyObject.Type expectFalse(_isClassOrObjCExistential(AnyClass.self)) expectFalse(_isClassOrObjCExistential_Opaque(AnyClass.self)) expectFalse(_isClassOrObjCExistential(AnyObject.Protocol.self)) expectFalse(_isClassOrObjCExistential_Opaque(AnyObject.Protocol.self)) expectFalse(_isClassOrObjCExistential(NSObjectCanary.Type.self)) expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanary.Type.self)) } Runtime.test("_canBeClass") { expectEqual(1, _canBeClass(NSObjectCanary.self)) expectEqual(0, _canBeClass(NSObjectCanaryStruct.self)) typealias ObjCClosure = @convention(block) () -> () expectEqual(1, _canBeClass(ObjCClosure.self)) expectEqual(1, _canBeClass(CFArray.self)) } Runtime.test("bridgeToObjectiveC") { expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedValueType(value: 42)) as! ClassA).value) expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedLargeValueType(value: 42)) as! ClassA).value) var bridgedVerbatimRef = BridgedVerbatimRefType() expectTrue(_bridgeAnythingToObjectiveC(bridgedVerbatimRef) === bridgedVerbatimRef) } Runtime.test("bridgeToObjectiveC/NoLeak") { withSwiftObjectCanary( { BridgedValueType(value: 42) }, { expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) }) withSwiftObjectCanary( { BridgedLargeValueType(value: 42) }, { expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) }) withSwiftObjectCanary( { BridgedVerbatimRefType() }, { expectTrue(_bridgeAnythingToObjectiveC($0) === $0) }) } Runtime.test("forceBridgeFromObjectiveC") { // Bridge back using BridgedValueType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedValueType.self)) expectEqual(42, _forceBridgeFromObjectiveC( ClassA(value: 42), BridgedValueType.self).value) expectEqual(42, _conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedValueType.self)!.value) expectNil(_conditionallyBridgeFromObjectiveC( BridgedVerbatimRefType(), BridgedValueType.self)) // Bridge back using BridgedLargeValueType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedLargeValueType.self)) expectEqual(42, _forceBridgeFromObjectiveC( ClassA(value: 42), BridgedLargeValueType.self).value) expectEqual(42, _conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedLargeValueType.self)!.value) expectNil(_conditionallyBridgeFromObjectiveC( BridgedVerbatimRefType(), BridgedLargeValueType.self)) // Bridge back using BridgedVerbatimRefType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedVerbatimRefType.self)) expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedVerbatimRefType.self)) var bridgedVerbatimRef = BridgedVerbatimRefType() expectTrue(_forceBridgeFromObjectiveC( bridgedVerbatimRef, BridgedVerbatimRefType.self) === bridgedVerbatimRef) expectTrue(_conditionallyBridgeFromObjectiveC( bridgedVerbatimRef, BridgedVerbatimRefType.self)! === bridgedVerbatimRef) } Runtime.test("isBridgedToObjectiveC") { expectTrue(_isBridgedToObjectiveC(BridgedValueType)) expectTrue(_isBridgedToObjectiveC(BridgedVerbatimRefType)) } Runtime.test("isBridgedVerbatimToObjectiveC") { expectFalse(_isBridgedVerbatimToObjectiveC(BridgedValueType)) expectTrue(_isBridgedVerbatimToObjectiveC(BridgedVerbatimRefType)) } //===----------------------------------------------------------------------===// class SomeClass {} @objc class SomeObjCClass {} class SomeNSObjectSubclass : NSObject {} Runtime.test("typeName") { expectEqual("a.SomeObjCClass", _typeName(SomeObjCClass.self)) expectEqual("a.SomeNSObjectSubclass", _typeName(SomeNSObjectSubclass.self)) expectEqual("NSObject", _typeName(NSObject.self)) var a : Any = SomeObjCClass() expectEqual("a.SomeObjCClass", _typeName(type(of: a))) a = SomeNSObjectSubclass() expectEqual("a.SomeNSObjectSubclass", _typeName(type(of: a))) a = NSObject() expectEqual("NSObject", _typeName(type(of: a))) } class GenericClass<T> {} class MultiGenericClass<T, U> {} struct GenericStruct<T> {} enum GenericEnum<T> {} struct PlainStruct {} enum PlainEnum {} protocol ProtocolA {} protocol ProtocolB {} Runtime.test("Generic class ObjC runtime names") { expectEqual("_TtGC1a12GenericClassSi_", NSStringFromClass(GenericClass<Int>.self)) expectEqual("_TtGC1a12GenericClassVS_11PlainStruct_", NSStringFromClass(GenericClass<PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassOS_9PlainEnum_", NSStringFromClass(GenericClass<PlainEnum>.self)) expectEqual("_TtGC1a12GenericClassTVS_11PlainStructOS_9PlainEnumS1___", NSStringFromClass(GenericClass<(PlainStruct, PlainEnum, PlainStruct)>.self)) expectEqual("_TtGC1a12GenericClassMVS_11PlainStruct_", NSStringFromClass(GenericClass<PlainStruct.Type>.self)) expectEqual("_TtGC1a12GenericClassFMVS_11PlainStructS1__", NSStringFromClass(GenericClass<(PlainStruct.Type) -> PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassFzMVS_11PlainStructS1__", NSStringFromClass(GenericClass<(PlainStruct.Type) throws -> PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassFTVS_11PlainStructROS_9PlainEnum_Si_", NSStringFromClass(GenericClass<(PlainStruct, inout PlainEnum) -> Int>.self)) expectEqual("_TtGC1a12GenericClassPS_9ProtocolA__", NSStringFromClass(GenericClass<ProtocolA>.self)) expectEqual("_TtGC1a12GenericClassPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<ProtocolA & ProtocolB>.self)) expectEqual("_TtGC1a12GenericClassPMPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<(ProtocolA & ProtocolB).Type>.self)) expectEqual("_TtGC1a12GenericClassMPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<(ProtocolB & ProtocolA).Protocol>.self)) expectEqual("_TtGC1a12GenericClassCSo7CFArray_", NSStringFromClass(GenericClass<CFArray>.self)) expectEqual("_TtGC1a12GenericClassVSC7Decimal_", NSStringFromClass(GenericClass<Decimal>.self)) expectEqual("_TtGC1a12GenericClassCSo8NSObject_", NSStringFromClass(GenericClass<NSObject>.self)) expectEqual("_TtGC1a12GenericClassCSo8NSObject_", NSStringFromClass(GenericClass<NSObject>.self)) expectEqual("_TtGC1a12GenericClassPSo9NSCopying__", NSStringFromClass(GenericClass<NSCopying>.self)) expectEqual("_TtGC1a12GenericClassPSo9NSCopyingS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<ProtocolB & NSCopying & ProtocolA>.self)) expectEqual("_TtGC1a17MultiGenericClassGVS_13GenericStructSi_GOS_11GenericEnumGS2_Si___", NSStringFromClass(MultiGenericClass<GenericStruct<Int>, GenericEnum<GenericEnum<Int>>>.self)) } Runtime.test("typeByName") { // Make sure we don't crash if we have foreign classes in the // table -- those don't have NominalTypeDescriptors print(CFArray.self) expectTrue(_typeByName("a.SomeClass") == SomeClass.self) expectTrue(_typeByName("DoesNotExist") == nil) } Runtime.test("casting AnyObject to class metatypes") { do { var ao: AnyObject = SomeClass.self expectTrue(ao as? Any.Type == SomeClass.self) expectTrue(ao as? AnyClass == SomeClass.self) expectTrue(ao as? SomeClass.Type == SomeClass.self) } do { var ao : AnyObject = SomeNSObjectSubclass() expectTrue(ao as? Any.Type == nil) expectTrue(ao as? AnyClass == nil) ao = SomeNSObjectSubclass.self expectTrue(ao as? Any.Type == SomeNSObjectSubclass.self) expectTrue(ao as? AnyClass == SomeNSObjectSubclass.self) expectTrue(ao as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self) } do { var a : Any = SomeNSObjectSubclass() expectTrue(a as? Any.Type == nil) expectTrue(a as? AnyClass == nil) } do { var nso: NSObject = SomeNSObjectSubclass() expectTrue(nso as? AnyClass == nil) nso = (SomeNSObjectSubclass.self as AnyObject) as! NSObject expectTrue(nso as? Any.Type == SomeNSObjectSubclass.self) expectTrue(nso as? AnyClass == SomeNSObjectSubclass.self) expectTrue(nso as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self) } } var RuntimeFoundationWrappers = TestSuite("RuntimeFoundationWrappers") RuntimeFoundationWrappers.test("_stdlib_NSObject_isEqual/NoLeak") { nsObjectCanaryCount = 0 autoreleasepool { let a = NSObjectCanary() let b = NSObjectCanary() expectEqual(2, nsObjectCanaryCount) _stdlib_NSObject_isEqual(a, b) } expectEqual(0, nsObjectCanaryCount) } var nsStringCanaryCount = 0 @objc class NSStringCanary : NSString { override init() { nsStringCanaryCount += 1 super.init() } required init(coder: NSCoder) { fatalError("don't call this initializer") } deinit { nsStringCanaryCount -= 1 } @objc override var length: Int { return 0 } @objc override func character(at index: Int) -> unichar { fatalError("out-of-bounds access") } } RuntimeFoundationWrappers.test( "_stdlib_compareNSStringDeterministicUnicodeCollation/NoLeak" ) { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) _stdlib_compareNSStringDeterministicUnicodeCollation(a, b) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test( "_stdlib_compareNSStringDeterministicUnicodeCollationPtr/NoLeak" ) { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) let ptrB = unsafeBitCast(b, to: OpaquePointer.self) _stdlib_compareNSStringDeterministicUnicodeCollationPointer(ptrA, ptrB) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHashValue/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringHashValue(a, true) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHashValueNonASCII/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringHashValue(a, false) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHashValuePointer/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) _stdlib_NSStringHashValuePointer(ptrA, true) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHashValuePointerNonASCII/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) _stdlib_NSStringHashValuePointer(ptrA, false) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHasPrefixNFDPointer/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) let ptrB = unsafeBitCast(b, to: OpaquePointer.self) _stdlib_NSStringHasPrefixNFDPointer(ptrA, ptrB) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHasSuffixNFDPointer/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) let ptrB = unsafeBitCast(b, to: OpaquePointer.self) _stdlib_NSStringHasSuffixNFDPointer(ptrA, ptrB) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHasPrefixNFD/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) _stdlib_NSStringHasPrefixNFD(a, b) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHasSuffixNFD/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) _stdlib_NSStringHasSuffixNFD(a, b) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringLowercaseString/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringLowercaseString(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringUppercaseString/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringUppercaseString(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringCreateCopy/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringCreateCopy(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringGetLength/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringGetLength(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringGetCharactersPtr/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringGetCharactersPtr(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("bridgedNSArray") { var c = [NSObject]() autoreleasepool { let a = [NSObject]() let b = a as NSArray c = b as! [NSObject] } c.append(NSObject()) // expect no crash. } var Reflection = TestSuite("Reflection") class SwiftFooMoreDerivedObjCClass : FooMoreDerivedObjCClass { let first: Int = 123 let second: String = "abc" } Reflection.test("Class/ObjectiveCBase/Default") { do { let value = SwiftFooMoreDerivedObjCClass() var output = "" dump(value, to: &output) let expected = "▿ This is FooObjCClass #0\n" + " - super: FooMoreDerivedObjCClass\n" + " - super: FooDerivedObjCClass\n" + " - super: FooObjCClass\n" + " - super: NSObject\n" + " - first: 123\n" + " - second: \"abc\"\n" expectEqual(expected, output) } } protocol SomeNativeProto {} @objc protocol SomeObjCProto {} extension SomeClass: SomeObjCProto {} Reflection.test("MetatypeMirror") { do { let concreteClassMetatype = SomeClass.self let expectedSomeClass = "- a.SomeClass #0\n" let objcProtocolMetatype: SomeObjCProto.Type = SomeClass.self var output = "" dump(objcProtocolMetatype, to: &output) expectEqual(expectedSomeClass, output) let objcProtocolConcreteMetatype = SomeObjCProto.self let expectedObjCProtocolConcrete = "- a.SomeObjCProto #0\n" output = "" dump(objcProtocolConcreteMetatype, to: &output) expectEqual(expectedObjCProtocolConcrete, output) let compositionConcreteMetatype = (SomeNativeProto & SomeObjCProto).self let expectedComposition = "- a.SomeObjCProto & a.SomeNativeProto #0\n" output = "" dump(compositionConcreteMetatype, to: &output) expectEqual(expectedComposition, output) let objcDefinedProtoType = NSObjectProtocol.self expectEqual(String(describing: objcDefinedProtoType), "NSObject") } } Reflection.test("CGPoint") { var output = "" dump(CGPoint(x: 1.25, y: 2.75), to: &output) let expected = "▿ (1.25, 2.75)\n" + " - x: 1.25\n" + " - y: 2.75\n" expectEqual(expected, output) } Reflection.test("CGSize") { var output = "" dump(CGSize(width: 1.25, height: 2.75), to: &output) let expected = "▿ (1.25, 2.75)\n" + " - width: 1.25\n" + " - height: 2.75\n" expectEqual(expected, output) } Reflection.test("CGRect") { var output = "" dump( CGRect( origin: CGPoint(x: 1.25, y: 2.25), size: CGSize(width: 10.25, height: 11.75)), to: &output) let expected = "▿ (1.25, 2.25, 10.25, 11.75)\n" + " ▿ origin: (1.25, 2.25)\n" + " - x: 1.25\n" + " - y: 2.25\n" + " ▿ size: (10.25, 11.75)\n" + " - width: 10.25\n" + " - height: 11.75\n" expectEqual(expected, output) } Reflection.test("Unmanaged/nil") { var output = "" var optionalURL: Unmanaged<CFURL>? dump(optionalURL, to: &output) let expected = "- nil\n" expectEqual(expected, output) } Reflection.test("Unmanaged/not-nil") { var output = "" var optionalURL: Unmanaged<CFURL>? = Unmanaged.passRetained(CFURLCreateWithString(nil, "http://llvm.org/" as CFString, nil)) dump(optionalURL, to: &output) let expected = "▿ Optional(Swift.Unmanaged<__ObjC.CFURL>(_value: http://llvm.org/))\n" + " ▿ some: Swift.Unmanaged<__ObjC.CFURL>\n" + " - _value: http://llvm.org/ #0\n" + " - super: NSObject\n" expectEqual(expected, output) optionalURL!.release() } Reflection.test("TupleMirror/NoLeak") { do { nsObjectCanaryCount = 0 autoreleasepool { var tuple = (1, NSObjectCanary()) expectEqual(1, nsObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, nsObjectCanaryCount) } do { nsObjectCanaryCount = 0 autoreleasepool { var tuple = (1, NSObjectCanaryStruct()) expectEqual(1, nsObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, nsObjectCanaryCount) } do { swiftObjectCanaryCount = 0 autoreleasepool { var tuple = (1, SwiftObjectCanary()) expectEqual(1, swiftObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, swiftObjectCanaryCount) } do { swiftObjectCanaryCount = 0 autoreleasepool { var tuple = (1, SwiftObjectCanaryStruct()) expectEqual(1, swiftObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, swiftObjectCanaryCount) } } class TestArtificialSubclass: NSObject { dynamic var foo = "foo" } var KVOHandle = 0 Reflection.test("Name of metatype of artificial subclass") { let obj = TestArtificialSubclass() // Trigger the creation of a KVO subclass for TestArtificialSubclass. obj.addObserver(obj, forKeyPath: "foo", options: [.new], context: &KVOHandle) obj.removeObserver(obj, forKeyPath: "foo") expectEqual("\(type(of: obj))", "TestArtificialSubclass") } @objc class StringConvertibleInDebugAndOtherwise : NSObject { override var description: String { return "description" } override var debugDescription: String { return "debugDescription" } } Reflection.test("NSObject is properly CustomDebugStringConvertible") { let object = StringConvertibleInDebugAndOtherwise() expectEqual(String(reflecting: object), object.debugDescription) } Reflection.test("NSRange QuickLook") { let rng = NSRange(location:Int.min, length:5) let ql = PlaygroundQuickLook(reflecting: rng) switch ql { case .range(let loc, let len): expectEqual(loc, Int64(Int.min)) expectEqual(len, 5) default: expectUnreachable("PlaygroundQuickLook for NSRange did not match Range") } } class SomeSubclass : SomeClass {} var ObjCConformsToProtocolTestSuite = TestSuite("ObjCConformsToProtocol") ObjCConformsToProtocolTestSuite.test("cast/instance") { expectTrue(SomeClass() is SomeObjCProto) expectTrue(SomeSubclass() is SomeObjCProto) } ObjCConformsToProtocolTestSuite.test("cast/metatype") { expectTrue(SomeClass.self is SomeObjCProto.Type) expectTrue(SomeSubclass.self is SomeObjCProto.Type) } runAllTests()
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/24769-std-function-func-swift-type-subst.swift
1
440
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class c<U,C{class A{class a<T{enum S<T>:a
apache-2.0
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/Library/QToasterSwift.swift
1
8720
// // QToasterSwift.swift // QToasterSwift // // Created by Ahmad Athaullah on 6/30/16. // Copyright © 2016 Ahmad Athaullah. All rights reserved. // import UIKit public class QToasterSwift: NSObject { /** On touch action for your toaster, Default value: empty Void */ public var toastAction:()->Void = ({}) /** The alignment of text inside your toaster, Default value: NSTextAlignment.Center */ public var textAlignment:NSTextAlignment = NSTextAlignment.center /** Font type used for toaster title, Default value: UIFont.systemFontOfSize(11.0, weight: 0.8) */ public var titleFont = QToasterConfig.titleFont /** Font type used for toaster text, Default value: UIFont.systemFontOfSize(11.0) */ public var textFont = QToasterConfig.textFont /** Your toaster title, can be nil, Default value: nil */ public var titleText:String? /** Your toaster message, Default value : "" (empty string) */ public var text:String = "" /** Your toaster icon, can be nil, Default value : nil */ public var iconImage:UIImage? /** Your toaster url icon, can be nil, Default value : nil */ public var iconURL:String? /** Your toaster background color, Default value : UIColor(red: 0, green: 0, blue: 0, alpha: 0.8) */ public var backgroundColor = QToasterConfig.backgroundColor /** Your toaster background color, Default value : UIColor.whiteColor() */ public var textColor = QToasterConfig.textColor /** Your toaster animation duration using NSTimeInterval class, Default value : 0.2 */ public var animateDuration = QToasterConfig.animateDuration /** Your toaster delay duration before start to disappar, using NSTimeInterval class, Default value : 3.0 */ public var delayDuration = QToasterConfig.delayDuration /** Your toaster badge size (always square), using CGFloat class, Default value : 35.0 */ public var iconSquareSize = QToasterConfig.iconSquareSize /** Your toaster badge corner radius, using CGFloat class, if you want to set circle badge, just set it to half of your icon SquareSize Default value : 3.0 */ public var iconCornerRadius = QToasterConfig.iconCornerRadius /** Your toaster badge background color, using UIColor class, can only shown when using icon badge url without placeholder image Default value : UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) */ public var iconBackgroundColor = QToasterConfig.iconBackgroundColor /** Toast message inside your **QToasterSwift** object - Parameter target: The **UIViewController** where toaster will appear - Parameter onTouch: **()->Void** as onTouch action for your toaster */ public func toast(target: UIViewController, onTouch:@escaping ()->Void = ({})){ if text != "" { self.addAction(action: onTouch) if let previousToast = QToasterSwift.otherToastExist(target: target){ previousToast.removeFromSuperview() } let toasterView = QToasterView() toasterView.setupToasterView(toaster: self) var previousToast: QToasterView? if let lastToast = QToasterSwift.otherToastExist(target: target){ previousToast = lastToast } target.navigationController?.view.addSubview(toasterView) target.navigationController?.view.isUserInteractionEnabled = true if previousToast != nil { previousToast?.hide(completion: { toasterView.show() }) }else{ toasterView.show() } } } /** Class function to show toaster with configuration and without initiation. - parameter target: The **UIViewController** where toaster will appear. - parameter text: **String** message to show in toaster. - parameter title: **String** text to show as toaster title. - parameter iconURL: **String** URL of your icon toaster. - parameter iconPlaceHolder: **UIImage** to show as icon toaster when loading iconURL. - parameter backgroundColor: the **UIColor** as your toaster background color. - parameter textColor: the **UIColor** as your toaster text color. - parameter onTouch: **()->Void** as onTouch action for your toaster. */ public class func toast(target: UIViewController, text: String, title:String? = nil, iconURL:String? = nil, iconPlaceHolder:UIImage? = nil, backgroundColor:UIColor? = nil, textColor:UIColor? = nil, onTouch: @escaping ()->Void = ({})){ if text != "" { let toaster = QToasterSwift() toaster.text = text toaster.titleText = title toaster.iconURL = iconURL toaster.iconImage = iconPlaceHolder toaster.toastAction = onTouch if backgroundColor != nil { toaster.backgroundColor = backgroundColor! } if textColor != nil { toaster.textColor = textColor! } var previousToast: QToasterView? if let lastToast = QToasterSwift.otherToastExist(target: target){ previousToast = lastToast } let toastButton = QToasterView() toastButton.setupToasterView(toaster: toaster) target.navigationController?.view.addSubview(toastButton) target.navigationController?.view.isUserInteractionEnabled = true if previousToast != nil { previousToast?.hide(completion: { toastButton.show() }) }else{ toastButton.show() } } } /** Class function to show toaster with badge icon - parameter target: The **UIViewController** where toaster will appear. - parameter text: **String** message to show in toaster. - parameter title: **String** text to show as toaster title. - parameter icon: **UIImage** to show as badge icon toaster. - parameter backgroundColor: the **UIColor** as your toaster background color. - parameter textColor: the **UIColor** as your toaster text color. - parameter onTouch: **()->Void** as onTouch action for your toaster. */ public class func toastWithIcon(target: UIViewController, text: String, icon:UIImage?, title:String? = nil, backgroundColor:UIColor? = nil, textColor:UIColor? = nil, onTouch: @escaping ()->Void = ({})){ if text != "" { let toaster = QToasterSwift() toaster.text = text toaster.titleText = title toaster.iconImage = icon toaster.toastAction = onTouch var previousToast: QToasterView? if backgroundColor != nil { toaster.backgroundColor = backgroundColor! } if textColor != nil { toaster.textColor = textColor! } if let lastToast = QToasterSwift.otherToastExist(target: target){ previousToast = lastToast } let toastButton = QToasterView() toastButton.setupToasterView(toaster: toaster) target.navigationController?.view.addSubview(toastButton) target.navigationController?.view.isUserInteractionEnabled = true if previousToast != nil { previousToast?.hide(completion: { toastButton.show() }) }else{ toastButton.show() } } } /** Private methode executed on QToaster onTouch */ func touchAction(){ self.toastAction() } /** Add onTouch action to QToaster - parameter action: **()->Void** as onTouch action for your toaster. */ public func addAction(action:@escaping ()->Void){ self.toastAction = action } /** Private function helper to check if other QToaster is shown - parameter target: The **UIViewController** to check. - returns: **QToasterView** object if QToaster is exist and nil if not. */ class func otherToastExist(target: UIViewController) -> QToasterView?{ return target.navigationController?.view.viewWithTag(1313) as? QToasterView } }
mit
somedev/LocalNotificationScheduler
LocalNotificationScheduler/LocalNotificationScheduler/TimeOfDay.swift
1
1237
// // Created by Eduard Panasiuk on 1/4/16. // Copyright © 2016 somedev. All rights reserved. // import Foundation public struct TimeOfDay{ static private let timeConstant:TimeInterval = 60 static public let oneDayTimeInterval:TimeInterval = 24 * timeConstant * timeConstant private var _timeInterval:TimeInterval = 0 public var hour:Int { get {return Int(_timeInterval / (TimeOfDay.timeConstant * TimeOfDay.timeConstant))} } public var minute:Int { get {return Int((_timeInterval - TimeInterval(hour) * TimeOfDay.timeConstant * TimeOfDay.timeConstant) / TimeOfDay.timeConstant)} } public var second:Int { get {return Int(_timeInterval - TimeInterval(hour) * TimeOfDay.timeConstant * TimeOfDay.timeConstant - TimeInterval(minute) * TimeOfDay.timeConstant)} } public var timeInterval:TimeInterval{ get {return _timeInterval} } public init(hours:Int = 0, minutes:Int = 0, seconds:Int = 0){ _timeInterval = 0 _timeInterval += TimeInterval(hours) * TimeOfDay.timeConstant * TimeOfDay.timeConstant _timeInterval += TimeInterval(minutes) * TimeOfDay.timeConstant _timeInterval += TimeInterval(seconds) } }
mit
radical-experiments/AIMES-Swift
viveks_workflow/data.04.00128.004/vivek.swift
10
6521
type file; int N = 128; int chunk_size = 8; # chunksize for stage 3 int n_chunks = 16; # number of chunks int verb = 1; # ----------------------------------------------------------------------------- # # Stage 1 # app (file output_1_1_i, file output_1_2_i, file output_1_3_i) stage_1 (int i, file input_shared_1_1, file input_shared_1_2, file input_shared_1_3, file input_shared_1_4, file input_shared_1_5) { stage_1_exe i filename(input_shared_1_1) filename(input_shared_1_2) filename(input_shared_1_3) filename(input_shared_1_4) filename(input_shared_1_5); } file input_shared_1_1 <"input_shared_1_1.txt">; file input_shared_1_2 <"input_shared_1_2.txt">; file input_shared_1_3 <"input_shared_1_3.txt">; file input_shared_1_4 <"input_shared_1_4.txt">; file input_shared_1_5 <"input_shared_1_5.txt">; file output_1_1[]; file output_1_2[]; file output_1_3[]; foreach i in [1:N] { file output_1_1_i <single_file_mapper; file=strcat("output_1_1_",i,".txt")>; file output_1_2_i <single_file_mapper; file=strcat("output_1_2_",i,".txt")>; file output_1_3_i <single_file_mapper; file=strcat("output_1_3_",i,".txt")>; if (verb == 1) { tracef("trace stage 1: %d : %s : %s : %s : %s : %s -> %s : %s : %s\n", i, filename(input_shared_1_1), filename(input_shared_1_2), filename(input_shared_1_3), filename(input_shared_1_4), filename(input_shared_1_5), filename(output_1_1_i), filename(output_1_2_i), filename(output_1_3_i)); } (output_1_1_i, output_1_2_i, output_1_3_i) = stage_1(i, input_shared_1_1, input_shared_1_2, input_shared_1_3, input_shared_1_4, input_shared_1_5); output_1_1[i] = output_1_1_i; output_1_2[i] = output_1_2_i; output_1_3[i] = output_1_3_i; } # ----------------------------------------------------------------------------- # # Stage 2 # app (file output_2_1_i, file output_2_2_i, file output_2_3_i, file output_2_4_i) stage_2 (int i, file input_shared_1_3, file input_shared_1_4, file output_1_1_i) { stage_2_exe i filename(input_shared_1_3) filename(input_shared_1_4) filename(output_1_1_i); } file output_2_1[]; file output_2_2[]; file output_2_3[]; file output_2_4[]; foreach i in [1:N] { file output_2_1_i <single_file_mapper; file=strcat("output_2_1_",i,".txt")>; file output_2_2_i <single_file_mapper; file=strcat("output_2_2_",i,".txt")>; file output_2_3_i <single_file_mapper; file=strcat("output_2_3_",i,".txt")>; file output_2_4_i <single_file_mapper; file=strcat("output_2_4_",i,".txt")>; if (verb == 1) { tracef("trace stage 2: %d : %s : %s : %s -> %s : %s : %s : %s\n", i, filename(input_shared_1_3), filename(input_shared_1_4), filename(output_1_1[i]), filename(output_2_1_i), filename(output_2_2_i), filename(output_2_3_i), filename(output_2_4_i)); } (output_2_1_i, output_2_2_i, output_2_3_i, output_2_4_i) = stage_2(i, input_shared_1_3, input_shared_1_4, output_1_1[i]); output_2_1[i] = output_2_1_i; output_2_2[i] = output_2_2_i; output_2_3[i] = output_2_3_i; output_2_4[i] = output_2_4_i; } # ----------------------------------------------------------------------------- # # Stage 3 # app (file[] output_3_1) stage_3 (int chunk, int chunksize, file input_shared_1_3, file[] output_2_2) { # N cores stage_3_exe chunk chunksize filename(input_shared_1_3) @output_2_2; } # we run stage_3 in chunks of C cores each, so we nee dto subdivide the file # list into such chunks # string[] output_3_1_s; # output files for all chunks # foreach i in [1:N] { # output_3_1_s[i] = strcat("output_3_1_",i,".txt"); # } file[] output_3_1; # over all chunks foreach c in [0:(n_chunks-1)] { # file lists for chunk file[] output_2_2_c; # input files for this chunk string[] output_3_1_c_s; # output files for this chunk # over all chunk elements foreach i in [1:chunk_size] { # global index int j = c*chunk_size + i; output_2_2_c[i] = output_2_2[j]; output_3_1_c_s[i] = strcat("output_3_1_",j,".txt"); } # convert into file sets file[] output_3_1_c <array_mapper; files=output_3_1_c_s>; # run this chunk if (verb == 1) { tracef("stage 3: %d : %s : %s -> %s", c, filename(input_shared_1_3), strjoin(output_2_2_c, " "), strjoin(output_3_1_c_s, " ")); } output_3_1_c = stage_3(c, chunk_size, input_shared_1_3, output_2_2_c); # now merge the received files from the chunk into the global thing foreach i in [1:chunk_size] { # global index int j = c*chunk_size + i; output_3_1[j] = output_3_1_c[i]; } } # ----------------------------------------------------------------------------- # # Stage 4 # app (file output_4_1) stage_4 (file input_shared_1_5, file[] output_3_1) { # 1 core stage_4_exe filename(input_shared_1_5) @output_3_1; } if (1 == 1) { file output_4_1 <"output_4_1.txt">; if (verb == 1) { tracef("stage 4: %s : %s -> %s", filename(input_shared_1_5), @output_3_1, filename(output_4_1)); } output_4_1 = stage_4(input_shared_1_5, output_3_1); } # -----------------------------------------------------------------------------
mit
adrfer/swift
validation-test/compiler_crashers_fixed/25561-swift-diagnosticengine-flushactivediagnostic.swift
13
276
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{enum b<T where g:a{struct A{enum A:b=protocol a{}var B
apache-2.0
AV8R-/SwiftUtils
UIView+Constrain.swift
1
1587
// // UIView+Constrain.swift // Jobok // // Created by Bogdan Manshilin on 26.04.17. // Copyright © 2017 Jobok. All rights reserved. // import UIKit enum UIError: Error { case noSuperview } enum UIViewBounds { case top(CGFloat), left(CGFloat), bottom(CGFloat), right(CGFloat) func constrain(view: UIView, to: UIView) { switch self { case let .top(constant): view.topAnchor.constraint(equalTo: to.topAnchor, constant: constant).isActive = true case let .left(constant): view.leadingAnchor.constraint(equalTo: to.leadingAnchor, constant: constant).isActive = true case let .bottom(constant): view.bottomAnchor.constraint(equalTo: to.bottomAnchor, constant: -constant).isActive = true case let .right(constant): view.trailingAnchor.constraint(equalTo: to.trailingAnchor, constant: -constant).isActive = true } } } extension UIViewBounds { static let topMargin = UIViewBounds.top(0) static let leftMargin = UIViewBounds.left(0) static let bottomMargin = UIViewBounds.bottom(0) static let rightMargin = UIViewBounds.right(0) } extension UIView { func constrainSuperview(bounds: UIViewBounds...) throws { guard let superview = superview else { throw UIError.noSuperview } var bounds = bounds if bounds.count == 0 { bounds = [.topMargin, .leftMargin, .bottomMargin, .rightMargin] } translatesAutoresizingMaskIntoConstraints = false bounds.forEach { $0.constrain(view: self, to: superview) } } }
mit
lanit-tercom-school/grouplock
GroupLockiOS/GroupLock/Scenes/Home_Stack/NumberOfKeysScene/NumberOfKeysInteractor.swift
1
638
// // NumberOfKeysInteractor.swift // GroupLock // // Created by Sergej Jaskiewicz on 20.07.16. // Copyright (c) 2016 Lanit-Tercom School. All rights reserved. // import Foundation protocol NumberOfKeysInteractorInput { var numberOfKeys: Int { get } var files: [File] { get } } protocol NumberOfKeysInteractorOutput { } class NumberOfKeysInteractor: NumberOfKeysInteractorInput { var output: NumberOfKeysInteractorOutput! var cryptoLibrary: CryptoWrapperProtocol = CryptoFake() // MARK: - Business logic var numberOfKeys: Int { return cryptoLibrary.maximumNumberOfKeys } var files: [File] = [] }
apache-2.0
Vaseltior/SFCore
SFCoreTests/SFQueueTests.swift
1
1337
// // SFQueueTests.swift // SFCore // // Created by Samuel Grau on 10/04/2016. // Copyright © 2016 Samuel Grau. All rights reserved. // import XCTest @testable import SFCore class SFQueueTests: XCTestCase { var queue3: SFQueue<String>! var queue4: SFQueue<String>! override func setUp() { super.setUp() self.queue3 = SFQueue<String>() self.queue4 = SFQueue<String>() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testFIFO() { self.queue4.enQueue("Dave Dee") self.queue4.enQueue("Dozy") self.queue4.enQueue("Beaky") XCTAssertEqual(self.queue4.deQueue(), "Dave Dee") XCTAssertEqual(self.queue4.deQueue(), "Dozy") XCTAssertEqual(self.queue4.deQueue(), "Beaky") } func testNilDequeue() { XCTAssertTrue(self.queue4.isEmpty()) XCTAssertNil(self.queue4.peek()) XCTAssertNil(self.queue4.deQueue()) XCTAssertTrue(self.queue4.isEmpty()) } func testNotNilDequeue() { self.queue4.enQueue("Dave Dee") self.queue4.enQueue("Dozy") self.queue4.enQueue("Beaky") XCTAssertFalse(self.queue4.isEmpty()) XCTAssertNotNil(self.queue4.peek()) XCTAssertNotNil(self.queue4.deQueue()) XCTAssertFalse(self.queue4.isEmpty()) } }
mit
nathantannar4/NTComponents
NTComponents/UI Kit/Table/NTTableView.swift
1
1750
// // NTTableView.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 2/12/17. // import UIKit public class NTTableView: UITableView { public weak var imageDataSource: NTTableViewImageDataSource? public init() { super.init(frame: .zero, style: .plain) self.backgroundColor = UIColor.clear self.rowHeight = UITableViewAutomaticDimension self.estimatedRowHeight = 44 self.register(NTTableViewCell.self, forCellReuseIdentifier: "NTTableViewCell") } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
Alchemistxxd/AXStylishNavigationBar
CarPro/RenditionCollectionViewController.swift
1
1248
// // RenditionCollectionViewController.swift // Final Car Pro // // Created by Xudong Xu on 1/12/21. // import Cocoa class RenditionCollectionViewController: NSViewController { private struct Layout { static let width: CGFloat = 100 static let height: CGFloat = 120 static let minimumInteritemSpacing: CGFloat = 20 static let minimumLineSpacing: CGFloat = 20 } @IBOutlet var collectionView: NSCollectionView! { didSet { let nib = NSNib(nibNamed: RenditionViewItem.nibName, bundle: nil) collectionView.register(nib, forItemWithIdentifier: .renditionItem) collectionView.collectionViewLayout = .flowLayout( width: Layout.width, height: Layout.height, minimumInteritemSpacing: Layout.minimumInteritemSpacing, minimumLineSpacing: Layout.minimumLineSpacing ) } } var dataProvider: (NSCollectionViewDataSource & NSCollectionViewDelegate)! { didSet { collectionView.dataSource = dataProvider collectionView.delegate = dataProvider } } override func viewDidLoad() { super.viewDidLoad() } }
mit
grantjbutler/Artikolo
ArtikoloKit/DataManager.swift
1
881
// // DataManager.swift // Artikolo // // Created by Grant Butler on 4/30/17. // Copyright © 2017 Grant Butler. All rights reserved. // import Foundation import RxSwift public protocol DataManagerBackend { var articles: Observable<[Article]> { get } var tags: Observable<[Tag]> { get } func save(article: Article) func reset() throws } public class DataManager { public let backend: DataManagerBackend public var articles: Observable<[Article]> { return backend.articles } public var tags: Observable<[Tag]> { return backend.tags } public init(backend: DataManagerBackend) { self.backend = backend } public func save(article: Article) { backend.save(article: article) } public func reset() throws { try backend.reset() } }
mit
shamanskyh/FluidQ
Shared Models/Instrument.swift
1
16920
// // Instrument.swift // FluidQ // // Created by Harry Shamansky on 11/10/15. // Modified from Precircuiter: https://github.com/shamanskyh/Precircuiter // Copyright © 2015 Harry Shamansky. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif // MARK: - Enumerations enum DeviceType: Int { case Light case MovingLight case Accessory case StaticAccessory case Device case Practical case SFX case Power case Other var description: String { switch self { case Light: return "Light" case MovingLight: return "MovingLight" case Accessory: return "Accessory" case StaticAccessory: return "StaticAccessory" case Device: return "Device" case Practical: return "Practical" case SFX: return "SFX" case Power: return "Power" case Other: return "Other" } } } enum Dimension { case X case Y case Z } // MARK: - Structs struct Coordinate { var x: Double var y: Double var z: Double init(xPos: Double, yPos: Double, zPos: Double) { x = xPos y = yPos z = zPos } } // MARK: - Instrument Class class Instrument: NSObject, NSCoding { var deviceType: DeviceType? = nil var instrumentType: String? = nil var wattage: String? = nil var purpose: String? = nil var position: String? = nil var unitNumber: String? = nil var color: String? = nil var dimmer: String? = nil var channel: Int? = nil var address: String? = nil var universe: String? = nil var uAddress: String? = nil var uDimmer: String? = nil var circuitNumber: String? = nil var circuitName: String? = nil var system: String? = nil var userField1: String? = nil var userField2: String? = nil var userField3: String? = nil var userField4: String? = nil var userField5: String? = nil var userField6: String? = nil var numChannels: String? = nil var frameSize: String? = nil var fieldAngle: String? = nil var fieldAngle2: String? = nil var beamAngle: String? = nil var beamAngle2: String? = nil var weight: String? = nil var gobo1: String? = nil var gobo1Rotation: String? = nil var gobo2: String? = nil var gobo2Rotation: String? = nil var goboShift: String? = nil var mark: String? = nil var drawBeam: Bool? = nil var drawBeamAs3DSolid: Bool? = nil var useVerticalBeam: Bool? = nil var showBeamAt: String? = nil var falloffDistance: String? = nil var lampRotationAngle: String? = nil var topShutterDepth: String? = nil var topShutterAngle: String? = nil var leftShutterDepth: String? = nil var leftShutterAngle: String? = nil var rightShutterDepth: String? = nil var rightShutterAngle: String? = nil var bottomShutterDepth: String? = nil var bottomShutterAngle: String? = nil var symbolName: String? = nil var useLegend: Bool? = nil var flipFrontBackLegendText: Bool? = nil var flipLeftRightLegendText: Bool? = nil var focus: String? = nil var set3DOrientation: Bool? = nil var xRotation: String? = nil var yRotation: String? = nil var location: Coordinate? = nil var rawXLocation: String? = nil var rawYLocation: String? = nil var rawZLocation: String? = nil var fixtureID: String? = nil var UID: String var accessories: String? = nil // MARK: Swatch Color private var savedSwatchColor: CGColor? private var isClearColor: Bool { return color?.stringByTrimmingCharactersInSet(.whitespaceCharacterSet()) == "N/C" || color?.stringByTrimmingCharactersInSet(.whitespaceCharacterSet()) == "NC" } internal var needsNewSwatchColor = false internal var swatchColor: CGColor? { if (savedSwatchColor == nil && color != nil) || needsNewSwatchColor { needsNewSwatchColor = false if let color = self.color?.toGelColor() { savedSwatchColor = color } else { savedSwatchColor = nil } } return savedSwatchColor } required init(UID: String?, location: Coordinate?) { if let id = UID { self.UID = id } else { self.UID = "" } self.location = location } // MARK: - NSCoding Protocol Conformance required init(coder aDecoder: NSCoder) { deviceType = DeviceType(rawValue: aDecoder.decodeIntegerForKey("deviceType")) instrumentType = aDecoder.decodeObjectForKey("instrumentType") as? String wattage = aDecoder.decodeObjectForKey("wattage") as? String purpose = aDecoder.decodeObjectForKey("purpose") as? String position = aDecoder.decodeObjectForKey("position") as? String unitNumber = aDecoder.decodeObjectForKey("unitNumber") as? String color = aDecoder.decodeObjectForKey("color") as? String dimmer = aDecoder.decodeObjectForKey("dimmer") as? String channel = aDecoder.decodeIntegerForKey("channel") address = aDecoder.decodeObjectForKey("address") as? String universe = aDecoder.decodeObjectForKey("universe") as? String uAddress = aDecoder.decodeObjectForKey("uAddress") as? String uDimmer = aDecoder.decodeObjectForKey("uDimmer") as? String circuitNumber = aDecoder.decodeObjectForKey("circuitNumber") as? String circuitName = aDecoder.decodeObjectForKey("circuitName") as? String system = aDecoder.decodeObjectForKey("system") as? String userField1 = aDecoder.decodeObjectForKey("userField1") as? String userField2 = aDecoder.decodeObjectForKey("userField2") as? String userField3 = aDecoder.decodeObjectForKey("userField3") as? String userField4 = aDecoder.decodeObjectForKey("userField4") as? String userField5 = aDecoder.decodeObjectForKey("userField5") as? String userField6 = aDecoder.decodeObjectForKey("userField6") as? String numChannels = aDecoder.decodeObjectForKey("numChannels") as? String frameSize = aDecoder.decodeObjectForKey("frameSize") as? String fieldAngle = aDecoder.decodeObjectForKey("fieldAngle") as? String fieldAngle2 = aDecoder.decodeObjectForKey("fieldAngle2") as? String beamAngle = aDecoder.decodeObjectForKey("beamAngle") as? String beamAngle2 = aDecoder.decodeObjectForKey("beamAngle2") as? String weight = aDecoder.decodeObjectForKey("weight") as? String gobo1 = aDecoder.decodeObjectForKey("gobo1") as? String gobo1Rotation = aDecoder.decodeObjectForKey("gobo1Rotation") as? String gobo2 = aDecoder.decodeObjectForKey("gobo2") as? String gobo2Rotation = aDecoder.decodeObjectForKey("gobo2Rotation") as? String goboShift = aDecoder.decodeObjectForKey("goboShift") as? String mark = aDecoder.decodeObjectForKey("mark") as? String drawBeam = aDecoder.decodeBoolForKey("drawBeam") drawBeamAs3DSolid = aDecoder.decodeBoolForKey("drawBeamAs3DSolid") useVerticalBeam = aDecoder.decodeBoolForKey("useVerticalBeam") showBeamAt = aDecoder.decodeObjectForKey("showBeamAt") as? String falloffDistance = aDecoder.decodeObjectForKey("falloffDistance") as? String lampRotationAngle = aDecoder.decodeObjectForKey("lampRotationAngle") as? String topShutterDepth = aDecoder.decodeObjectForKey("topShutterDepth") as? String topShutterAngle = aDecoder.decodeObjectForKey("topShutterAngle") as? String leftShutterDepth = aDecoder.decodeObjectForKey("leftShutterDepth") as? String leftShutterAngle = aDecoder.decodeObjectForKey("leftShutterAngle") as? String rightShutterDepth = aDecoder.decodeObjectForKey("rightShutterDepth") as? String rightShutterAngle = aDecoder.decodeObjectForKey("rightShutterAngle") as? String bottomShutterDepth = aDecoder.decodeObjectForKey("bottomShutterDepth") as? String bottomShutterAngle = aDecoder.decodeObjectForKey("bottomShutterAngle") as? String symbolName = aDecoder.decodeObjectForKey("symbolName") as? String useLegend = aDecoder.decodeBoolForKey("useLegend") flipFrontBackLegendText = aDecoder.decodeBoolForKey("flipFrontBackLegendText") flipLeftRightLegendText = aDecoder.decodeBoolForKey("flipLeftRightLegendText") focus = aDecoder.decodeObjectForKey("focus") as? String set3DOrientation = aDecoder.decodeBoolForKey("set3DOrientation") xRotation = aDecoder.decodeObjectForKey("xRotation") as? String yRotation = aDecoder.decodeObjectForKey("yRotation") as? String location = Coordinate(xPos: aDecoder.decodeDoubleForKey("convertedXLocation"), yPos: aDecoder.decodeDoubleForKey("convertedYLocation"), zPos: aDecoder.decodeDoubleForKey("convertedZLocation")) rawXLocation = aDecoder.decodeObjectForKey("rawXLocation") as? String rawYLocation = aDecoder.decodeObjectForKey("rawYLocation") as? String rawZLocation = aDecoder.decodeObjectForKey("rawZLocation") as? String fixtureID = aDecoder.decodeObjectForKey("fixtureID") as? String UID = aDecoder.decodeObjectForKey("UID") as! String accessories = aDecoder.decodeObjectForKey("accessories") as? String } func encodeWithCoder(aCoder: NSCoder) { if let devType = deviceType { aCoder.encodeInteger(devType.rawValue, forKey: "deviceType") } aCoder.encodeObject(instrumentType, forKey: "instrumentType") aCoder.encodeObject(wattage, forKey: "wattage") aCoder.encodeObject(purpose, forKey: "purpose") aCoder.encodeObject(position, forKey: "position") aCoder.encodeObject(unitNumber, forKey: "unitNumber") aCoder.encodeObject(color, forKey: "color") aCoder.encodeObject(dimmer, forKey: "dimmer") if let chan = channel { aCoder.encodeInteger(chan, forKey: "channel") } aCoder.encodeObject(address, forKey: "address") aCoder.encodeObject(universe, forKey: "universe") aCoder.encodeObject(uAddress, forKey: "uAddress") aCoder.encodeObject(uDimmer, forKey: "uDimmer") aCoder.encodeObject(circuitNumber, forKey: "circuitNumber") aCoder.encodeObject(circuitName, forKey: "circuitName") aCoder.encodeObject(system, forKey: "system") aCoder.encodeObject(userField1, forKey: "userField1") aCoder.encodeObject(userField2, forKey: "userField2") aCoder.encodeObject(userField3, forKey: "userField3") aCoder.encodeObject(userField4, forKey: "userField4") aCoder.encodeObject(userField5, forKey: "userField5") aCoder.encodeObject(userField6, forKey: "userField6") aCoder.encodeObject(numChannels, forKey: "numChannels") aCoder.encodeObject(frameSize, forKey: "frameSize") aCoder.encodeObject(fieldAngle, forKey: "fieldAngle") aCoder.encodeObject(fieldAngle2, forKey: "fieldAngle2") aCoder.encodeObject(beamAngle, forKey: "beamAngle") aCoder.encodeObject(beamAngle2, forKey: "beamAngle2") aCoder.encodeObject(weight, forKey: "weight") aCoder.encodeObject(gobo1, forKey: "gobo1") aCoder.encodeObject(gobo1Rotation, forKey: "gobo1Rotation") aCoder.encodeObject(gobo2, forKey: "gobo2") aCoder.encodeObject(gobo2Rotation, forKey: "gobo2Rotation") aCoder.encodeObject(goboShift, forKey: "goboShift") aCoder.encodeObject(mark, forKey: "mark") aCoder.encodeObject(showBeamAt, forKey: "showBeamAt") aCoder.encodeObject(falloffDistance, forKey: "falloffDistance") aCoder.encodeObject(lampRotationAngle, forKey: "lampRotationAngle") aCoder.encodeObject(topShutterDepth, forKey: "topShutterDepth") aCoder.encodeObject(topShutterAngle, forKey: "topShutterAngle") aCoder.encodeObject(leftShutterDepth, forKey: "leftShutterDepth") aCoder.encodeObject(leftShutterAngle, forKey: "leftShutterAngle") aCoder.encodeObject(rightShutterDepth, forKey: "rightShutterDepth") aCoder.encodeObject(rightShutterAngle, forKey: "rightShutterAngle") aCoder.encodeObject(bottomShutterDepth, forKey: "bottomShutterDepth") aCoder.encodeObject(bottomShutterAngle, forKey: "bottomShutterAngle") aCoder.encodeObject(symbolName, forKey: "symbolName") aCoder.encodeObject(focus, forKey: "focus") aCoder.encodeObject(xRotation, forKey: "xRotation") aCoder.encodeObject(yRotation, forKey: "yRotation") if let l = location { aCoder.encodeDouble(l.x, forKey: "convertedXLocation") aCoder.encodeDouble(l.y, forKey: "convertedYLocation") aCoder.encodeDouble(l.z, forKey: "convertedZLocation") } aCoder.encodeObject(rawXLocation, forKey: "rawXLocation") aCoder.encodeObject(rawYLocation, forKey: "rawYLocation") aCoder.encodeObject(rawZLocation, forKey: "rawZLocation") aCoder.encodeObject(fixtureID, forKey: "fixtureID") aCoder.encodeObject(UID, forKey: "UID") aCoder.encodeObject(accessories, forKey: "accessories") } func addCoordinateToLocation(type: Dimension, value: String) throws { var coord = self.location if coord == nil { coord = Coordinate(xPos: 0.0, yPos: 0.0, zPos: 0.0) } var convertedValue: Double = 0.0; do { try convertedValue = value.unknownUnitToMeters() } catch { throw InstrumentError.UnrecognizedCoordinate } switch type { case .X: coord!.x = convertedValue case .Y: coord!.y = convertedValue case .Z: coord!.z = convertedValue } self.location = coord! } } // MARK: - NSCopying Protocol Conformance extension Instrument: NSCopying { func copyWithZone(zone: NSZone) -> AnyObject { let copy = self.dynamicType.init(UID: self.UID, location: self.location) copy.deviceType = self.deviceType copy.instrumentType = self.instrumentType copy.wattage = self.wattage copy.purpose = self.purpose copy.position = self.position copy.unitNumber = self.unitNumber copy.color = self.color copy.dimmer = self.dimmer copy.channel = self.channel copy.address = self.address copy.universe = self.universe copy.uAddress = self.uAddress copy.uDimmer = self.uDimmer copy.circuitNumber = self.circuitNumber copy.circuitName = self.circuitName copy.system = self.system copy.userField1 = self.userField1 copy.userField2 = self.userField2 copy.userField3 = self.userField3 copy.userField4 = self.userField4 copy.userField5 = self.userField5 copy.userField6 = self.userField6 copy.numChannels = self.numChannels copy.frameSize = self.frameSize copy.fieldAngle = self.fieldAngle copy.fieldAngle2 = self.fieldAngle2 copy.beamAngle = self.beamAngle copy.beamAngle2 = self.beamAngle2 copy.weight = self.weight copy.gobo1 = self.gobo1 copy.gobo1Rotation = self.gobo1Rotation copy.gobo2 = self.gobo2 copy.gobo2Rotation = self.gobo2Rotation copy.goboShift = self.goboShift copy.mark = self.mark copy.drawBeam = self.drawBeam copy.drawBeamAs3DSolid = self.drawBeamAs3DSolid copy.useVerticalBeam = self.useVerticalBeam copy.showBeamAt = self.showBeamAt copy.falloffDistance = self.falloffDistance copy.lampRotationAngle = self.lampRotationAngle copy.topShutterDepth = self.topShutterDepth copy.topShutterAngle = self.topShutterAngle copy.leftShutterDepth = self.leftShutterDepth copy.leftShutterAngle = self.leftShutterAngle copy.rightShutterDepth = self.rightShutterDepth copy.rightShutterAngle = self.rightShutterAngle copy.bottomShutterDepth = self.bottomShutterDepth copy.bottomShutterAngle = self.bottomShutterAngle copy.symbolName = self.symbolName copy.useLegend = self.useLegend copy.flipFrontBackLegendText = self.flipFrontBackLegendText copy.flipLeftRightLegendText = self.flipLeftRightLegendText copy.focus = self.focus copy.set3DOrientation = self.set3DOrientation copy.xRotation = self.xRotation copy.yRotation = self.yRotation copy.rawXLocation = self.rawXLocation copy.rawYLocation = self.rawYLocation copy.rawZLocation = self.rawZLocation copy.fixtureID = self.fixtureID copy.accessories = self.accessories return copy } }
mit
yasuoza/graphPON
graphPON iOS/Views/ChartViewContainerView.swift
1
312
import UIKit import JBChartFramework class ChartViewContainerView: UIView { @IBOutlet weak var chartView: JBChartView! override func layoutSubviews() { super.layoutSubviews() self.chartView.reloadData() } func reloadChartData() { self.chartView.reloadData() } }
mit
dleonard00/firebase-user-signup
Pods/Material/Sources/TextField.swift
1
19127
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public protocol TextFieldDelegate : UITextFieldDelegate {} public class TextField : UITextField { /** This property is the same as clipsToBounds. It crops any of the view's contents from bleeding past the view's frame. */ public var masksToBounds: Bool { get { return layer.masksToBounds } set(value) { layer.masksToBounds = value } } /// A property that accesses the backing layer's backgroundColor. public override var backgroundColor: UIColor? { didSet { layer.backgroundColor = backgroundColor?.CGColor } } /// A property that accesses the layer.frame.origin.x property. public var x: CGFloat { get { return layer.frame.origin.x } set(value) { layer.frame.origin.x = value } } /// A property that accesses the layer.frame.origin.y property. public var y: CGFloat { get { return layer.frame.origin.y } set(value) { layer.frame.origin.y = value } } /** A property that accesses the layer.frame.origin.width property. When setting this property in conjunction with the shape property having a value that is not .None, the height will be adjusted to maintain the correct shape. */ public var width: CGFloat { get { return layer.frame.size.width } set(value) { layer.frame.size.width = value if .None != shape { layer.frame.size.height = value } } } /** A property that accesses the layer.frame.origin.height property. When setting this property in conjunction with the shape property having a value that is not .None, the width will be adjusted to maintain the correct shape. */ public var height: CGFloat { get { return layer.frame.size.height } set(value) { layer.frame.size.height = value if .None != shape { layer.frame.size.width = value } } } /// A property that accesses the backing layer's shadowColor. public var shadowColor: UIColor? { didSet { layer.shadowColor = shadowColor?.CGColor } } /// A property that accesses the backing layer's shadowOffset. public var shadowOffset: CGSize { get { return layer.shadowOffset } set(value) { layer.shadowOffset = value } } /// A property that accesses the backing layer's shadowOpacity. public var shadowOpacity: Float { get { return layer.shadowOpacity } set(value) { layer.shadowOpacity = value } } /// A property that accesses the backing layer's shadowRadius. public var shadowRadius: CGFloat { get { return layer.shadowRadius } set(value) { layer.shadowRadius = value } } /// A property that accesses the backing layer's shadowPath. public var shadowPath: CGPath? { get { return layer.shadowPath } set(value) { layer.shadowPath = value } } /// Enables automatic shadowPath sizing. public var shadowPathAutoSizeEnabled: Bool = true { didSet { if shadowPathAutoSizeEnabled { layoutShadowPath() } else { shadowPath = nil } } } /** A property that sets the shadowOffset, shadowOpacity, and shadowRadius for the backing layer. This is the preferred method of setting depth in order to maintain consitency across UI objects. */ public var depth: MaterialDepth = .None { didSet { let value: MaterialDepthType = MaterialDepthToValue(depth) shadowOffset = value.offset shadowOpacity = value.opacity shadowRadius = value.radius layoutShadowPath() } } /** A property that sets the cornerRadius of the backing layer. If the shape property has a value of .Circle when the cornerRadius is set, it will become .None, as it no longer maintains its circle shape. */ public var cornerRadiusPreset: MaterialRadius = .None { didSet { if let v: MaterialRadius = cornerRadiusPreset { cornerRadius = MaterialRadiusToValue(v) } } } /// A property that accesses the layer.cornerRadius. public var cornerRadius: CGFloat { get { return layer.cornerRadius } set(value) { layer.cornerRadius = value layoutShadowPath() if .Circle == shape { shape = .None } } } /** A property that manages the overall shape for the object. If either the width or height property is set, the other will be automatically adjusted to maintain the shape of the object. */ public var shape: MaterialShape = .None { didSet { if .None != shape { if width < height { frame.size.width = height } else { frame.size.height = width } layoutShadowPath() } } } /// A preset property to set the borderWidth. public var borderWidthPreset: MaterialBorder = .None { didSet { borderWidth = MaterialBorderToValue(borderWidthPreset) } } /// A property that accesses the layer.borderWith. public var borderWidth: CGFloat { get { return layer.borderWidth } set(value) { layer.borderWidth = value } } /// A property that accesses the layer.borderColor property. public var borderColor: UIColor? { get { return nil == layer.borderColor ? nil : UIColor(CGColor: layer.borderColor!) } set(value) { layer.borderColor = value?.CGColor } } /// A property that accesses the layer.position property. public var position: CGPoint { get { return layer.position } set(value) { layer.position = value } } /// A property that accesses the layer.zPosition property. public var zPosition: CGFloat { get { return layer.zPosition } set(value) { layer.zPosition = value } } /// The UIImage for the clear icon. public var clearButton: UIButton? { didSet { if let v: UIButton = clearButton { clearButtonMode = .Never rightViewMode = .WhileEditing v.contentEdgeInsets = UIEdgeInsetsZero v.addTarget(self, action: "handleClearButton", forControlEvents: .TouchUpInside) } else { clearButtonMode = .WhileEditing rightViewMode = .Never } rightView = clearButton reloadView() } } /// The bottom border layer. public private(set) lazy var bottomBorderLayer: CAShapeLayer = CAShapeLayer() /** A property that sets the distance between the textField and bottomBorderLayer. */ public var bottomBorderLayerDistance: CGFloat = 4 /** The title UILabel that is displayed when there is text. The titleLabel text value is updated with the placeholder text value before being displayed. */ public var titleLabel: UILabel? { didSet { prepareTitleLabel() } } /// The color of the titleLabel text when the textField is not active. public var titleLabelColor: UIColor? { didSet { titleLabel?.textColor = titleLabelColor MaterialAnimation.animationDisabled { [unowned self] in self.bottomBorderLayer.backgroundColor = self.titleLabelColor?.CGColor } } } /// The color of the titleLabel text when the textField is active. public var titleLabelActiveColor: UIColor? /** A property that sets the distance between the textField and titleLabel. */ public var titleLabelAnimationDistance: CGFloat = 8 /// An override to the text property. public override var text: String? { didSet { textFieldDidChange() } } /** The detail UILabel that is displayed when the detailLabelHidden property is set to false. */ public var detailLabel: UILabel? { didSet { prepareDetailLabel() } } /** The color of the detailLabel text when the detailLabelHidden property is set to false. */ public var detailLabelActiveColor: UIColor? { didSet { if !detailLabelHidden { detailLabel?.textColor = detailLabelActiveColor MaterialAnimation.animationDisabled { [unowned self] in self.bottomBorderLayer.backgroundColor = self.detailLabelActiveColor?.CGColor } } } } /** A property that sets the distance between the textField and detailLabel. */ public var detailLabelAnimationDistance: CGFloat = 8 /** A Boolean that indicates the detailLabel should hide automatically when text changes. */ public var detailLabelAutoHideEnabled: Bool = true /** :name: detailLabelHidden */ public var detailLabelHidden: Bool = true { didSet { if detailLabelHidden { detailLabel?.textColor = titleLabelColor MaterialAnimation.animationDisabled { [unowned self] in self.bottomBorderLayer.backgroundColor = self.editing ? self.titleLabelActiveColor?.CGColor : self.titleLabelColor?.CGColor } hideDetailLabel() } else { detailLabel?.textColor = detailLabelActiveColor MaterialAnimation.animationDisabled { [unowned self] in self.bottomBorderLayer.backgroundColor = self.detailLabelActiveColor?.CGColor } showDetailLabel() } } } /// A wrapper for searchBar.placeholder. public override var placeholder: String? { didSet { if let v: String = placeholder { attributedPlaceholder = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: placeholderTextColor]) } } } /// Placeholder textColor. public var placeholderTextColor: UIColor = MaterialColor.black { didSet { if let v: String = placeholder { attributedPlaceholder = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: placeholderTextColor]) } } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareView() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) prepareView() } /// A convenience initializer. public convenience init() { self.init(frame: CGRectNull) } /// Overriding the layout callback for sublayers. public override func layoutSublayersOfLayer(layer: CALayer) { super.layoutSublayersOfLayer(layer) if self.layer == layer { bottomBorderLayer.frame = CGRectMake(0, bounds.height + bottomBorderLayerDistance, bounds.width, 1) layoutShape() layoutShadowPath() } } /** A method that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ public func animate(animation: CAAnimation) { animation.delegate = self if let a: CABasicAnimation = animation as? CABasicAnimation { a.fromValue = (nil == layer.presentationLayer() ? layer : layer.presentationLayer() as! CALayer).valueForKeyPath(a.keyPath!) } if let a: CAPropertyAnimation = animation as? CAPropertyAnimation { layer.addAnimation(a, forKey: a.keyPath!) } else if let a: CAAnimationGroup = animation as? CAAnimationGroup { layer.addAnimation(a, forKey: nil) } else if let a: CATransition = animation as? CATransition { layer.addAnimation(a, forKey: kCATransition) } } /** A delegation method that is executed when the backing layer starts running an animation. - Parameter anim: The currently running CAAnimation instance. */ public override func animationDidStart(anim: CAAnimation) { (delegate as? MaterialAnimationDelegate)?.materialAnimationDidStart?(anim) } /** A delegation method that is executed when the backing layer stops running an animation. - Parameter anim: The CAAnimation instance that stopped running. - Parameter flag: A boolean that indicates if the animation stopped because it was completed or interrupted. True if completed, false if interrupted. */ public override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if let a: CAPropertyAnimation = anim as? CAPropertyAnimation { if let b: CABasicAnimation = a as? CABasicAnimation { if let v: AnyObject = b.toValue { if let k: String = b.keyPath { layer.setValue(v, forKeyPath: k) layer.removeAnimationForKey(k) } } } (delegate as? MaterialAnimationDelegate)?.materialAnimationDidStop?(anim, finished: flag) } else if let a: CAAnimationGroup = anim as? CAAnimationGroup { for x in a.animations! { animationDidStop(x, finished: true) } } } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepareView method to initialize property values and other setup operations. The super.prepareView method should always be called immediately when subclassing. */ public func prepareView() { backgroundColor = MaterialColor.white masksToBounds = false clearButtonMode = .WhileEditing prepareBottomBorderLayer() } /// Reloads the view. public func reloadView() { /// Prepare the clearButton. if let v: UIButton = clearButton { v.frame = CGRectMake(0, 0, height, height) } } /// Clears the textField text. internal func handleClearButton() { text = "" } /// Ahdnler when text value changed. internal func textFieldValueChanged() { if detailLabelAutoHideEnabled && !detailLabelHidden { detailLabelHidden = true MaterialAnimation.animationDisabled { [unowned self] in self.bottomBorderLayer.backgroundColor = self.titleLabelActiveColor?.CGColor } } } /// Handler for text editing began. internal func textFieldDidBegin() { titleLabel?.textColor = titleLabelActiveColor MaterialAnimation.animationDisabled { [unowned self] in self.bottomBorderLayer.backgroundColor = self.detailLabelHidden ? self.titleLabelActiveColor?.CGColor : self.detailLabelActiveColor?.CGColor } } /// Handler for text changed. internal func textFieldDidChange() { if 0 < text?.utf16.count { showTitleLabel() } else if 0 == text?.utf16.count { hideTitleLabel() } sendActionsForControlEvents(.ValueChanged) } /// Handler for text editing ended. internal func textFieldDidEnd() { if 0 < text?.utf16.count { showTitleLabel() } else if 0 == text?.utf16.count { hideTitleLabel() } titleLabel?.textColor = titleLabelColor MaterialAnimation.animationDisabled { [unowned self] in self.bottomBorderLayer.backgroundColor = self.detailLabelHidden ? self.titleLabelColor?.CGColor : self.detailLabelActiveColor?.CGColor } } /// Manages the layout for the shape of the view instance. internal func layoutShape() { if .Circle == shape { let w: CGFloat = (width / 2) if w != cornerRadius { cornerRadius = w } } } /// Sets the shadow path. internal func layoutShadowPath() { if shadowPathAutoSizeEnabled { if .None == depth { shadowPath = nil } else if nil == shadowPath { shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath } else { animate(MaterialAnimation.shadowPath(UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath, duration: 0)) } } } /// Prepares the titleLabel property. private func prepareTitleLabel() { if let v: UILabel = titleLabel { v.hidden = true addSubview(v) if 0 < text?.utf16.count { showTitleLabel() } else { v.alpha = 0 } addTarget(self, action: "textFieldDidBegin", forControlEvents: .EditingDidBegin) addTarget(self, action: "textFieldDidChange", forControlEvents: .EditingChanged) addTarget(self, action: "textFieldDidEnd", forControlEvents: .EditingDidEnd) } } /// Prepares the detailLabel property. private func prepareDetailLabel() { if let v: UILabel = detailLabel { v.hidden = true addSubview(v) if detailLabelHidden { v.alpha = 0 } else { showDetailLabel() } if nil == titleLabel { addTarget(self, action: "textFieldDidBegin", forControlEvents: .EditingDidBegin) addTarget(self, action: "textFieldDidChange", forControlEvents: .EditingChanged) addTarget(self, action: "textFieldDidEnd", forControlEvents: .EditingDidEnd) } addTarget(self, action: "textFieldValueChanged", forControlEvents: .ValueChanged) } } /// Prepares the bottomBorderLayer property. private func prepareBottomBorderLayer() { layer.addSublayer(bottomBorderLayer) } /// Shows and animates the titleLabel property. private func showTitleLabel() { if let v: UILabel = titleLabel { if v.hidden { if let s: String = placeholder { if 0 == v.text?.utf16.count || nil == v.text { v.text = s } } let h: CGFloat = ceil(v.font.lineHeight) v.frame = CGRectMake(0, -h, bounds.width, h) v.hidden = false UIView.animateWithDuration(0.25, animations: { [unowned self] in v.alpha = 1 v.frame.origin.y -= self.titleLabelAnimationDistance }) } } } /// Hides and animates the titleLabel property. private func hideTitleLabel() { if let v: UILabel = titleLabel { UIView.animateWithDuration(0.25, animations: { [unowned self] in v.alpha = 0 v.frame.origin.y += self.titleLabelAnimationDistance }) { _ in v.hidden = true } } } /// Shows and animates the detailLabel property. private func showDetailLabel() { if let v: UILabel = detailLabel { if v.hidden { let h: CGFloat = ceil(v.font.lineHeight) v.frame = CGRectMake(0, bounds.height + bottomBorderLayerDistance, bounds.width, h) v.hidden = false UIView.animateWithDuration(0.25, animations: { [unowned self] in v.frame.origin.y = self.frame.height + self.bottomBorderLayerDistance + self.detailLabelAnimationDistance v.alpha = 1 }) } } } /// Hides and animates the detailLabel property. private func hideDetailLabel() { if let v: UILabel = detailLabel { UIView.animateWithDuration(0.25, animations: { [unowned self] in v.alpha = 0 v.frame.origin.y -= self.detailLabelAnimationDistance }) { _ in v.hidden = true } } } }
mit
hejunbinlan/SwiftGraphics
SwiftGraphics_UnitTests/SwiftDocTests/CGPointSwiftDocTests.swift
4
3219
// // CGPointSwiftDocTests.swift // SOMETHING // // Created by SOMEONE on SOMEWHEN. // Copyright (c) SOME STUFF. All rights reserved. // // ******************************************************************************************* // * These unit tests were automatically generated by: https://github.com/schwa/SwiftDocTest * // ******************************************************************************************* import Cocoa import XCTest import SwiftGraphics class CGPointSwiftDocTests: XCTestCase { func test_23126dc80bdd3fdb985aee0b2234ff3ec00ecab6() { let result = CGPoint(x:1, y:2) + CGPoint(x:10, y:20) let expected_result = CGPoint(x:11, y:22) XCTAssertEqual(result, expected_result) } func test_a9147ff57b6fc28170f2fd34010dcd805088553d() { let result = CGPoint(x:11, y:22) - CGPoint(x:10, y:20) let expected_result = CGPoint(x:1, y:2) XCTAssertEqual(result, expected_result) } func test_5ae06e9ba2b24c91d5e85550b59bae6a9beaa17b() { let result = CGPoint(x:0, y:0).isZero let expected_result = true XCTAssertEqual(result, expected_result) } func test_2ce3d4cb2d1f009553ca51dd2bf4982098687749() { let result = CGPoint(x:1, y:0).isZero let expected_result = false XCTAssertEqual(result, expected_result) } func test_b8a1a3cfeef1e64f1cfbd8a3252890e16d397200() { let result = CGPoint(x:50, y:50).clampedTo(CGRect(x:10, y:20, w:100, h:100)) let expected_result = CGPoint(x:50, y:50) XCTAssertEqual(result, expected_result) } func test_0ccbe0a5a9a42bbbcf25eb107c1cf3d83a81dae9() { let result = CGPoint(x:150, y:50).clampedTo(CGRect(x:10, y:20, w:100, h:100)) let expected_result = CGPoint(x:110, y:50) XCTAssertEqual(result, expected_result) } func test_e7bd44171946f518cafde41445ef0993c3782132() { let result = CGPoint(x:0, y:50).clampedTo(CGRect(x:10, y:20, w:100, h:100)) let expected_result = CGPoint(x:10, y:50) XCTAssertEqual(result, expected_result) } func test_ed4f3f458ec7eb65cb43891e5fb41a5f9295b102() { let result = CGPoint(x:50, y:00).clampedTo(CGRect(x:10, y:20, w:100, h:100)) let expected_result = CGPoint(x:50, y:20) XCTAssertEqual(result, expected_result) } func test_ba0a788729712c63dbc83cbf9ba39ef96f6a3746() { let result = floor(CGPoint(x:10.9, y:-10.5)) let expected_result = CGPoint(x:10, y:-11) XCTAssertEqual(result, expected_result) } func test_c6cdf9945105f6f702b9d22d909d3c0c505ea2b7() { let result = ceil(CGPoint(x:10.9, y:-10.5)) let expected_result = CGPoint(x:11, y:-10) XCTAssertEqual(result, expected_result) } func test_e71dd9bf7127b87065bf7412149f4c625ceecd68() { let result = round(CGPoint(x:10.9, y:-10.6)) let expected_result = CGPoint(x:11, y:-11) XCTAssertEqual(result, expected_result) } func test_5097696df2ec6230b235df30db56741689018f69() { let result = floor(CGPoint(x:10.09, y:-10.95)) let expected_result = CGPoint(x:10, y:-11) XCTAssertEqual(result, expected_result) } }
bsd-2-clause
aschwaighofer/swift
test/Constraints/function_builder_diags.swift
2
14261
// RUN: %target-typecheck-verify-swift -disable-availability-checking enum Either<T,U> { case first(T) case second(U) } @_functionBuilder struct TupleBuilder { // expected-note 3{{struct 'TupleBuilder' declared here}} static func buildBlock() -> () { } static func buildBlock<T1>(_ t1: T1) -> T1 { return t1 } static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) { return (t1, t2) } static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3) -> (T1, T2, T3) { return (t1, t2, t3) } static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4) -> (T1, T2, T3, T4) { return (t1, t2, t3, t4) } static func buildBlock<T1, T2, T3, T4, T5>( _ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5 ) -> (T1, T2, T3, T4, T5) { return (t1, t2, t3, t4, t5) } static func buildDo<T>(_ value: T) -> T { return value } static func buildIf<T>(_ value: T?) -> T? { return value } static func buildEither<T,U>(first value: T) -> Either<T,U> { return .first(value) } static func buildEither<T,U>(second value: U) -> Either<T,U> { return .second(value) } } @_functionBuilder struct TupleBuilderWithoutIf { // expected-note {{struct 'TupleBuilderWithoutIf' declared here}} static func buildBlock() -> () { } static func buildBlock<T1>(_ t1: T1) -> T1 { return t1 } static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) { return (t1, t2) } static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3) -> (T1, T2, T3) { return (t1, t2, t3) } static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4) -> (T1, T2, T3, T4) { return (t1, t2, t3, t4) } static func buildBlock<T1, T2, T3, T4, T5>( _ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5 ) -> (T1, T2, T3, T4, T5) { return (t1, t2, t3, t4, t5) } static func buildDo<T>(_ value: T) -> T { return value } } func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) { print(body(cond)) } func tuplifyWithoutIf<T>(_ cond: Bool, @TupleBuilderWithoutIf body: (Bool) -> T) { print(body(cond)) } func testDiags() { // For loop tuplify(true) { _ in 17 for c in name { // expected-error{{closure containing control flow statement cannot be used with function builder 'TupleBuilder'}} // expected-error@-1 {{cannot find 'name' in scope}} } } // Declarations tuplify(true) { _ in 17 let x = 17 let y: Int // expected-error{{closure containing a declaration cannot be used with function builder 'TupleBuilder'}} x + 25 } // Statements unsupported by the particular builder. tuplifyWithoutIf(true) { if $0 { // expected-error{{closure containing control flow statement cannot be used with function builder 'TupleBuilderWithoutIf'}} "hello" } } } struct A { } struct B { } func overloadedTuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) -> A { // expected-note {{found this candidate}} return A() } func overloadedTuplify<T>(_ cond: Bool, @TupleBuilderWithoutIf body: (Bool) -> T) -> B { // expected-note {{found this candidate}} return B() } func testOverloading(name: String) { let a1 = overloadedTuplify(true) { b in if b { "Hello, \(name)" } } let _: A = a1 _ = overloadedTuplify(true) { b in // expected-error {{ambiguous use of 'overloadedTuplify(_:body:)'}} b ? "Hello, \(name)" : "Goodbye" 42 overloadedTuplify(false) { $0 ? "Hello, \(name)" : "Goodbye" 42 if $0 { "Hello, \(name)" } } } } protocol P { associatedtype T } struct AnyP : P { typealias T = Any init<T>(_: T) where T : P {} } struct TupleP<U> : P { typealias T = U init(_: U) {} } @_functionBuilder struct Builder { static func buildBlock<S0, S1>(_ stmt1: S0, _ stmt2: S1) // expected-note {{required by static method 'buildBlock' where 'S1' = 'Label<_>.Type'}} -> TupleP<(S0, S1)> where S0: P, S1: P { return TupleP((stmt1, stmt2)) } } struct G<C> : P where C : P { typealias T = C init(@Builder _: () -> C) {} } struct Text : P { typealias T = String init(_: T) {} } struct Label<L> : P where L : P { // expected-note 2 {{'L' declared as parameter to type 'Label'}} typealias T = L init(@Builder _: () -> L) {} // expected-note {{'init(_:)' declared here}} } func test_51167632() -> some P { AnyP(G { // expected-error {{type 'Label<_>.Type' cannot conform to 'P'; only struct/enum/class types can conform to protocols}} Text("hello") Label // expected-error {{generic parameter 'L' could not be inferred}} // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{10-10=<<#L: P#>>}} }) } func test_56221372() -> some P { AnyP(G { Text("hello") Label() // expected-error {{generic parameter 'L' could not be inferred}} // expected-error@-1 {{missing argument for parameter #1 in call}} // expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{10-10=<<#L: P#>>}} }) } struct SR11440 { typealias ReturnsTuple<T> = () -> (T, T) subscript<T, U>(@TupleBuilder x: ReturnsTuple<T>) -> (ReturnsTuple<U>) -> Void { //expected-note {{in call to 'subscript(_:)'}} return { _ in } } func foo() { // This is okay, we apply the function builder for the subscript arg. self[{ 5 5 }]({ (5, 5) }) // But we shouldn't perform the transform for the argument to the call // made on the function returned from the subscript. self[{ // expected-error {{generic parameter 'U' could not be inferred}} 5 5 }]({ 5 5 }) } } func acceptInt(_: Int, _: () -> Void) { } // SR-11350 crash due to improper recontextualization. func erroneousSR11350(x: Int) { tuplify(true) { b in 17 x + 25 Optional(tuplify(false) { b in if b { acceptInt(0) { } } }).domap(0) // expected-error{{value of type '()?' has no member 'domap'}} } } func extraArg() { tuplify(true) { _ in 1 2 3 4 5 6 // expected-error {{extra argument in call}} } } // rdar://problem/53209000 - use of #warning and #error tuplify(true) { x in 1 #error("boom") // expected-error{{boom}} "hello" #warning("oops") // expected-warning{{oops}} 3.14159 } struct MyTuplifiedStruct { var condition: Bool @TupleBuilder var computed: some Any { // expected-note{{remove the attribute to explicitly disable the function builder}}{{3-17=}} if condition { return 17 // expected-warning{{application of function builder 'TupleBuilder' disabled by explicit 'return' statement}} // expected-note@-1{{remove 'return' statements to apply the function builder}}{{7-14=}}{{12-19=}} } else { return 42 } } } // Check that we're performing syntactic use diagnostics. func acceptMetatype<T>(_: T.Type) -> Bool { true } func syntacticUses<T>(_: T) { tuplify(true) { x in if x && acceptMetatype(T) { // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{use '.self' to reference the type object}} acceptMetatype(T) // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{use '.self' to reference the type object}} } } } // Check custom diagnostics within "if" conditions. struct HasProperty { var property: Bool = false } func checkConditions(cond: Bool) { var x = HasProperty() tuplify(cond) { value in if x.property = value { // expected-error{{use of '=' in a boolean context, did you mean '=='?}} "matched it" } } } // Check that a closure with a single "return" works with function builders. func checkSingleReturn(cond: Bool) { tuplify(cond) { value in return (value, 17) } tuplify(cond) { value in (value, 17) } tuplify(cond) { ($0, 17) } } // rdar://problem/59116520 func checkImplicitSelfInClosure() { @_functionBuilder struct Builder { static func buildBlock(_ children: String...) -> Element { Element() } } struct Element { static func nonEscapingClosure(@Builder closure: (() -> Element)) {} static func escapingClosure(@Builder closure: @escaping (() -> Element)) {} } class C { let identifier: String = "" func testImplicitSelf() { Element.nonEscapingClosure { identifier // okay } Element.escapingClosure { // expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} identifier // expected-error {{reference to property 'identifier' in closure requires explicit use of 'self' to make capture semantics explicit}} // expected-note@-1 {{reference 'self.' explicitly}} } } } } // rdar://problem/59239224 - crash because some nodes don't have type // information during solution application. struct X<T> { init(_: T) { } } @TupleBuilder func foo(cond: Bool) -> some Any { if cond { tuplify(cond) { x in X(x) } } } // switch statements don't allow fallthrough enum E { case a case b(Int, String?) } func testSwitch(e: E) { tuplify(true) { c in "testSwitch" switch e { case .a: "a" case .b(let i, let s?): i * 2 s + "!" fallthrough // expected-error{{closure containing control flow statement cannot be used with function builder 'TupleBuilder'}} case .b(let i, nil): "just \(i)" } } } // Ensure that we don't back-propagate constraints to the subject // expression. This is a potential avenue for future exploration, but // is currently not supported by switch statements outside of function // builders. It's better to be consistent for now. enum E2 { case b(Int, String?) // expected-note{{'b' declared here}} } func getSomeEnumOverloaded(_: Double) -> E { return .a } func getSomeEnumOverloaded(_: Int) -> E2 { return .b(0, nil) } func testOverloadedSwitch() { tuplify(true) { c in // FIXME: Bad source location. switch getSomeEnumOverloaded(17) { // expected-error{{type 'E2' has no member 'a'; did you mean 'b'?}} case .a: "a" default: "default" } } } // Check exhaustivity. func testNonExhaustiveSwitch(e: E) { tuplify(true) { c in "testSwitch" switch e { // expected-error{{switch must be exhaustive}} // expected-note @-1{{add missing case: '.b(_, .none)'}} case .a: "a" case .b(let i, let s?): i * 2 s + "!" } } } // rdar://problem/59856491 struct TestConstraintGenerationErrors { @TupleBuilder var buildTupleFnBody: String { String(nothing) // expected-error {{cannot find 'nothing' in scope}} } func buildTupleClosure() { tuplify(true) { _ in String(nothing) // expected-error {{cannot find 'nothing' in scope}} } } } // Check @unknown func testUnknownInSwitchSwitch(e: E) { tuplify(true) { c in "testSwitch" switch e { @unknown case .a: // expected-error{{'@unknown' is only supported for catch-all cases ("case _")}} "a" case .b(let i, let s?): i * 2 s + "!" default: "nothing" } } } // Check for mutability mismatches when there are multiple case items // referring to same-named variables. enum E3 { case a(Int, String) case b(String, Int) case c(String, Int) } func testCaseMutabilityMismatches(e: E3) { tuplify(true) { c in "testSwitch" switch e { case .a(let x, var y), .b(let y, // expected-error{{'let' pattern binding must match previous 'var' pattern binding}} var x), // expected-error{{'var' pattern binding must match previous 'let' pattern binding}} .c(let y, // expected-error{{'let' pattern binding must match previous 'var' pattern binding}} var x): // expected-error{{'var' pattern binding must match previous 'let' pattern binding}} x y += "a" } } } // Check for type equivalence among different case variables with the same name. func testCaseVarTypes(e: E3) { // FIXME: Terrible diagnostic tuplify(true) { c in // expected-error{{type of expression is ambiguous without more context}} "testSwitch" switch e { case .a(let x, let y), .c(let x, let y): x y + "a" } } } // Test for buildFinalResult. @_functionBuilder struct WrapperBuilder { static func buildBlock() -> () { } static func buildBlock<T1>(_ t1: T1) -> T1 { return t1 } static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) { return (t1, t2) } static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3) -> (T1, T2, T3) { return (t1, t2, t3) } static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4) -> (T1, T2, T3, T4) { return (t1, t2, t3, t4) } static func buildBlock<T1, T2, T3, T4, T5>( _ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5 ) -> (T1, T2, T3, T4, T5) { return (t1, t2, t3, t4, t5) } static func buildDo<T>(_ value: T) -> T { return value } static func buildIf<T>(_ value: T?) -> T? { return value } static func buildEither<T,U>(first value: T) -> Either<T,U> { return .first(value) } static func buildEither<T,U>(second value: U) -> Either<T,U> { return .second(value) } static func buildFinalResult<T>(_ value: T) -> Wrapper<T> { return Wrapper(value: value) } } struct Wrapper<T> { var value: T } func wrapperify<T>(_ cond: Bool, @WrapperBuilder body: (Bool) -> T) -> T{ return body(cond) } func testWrapperBuilder() { let x = wrapperify(true) { c in 3.14159 "hello" } let _: Int = x // expected-error{{cannot convert value of type 'Wrapper<(Double, String)>' to specified type 'Int'}} } // rdar://problem/61347993 - empty function builder doesn't compile func rdar61347993() { struct Result {} @_functionBuilder struct Builder { static func buildBlock() -> Result { Result() } } func test_builder<T>(@Builder _: () -> T) {} test_builder {} // Ok func test_closure(_: () -> Result) {} test_closure {} // expected-error {{cannot convert value of type '()' to closure result type 'Result'}} }
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/23188-swift-parser-parsedeclfunc.swift
11
253
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class d<T where g:a{var b{protocol P{func f:a func a(xea{}protocol P{let f={{{func}
mit
radex/swift-compiler-crashes
crashes-fuzzing/10199-swift-parser-parsetoken.swift
11
231
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class b<d where B:a{ var b{ let c=(n<c enum a{ enum B{ let c={
mit
charmaex/JDCoordinator
Example/JDCoordinator/Controller/IntroViewController.swift
1
450
// // IntroVC.swift // Demo // // Created by Jan Dammshäuser on 05.09.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit class IntroVC: UIViewController { // needed on iOS 8 init() { super.init(nibName: "IntroVC", bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { NSLog("\(type(of: self)) got deinitialized") } }
mit
notbenoit/tvOS-Twitch
Code/Common/Views/NibDesignable.swift
1
2527
// Copyright (c) 2015 Benoit Layer // // 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 protocol NibDesignableType: NSObjectProtocol { var nibName: String { get } var containerView: UIView { get } } extension NibDesignableType { // MARK: - Nib loading /** Called to load the nib in setupNib(). - returns: UIView instance loaded from a nib file. */ func loadNib() -> UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: self.nibName, bundle: bundle) return nib.instantiate(withOwner: self, options: nil)[0] as! UIView } // MARK: - Nib loading /** Called in init(frame:) and init(aDecoder:) to load the nib and add it as a subview. */ fileprivate func setupNib() { let view = self.loadNib() self.containerView.addAndFitSubview(view) } } extension UIView: NibDesignableType { var containerView: UIView { return self } var nibName: String { return type(of: self).description().components(separatedBy: ".").last! } } /// This class only exists in order to be subclassed. class NibDesignable: UIView { override init(frame: CGRect) { super.init(frame: frame) setupNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupNib() } } /// This class only exists in order to be subclassed. class ControlNibDesignable: UIControl { override init(frame: CGRect) { super.init(frame: frame) setupNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupNib() } }
bsd-3-clause
bermudadigitalstudio/Rope
Tests/RopeTests/RopeQueryJSONTests.swift
1
2387
import XCTest import Rope final class RopeQueryJSONTests: XCTestCase { let creds = TestCredentials.getCredentials() var conn: Rope? // auto-tested optional db connection let insertQuery = "INSERT INTO json (json) VALUES " + "('{\"due_in_seconds\":0,\"method\":\"POST\",\"headers\":{},\"url\":\"http://localhost\"}') " + "RETURNING id;" override func setUp() { super.setUp() // create connection conn = try? Rope.connect(credentials: creds) XCTAssertNotNil(conn) guard let dropRes = try? conn?.query("DROP TABLE IF EXISTS json") else { XCTFail("res should not be nil"); return } XCTAssertNotNil(dropRes) // create a table with different types as test, payload can be nil let sql = "CREATE TABLE IF NOT EXISTS json (id SERIAL PRIMARY KEY, json JSONB);" guard let createRes = try? conn?.query(sql) else { XCTFail("res should not be nil"); return } XCTAssertNotNil(createRes) } override func tearDown() { super.tearDown() } func testQueryInsertStatement() { guard let res = try? conn?.query(insertQuery) else { XCTFail("res should not be nil"); return } XCTAssertEqual(res?.rows().count, 1) guard let row = res?.rows().first else { XCTFail("res should not be nil"); return } let id = row["id"] as? Int XCTAssertNotNil(id) XCTAssertEqual(id, 1) } func testQuerySelectStatement() { guard let _ = try? conn?.query(insertQuery), let select = try? conn?.query("SELECT * FROM json") else { XCTFail("res should not be nil"); return } guard let row = select?.rows().first else { XCTFail("res should not be nil"); return } let payload = row["json"] as? [String: Any] XCTAssertNotNil(payload) guard let method = payload?["method"] as? String, let dueInSeconds = payload?["due_in_seconds"] as? Int, let urlString = payload?["url"] as? String else { XCTFail("res should not be nil"); return } XCTAssertEqual(urlString, "http://localhost") XCTAssertEqual(method, "POST") XCTAssertEqual(dueInSeconds, 0) } }
apache-2.0
manavgabhawala/CAEN-Lecture-Scraper
CAEN Lecture Scraper/GenericExtensions.swift
1
1310
// // GenericExtensions.swift // CAEN Lecture Scraper // // Created by Manav Gabhawala on 6/3/15. // Copyright (c) 2015 Manav Gabhawala. All rights reserved. // import Foundation extension String { init?(data: NSData?) { if let data = data { if let some = NSString(data: data, encoding: NSUTF8StringEncoding) { self = some as String return } return nil } return nil } func textBetween(start: String, end: String) -> String? { let startIndex = self.rangeOfString(start)?.endIndex if (startIndex == nil) { return nil } let endIndex = self.rangeOfString(end, range: Range(start: startIndex!, end: self.endIndex))?.startIndex if startIndex != nil && endIndex != nil { return self.substringWithRange(Range(start: startIndex!, end: endIndex!)) } return nil } mutating func safeString() { self = self.safeString() } func safeString() -> String { return self.stringByReplacingOccurrencesOfString("Lecture recorded on ", withString: "").stringByReplacingOccurrencesOfString("/", withString: "-") } } /* let fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(directory.absoluteString!) { fileManager.createDirectoryAtPath(directory.absoluteString!, withIntermediateDirectories: true, attributes: nil, error: nil) } */
mit
eugeneego/utilities-ios
Sources/Network/Http/Serializers/UrlEncodedHttpSerializer.swift
1
2221
// // UrlEncodedHttpSerializer // Legacy // // Copyright (c) 2015 Eugene Egorov. // License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE // import Foundation public struct UrlEncodedHttpSerializer: HttpSerializer { public typealias Value = [String: String] public let contentType: String = "application/x-www-form-urlencoded" public init() {} public func serialize(_ value: Value?) -> Result<Data, HttpSerializationError> { guard let value = value else { return .success(Data()) } let data = serialize(value).data(using: String.Encoding.utf8) return Result(data, HttpSerializationError.noData) } public func deserialize(_ data: Data?) -> Result<Value, HttpSerializationError> { guard let data = data, !data.isEmpty else { return .success([:]) } let value = String(data: data, encoding: String.Encoding.utf8).map(deserialize) return Result(value, HttpSerializationError.noData) } public func serialize(_ value: Value) -> String { let result = value .map { name, value in UrlEncodedHttpSerializer.encode(name) + "=" + UrlEncodedHttpSerializer.encode("\(value)") } .joined(separator: "&") return result } public func deserialize(_ string: String) -> Value { var params: Value = [:] let cmp = string.components(separatedBy: "&") cmp.forEach { param in let parts = param.components(separatedBy: "=") if parts.count == 2 { let name = UrlEncodedHttpSerializer.decode(parts[0]) let value = UrlEncodedHttpSerializer.decode(parts[1]) params[name] = value } } return params } private static var characters: CharacterSet = { var characters = CharacterSet.alphanumerics characters.insert(charactersIn: "-_.") return characters }() public static func encode(_ string: String) -> String { string.addingPercentEncoding(withAllowedCharacters: characters) ?? "" } public static func decode(_ string: String) -> String { string.removingPercentEncoding ?? "" } }
mit
jtbandes/swift-compiler-crashes
fixed/27061-swift-archetypebuilder-getallarchetypes.swift
4
211
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var a{{func f<w{{var a{class A{func f{e=p
mit
xiandan/diaobaoweibo-swift
XWeibo-swift/Classes/Module/XUserAccount.swift
1
3802
// // XUserAccount.swift // XWeibo-swift // // Created by Apple on 15/10/31. // Copyright © 2015年 Apple. All rights reserved. // import UIKit class XUserAccount: NSObject, NSCoding { //记录用户是否登录 class func isUserLogin() -> Bool { return XUserAccount.loadAccount() != nil } //MARK: - 属性 //用户的access_token var access_token: String? //用户的expires_in的生命周期 var expires_in: NSTimeInterval = 0 { didSet { expires_date = NSDate(timeIntervalSinceNow: expires_in) } } //用户的uid var uid: String? //过期时间 var expires_date: NSDate? //友好显示名称 var name: String? //头像 var avatar_large: String? //MARK: - 构造方法 字典转模型 init(dic: [String:AnyObject]) { super.init() setValuesForKeysWithDictionary(dic) } override func setValue(value: AnyObject?, forUndefinedKey key: String){} //MARK: - 加载用户数据 func loadUserInfo(finish: (error: NSError?) -> ()) { XNetWorkTool.sharedInstance.loadUserInfo { (result, error) -> () in if result == nil || error != nil { finish(error: error) return } //加载成功 self.name = result!["name"] as? String self.avatar_large = result!["avatar_large"] as? String //保存数据 self.saveAccount() //同步到内存中 XUserAccount.userAccount = self finish(error: nil) } } //沙盒路径 static let savePath = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/Account.plist" //MARK; - 把数据保存到沙盒中 func saveAccount() { NSKeyedArchiver.archiveRootObject(self, toFile: XUserAccount.savePath) print(XUserAccount.savePath) } //MARK: - 从内存中取出用户数据 private static var userAccount: XUserAccount? //MARK: - 从内存中加载用户数据 class func loadAccount() -> XUserAccount? { //如果内存中没有数据 if userAccount == nil { userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(savePath) as? XUserAccount } //判断账号是否有效 if userAccount != nil && userAccount?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending { print("账号有效") return userAccount } return nil } // MARK: - 归档和解档 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeDouble(expires_in, forKey: "expires_in") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(expires_date, forKey: "expires_date") aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(avatar_large, forKey: "avatar_large") } required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expires_in = aDecoder.decodeDoubleForKey("expires_in") uid = aDecoder.decodeObjectForKey("uid") as? String expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate name = aDecoder.decodeObjectForKey("name") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String } }
apache-2.0
tobyliu-sw/CameraFrameCapturer
CameraFrameCapturer/AppDelegate.swift
1
2473
// // AppDelegate.swift // CameraFrameCapturer // // Created by Pin-Chou Liu on 6/20/17. // Copyright © 2017 Pin-Chou Liu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UIDevice.current.beginGeneratingDeviceOrientationNotifications() 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. UIDevice.current.endGeneratingDeviceOrientationNotifications() } 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. UIDevice.current.beginGeneratingDeviceOrientationNotifications() } 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:. UIDevice.current.endGeneratingDeviceOrientationNotifications() } }
apache-2.0
apple/swift-nio
Tests/NIOFoundationCompatTests/ByteBufferView+MutableDataProtocolTest+XCTest.swift
1
1197
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // ByteBufferView+MutableDataProtocolTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension ByteBufferViewDataProtocolTests { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (ByteBufferViewDataProtocolTests) -> () throws -> Void)] { return [ ("testResetBytes", testResetBytes), ("testCreateDataFromBuffer", testCreateDataFromBuffer), ] } }
apache-2.0
ispiropoulos/PRGLocationSearchBar
PRGLocationSearchBarTests/PRGLocationSearchBarTests.swift
1
1028
// // PRGLocationSearchBarTests.swift // PRGLocationSearchBarTests // // Created by John Spiropoulos on 28/12/2016. // Copyright © 2016 Programize. All rights reserved. // import XCTest @testable import PRGLocationSearchBar class PRGLocationSearchBarTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
RameshRM/swift-tapper
swift-tapper/swift-tapper/AppDelegate.swift
1
7067
// // AppDelegate.swift // swift-tapper // // Created by Mahadevan, Ramesh on 7/13/14. // Copyright (c) 2014 Mahadevan, Ramesh. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication!) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication!) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication!) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication!) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication!) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } func saveContext () { var error: NSError? = nil let managedObjectContext = self.managedObjectContext if managedObjectContext != nil { if managedObjectContext.hasChanges && !managedObjectContext.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } } } // #pragma mark - Core Data stack // Returns the managed object context for the application. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. var managedObjectContext: NSManagedObjectContext { if !_managedObjectContext { let coordinator = self.persistentStoreCoordinator if coordinator != nil { _managedObjectContext = NSManagedObjectContext() _managedObjectContext!.persistentStoreCoordinator = coordinator } } return _managedObjectContext! } var _managedObjectContext: NSManagedObjectContext? = nil // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. var managedObjectModel: NSManagedObjectModel { if !_managedObjectModel { let modelURL = NSBundle.mainBundle().URLForResource("swift_tapper", withExtension: "momd") _managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL) } return _managedObjectModel! } var _managedObjectModel: NSManagedObjectModel? = nil // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. var persistentStoreCoordinator: NSPersistentStoreCoordinator { if !_persistentStoreCoordinator { let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("swift_tapper.sqlite") var error: NSError? = nil _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil) * Performing automatic lightweight migration by passing the following dictionary as the options parameter: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ //println("Unresolved error \(error), \(error!.userInfo)") abort() } } return _persistentStoreCoordinator! } var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil // #pragma mark - Application's Documents directory // Returns the URL to the application's Documents directory. var applicationDocumentsDirectory: NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL } }
apache-2.0
vadymmarkov/Faker
Tests/Fakery/Generators/NameSpec.swift
3
1336
import Quick import Nimble @testable import Fakery final class NameSpec: QuickSpec { override func spec() { describe("Name") { var name: Faker.Name! beforeEach { let parser = Parser(locale: "en-TEST") name = Faker.Name(parser: parser) } describe("#name") { it("returns the correct text") { let text = name.name() expect(text).to(equal("Mr. Vadym Markov")) } } describe("#firstName") { it("returns the correct text") { let firstName = name.firstName() expect(firstName).to(equal("Vadym")) } } describe("#lastName") { it("returns the correct text") { let lastName = name.lastName() expect(lastName).to(equal("Markov")) } } describe("#prefix") { it("returns the correct text") { let prefix = name.prefix() expect(prefix).to(equal("Mr.")) } } describe("#suffix") { it("returns the correct text") { let suffix = name.suffix() expect(suffix).to(equal("I")) } } describe("#title") { it("returns the correct text") { let title = name.title() expect(title).to(equal("Lead Mobility Engineer")) } } } } }
mit
Samarkin/PixelEditor
PixelEditor/ViewController.swift
1
2636
import Cocoa class ViewController: NSViewController { @IBOutlet var colorSelectorView: ColorSelectorView! @IBOutlet var selectedColorView: SolidColorView! @IBOutlet var selectedAltColorView: SolidColorView! @IBOutlet var canvasView: CanvasView! override func viewDidLoad() { super.viewDidLoad() colorSelectorView.colorSelected = { [weak self] in self?.selectedColorView?.backgroundColor = $0 } colorSelectorView.altColorSelected = { [weak self] in self?.selectedAltColorView?.backgroundColor = $0 } canvasView.delegate = { [weak self] in let colorMap: [CanvasColor : NSColor?] = [ .Main : self?.selectedColorView?.backgroundColor, .Alternative : self?.selectedAltColorView?.backgroundColor ] // TODO: Is there a better way to unwrap a double optional? if let color = colorMap[$2], let c = color { self?.document?.setPixel(i: $0, j: $1, color: c) } } } var document: Document? { didSet { oldValue?.removeObserver(self, forKeyPath: "pixels") if let document = document { canvasView.loadImage(document.pixels) document.addObserver(self, forKeyPath: "pixels", options: NSKeyValueObservingOptions.New, context: nil) } } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let document = document where object as? Document == document { if keyPath == "pixels" { // TODO: better changes tracking, don't reload the whole image every single time it changes canvasView.loadImage(document.pixels) } } } func export(sender: AnyObject?) { guard let window = self.view.window else { return } let panel = NSSavePanel() panel.allowedFileTypes = ["png"] if let fileName = self.document?.displayName { panel.nameFieldStringValue = fileName } panel.canSelectHiddenExtension = true panel.beginSheetModalForWindow(window) { guard $0 == NSFileHandlingPanelOKButton, let url = panel.URL else { return } print("exporting to \(url)...") self.document?.export().writeToURL(url, atomically: true) } } deinit { document?.removeObserver(self, forKeyPath: "pixels") } }
mit
shiguredo/sora-ios-sdk
Sora/VideoFrame.swift
1
2274
import CoreMedia import Foundation import WebRTC /** 映像フレームの種別です。 現在の実装では次の映像フレームに対応しています。 - ネイティブの映像フレーム (`RTCVideoFrame`) - `CMSampleBuffer` (映像のみ、音声は非対応。 `RTCVideoFrame` に変換されます) */ public enum VideoFrame { // MARK: - 定義 /// ネイティブの映像フレーム。 /// `CMSampleBuffer` から生成した映像フレームは、ネイティブの映像フレームに変換されます。 case native(capturer: RTCVideoCapturer?, frame: RTCVideoFrame) // MARK: - プロパティ /// 映像フレームの幅 public var width: Int { switch self { case .native(capturer: _, frame: let frame): return Int(frame.width) } } /// 映像フレームの高さ public var height: Int { switch self { case .native(capturer: _, frame: let frame): return Int(frame.height) } } /// 映像フレームの生成時刻 public var timestamp: CMTime? { switch self { case .native(capturer: _, frame: let frame): return CMTimeMake(value: frame.timeStampNs, timescale: 1_000_000_000) } } // MARK: - 初期化 /** 初期化します。 指定されたサンプルバッファーからピクセル画像データを取得できなければ `nil` を返します。 音声データを含むサンプルバッファーには対応していません。 - parameter sampleBuffer: ピクセルバッファーを含むサンプルバッファー */ public init?(from sampleBuffer: CMSampleBuffer) { guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil } let timeStamp = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) let timeStampNs = Int64(timeStamp * 1_000_000_000) let frame = RTCVideoFrame(buffer: RTCCVPixelBuffer(pixelBuffer: pixelBuffer), rotation: RTCVideoRotation._0, timeStampNs: timeStampNs) self = .native(capturer: nil, frame: frame) } }
apache-2.0
vpeschenkov/LetterAvatarKit
LetterAvatarKit/Extensions/Character+LetterAvatarKit.swift
1
1367
// // Character+LetterAvatarKit.swift // LetterAvatarKit // // Copyright 2017 Victor Peschenkov // // Permission is hereby granted, free of charge, to any person obtaining a copy // o 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 internal extension Character { var ASCIIValue: Int { let unicode = String(self).unicodeScalars return Int(unicode[unicode.startIndex].value) } }
mit
LibraryLoupe/PhotosPlus
PhotosPlus/Cameras/Canon/CanonEOSRebelT3i.swift
3
512
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import Foundation extension Cameras.Manufacturers.Canon { public struct EOSRebelT3i: CameraModel { public init() {} public let name = "Canon EOS Rebel T3i " public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Canon.self } } public typealias CanonEOSRebelT3i = Cameras.Manufacturers.Canon.EOSRebelT3i
mit
matthewpurcell/firefox-ios
Client/Frontend/Browser/TabTrayController.swift
1
41135
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import SnapKit import Storage import ReadingList struct TabTrayControllerUX { static let CornerRadius = CGFloat(4.0) static let BackgroundColor = UIConstants.AppBackgroundColor static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1) static let TextBoxHeight = CGFloat(32.0) static let FaviconSize = CGFloat(18.0) static let Margin = CGFloat(15) static let ToolbarBarTintColor = UIConstants.AppBackgroundColor static let ToolbarButtonOffset = CGFloat(10.0) static let CloseButtonSize = CGFloat(18.0) static let CloseButtonMargin = CGFloat(6.0) static let CloseButtonEdgeInset = CGFloat(10) static let NumberOfColumnsThin = 1 static let NumberOfColumnsWide = 3 static let CompactNumberOfColumnsThin = 2 // Moved from UIConstants temporarily until animation code is merged static var StatusBarHeight: CGFloat { if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact { return 0 } return 20 } } struct LightTabCellUX { static let TabTitleTextColor = UIColor.blackColor() } struct DarkTabCellUX { static let TabTitleTextColor = UIColor.whiteColor() } protocol TabCellDelegate: class { func tabCellDidClose(cell: TabCell) } class TabCell: UICollectionViewCell { enum Style { case Light case Dark } static let Identifier = "TabCellIdentifier" var style: Style = .Light { didSet { applyStyle(style) } } let backgroundHolder = UIView() let background = UIImageViewAligned() let titleText: UILabel let innerStroke: InnerStrokedView let favicon: UIImageView = UIImageView() let closeButton: UIButton var title: UIVisualEffectView! var animator: SwipeAnimator! weak var delegate: TabCellDelegate? // Changes depending on whether we're full-screen or not. var margin = CGFloat(0) override init(frame: CGRect) { self.backgroundHolder.backgroundColor = UIColor.whiteColor() self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius self.backgroundHolder.clipsToBounds = true self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor self.background.contentMode = UIViewContentMode.ScaleAspectFill self.background.clipsToBounds = true self.background.userInteractionEnabled = false self.background.alignLeft = true self.background.alignTop = true self.favicon.backgroundColor = UIColor.clearColor() self.favicon.layer.cornerRadius = 2.0 self.favicon.layer.masksToBounds = true self.titleText = UILabel() self.titleText.textAlignment = NSTextAlignment.Left self.titleText.userInteractionEnabled = false self.titleText.numberOfLines = 1 self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold self.closeButton = UIButton() self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal) self.closeButton.tintColor = UIColor.lightGrayColor() self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset) self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame) self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor super.init(frame: frame) self.opaque = true self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self) self.closeButton.addTarget(self, action: "SELclose", forControlEvents: UIControlEvents.TouchUpInside) contentView.addSubview(backgroundHolder) backgroundHolder.addSubview(self.background) backgroundHolder.addSubview(innerStroke) // Default style is light applyStyle(style) self.accessibilityCustomActions = [ UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture") ] } private func applyStyle(style: Style) { self.title?.removeFromSuperview() let title: UIVisualEffectView switch style { case .Light: title = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight)) self.titleText.textColor = LightTabCellUX.TabTitleTextColor case .Dark: title = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) self.titleText.textColor = DarkTabCellUX.TabTitleTextColor } titleText.backgroundColor = UIColor.clearColor() title.layer.shadowColor = UIColor.blackColor().CGColor title.layer.shadowOpacity = 0.2 title.layer.shadowOffset = CGSize(width: 0, height: 0.5) title.layer.shadowRadius = 0 title.addSubview(self.closeButton) title.addSubview(self.titleText) title.addSubview(self.favicon) backgroundHolder.addSubview(title) self.title = title } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let w = frame.width let h = frame.height backgroundHolder.frame = CGRect(x: margin, y: margin, width: w, height: h) background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size) title.frame = CGRect(x: 0, y: 0, width: backgroundHolder.frame.width, height: TabTrayControllerUX.TextBoxHeight) favicon.frame = CGRect(x: 6, y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2, width: TabTrayControllerUX.FaviconSize, height: TabTrayControllerUX.FaviconSize) let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6 titleText.frame = CGRect(x: titleTextLeft, y: 0, width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2, height: title.frame.height) innerStroke.frame = background.frame closeButton.snp_makeConstraints { make in make.size.equalTo(title.snp_height) make.trailing.centerY.equalTo(title) } let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0 titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top)) } override func prepareForReuse() { // Reset any close animations. backgroundHolder.transform = CGAffineTransformIdentity backgroundHolder.alpha = 1 self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold } override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool { var right: Bool switch direction { case .Left: right = false case .Right: right = true default: return false } animator.close(right: right) return true } @objc func SELclose() { self.animator.SELcloseWithoutGesture() } } @available(iOS 9, *) struct PrivateModeStrings { static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode") static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode") static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value") static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value") } protocol TabTrayDelegate: class { func tabTrayDidDismiss(tabTray: TabTrayController) func tabTrayDidAddBookmark(tab: Browser) func tabTrayDidAddToReadingList(tab: Browser) -> ReadingListClientRecord? func tabTrayRequestsPresentationOf(viewController viewController: UIViewController) } class TabTrayController: UIViewController { let tabManager: TabManager let profile: Profile weak var delegate: TabTrayDelegate? var collectionView: UICollectionView! var navBar: UIView! var addTabButton: UIButton! var settingsButton: UIButton! var collectionViewTransitionSnapshot: UIView? private(set) internal var privateMode: Bool = false { didSet { if #available(iOS 9, *) { togglePrivateMode.selected = privateMode togglePrivateMode.accessibilityValue = privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff tabDataSource.tabs = tabsToDisplay collectionView?.reloadData() } } } private var tabsToDisplay: [Browser] { return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs } @available(iOS 9, *) lazy var togglePrivateMode: ToggleButton = { let button = ToggleButton() button.setImage(UIImage(named: "smallPrivateMask"), forState: UIControlState.Normal) button.addTarget(self, action: "SELdidTogglePrivateMode", forControlEvents: .TouchUpInside) button.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel button.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint button.accessibilityValue = self.privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff return button }() @available(iOS 9, *) private lazy var emptyPrivateTabsView: EmptyPrivateTabsView = { let emptyView = EmptyPrivateTabsView() emptyView.learnMoreButton.addTarget(self, action: "SELdidTapLearnMore", forControlEvents: UIControlEvents.TouchUpInside) return emptyView }() private lazy var tabDataSource: TabManagerDataSource = { return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self) }() private lazy var tabLayoutDelegate: TabLayoutDelegate = { let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection) delegate.tabSelectionDelegate = self return delegate }() init(tabManager: TabManager, profile: Profile) { self.tabManager = tabManager self.profile = profile super.init(nibName: nil, bundle: nil) } convenience init(tabManager: TabManager, profile: Profile, tabTrayDelegate: TabTrayDelegate) { self.init(tabManager: tabManager, profile: profile) self.delegate = tabTrayDelegate } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.tabManager.removeDelegate(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tabManager.addDelegate(self) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationDynamicFontChanged, object: nil) } func SELDynamicFontChanged(notification: NSNotification) { guard notification.name == NotificationDynamicFontChanged else { return } self.collectionView.reloadData() } // MARK: View Controller Callbacks override func viewDidLoad() { super.viewDidLoad() view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.") navBar = UIView() navBar.backgroundColor = TabTrayControllerUX.BackgroundColor addTabButton = UIButton() addTabButton.setImage(UIImage(named: "add"), forState: .Normal) addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside) addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.") settingsButton = UIButton() settingsButton.setImage(UIImage(named: "settings"), forState: .Normal) settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside) settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.") let flowLayout = TabTrayCollectionViewLayout() collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout) collectionView.dataSource = tabDataSource collectionView.delegate = tabLayoutDelegate collectionView.registerClass(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier) collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor view.addSubview(collectionView) view.addSubview(navBar) view.addSubview(addTabButton) view.addSubview(settingsButton) makeConstraints() if #available(iOS 9, *) { view.addSubview(togglePrivateMode) togglePrivateMode.snp_makeConstraints { make in make.right.equalTo(addTabButton.snp_left).offset(-10) make.size.equalTo(UIConstants.ToolbarHeight) make.centerY.equalTo(self.navBar) } view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView) emptyPrivateTabsView.alpha = privateMode && tabManager.privateTabs.count == 0 ? 1 : 0 emptyPrivateTabsView.snp_makeConstraints { make in make.edges.equalTo(self.view) } if let tab = tabManager.selectedTab where tab.isPrivate { privateMode = true } // register for previewing delegate to enable peek and pop if force touch feature available if traitCollection.forceTouchCapability == .Available { registerForPreviewingWithDelegate(self, sourceView: view) } } NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELappWillResignActiveNotification", name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELappDidBecomeActiveNotification", name: UIApplicationDidBecomeActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELDynamicFontChanged:", name: NotificationDynamicFontChanged, object: nil) } override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // Update the trait collection we reference in our layout delegate tabLayoutDelegate.traitCollection = traitCollection } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition({ _ in self.collectionView.collectionViewLayout.invalidateLayout() }, completion: nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } private func makeConstraints() { navBar.snp_makeConstraints { make in make.top.equalTo(snp_topLayoutGuideBottom) make.height.equalTo(UIConstants.ToolbarHeight) make.left.right.equalTo(self.view) } addTabButton.snp_makeConstraints { make in make.trailing.bottom.equalTo(self.navBar) make.size.equalTo(UIConstants.ToolbarHeight) } settingsButton.snp_makeConstraints { make in make.leading.bottom.equalTo(self.navBar) make.size.equalTo(UIConstants.ToolbarHeight) } collectionView.snp_makeConstraints { make in make.top.equalTo(navBar.snp_bottom) make.left.right.bottom.equalTo(self.view) } } // MARK: Selectors func SELdidClickDone() { presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } func SELdidClickSettingsItem() { let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager settingsTableViewController.settingsDelegate = self let controller = SettingsNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet presentViewController(controller, animated: true, completion: nil) } func SELdidClickAddTab() { openNewTab() } @available(iOS 9, *) func SELdidTapLearnMore() { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String if let langID = NSLocale.preferredLanguages().first { let learnMoreRequest = NSURLRequest(URL: "https://support.mozilla.org/1/mobile/\(appVersion)/iOS/\(langID)/private-browsing-ios".asURL!) openNewTab(learnMoreRequest) } } @available(iOS 9, *) func SELdidTogglePrivateMode() { let scaleDownTransform = CGAffineTransformMakeScale(0.9, 0.9) let fromView: UIView if privateTabsAreEmpty() { fromView = emptyPrivateTabsView } else { let snapshot = collectionView.snapshotViewAfterScreenUpdates(false) snapshot.frame = collectionView.frame view.insertSubview(snapshot, aboveSubview: collectionView) fromView = snapshot } privateMode = !privateMode // If we are exiting private mode and we have the close private tabs option selected, make sure // we clear out all of the private tabs if !privateMode && profile.prefs.boolForKey("settings.closePrivateTabs") ?? false { tabManager.removeAllPrivateTabsAndNotify(false) } togglePrivateMode.setSelected(privateMode, animated: true) collectionView.layoutSubviews() let toView: UIView if privateTabsAreEmpty() { toView = emptyPrivateTabsView } else { let newSnapshot = collectionView.snapshotViewAfterScreenUpdates(true) newSnapshot.frame = collectionView.frame view.insertSubview(newSnapshot, aboveSubview: fromView) collectionView.alpha = 0 toView = newSnapshot } toView.alpha = 0 toView.transform = scaleDownTransform UIView.animateWithDuration(0.2, delay: 0, options: [], animations: { () -> Void in fromView.transform = scaleDownTransform fromView.alpha = 0 toView.transform = CGAffineTransformIdentity toView.alpha = 1 }) { finished in if fromView != self.emptyPrivateTabsView { fromView.removeFromSuperview() } if toView != self.emptyPrivateTabsView { toView.removeFromSuperview() } self.collectionView.alpha = 1 } } @available(iOS 9, *) private func privateTabsAreEmpty() -> Bool { return privateMode && tabManager.privateTabs.count == 0 } @available(iOS 9, *) func changePrivacyMode(isPrivate: Bool) { if isPrivate != privateMode { guard let _ = collectionView else { privateMode = isPrivate return } SELdidTogglePrivateMode() } } private func openNewTab(request: NSURLRequest? = nil) { if #available(iOS 9, *) { if privateMode { emptyPrivateTabsView.hidden = true } } // We're only doing one update here, but using a batch update lets us delay selecting the tab // until after its insert animation finishes. self.collectionView.performBatchUpdates({ _ in var tab: Browser if #available(iOS 9, *) { tab = self.tabManager.addTab(request, isPrivate: self.privateMode) } else { tab = self.tabManager.addTab(request) } self.tabManager.selectTab(tab) }, completion: { finished in if finished { self.navigationController?.popViewControllerAnimated(true) } }) } } // MARK: - App Notifications extension TabTrayController { func SELappWillResignActiveNotification() { if privateMode { collectionView.alpha = 0 } } func SELappDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.collectionView.alpha = 1 }, completion: nil) } } extension TabTrayController: TabSelectionDelegate { func didSelectTabAtIndex(index: Int) { let tab = tabsToDisplay[index] tabManager.selectTab(tab) self.navigationController?.popViewControllerAnimated(true) } } extension TabTrayController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(modalViewController: UIViewController, animated: Bool) { dismissViewControllerAnimated(animated, completion: { self.collectionView.reloadData() }) } } extension TabTrayController: TabManagerDelegate { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) { } func tabManager(tabManager: TabManager, didCreateTab tab: Browser) { } func tabManager(tabManager: TabManager, didAddTab tab: Browser) { // Get the index of the added tab from it's set (private or normal) guard let index = tabsToDisplay.indexOf(tab) else { return } tabDataSource.addTab(tab) self.collectionView?.performBatchUpdates({ _ in self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)]) }, completion: { finished in if finished { tabManager.selectTab(tab) // don't pop the tab tray view controller if it is not in the foreground if self.presentedViewController == nil { self.navigationController?.popViewControllerAnimated(true) } } }) } func tabManager(tabManager: TabManager, didRemoveTab tab: Browser) { let removedIndex = tabDataSource.removeTab(tab) self.collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: removedIndex, inSection: 0)]) // Workaround: On iOS 8.* devices, cells don't get reloaded during the deletion but after the // animation has finished which causes cells that animate from above to suddenly 'appear'. This // is fixed on iOS 9 but for iOS 8 we force a reload on non-visible cells during the animation. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_8_3) { let visibleCount = collectionView.indexPathsForVisibleItems().count var offscreenIndexPaths = [NSIndexPath]() for i in 0..<(tabsToDisplay.count - visibleCount) { offscreenIndexPaths.append(NSIndexPath(forItem: i, inSection: 0)) } self.collectionView.reloadItemsAtIndexPaths(offscreenIndexPaths) } if #available(iOS 9, *) { if privateTabsAreEmpty() { emptyPrivateTabsView.alpha = 1 } } } func tabManagerDidAddTabs(tabManager: TabManager) { } func tabManagerDidRestoreTabs(tabManager: TabManager) { } } extension TabTrayController: UIScrollViewAccessibilityDelegate { func accessibilityScrollStatusForScrollView(scrollView: UIScrollView) -> String? { var visibleCells = collectionView.visibleCells() as! [TabCell] var bounds = collectionView.bounds bounds = CGRectOffset(bounds, collectionView.contentInset.left, collectionView.contentInset.top) bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom // visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...) visibleCells = visibleCells.filter { !CGRectIsEmpty(CGRectIntersection($0.frame, bounds)) } let cells = visibleCells.map { self.collectionView.indexPathForCell($0)! } let indexPaths = cells.sort { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) } if indexPaths.count == 0 { return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray") } let firstTab = indexPaths.first!.row + 1 let lastTab = indexPaths.last!.row + 1 let tabCount = collectionView.numberOfItemsInSection(0) if (firstTab == lastTab) { let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.") return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: tabCount)) } else { let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.") return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: lastTab), NSNumber(integer: tabCount)) } } } extension TabTrayController: SwipeAnimatorDelegate { func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) { let tabCell = animator.container as! TabCell if let indexPath = collectionView.indexPathForCell(tabCell) { let tab = tabsToDisplay[indexPath.item] tabManager.removeTab(tab) UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: "")) } } } extension TabTrayController: TabCellDelegate { func tabCellDidClose(cell: TabCell) { let indexPath = collectionView.indexPathForCell(cell)! let tab = tabsToDisplay[indexPath.item] tabManager.removeTab(tab) } } extension TabTrayController: SettingsDelegate { func settingsOpenURLInNewTab(url: NSURL) { let request = NSURLRequest(URL: url) openNewTab(request) } } private class TabManagerDataSource: NSObject, UICollectionViewDataSource { unowned var cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate> private var tabs: [Browser] init(tabs: [Browser], cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>) { self.cellDelegate = cellDelegate self.tabs = tabs super.init() } /** Removes the given tab from the data source - parameter tab: Tab to remove - returns: The index of the removed tab, -1 if tab did not exist */ func removeTab(tabToRemove: Browser) -> Int { var index: Int = -1 for (i, tab) in tabs.enumerate() { if tabToRemove === tab { index = i break } } tabs.removeAtIndex(index) return index } /** Adds the given tab to the data source - parameter tab: Tab to add */ func addTab(tab: Browser) { tabs.append(tab) } @objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let tabCell = collectionView.dequeueReusableCellWithReuseIdentifier(TabCell.Identifier, forIndexPath: indexPath) as! TabCell tabCell.animator.delegate = cellDelegate tabCell.delegate = cellDelegate let tab = tabs[indexPath.item] tabCell.style = tab.isPrivate ? .Dark : .Light tabCell.titleText.text = tab.displayTitle if !tab.displayTitle.isEmpty { tabCell.accessibilityLabel = tab.displayTitle } else { tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url) } tabCell.isAccessibilityElement = true tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.") if let favIcon = tab.displayFavicon { tabCell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!) } else { var defaultFavicon = UIImage(named: "defaultFavicon") if tab.isPrivate { defaultFavicon = defaultFavicon?.imageWithRenderingMode(.AlwaysTemplate) tabCell.favicon.image = defaultFavicon tabCell.favicon.tintColor = UIColor.whiteColor() } else { tabCell.favicon.image = defaultFavicon } } tabCell.background.image = tab.screenshot return tabCell } @objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tabs.count } } @objc protocol TabSelectionDelegate: class { func didSelectTabAtIndex(index :Int) } private class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout { weak var tabSelectionDelegate: TabSelectionDelegate? private var traitCollection: UITraitCollection private var profile: Profile private var numberOfColumns: Int { let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true // iPhone 4-6+ portrait if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular { return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin } else { return TabTrayControllerUX.NumberOfColumnsWide } } init(profile: Profile, traitCollection: UITraitCollection) { self.profile = profile self.traitCollection = traitCollection super.init() } private func cellHeightForCurrentDevice() -> CGFloat { let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5) if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact { return shortHeight } else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact { return shortHeight } else { return TabTrayControllerUX.TextBoxHeight * 8 } } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return TabTrayControllerUX.Margin } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)) return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice()) } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin) } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return TabTrayControllerUX.Margin } @objc func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row) } } // There seems to be a bug with UIKit where when the UICollectionView changes its contentSize // from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the // final state. // This workaround forces the contentSize to always be larger than the frame size so the animation happens more // smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I // think is fine, but if needed we can disable user scrolling in this case. private class TabTrayCollectionViewLayout: UICollectionViewFlowLayout { private override func collectionViewContentSize() -> CGSize { var calculatedSize = super.collectionViewContentSize() let collectionViewHeight = collectionView?.bounds.size.height ?? 0 if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 { calculatedSize.height = collectionViewHeight + 1 } return calculatedSize } } struct EmptyPrivateTabsViewUX { static let TitleColor = UIColor.whiteColor() static let TitleFont = UIFont.systemFontOfSize(22, weight: UIFontWeightMedium) static let DescriptionColor = UIColor.whiteColor() static let DescriptionFont = UIFont.systemFontOfSize(17) static let LearnMoreFont = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium) static let TextMargin: CGFloat = 18 static let LearnMoreMargin: CGFloat = 30 static let MaxDescriptionWidth: CGFloat = 250 } // View we display when there are no private tabs created private class EmptyPrivateTabsView: UIView { private lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = EmptyPrivateTabsViewUX.TitleColor label.font = EmptyPrivateTabsViewUX.TitleFont label.textAlignment = NSTextAlignment.Center return label }() private var descriptionLabel: UILabel = { let label = UILabel() label.textColor = EmptyPrivateTabsViewUX.DescriptionColor label.font = EmptyPrivateTabsViewUX.DescriptionFont label.textAlignment = NSTextAlignment.Center label.numberOfLines = 0 label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth return label }() private var learnMoreButton: UIButton = { let button = UIButton(type: .System) button.setTitle( NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode"), forState: .Normal) button.setTitleColor(UIConstants.PrivateModeTextHighlightColor, forState: .Normal) button.titleLabel?.font = EmptyPrivateTabsViewUX.LearnMoreFont return button }() private var iconImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "largePrivateMask")) return imageView }() override init(frame: CGRect) { super.init(frame: frame) titleLabel.text = NSLocalizedString("Private Browsing", tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode") descriptionLabel.text = NSLocalizedString("Firefox won't remember any of your history or cookies, but new bookmarks will be saved.", tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode") addSubview(titleLabel) addSubview(descriptionLabel) addSubview(iconImageView) addSubview(learnMoreButton) titleLabel.snp_makeConstraints { make in make.center.equalTo(self) } iconImageView.snp_makeConstraints { make in make.bottom.equalTo(titleLabel.snp_top).offset(-EmptyPrivateTabsViewUX.TextMargin) make.centerX.equalTo(self) } descriptionLabel.snp_makeConstraints { make in make.top.equalTo(titleLabel.snp_bottom).offset(EmptyPrivateTabsViewUX.TextMargin) make.centerX.equalTo(self) } learnMoreButton.snp_makeConstraints { (make) -> Void in make.top.equalTo(descriptionLabel.snp_bottom).offset(EmptyPrivateTabsViewUX.LearnMoreMargin) make.centerX.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } @available(iOS 9.0, *) extension TabTrayController: TabPeekDelegate { func tabPeekDidAddBookmark(tab: Browser) { delegate?.tabTrayDidAddBookmark(tab) } func tabPeekDidAddToReadingList(tab: Browser) -> ReadingListClientRecord? { return delegate?.tabTrayDidAddToReadingList(tab) } func tabPeekDidCloseTab(tab: Browser) { if let index = self.tabDataSource.tabs.indexOf(tab), let cell = self.collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as? TabCell { cell.SELclose() } } func tabPeekRequestsPresentationOf(viewController viewController: UIViewController) { delegate?.tabTrayRequestsPresentationOf(viewController: viewController) } } @available(iOS 9.0, *) extension TabTrayController: UIViewControllerPreviewingDelegate { func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let collectionView = collectionView else { return nil } let convertedLocation = self.view.convertPoint(location, toView: collectionView) guard let indexPath = collectionView.indexPathForItemAtPoint(convertedLocation), let cell = collectionView.cellForItemAtIndexPath(indexPath) else { return nil } let tab = tabDataSource.tabs[indexPath.row] let tabVC = TabPeekViewController(tab: tab, delegate: self) if let browserProfile = profile as? BrowserProfile { tabVC.setState(withProfile: browserProfile, clientPickerDelegate: self) } previewingContext.sourceRect = self.view.convertRect(cell.frame, fromView: collectionView) return tabVC } func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) { guard let tpvc = viewControllerToCommit as? TabPeekViewController else { return } tabManager.selectTab(tpvc.tab) self.navigationController?.popViewControllerAnimated(true) delegate?.tabTrayDidDismiss(self) } } extension TabTrayController: ClientPickerViewControllerDelegate { func clientPickerViewController(clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) { if let item = clientPickerViewController.shareItem { self.profile.sendItems([item], toClients: clients) } clientPickerViewController.dismissViewControllerAnimated(true, completion: nil) } func clientPickerViewControllerDidCancel(clientPickerViewController: ClientPickerViewController) { clientPickerViewController.dismissViewControllerAnimated(true, completion: nil) } }
mpl-2.0
dunkelstern/UnchainedUUID
Package.swift
1
500
// // Package.swift // UnchainedUUID // // Created by Johannes Schriewer on 2015-12-20. // Copyright © 2015 Johannes Schriewer. All rights reserved. // import PackageDescription let package = Package( name: "UnchainedUUID", targets: [ Target(name:"UnchainedUUIDTests", dependencies: [.Target(name: "UnchainedUUID")]), Target(name:"UnchainedUUID") ], dependencies: [ .Package(url: "https://github.com/dunkelstern/UnchainedString.git", majorVersion: 1) ] )
bsd-3-clause
palle-k/Covfefe
Tests/CovfefeTests/PerformanceTests.swift
1
2850
// // PerformanceTests.swift // CovfefeTests // // Created by Palle Klewitz on 17.02.18. // import XCTest @testable import Covfefe class PerformanceTests: XCTestCase { static let jsonGrammar: Grammar = { let grammarString = """ <any> ::= <optional-whitespace> <node> <optional-whitespace> <node> ::= <dictionary> | <array> | <value> <value> ::= <string> | <number> | <boolean> | <null> <dictionary> ::= "{" <dictionary-content> "}" | "{" <optional-whitespace> "}" <dictionary-content> ::= <dictionary-content> "," <optional-whitespace> <key-value-pair> <optional-whitespace> | <optional-whitespace> <key-value-pair> <optional-whitespace> <key-value-pair> ::= <key> <optional-whitespace> ":" <optional-whitespace> <any> <array> ::= "[" <array-contents> "]" | "[" <optional-whitespace> "]" <array-contents> ::= <array-contents> "," <optional-whitespace> <any> <optional-whitespace> | <optional-whitespace> <any> <optional-whitespace> <key> ::= '"' [{<character>}] '"' <string> ::= '"' [{<character>}] '"' <string-content> ::= <string-content> <character> | <character> <digit-except-zero> ::= '1' ... '9' <digit> ::= '0' ... '9' <hex-digit> ::= <digit> | 'a' ... 'f' | 'A' ... 'F' <whitespace> ::= ' ' | '\\t' | <EOL> <character> ::= <escaped-sequence> | '#' ... '[' (* includes all letters and numbers *) | ']' ... '~' | '!' | <whitespace> <escaped-sequence> ::= '\\\\' <escaped> <escaped> ::= '"' | '\\\\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' | 'u' <hex-digit> <hex-digit> <hex-digit> <hex-digit> <number> ::= ['-'] <integer> ['.' {'0' ... '9'}] [('E' | 'e') <exponent>] <integer> ::= '1'...'9' [{'0'...'9'}] <integer-prefix> ::= <digit-except-zero> | <integer-prefix> <digit> <fraction> ::= <digit> | <fraction> <digit> <exponent> ::= ['-' | '+'] <integer> <boolean> ::= 't' 'r' 'u' 'e' | 'f' 'a' 'l' 's' 'e' <null> ::= 'n' 'u' 'l' 'l' <optional-whitespace> ::= <optional-whitespace> <whitespace> | '' """ return try! Grammar(bnf: grammarString, start: "any") }() func testEarleyPerformance() { let grammar = PerformanceTests.jsonGrammar let parser = EarleyParser(grammar: grammar) let testString = """ {"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } }} """ measure { for _ in 0 ..< 3 { if parser.recognizes(testString) == false { XCTFail() } } } } }
mit
steve-holmes/music-app-2
MusicApp/AppDelegate.swift
1
1149
// // AppDelegate.swift // MusicApp // // Created by Hưng Đỗ on 6/9/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import GoogleMobileAds import AlamofireNetworkActivityIndicator @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { let module = ModuleContainer() var musicNotification: MusicNotification! var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { GADMobileAds.configure(withApplicationID: "ca-app-pub-3982247659947570~8380730445") NetworkActivityIndicatorManager.shared.isEnabled = true let musicModule = self.module.musicModule musicNotification = musicModule.container.resolve(MusicNotification.self)! window = UIWindow() let mainModule = module.mainModule let mainController = mainModule.container.resolve(MainViewController.self)! window?.rootViewController = mainController window?.makeKeyAndVisible() return true } }
mit
TheNounProject/CollectionView
CollectionView/DataStructures/IndexedSet.swift
1
5294
// // IndexedSet.swift // CollectionView // // Created by Wes Byrne on 1/20/17. // Copyright © 2017 Noun Project. All rights reserved. // import Foundation public struct IndexedSet<Index: Hashable, Value: Hashable>: Sequence, CustomDebugStringConvertible, ExpressibleByDictionaryLiteral { // var table = MapTab fileprivate var byValue = [Value: Index]() fileprivate var byIndex = [Index: Value]() // fileprivate var _sequenced = OrderedSet<Value>() public var indexes: [Index] { return Array(byIndex.keys) } public var indexSet: Set<Index> { return Set(byIndex.keys) } public var dictionary: [Index: Value] { return byIndex } public var values: [Value] { return Array(byIndex.values) } public var valuesSet: Set<Value> { return Set(byIndex.values) } public var count: Int { return byValue.count } public var isEmpty: Bool { return byValue.isEmpty } public func value(for index: Index) -> Value? { return byIndex[index] } public func index(of value: Value) -> Index? { return byValue[value] } public init() { } public init(dictionaryLiteral elements: (Index, Value)...) { for e in elements { self.insert(e.1, for: e.0) } } public init(_ dictionary: [Index: Value]) { for e in dictionary { self.insert(e.1, for: e.0) } } public subscript(index: Index) -> Value? { get { return value(for: index) } set(newValue) { if let v = newValue { insert(v, for: index) } else { _ = removeValue(for: index) } } } public var debugDescription: String { var str = "\(type(of: self)) [\n" for i in self { str += "\(i.index) : \(i.value)\n" } str += "]" return str } public func contains(_ object: Value) -> Bool { return byValue[object] != nil } public func containsValue(for index: Index) -> Bool { return byIndex[index] != nil } /// Set the value-index pair removing any existing entries for either /// /// - Parameter value: The value /// - Parameter index: The index public mutating func set(_ value: Value, for index: Index) { self.removeValue(for: index) self.remove(value) byValue[value] = index byIndex[index] = value } /// Insert value for the given index if the value does not exist. /// /// - Parameter value: A value /// - Parameter index: An index public mutating func insert(_ value: Value, for index: Index) { self.set(value, for: index) } @discardableResult public mutating func removeValue(for index: Index) -> Value? { guard let value = byIndex.removeValue(forKey: index) else { return nil } byValue.removeValue(forKey: value) return value } @discardableResult public mutating func remove(_ value: Value) -> Index? { guard let index = byValue.removeValue(forKey: value) else { return nil } byIndex.removeValue(forKey: index) return index } public mutating func removeAll() { byValue.removeAll() byIndex.removeAll() } public typealias Iterator = AnyIterator<(index: Index, value: Value)> public func makeIterator() -> Iterator { var it = byIndex.makeIterator() return AnyIterator { if let val = it.next() { return (val.key, val.value) } return nil } } } extension IndexedSet { func union(_ other: IndexedSet) -> IndexedSet { var new = self for e in other.byIndex { new.insert(e.value, for: e.key) } return new } } extension Array where Element: Hashable { public var indexedSet: IndexedSet<Int, Element> { var set = IndexedSet<Int, Element>() for (idx, v) in self.enumerated() { set.insert(v, for: idx) } return set } } extension Collection where Iterator.Element: Hashable { public var indexedSet: IndexedSet<Int, Iterator.Element> { var set = IndexedSet<Int, Iterator.Element>() for (idx, v) in self.enumerated() { set.insert(v, for: idx) } return set } } extension IndexedSet where Index: Comparable { var orderedIndexes: [Index] { return self.byIndex.keys.sorted() } func ordered() -> [Iterator.Element] { return self.makeIterator().sorted { (a, b) -> Bool in return a.index < b.index } } func orderedLog() -> String { var str = "\(type(of: self)) [\n" for i in self.ordered() { str += "\(i.index) : \(i.value)\n" } str += "]" return str } var orderedValues: [Value] { let sorted = self.byIndex.sorted(by: { (v1, v2) -> Bool in return v1.key < v2.key }) var res = [Value]() for element in sorted { res.append(element.value) } return res } }
mit
garynewby/GLNPianoView
Source/Extensions.swift
1
5942
// // Extensions.swift // PianoView // // Created by Gary Newby on 23/09/2017. // import UIKit import QuartzCore extension UIImage { static func keyImage(_ aSize: CGSize, blackKey: Bool, keyDown: Bool, keyCornerRadius: CGFloat, noteNumber: Int) -> UIImage? { let scale = UIScreen.main.scale var size: CGSize = aSize size.width *= scale size.height *= scale UIGraphicsBeginImageContext(size) if let context = UIGraphicsGetCurrentContext() { let colorSpace = CGColorSpaceCreateDeviceRGB() if blackKey { let strokeColor1 = UIColor(red: 0, green: 0, blue: 0, alpha: 0.951) let strokeColor2 = UIColor(red: 0.379, green: 0.379, blue: 0.379, alpha: 1) let gradientColors = [strokeColor1.cgColor, strokeColor2.cgColor] let gradientLocations: [CGFloat] = [0.11, 1.0] if let gradient = CGGradient(colorsSpace: colorSpace, colors: gradientColors as CFArray, locations: gradientLocations) { let frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) let rectanglePath = UIBezierPath(rect: CGRect(x: frame.minX, y: frame.minY, width: size.width, height: size.height)) strokeColor1.setFill() rectanglePath.fill() let border = size.width * 0.15 let width = size.width * 0.7 var topRectHeight = size.height * 0.86 var bottomRectOffset = size.height * 0.875 let bottomRectHeight = size.height * 0.125 if keyDown { topRectHeight = size.height * 0.91 bottomRectOffset = size.height * 0.925 } let roundedRectangleRect = CGRect(x: frame.minX + border, y: frame.minY, width: width, height: topRectHeight) let roundedRectanglePath = UIBezierPath(roundedRect: roundedRectangleRect, cornerRadius: keyCornerRadius) context.saveGState() roundedRectanglePath.addClip() context.drawLinearGradient(gradient, start: CGPoint(x: roundedRectangleRect.midX, y: roundedRectangleRect.minY), end: CGPoint(x: roundedRectangleRect.midX, y: roundedRectangleRect.maxY), options: []) context.restoreGState() let roundedRectangle2Rect = CGRect(x: frame.minX + border, y: frame.minY + bottomRectOffset, width: width, height: bottomRectHeight) let roundedRectangle2Path = UIBezierPath(roundedRect: roundedRectangle2Rect, cornerRadius: keyCornerRadius) context.saveGState() roundedRectangle2Path.addClip() context.drawLinearGradient(gradient, start: CGPoint(x: roundedRectangle2Rect.midX, y: roundedRectangle2Rect.maxY), end: CGPoint(x: roundedRectangle2Rect.midX, y: roundedRectangle2Rect.minY), options: []) } } else { // White key let strokeColor1 = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.0) var strokeColor2 = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.20) if keyDown { strokeColor2 = UIColor.noteColourFor(midiNumber: noteNumber, alpha: 0.75) // Background let frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.setFillColor(UIColor.noteColourFor(midiNumber: noteNumber, alpha: 0.30).cgColor) context.fill(frame) } let gradientColors = [strokeColor1.cgColor, strokeColor2.cgColor] let gradientLocations: [CGFloat] = [0.1, 1.0] if let gradient = CGGradient(colorsSpace: colorSpace, colors: gradientColors as CFArray, locations: gradientLocations) { let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: size.width, height: size.height)) context.saveGState() rectanglePath.addClip() context.drawRadialGradient(gradient, startCenter: CGPoint(x: size.width / 2.0, y: size.height / 2.0), startRadius: size.height * 0.01, endCenter: CGPoint(x: size.width / 2.0, y: size.height / 2.0), endRadius: size.height * 0.6, options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]) } } context.restoreGState() } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } extension UIColor { static func noteColourFor(midiNumber: Int, alpha: Float) -> UIColor { let hue = (CGFloat(midiNumber).truncatingRemainder(dividingBy: 12.0) / 12.0) return UIColor(hue: hue, saturation: 0.0, brightness: 0.40, alpha: CGFloat(alpha)) } } extension Int { func clamp(min: Int, max: Int) -> Int { let r = self < min ? min : self return r > max ? max : r } func isWhiteKey() -> Bool { let k = self % 12 return (k == 0 || k == 2 || k == 4 || k == 5 || k == 7 || k == 9 || k == 11) } } extension CGFloat { func clamp(min: CGFloat, max: CGFloat) -> CGFloat { let r = self < min ? min : self return r > max ? max : r } }
mit
pantuspavel/PPAssetsActionController
PPAssetsActionController/Classes/PPAssetsCollectionController.swift
1
10578
import UIKit import AVFoundation protocol PPAssetsViewControllerDelegate: class { func assetsViewController(_ controller: PPAssetsCollectionController, didChange itemsCount: Int) func assetsViewControllerDidRequestCameraController(_ controller: PPAssetsCollectionController) } /** Top part of Assets Action Controller that represents camera roll assets preview. */ class PPAssetsCollectionController: UICollectionViewController { public weak var delegate: PPAssetsViewControllerDelegate? private var flowLayout: PPCollectionViewLayout! fileprivate var heightConstraint: NSLayoutConstraint! private let assetManager = PPAssetManager() fileprivate var assets: [MediaProvider] = [] private var selectedItemRows = Set<Int>() fileprivate var config: PPAssetsActionConfig! fileprivate var captureSession: AVCaptureSession? fileprivate var captureLayer: AVCaptureVideoPreviewLayer? fileprivate let cameraIsAvailable = UIImagePickerController.isSourceTypeAvailable(.camera) public init(aConfig: PPAssetsActionConfig) { flowLayout = PPCollectionViewLayout() config = aConfig super.init(collectionViewLayout: flowLayout) flowLayout.itemsInfoProvider = self } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopCaptureSession() } override func viewDidLoad() { super.viewDidLoad() collectionView?.backgroundColor = UIColor.clear collectionView?.translatesAutoresizingMaskIntoConstraints = false collectionView?.register(PPPhotoViewCell.self, forCellWithReuseIdentifier: PPPhotoViewCell.reuseIdentifier) collectionView?.register(PPVideoViewCell.self, forCellWithReuseIdentifier: PPVideoViewCell.reuseIdentifier) collectionView?.register(PPLiveCameraCell.self, forCellWithReuseIdentifier: PPLiveCameraCell.reuseIdentifier) collectionView?.showsVerticalScrollIndicator = false collectionView?.showsHorizontalScrollIndicator = false heightConstraint = NSLayoutConstraint(item: collectionView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: config.assetsPreviewRegularHeight) collectionView?.addConstraint(heightConstraint) self.flowLayout.viewWidth = self.view!.frame.width let requestImages = { self.assetManager.getAssets(offset: 0, count: 20, imagesOnly: !self.config.showVideos) { assets in if assets.count > 0 { self.assets = assets self.collectionView?.reloadData() } else { self.heightConstraint.constant = 0 } } } if assetManager.authorizationStatus() == .authorized { requestImages() } else if config.askPhotoPermissions { assetManager.requestAuthorization { status in if status == .authorized { requestImages() } else { self.heightConstraint.constant = 0 } } } else { self.heightConstraint.constant = 0 } if rowCountForLiveCameraCell() == 1 { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.setupCaptureSession() } } } func selectedMedia() -> [MediaProvider] { return selectedItemRows.map { assets[$0] } } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return assets.count + rowCountForLiveCameraCell(); } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.row == 0 && rowCountForLiveCameraCell() == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PPLiveCameraCell.reuseIdentifier, for: indexPath) as! PPLiveCameraCell cell.backgroundColor = UIColor.black cell.accessibilityLabel = PPLiveCameraCell.reuseIdentifier if let layer = captureLayer { cell.set(layer: layer) } return cell } let mediaProvider = assets[modifiedRow(for: indexPath.row)] var cell: PPCheckedViewCell! if let video = mediaProvider.video() { let videoCell = collectionView.dequeueReusableCell(withReuseIdentifier: PPVideoViewCell.reuseIdentifier, for: indexPath) as! PPVideoViewCell let item = AVPlayerItem(asset: video) let player = AVPlayer(playerItem: item) player.volume = 0.0 let playerLayer = AVPlayerLayer(player: player) videoCell.set(mediaProvider.image()!, playerLayer) cell = videoCell } else if let image = mediaProvider.image() { let photoCell = collectionView.dequeueReusableCell(withReuseIdentifier: PPPhotoViewCell.reuseIdentifier, for: indexPath) as! PPPhotoViewCell photoCell.set(image) cell = photoCell } cell.checked.tintColor = config.tintColor if (heightConstraint.constant == config.assetsPreviewExpandedHeight) { cell.set(selected: selectedItemRows.contains(modifiedRow(for: indexPath.row))) } cell.accessibilityLabel = "asset-\(modifiedRow(for: indexPath.row))" return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.row == 0 && rowCountForLiveCameraCell() == 1 { delegate?.assetsViewControllerDidRequestCameraController(self) return } if selectedItemRows.contains(modifiedRow(for: indexPath.row)) { selectedItemRows.remove(modifiedRow(for: indexPath.row)) } else { selectedItemRows.insert(modifiedRow(for: indexPath.row)) } delegate?.assetsViewController(self, didChange: selectedItemRows.count) if (heightConstraint.constant < config.assetsPreviewExpandedHeight) { heightConstraint.constant = config.assetsPreviewExpandedHeight collectionView.setNeedsLayout() let flowLayout = PPCollectionViewLayout() flowLayout.itemsInfoProvider = self flowLayout.viewWidth = view.frame.width UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseIn, animations: { // FIXME: iOS10 layout workaround. Think of a better way. collectionView.superview?.superview?.layoutIfNeeded() collectionView.setCollectionViewLayout(flowLayout, animated: true) }) { result in collectionView.reloadData() } } else { collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) if let cell = collectionView.cellForItem(at: indexPath) as? PPPhotoViewCell { cell.set(selected: selectedItemRows.contains(modifiedRow(for: indexPath.row))) } } } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if (indexPath.row == assets.count - 2) { self.assetManager.getAssets(offset: assets.count, count: 20, imagesOnly: !config.showVideos) { assets in if assets.count > self.assets.count { self.assets = assets self.collectionView?.reloadData() } } } if let videoCell = cell as? PPVideoViewCell { videoCell.startVideo() } } override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let videoCell = cell as? PPVideoViewCell { videoCell.stopVideo() } } } // MARK: - Camera extension PPAssetsCollectionController { func setupCaptureSession() { let defaultDevice = AVCaptureDevice.default(for: AVMediaType.video) if let input = try? AVCaptureDeviceInput(device: defaultDevice!) { captureSession = AVCaptureSession() captureSession?.addInput(input) captureLayer = AVCaptureVideoPreviewLayer(session: captureSession!) captureLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill captureSession?.startRunning() collectionView?.reloadData() } } func stopCaptureSession() { if let session = captureSession { session.stopRunning() captureSession = nil } } } extension PPAssetsCollectionController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.row == 0 && rowCountForLiveCameraCell() == 1 { return CGSize(width: heightConstraint.constant, height: heightConstraint.constant) } let imageView = UIImageView(image: assets[modifiedRow(for: indexPath.row)].image()!) imageView.contentMode = .scaleAspectFill let factor = heightConstraint.constant / imageView.frame.height return CGSize(width: imageView.frame.width * factor, height: heightConstraint.constant) } } extension PPAssetsCollectionController { func modifiedRow(for row: Int) -> Int { return row - (config.showLiveCameraCell ? rowCountForLiveCameraCell() : 0) } func rowCountForLiveCameraCell() -> Int { return cameraIsAvailable ? 1 : 0 } }
mit
RevenueCat/purchases-ios
Tests/BackendIntegrationTestApp/BackendIntegrationTestApp.swift
1
325
// // BackendIntegrationTestApp.swift // BackendIntegrationTestApp // // Created by Andrés Boedo on 5/3/21. // Copyright © 2021 Purchases. All rights reserved. // import SwiftUI @main struct BackendIntegrationTestApp: App { var body: some Scene { WindowGroup { ContentView() } } }
mit
jmgc/swift
test/Interop/Cxx/implementation-only-imports/check-function-transitive-visibility.swift
1
1061
// RUN: %empty-directory(%t) // RUN: mkdir %t/use_module_a %t/use_module_b // RUN: %target-swift-frontend -enable-library-evolution -swift-version 5 -emit-module -o %t/use_module_a/UseModuleA.swiftmodule %S/Inputs/use-module-a.swift -I %S/Inputs -enable-cxx-interop // RUN: %target-swift-frontend -enable-library-evolution -swift-version 5 -emit-module -o %t/use_module_b/UseModuleB.swiftmodule %S/Inputs/use-module-b.swift -I %S/Inputs -enable-cxx-interop // RUN: %target-swift-frontend -typecheck -swift-version 5 -I %t/use_module_a -I %t/use_module_b -I %S/Inputs -enable-cxx-interop %s // Swift should consider all sources for a decl and recognize that the // decl is not hidden behind @_implementationOnly in all modules. // This test, as well as `check-function-transitive-visibility-inversed.swift` // ensures that Swift looks into the transitive visible modules as well // when looking for the `getFortyTwo()` decl. import UseModuleA @_implementationOnly import UseModuleB @inlinable public func callFortyTwo() -> CInt { return getFortyTwo() }
apache-2.0
VirgilSecurity/virgil-sdk-keys-ios
Source/Keyknox/Client/KeyknoxClientProtocol.swift
1
3370
// // Copyright (C) 2015-2020 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> // import Foundation /// Protocol for KeyknoxClient /// /// See: KeyknoxClient for default implementation @objc(VSSKeyknoxClientProtocol) public protocol KeyknoxClientProtocol: class { /// Push value to Keyknox service /// /// - Parameters: /// - params: params /// - meta: meta data /// - value: encrypted blob /// - previousHash: hash of previous blob /// - Returns: EncryptedKeyknoxValue /// - Throws: Depends on implementation @objc func pushValue(params: KeyknoxPushParams?, meta: Data, value: Data, previousHash: Data?) throws -> EncryptedKeyknoxValue /// Pulls values from Keyknox service /// /// - Parameter params: Pull params /// - Returns: EncryptedKeyknoxValue /// - Throws: Depends on implementation @objc func pullValue(params: KeyknoxPullParams?) throws -> EncryptedKeyknoxValue /// Get keys for given root /// /// - Parameter params: Get keys params /// - Returns: Array of keys /// - Throws: Depends on implementation @objc func getKeys(params: KeyknoxGetKeysParams) throws -> Set<String> /// Resets Keyknox value (makes it empty) /// /// - Parameter params: Reset params /// - Returns: DecryptedKeyknoxValue /// - Throws: Depends on implementation @objc func resetValue(params: KeyknoxResetParams?) throws -> DecryptedKeyknoxValue /// Deletes recipient /// /// - Parameter params: Delete recipient params /// - Returns: DecryptedKeyknoxValue /// - Throws: Depends on implementation @objc func deleteRecipient(params: KeyknoxDeleteRecipientParams) throws -> DecryptedKeyknoxValue }
bsd-3-clause
DarrenKong/firefox-ios
XCUITests/TopTabsTest.swift
1
9393
/* 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 XCTest let url = "www.mozilla.org" let urlLabel = "Internet for people, not profit — Mozilla" let urlValue = "mozilla.org" let urlExample = "example.com" let urlLabelExample = "Example Domain" let urlValueExample = "example" class TopTabsTest: BaseTestCase { func testAddTabFromSettings() { navigator.createNewTab() navigator.openURL(url) waitForValueContains(app.textFields["url"], value: urlValue) waitforExistence(app.buttons["Show Tabs"]) let numTab = app.buttons["Show Tabs"].value as? String XCTAssertEqual("2", numTab) } func testAddTabFromTabTray() { navigator.goto(TabTray) navigator.openURL(url) waitUntilPageLoad() waitForValueContains(app.textFields["url"], value: urlValue) // The tabs counter shows the correct number let tabsOpen = app.buttons["Show Tabs"].value XCTAssertEqual("2", tabsOpen as? String) // The tab tray shows the correct tabs navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[urlLabel]) } private func checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: Int) { navigator.goto(TabTray) let numTabsOpen = userState.numTabs XCTAssertEqual(numTabsOpen, expectedNumberOfTabsOpen, "The number of tabs open is not correct") } private func closeTabTrayView(goBackToBrowserTab: String) { app.collectionViews.cells[goBackToBrowserTab].firstMatch.tap() navigator.nowAt(BrowserTab) } func testAddTabFromContext() { navigator.openURL(urlExample) // Initially there is only one tab open let tabsOpenInitially = app.buttons["Show Tabs"].value XCTAssertEqual("1", tabsOpenInitially as? String) // Open link in a different tab and switch to it waitforExistence(app.webViews.links.staticTexts["More information..."]) app.webViews.links.staticTexts["More information..."].press(forDuration: 5) app.buttons["Open in New Tab"].tap() waitUntilPageLoad() // Open tab tray to check that both tabs are there checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 2) waitforExistence(app.collectionViews.cells["Example Domain"]) waitforExistence(app.collectionViews.cells["IANA — IANA-managed Reserved Domains"]) } // This test only runs for iPhone see bug 1409750 func testAddTabByLongPressTabsButton() { navigator.performAction(Action.OpenNewTabLongPressTabsButton) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 2) } // This test only runs for iPhone see bug 1409750 func testAddPrivateTabByLongPressTabsButton() { navigator.performAction(Action.OpenPrivateTabLongPressTabsButton) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1) waitforExistence(app.buttons["TabTrayController.maskButton"]) XCTAssertTrue(app.buttons["TabTrayController.maskButton"].isEnabled) XCTAssertTrue(userState.isPrivate) } func testSwitchBetweenTabs() { // Open two urls from tab tray and switch between them navigator.openURL(url) navigator.goto(TabTray) navigator.openURL(urlExample) navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[urlLabel]) app.collectionViews.cells[urlLabel].tap() waitForValueContains(app.textFields["url"], value: urlValue) navigator.nowAt(BrowserTab) navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[urlLabelExample]) app.collectionViews.cells[urlLabelExample].tap() waitForValueContains(app.textFields["url"], value: urlValueExample) } func testCloseOneTab() { navigator.openURL(url) waitUntilPageLoad() navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[urlLabel]) // 'x' button to close the tab is not visible, so closing by swiping the tab app.collectionViews.cells[urlLabel].swipeRight() // After removing only one tab it automatically goes to HomepanelView waitforExistence(app.collectionViews.cells["TopSitesCell"]) XCTAssert(app.buttons["HomePanels.TopSites"].exists) } func testCloseAllTabsUndo() { // A different tab than home is open to do the proper checks navigator.openURL(url) waitUntilPageLoad() navigator.createSeveralTabsFromTabTray (numberTabs: 3) navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[urlLabel]) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4) // Close all tabs, undo it and check that the number of tabs is correct navigator.closeAllTabs() app.buttons["Undo"].tap() navigator.nowAt(BrowserTab) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4) waitforExistence(app.collectionViews.cells[urlLabel]) } func testCloseAllTabsPrivateModeUndo() { // A different tab than home is open to do the proper checks navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.openURL(url) waitUntilPageLoad() navigator.createSeveralTabsFromTabTray (numberTabs: 3) navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[urlLabel]) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4) // Close all tabs, undo it and check that the number of tabs is correct navigator.closeAllTabs() XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private welcome screen is not shown") app.buttons["Undo"].tap() navigator.nowAt(BrowserTab) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4) waitforExistence(app.collectionViews.cells[urlLabel]) } func testCloseAllTabs() { // A different tab than home is open to do the proper checks navigator.openURL(url) waitUntilPageLoad() // Add several tabs from tab tray menu and check that the number is correct before closing all navigator.createSeveralTabsFromTabTray (numberTabs: 3) navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[urlLabel]) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4) // Close all tabs and check that the number of tabs is correct navigator.closeAllTabs() checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1) waitforNoExistence(app.collectionViews.cells[urlLabel]) } func testCloseAllTabsPrivateMode() { // A different tab than home is open to do the proper checks navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.openURL(url) waitUntilPageLoad() // Add several tabs from tab tray menu and check that the number is correct before closing all navigator.createSeveralTabsFromTabTray (numberTabs: 3) navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[urlLabel]) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4) // Close all tabs and check that the number of tabs is correct navigator.closeAllTabs() XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private welcome screen is not shown") } func testCloseTabFromPageOptionsMenu() { // Open two websites so that there are two tabs open and the page options menu is available navigator.openURL(urlValue) navigator.openNewURL(urlString: urlExample) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 2) // Go back to one website so that the page options menu is available and close one tab from there closeTabTrayView(goBackToBrowserTab: urlLabelExample) navigator.performAction(Action.CloseTabFromPageOptions) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1) // Go back to the website left open, close it and check that it has been closed closeTabTrayView(goBackToBrowserTab: urlLabel) navigator.performAction(Action.CloseTabFromPageOptions) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1) waitforNoExistence(app.collectionViews.cells[urlLabel]) } func testCloseTabFromLongPressTabsButton() { // This menu is available in HomeScreen or NewTabScreen, so no need to open new websites navigator.performAction(Action.OpenNewTabFromTabTray) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 2) closeTabTrayView(goBackToBrowserTab: "home") navigator.performAction(Action.CloseTabFromTabTrayLongPressMenu) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1) closeTabTrayView(goBackToBrowserTab: "home") navigator.performAction(Action.CloseTabFromTabTrayLongPressMenu) checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1) closeTabTrayView(goBackToBrowserTab: "home") } }
mpl-2.0
zirinisp/SlackKit
SlackKit/Sources/AttachmentField.swift
1
1856
// // AttachmentField.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public struct AttachmentField { public let title: String? public let value: String? public let short: Bool? internal init(field: [String: Any]?) { title = field?["title"] as? String value = field?["value"] as? String short = field?["short"] as? Bool } public init(title:String, value:String, short: Bool? = nil) { self.title = title self.value = value.slackFormatEscaping self.short = short } internal var dictionary: [String: Any] { var field = [String: Any]() field["title"] = title field["value"] = value field["short"] = short return field } }
mit
rcasanovan/MarvelApp
Marvel App/Marvel AppTests/Provider/Marvel List Provider/MCharacterProviderTests.swift
1
1704
// // MCharacterProviderTests.swift // Marvel App // // Created by Ricardo Casanova on 22/2/16. // Copyright © 2016 Marvel. All rights reserved. // import XCTest class MCharacterProviderTests: XCTestCase { var charactersProvider : MCharactersProvider? override func setUp() { super.setUp() self.charactersProvider = MCharactersProvider() } override func tearDown() { super.tearDown() } func testCharacterCreateProvider() { XCTAssert(self.charactersProvider != nil, "TEST FAILED: No provider could be created.") } func testCharacterGetAllCharacters() { let allCharacters:XCTestExpectation = self.expectation(description: "allCharacters") self.charactersProvider?.charactersProviderGetAllCharacters(withLimit: 80, offset: 0, onCompletion: { (characters, total, alert, errorCode, errorMessage) -> Void in XCTAssertEqual(errorCode, DRErrorCode.everythingOKCode, "TEST FAILED: No response from api.") allCharacters.fulfill() }) self.waitForExpectations(timeout: 30.0, handler: nil) } func testCharacterGetCharacterByName() { let characterByName:XCTestExpectation = self.expectation(description: "characterByName") self.charactersProvider?.charactersProviderCharacter(withName: "Hulk", limit: 80, offset: 0, onCompletion: { (characters, total, alert, errorCode, errorMessage) -> Void in XCTAssertEqual(errorCode, DRErrorCode.everythingOKCode, "TEST FAILED: No response from api.") characterByName.fulfill() }) self.waitForExpectations(timeout: 30.0, handler: nil) } }
apache-2.0
blstream/TOZ_iOS
TOZ_iOS/SignUpRequest.swift
1
1065
// // SignUpRequest.swift // TOZ_iOS // // Created by patronage on 28.04.2017. // Copyright © 2017 intive. All rights reserved. // import Foundation final class SignUpRequest: BackendAPIRequest { private let name: String private let surname: String private let phoneNumber: String private let email: String private let roles: [Role] init(name: String, surname: String, phoneNumber: String, email: String, roles: [Role]) { self.name = name self.surname = surname self.phoneNumber = phoneNumber self.email = email self.roles = roles } var endpoint: String { return "/users" } var method: NetworkService.Method { return .POST } var parameters: [String: Any]? { return [ "name": name, "surname": surname, "phoneNumber": phoneNumber, "email": email, "roles": roles.map {$0.rawValue} ] } var headers: [String: String]? { return defaultJSONHeaders() } }
apache-2.0
haibtdt/NotifiOS-Cumulation
NotifiOSCumulation/DefaultNotificationsTableViewController.swift
1
2618
// // DefaultNotificationsTableViewController.swift // NotifiOSCumulation // // Created by SB 8 on 9/29/15. // Copyright © 2015 Bui Hai. All rights reserved. // import UIKit public class DefaultNotificationsTableViewController: UITableViewController { @IBOutlet var clearAllButton: UIBarButtonItem! @IBOutlet var markAllAsReadButton: UIBarButtonItem! var notificationCumulationCenter_ : NotifiOSCumulationCenter? = nil public var notificationCumulationCenter : NotifiOSCumulationCenter? { get { return notificationCumulationCenter_ } set { notificationCumulationCenter_ = newValue refreshViewData() } } public func refreshViewData () { allNotifications_ = notificationCumulationCenter_?.allNotifications ?? [] tableView?.reloadData() } var allNotifications_ : [NCNotification] = [] public var allNotifcations : [NCNotification] { get { return allNotifications_ } } @IBAction func markAllAsRead(sender: AnyObject) { notificationCumulationCenter!.onceMarkAsRead(allNotifcations) { (_) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } } @IBAction func clearAllNotifications(sender: AnyObject) { notificationCumulationCenter!.removeAll { (_) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.refreshViewData() }) } } override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return allNotifcations.count } let cellID = "vn.haibui.NCNotificationCell" override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! NCNotificationTableViewCell // Configure the cell... cell.notif = allNotifcations[indexPath.row] return cell } }
mit
onevcat/CotEditor
CotEditor/Sources/SyntaxParser.swift
1
13243
// // SyntaxParser.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-04-28. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2022 1024jp // // 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 // // https://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 Combine import Foundation import AppKit.NSTextStorage private extension NSAttributedString.Key { static let syntaxType = NSAttributedString.Key("CotEditor.SyntaxType") } // MARK: - final class SyntaxParser { private struct Cache { var styleName: String var string: String var highlights: [SyntaxType: [NSRange]] } // MARK: Public Properties let textStorage: NSTextStorage var style: SyntaxStyle @Published private(set) var outlineItems: [OutlineItem]? // MARK: Private Properties private var outlineParseTask: Task<Void, Error>? private var highlightParseTask: Task<Void, Error>? private var highlightCache: Cache? // results cache of the last whole string highlights private var textEditingObserver: AnyCancellable? // MARK: - // MARK: Lifecycle init(textStorage: NSTextStorage, style: SyntaxStyle = SyntaxStyle()) { self.textStorage = textStorage self.style = style // give up if the string is changed while parsing self.textEditingObserver = NotificationCenter.default.publisher(for: NSTextStorage.willProcessEditingNotification, object: textStorage) .map { $0.object as! NSTextStorage } .filter { $0.editedMask.contains(.editedCharacters) } .sink { [weak self] _ in self?.highlightParseTask?.cancel() } } deinit { self.invalidateCurrentParse() } // MARK: Public Methods /// Whether syntax should be parsed. var canParse: Bool { return UserDefaults.standard[.enableSyntaxHighlight] && !self.style.isNone } /// Cancel all syntax parse including ones in the queues. func invalidateCurrentParse() { self.highlightCache = nil self.outlineParseTask?.cancel() self.highlightParseTask?.cancel() } } // MARK: - Outline extension SyntaxParser { /// Parse outline. func invalidateOutline() { self.outlineParseTask?.cancel() guard self.canParse, !self.style.outlineExtractors.isEmpty, !self.textStorage.range.isEmpty else { self.outlineItems = [] return } self.outlineItems = nil let extractors = self.style.outlineExtractors let string = self.textStorage.string.immutable let range = self.textStorage.range self.outlineParseTask = Task.detached(priority: .utility) { [weak self] in self?.outlineItems = try await withThrowingTaskGroup(of: [OutlineItem].self) { group in for extractor in extractors { _ = group.addTaskUnlessCancelled { try await extractor.items(in: string, range: range) } } return try await group.reduce(into: []) { $0 += $1 } .sorted(\.range.location) } } } } // MARK: - Syntax Highlight extension SyntaxParser { /// Update highlights around passed-in range. /// /// - Parameters: /// - editedRange: The character range that was edited, or highlight whole range if `nil` is passed in. /// - Returns: The progress of the async highlight task if performed. @MainActor func highlight(around editedRange: NSRange? = nil) -> Progress? { assert(Thread.isMainThread) guard UserDefaults.standard[.enableSyntaxHighlight] else { return nil } guard !self.textStorage.string.isEmpty else { return nil } // in case that wholeRange length is changed from editedRange guard editedRange.flatMap({ $0.upperBound > self.textStorage.length }) != true else { assertionFailure("Invalid range \(editedRange?.description ?? "nil") is passed in to \(#function)") return nil } let wholeRange = self.textStorage.range let highlightRange: NSRange = { guard let editedRange = editedRange, editedRange != wholeRange else { return wholeRange } // highlight whole if string is enough short let bufferLength = UserDefaults.standard[.coloringRangeBufferLength] if wholeRange.length <= bufferLength { return wholeRange } // highlight whole visible area if edited point is visible var highlightRange = self.textStorage.layoutManagers .compactMap(\.textViewForBeginningOfSelection?.visibleRange) .filter { $0.intersects(editedRange) } .reduce(into: editedRange) { $0.formUnion($1) } highlightRange = (self.textStorage.string as NSString).lineRange(for: highlightRange) // expand highlight area if the character just before/after the highlighting area is the same syntax type if let layoutManager = self.textStorage.layoutManagers.first { if highlightRange.lowerBound > 0, let effectiveRange = layoutManager.effectiveRange(of: .syntaxType, at: highlightRange.lowerBound) { highlightRange = NSRange(location: effectiveRange.lowerBound, length: highlightRange.upperBound - effectiveRange.lowerBound) } if highlightRange.upperBound < wholeRange.upperBound, let effectiveRange = layoutManager.effectiveRange(of: .syntaxType, at: highlightRange.upperBound) { highlightRange.length = effectiveRange.upperBound - highlightRange.location } } if highlightRange.upperBound < bufferLength { return NSRange(location: 0, length: highlightRange.upperBound) } return highlightRange }() guard !highlightRange.isEmpty else { return nil } // just clear current highlight and return if no coloring needs guard self.style.hasHighlightDefinition else { self.textStorage.apply(highlights: [:], range: highlightRange) return nil } // use cache if the content of the whole document is the same as the last if highlightRange == wholeRange, let cache = self.highlightCache, cache.styleName == self.style.name, cache.string == self.textStorage.string { self.textStorage.apply(highlights: cache.highlights, range: highlightRange) return nil } // make sure that string is immutable // -> `string` of NSTextStorage is actually a mutable object // and it can cause crash when a mutable string is given to NSRegularExpression instance. // (2016-11, macOS 10.12.1 SDK) let string = self.textStorage.string.immutable return self.highlight(string: string, range: highlightRange) } // MARK: Private Methods /// perform highlighting private func highlight(string: String, range highlightRange: NSRange) -> Progress { assert(Thread.isMainThread) assert(!(string as NSString).className.contains("MutableString")) assert(!highlightRange.isEmpty) assert(!self.style.isNone) let definition = HighlightParser.Definition(extractors: self.style.highlightExtractors, nestablePaires: self.style.nestablePaires, inlineCommentDelimiter: self.style.inlineCommentDelimiter, blockCommentDelimiters: self.style.blockCommentDelimiters) let parser = HighlightParser(definition: definition, string: string, range: highlightRange) let progress = Progress(totalUnitCount: 10) let task = Task.detached(priority: .userInitiated) { [weak self, styleName = self.style.name] in progress.localizedDescription = "Parsing text…".localized progress.addChild(parser.progress, withPendingUnitCount: 9) let highlights = try await parser.parse() if highlightRange == string.nsRange { self?.highlightCache = Cache(styleName: styleName, string: string, highlights: highlights) } try Task.checkCancellation() progress.localizedDescription = "Applying colors to text…".localized try await Task.sleep(nanoseconds: 10_000_000) // wait 0.01 seconds for GUI update await self?.textStorage.apply(highlights: highlights, range: highlightRange) progress.completedUnitCount += 1 } progress.cancellationHandler = { task.cancel() } self.highlightParseTask?.cancel() self.highlightParseTask = task return progress } } private extension NSTextStorage { /// apply highlights to the document @MainActor func apply(highlights: [SyntaxType: [NSRange]], range highlightRange: NSRange) { assert(Thread.isMainThread) guard self.length > 0 else { return } let hasHighlight = highlights.values.contains { !$0.isEmpty } for layoutManager in self.layoutManagers { // skip if never colorlized yet to avoid heavy `layoutManager.invalidateDisplay(forCharacterRange:)` guard hasHighlight || layoutManager.hasTemporaryAttribute(.syntaxType, in: highlightRange) else { continue } let theme = (layoutManager.firstTextView as? any Themable)?.theme layoutManager.groupTemporaryAttributesUpdate(in: highlightRange) { layoutManager.removeTemporaryAttribute(.foregroundColor, forCharacterRange: highlightRange) layoutManager.removeTemporaryAttribute(.syntaxType, forCharacterRange: highlightRange) for type in SyntaxType.allCases { guard let ranges = highlights[type]?.compactMap({ $0.intersection(highlightRange) }), !ranges.isEmpty else { continue } for range in ranges { layoutManager.addTemporaryAttribute(.syntaxType, value: type, forCharacterRange: range) } if let color = theme?.style(for: type)?.color { for range in ranges { layoutManager.addTemporaryAttribute(.foregroundColor, value: color, forCharacterRange: range) } } else { for range in ranges { layoutManager.removeTemporaryAttribute(.foregroundColor, forCharacterRange: range) } } } } } } } extension NSLayoutManager { /// Apply the theme based on the current `syntaxType` attributes. /// /// - Parameter theme: The theme to apply. /// - Parameter range: The range to invalidate. If `nil`, whole string will be invalidated. @MainActor func invalidateHighlight(theme: Theme, range: NSRange? = nil) { assert(Thread.isMainThread) let wholeRange = range ?? self.attributedString().range self.groupTemporaryAttributesUpdate(in: wholeRange) { self.enumerateTemporaryAttribute(.syntaxType, in: wholeRange) { (type, range, _) in guard let type = type as? SyntaxType else { return } if let color = theme.style(for: type)?.color { self.addTemporaryAttribute(.foregroundColor, value: color, forCharacterRange: range) } else { self.removeTemporaryAttribute(.foregroundColor, forCharacterRange: range) } } } } }
apache-2.0
sschiau/swift
test/stdlib/Accelerate_vDSPFourierTransform.swift
6
30371
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: rdar50301438 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Accelerate var Accelerate_vDSPFourierTransformTests = TestSuite("Accelerate_vDSPFourierTransform") //===----------------------------------------------------------------------===// // // vDSP discrete Fourier transform tests; single-precision // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { let n = 2048 let tau: Float = .pi * 2 let frequencies: [Float] = [1, 5, 25, 30, 75, 100, 300, 500, 512, 1023] let inputReal: [Float] = (0 ..< n).map { index in frequencies.reduce(0) { accumulator, frequency in let normalizedIndex = Float(index) / Float(n) return accumulator + sin(normalizedIndex * frequency * tau) } } let inputImag: [Float] = (0 ..< n).map { index in frequencies.reduce(0) { accumulator, frequency in let normalizedIndex = Float(index) / Float(n) return accumulator + sin(normalizedIndex * 1/frequency * tau) } } Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionForwardComplexComplex") { let fwdDFT = vDSP.DFT(count: n, direction: .forward, transformType: .complexComplex, ofType: Float.self)! var outputReal = [Float](repeating: 0, count: n) var outputImag = [Float](repeating: 0, count: n) fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag, outputReal: &outputReal, outputImaginary: &outputImag) // legacy... let legacySetup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(n), .FORWARD)! var legacyOutputReal = [Float](repeating: -1, count: n) var legacyOutputImag = [Float](repeating: -1, count: n) vDSP_DFT_Execute(legacySetup, inputReal, inputImag, &legacyOutputReal, &legacyOutputImag) expectTrue(outputReal.elementsEqual(legacyOutputReal)) expectTrue(outputImag.elementsEqual(legacyOutputImag)) let returnedResult = fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag) expectTrue(outputReal.elementsEqual(returnedResult.real)) expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) } Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionInverseComplexComplex") { let fwdDFT = vDSP.DFT(count: n, direction: .inverse, transformType: .complexComplex, ofType: Float.self)! var outputReal = [Float](repeating: 0, count: n) var outputImag = [Float](repeating: 0, count: n) fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag, outputReal: &outputReal, outputImaginary: &outputImag) // legacy... let legacySetup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(n), .INVERSE)! var legacyOutputReal = [Float](repeating: -1, count: n) var legacyOutputImag = [Float](repeating: -1, count: n) vDSP_DFT_Execute(legacySetup, inputReal, inputImag, &legacyOutputReal, &legacyOutputImag) expectTrue(outputReal.elementsEqual(legacyOutputReal)) expectTrue(outputImag.elementsEqual(legacyOutputImag)) let returnedResult = fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag) expectTrue(outputReal.elementsEqual(returnedResult.real)) expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) } Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionForwardComplexReal") { let fwdDFT = vDSP.DFT(count: n, direction: .forward, transformType: .complexReal, ofType: Float.self)! var outputReal = [Float](repeating: 0, count: n / 2) var outputImag = [Float](repeating: 0, count: n / 2) fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag, outputReal: &outputReal, outputImaginary: &outputImag) // legacy... let legacySetup = vDSP_DFT_zrop_CreateSetup(nil, vDSP_Length(n), .FORWARD)! var legacyOutputReal = [Float](repeating: -1, count: n / 2) var legacyOutputImag = [Float](repeating: -1, count: n / 2) vDSP_DFT_Execute(legacySetup, inputReal, inputImag, &legacyOutputReal, &legacyOutputImag) expectTrue(outputReal.elementsEqual(legacyOutputReal)) expectTrue(outputImag.elementsEqual(legacyOutputImag)) let returnedResult = fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag) expectTrue(outputReal.elementsEqual(returnedResult.real)) expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) } Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionInverseComplexReal") { let fwdDFT = vDSP.DFT(count: n, direction: .inverse, transformType: .complexReal, ofType: Float.self)! var outputReal = [Float](repeating: 0, count: n / 2) var outputImag = [Float](repeating: 0, count: n / 2) fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag, outputReal: &outputReal, outputImaginary: &outputImag) // legacy... let legacySetup = vDSP_DFT_zrop_CreateSetup(nil, vDSP_Length(n), .INVERSE)! var legacyOutputReal = [Float](repeating: -1, count: n / 2) var legacyOutputImag = [Float](repeating: -1, count: n / 2) vDSP_DFT_Execute(legacySetup, inputReal, inputImag, &legacyOutputReal, &legacyOutputImag) expectTrue(outputReal.elementsEqual(legacyOutputReal)) expectTrue(outputImag.elementsEqual(legacyOutputImag)) let returnedResult = fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag) expectTrue(outputReal.elementsEqual(returnedResult.real)) expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) } } //===----------------------------------------------------------------------===// // // vDSP discrete Fourier transform tests; double-precision // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { let n = 2048 let tau: Double = .pi * 2 let frequencies: [Double] = [1, 5, 25, 30, 75, 100, 300, 500, 512, 1023] let inputReal: [Double] = (0 ..< n).map { index in frequencies.reduce(0) { accumulator, frequency in let normalizedIndex = Double(index) / Double(n) return accumulator + sin(normalizedIndex * frequency * tau) } } let inputImag: [Double] = (0 ..< n).map { index in frequencies.reduce(0) { accumulator, frequency in let normalizedIndex = Double(index) / Double(n) return accumulator + sin(normalizedIndex * 1/frequency * tau) } } Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionForwardComplexComplex") { let fwdDFT = vDSP.DFT(count: n, direction: .forward, transformType: .complexComplex, ofType: Double.self)! var outputReal = [Double](repeating: 0, count: n) var outputImag = [Double](repeating: 0, count: n) fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag, outputReal: &outputReal, outputImaginary: &outputImag) // legacy... let legacySetup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(n), .FORWARD)! var legacyOutputReal = [Double](repeating: -1, count: n) var legacyOutputImag = [Double](repeating: -1, count: n) vDSP_DFT_ExecuteD(legacySetup, inputReal, inputImag, &legacyOutputReal, &legacyOutputImag) expectTrue(outputReal.elementsEqual(legacyOutputReal)) expectTrue(outputImag.elementsEqual(legacyOutputImag)) let returnedResult = fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag) expectTrue(outputReal.elementsEqual(returnedResult.real)) expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) } Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionInverseComplexComplex") { let fwdDFT = vDSP.DFT(count: n, direction: .inverse, transformType: .complexComplex, ofType: Double.self)! var outputReal = [Double](repeating: 0, count: n) var outputImag = [Double](repeating: 0, count: n) fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag, outputReal: &outputReal, outputImaginary: &outputImag) // legacy... let legacySetup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(n), .INVERSE)! var legacyOutputReal = [Double](repeating: -1, count: n) var legacyOutputImag = [Double](repeating: -1, count: n) vDSP_DFT_ExecuteD(legacySetup, inputReal, inputImag, &legacyOutputReal, &legacyOutputImag) expectTrue(outputReal.elementsEqual(legacyOutputReal)) expectTrue(outputImag.elementsEqual(legacyOutputImag)) let returnedResult = fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag) expectTrue(outputReal.elementsEqual(returnedResult.real)) expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) } Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionForwardComplexReal") { let fwdDFT = vDSP.DFT(count: n, direction: .forward, transformType: .complexReal, ofType: Double.self)! var outputReal = [Double](repeating: 0, count: n / 2) var outputImag = [Double](repeating: 0, count: n / 2) fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag, outputReal: &outputReal, outputImaginary: &outputImag) // legacy... let legacySetup = vDSP_DFT_zrop_CreateSetupD(nil, vDSP_Length(n), .FORWARD)! var legacyOutputReal = [Double](repeating: -1, count: n / 2) var legacyOutputImag = [Double](repeating: -1, count: n / 2) vDSP_DFT_ExecuteD(legacySetup, inputReal, inputImag, &legacyOutputReal, &legacyOutputImag) expectTrue(outputReal.elementsEqual(legacyOutputReal)) expectTrue(outputImag.elementsEqual(legacyOutputImag)) let returnedResult = fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag) expectTrue(outputReal.elementsEqual(returnedResult.real)) expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) } Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionInverseComplexReal") { let fwdDFT = vDSP.DFT(count: n, direction: .inverse, transformType: .complexReal, ofType: Double.self)! var outputReal = [Double](repeating: 0, count: n / 2) var outputImag = [Double](repeating: 0, count: n / 2) fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag, outputReal: &outputReal, outputImaginary: &outputImag) // legacy... let legacySetup = vDSP_DFT_zrop_CreateSetupD(nil, vDSP_Length(n), .INVERSE)! var legacyOutputReal = [Double](repeating: -1, count: n / 2) var legacyOutputImag = [Double](repeating: -1, count: n / 2) vDSP_DFT_ExecuteD(legacySetup, inputReal, inputImag, &legacyOutputReal, &legacyOutputImag) expectTrue(outputReal.elementsEqual(legacyOutputReal)) expectTrue(outputImag.elementsEqual(legacyOutputImag)) let returnedResult = fwdDFT.transform(inputReal: inputReal, inputImaginary: inputImag) expectTrue(outputReal.elementsEqual(returnedResult.real)) expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) } } //===----------------------------------------------------------------------===// // // vDSP Fast Fourier Transform Tests // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionComplexConversions") { func convert(splitComplexVector: DSPSplitComplex, toInterleavedComplexVector interleavedComplexVector: inout [DSPComplex]) { withUnsafePointer(to: splitComplexVector) { vDSP_ztoc($0, 1, &interleavedComplexVector, 2, vDSP_Length(interleavedComplexVector.count)) } } func convert(interleavedComplexVector: [DSPComplex], toSplitComplexVector splitComplexVector: inout DSPSplitComplex) { vDSP_ctoz(interleavedComplexVector, 2, &splitComplexVector, 1, vDSP_Length(interleavedComplexVector.count)) } var realSrc: [Float] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var imagSrc: [Float] = realSrc.reversed() let splitSrc = DSPSplitComplex(realp: &realSrc, imagp: &imagSrc) var interleavedDest = [DSPComplex](repeating: DSPComplex(), count: realSrc.count) convert(splitComplexVector: splitSrc, toInterleavedComplexVector: &interleavedDest) var realDest = [Float](repeating: .nan, count: realSrc.count) var imagDest = [Float](repeating: .nan, count: realSrc.count) var splitDest = DSPSplitComplex(realp: &realDest, imagp: &imagDest) convert(interleavedComplexVector: interleavedDest, toSplitComplexVector: &splitDest) expectTrue(realSrc.elementsEqual(realDest)) expectTrue(imagSrc.elementsEqual(imagDest)) } Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionComplexConversions") { func convert(splitComplexVector: DSPDoubleSplitComplex, toInterleavedComplexVector interleavedComplexVector: inout [DSPDoubleComplex]) { withUnsafePointer(to: splitComplexVector) { vDSP_ztocD($0, 1, &interleavedComplexVector, 2, vDSP_Length(interleavedComplexVector.count)) } } func convert(interleavedComplexVector: [DSPDoubleComplex], toSplitComplexVector splitComplexVector: inout DSPDoubleSplitComplex) { vDSP_ctozD(interleavedComplexVector, 2, &splitComplexVector, 1, vDSP_Length(interleavedComplexVector.count)) } var realSrc: [Double] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var imagSrc: [Double] = realSrc.reversed() let splitSrc = DSPDoubleSplitComplex(realp: &realSrc, imagp: &imagSrc) var interleavedDest = [DSPDoubleComplex](repeating: DSPDoubleComplex(), count: realSrc.count) convert(splitComplexVector: splitSrc, toInterleavedComplexVector: &interleavedDest) var realDest = [Double](repeating: .nan, count: realSrc.count) var imagDest = [Double](repeating: .nan, count: realSrc.count) var splitDest = DSPDoubleSplitComplex(realp: &realDest, imagp: &imagDest) convert(interleavedComplexVector: interleavedDest, toSplitComplexVector: &splitDest) expectTrue(realSrc.elementsEqual(realDest)) expectTrue(imagSrc.elementsEqual(imagDest)) } Accelerate_vDSPFourierTransformTests.test("vDSP/2DSinglePrecision") { let width = 256 let height = 256 let pixelCount = width * height let n = pixelCount / 2 let pixels: [Float] = (0 ..< pixelCount).map { i in return abs(sin(Float(i) * 0.001 * 2)) } var sourceImageReal = [Float](repeating: 0, count: n) var sourceImageImaginary = [Float](repeating: 0, count: n) var sourceImage = DSPSplitComplex(fromInputArray: pixels, realParts: &sourceImageReal, imaginaryParts: &sourceImageImaginary) let pixelsRecreated = [Float](fromSplitComplex: sourceImage, scale: 1, count: pixelCount) expectTrue(pixelsRecreated.elementsEqual(pixels)) // Create FFT2D object let fft2D = vDSP.FFT2D(width: 256, height: 256, ofType: DSPSplitComplex.self)! // New style transform var transformedImageReal = [Float](repeating: 0, count: n) var transformedImageImaginary = [Float](repeating: 0, count: n) var transformedImage = DSPSplitComplex( realp: &transformedImageReal, imagp: &transformedImageImaginary) fft2D.transform(input: sourceImage, output: &transformedImage, direction: .forward) // Legacy 2D FFT let log2n = vDSP_Length(log2(Float(width * height))) let legacySetup = vDSP_create_fftsetup( log2n, FFTRadix(kFFTRadix2))! var legacyTransformedImageReal = [Float](repeating: -1, count: n) var legacyTransformedImageImaginary = [Float](repeating: -1, count: n) var legacyTransformedImage = DSPSplitComplex( realp: &legacyTransformedImageReal, imagp: &legacyTransformedImageImaginary) vDSP_fft2d_zrop(legacySetup, &sourceImage, 1, 0, &legacyTransformedImage, 1, 0, vDSP_Length(log2(Float(width))), vDSP_Length(log2(Float(height))), FFTDirection(kFFTDirection_Forward)) expectTrue(transformedImageReal.elementsEqual(legacyTransformedImageReal)) expectTrue(transformedImageImaginary.elementsEqual(legacyTransformedImageImaginary)) } Accelerate_vDSPFourierTransformTests.test("vDSP/2DDoublePrecision") { let width = 256 let height = 256 let pixelCount = width * height let n = pixelCount / 2 let pixels: [Double] = (0 ..< pixelCount).map { i in return abs(sin(Double(i) * 0.001 * 2)) } var sourceImageReal = [Double](repeating: 0, count: n) var sourceImageImaginary = [Double](repeating: 0, count: n) var sourceImage = DSPDoubleSplitComplex(fromInputArray: pixels, realParts: &sourceImageReal, imaginaryParts: &sourceImageImaginary) let pixelsRecreated = [Double](fromSplitComplex: sourceImage, scale: 1, count: pixelCount) expectTrue(pixelsRecreated.elementsEqual(pixels)) // Create FFT2D object let fft2D = vDSP.FFT2D(width: width, height: height, ofType: DSPDoubleSplitComplex.self)! // New style transform var transformedImageReal = [Double](repeating: 0, count: n) var transformedImageImaginary = [Double](repeating: 0, count: n) var transformedImage = DSPDoubleSplitComplex( realp: &transformedImageReal, imagp: &transformedImageImaginary) fft2D.transform(input: sourceImage, output: &transformedImage, direction: .forward) // Legacy 2D FFT let log2n = vDSP_Length(log2(Float(width * height))) let legacySetup = vDSP_create_fftsetupD( log2n, FFTRadix(kFFTRadix2))! var legacyTransformedImageReal = [Double](repeating: -1, count: n) var legacyTransformedImageImaginary = [Double](repeating: -1, count: n) var legacyTransformedImage = DSPDoubleSplitComplex( realp: &legacyTransformedImageReal, imagp: &legacyTransformedImageImaginary) vDSP_fft2d_zropD(legacySetup, &sourceImage, 1, 0, &legacyTransformedImage, 1, 0, vDSP_Length(log2(Float(width))), vDSP_Length(log2(Float(height))), FFTDirection(kFFTDirection_Forward)) expectTrue(transformedImageReal.elementsEqual(legacyTransformedImageReal)) expectTrue(transformedImageImaginary.elementsEqual(legacyTransformedImageImaginary)) } Accelerate_vDSPFourierTransformTests.test("vDSP/1DSinglePrecision") { let n = vDSP_Length(2048) let frequencies: [Float] = [1, 5, 25, 30, 75, 100, 300, 500, 512, 1023] let tau: Float = .pi * 2 let signal: [Float] = (0 ... n).map { index in frequencies.reduce(0) { accumulator, frequency in let normalizedIndex = Float(index) / Float(n) return accumulator + sin(normalizedIndex * frequency * tau) } } let halfN = Int(n / 2) var forwardInputReal = [Float](repeating: 0, count: halfN) var forwardInputImag = [Float](repeating: 0, count: halfN) var forwardInput = DSPSplitComplex(fromInputArray: signal, realParts: &forwardInputReal, imaginaryParts: &forwardInputImag) let log2n = vDSP_Length(log2(Float(n))) // New API guard let fft = vDSP.FFT(log2n: log2n, radix: .radix2, ofType: DSPSplitComplex.self) else { fatalError("Can't create FFT.") } var outputReal = [Float](repeating: 0, count: halfN) var outputImag = [Float](repeating: 0, count: halfN) var forwardOutput = DSPSplitComplex(realp: &outputReal, imagp: &outputImag) fft.transform(input: forwardInput, output: &forwardOutput, direction: .forward) // Legacy Style let legacySetup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2))! var legacyoutputReal = [Float](repeating: -1, count: halfN) var legacyoutputImag = [Float](repeating: -1, count: halfN) var legacyForwardOutput = DSPSplitComplex(realp: &legacyoutputReal, imagp: &legacyoutputImag) vDSP_fft_zrop(legacySetup, &forwardInput, 1, &legacyForwardOutput, 1, log2n, FFTDirection(kFFTDirection_Forward)) expectTrue(outputReal.elementsEqual(legacyoutputReal)) expectTrue(outputImag.elementsEqual(legacyoutputImag)) } Accelerate_vDSPFourierTransformTests.test("vDSP/1DDoublePrecision") { let n = vDSP_Length(2048) let frequencies: [Double] = [1, 5, 25, 30, 75, 100, 300, 500, 512, 1023] let tau: Double = .pi * 2 let signal: [Double] = (0 ... n).map { index in frequencies.reduce(0) { accumulator, frequency in let normalizedIndex = Double(index) / Double(n) return accumulator + sin(normalizedIndex * frequency * tau) } } let halfN = Int(n / 2) var forwardInputReal = [Double](repeating: 0, count: halfN) var forwardInputImag = [Double](repeating: 0, count: halfN) var forwardInput = DSPDoubleSplitComplex(fromInputArray: signal, realParts: &forwardInputReal, imaginaryParts: &forwardInputImag) let log2n = vDSP_Length(log2(Double(n))) // New API guard let fft = vDSP.FFT(log2n: log2n, radix: .radix2, ofType: DSPDoubleSplitComplex.self) else { fatalError("Can't create FFT.") } var outputReal = [Double](repeating: 0, count: halfN) var outputImag = [Double](repeating: 0, count: halfN) var forwardOutput = DSPDoubleSplitComplex(realp: &outputReal, imagp: &outputImag) fft.transform(input: forwardInput, output: &forwardOutput, direction: .forward) // Legacy Style let legacySetup = vDSP_create_fftsetupD(log2n, FFTRadix(kFFTRadix2))! var legacyoutputReal = [Double](repeating: 0, count: halfN) var legacyoutputImag = [Double](repeating: 0, count: halfN) var legacyForwardOutput = DSPDoubleSplitComplex(realp: &legacyoutputReal, imagp: &legacyoutputImag) vDSP_fft_zropD(legacySetup, &forwardInput, 1, &legacyForwardOutput, 1, log2n, FFTDirection(kFFTDirection_Forward)) expectTrue(outputReal.elementsEqual(legacyoutputReal)) expectTrue(outputImag.elementsEqual(legacyoutputImag)) } } runAllTests()
apache-2.0
Aymarick/DisplayKit
Package.swift
1
177
import PackageDescription let package = Package( name: "DisplayKit", dependencies: [ .Package(url: "https://github.com/Aymarick/CSDL2.git", Version(1,0,1)) ] )
mit
Chen-Dixi/SwiftHashDict
sy4/sy4/Algorithm.swift
1
381
// // Algorithm.swift // SwiftStructures // // Created by Wayne Bishop on 4/25/16. // Copyright © 2016 Arbutus Software Inc. All rights reserved. // import Foundation //recusive enum used to help build example Algorithm "models" indirect enum Algorithm { case Empty case Sequence(Array<Int>) case InsertionSort(Algorithm) case BubbleSort(Algorithm) }
mit
practicalswift/swift
validation-test/compiler_crashers_fixed/28380-swift-type-transform.swift
65
423
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<T{{if true as[T.h
apache-2.0
gxf2015/DYZB
DYZB/DYZB/Classes/Home/Controller/RecommendViewController.swift
1
5421
// // RecommendViewController.swift // DYZB // // Created by guo xiaofei on 2017/8/11. // Copyright © 2017年 guo xiaofei. All rights reserved. // import UIKit fileprivate let kItemMargin : CGFloat = 10 fileprivate let kItemW = (kScreenW - 3 * kItemMargin) / 2 fileprivate let kNormalItemH = kItemW * 3 / 4 fileprivate let kPrettyItemH = kItemW * 4 / 3 fileprivate let kHeaderViewH : CGFloat = 50 fileprivate let kCycleViewH = kScreenW * 3 / 8 fileprivate let kGameViewH : CGFloat = 90 fileprivate let kNormalCellID = "kNormalCellID" fileprivate let kPrettyCellID = "kPrettyCellID" fileprivate let kHeaderViewID = "kHeaderViewID" class RecommendViewController: UIViewController { // fileprivate lazy var recommendVM :RecommendViewModel = RecommendViewModel() fileprivate lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() fileprivate lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() // fileprivate lazy var collectionView : UICollectionView = {[unowned self] in let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.backgroundColor = UIColor.white return collectionView }() // override func viewDidLoad() { super.viewDidLoad() //1 setupUI() //2 loadData() } } extension RecommendViewController { fileprivate func setupUI(){ view.addSubview(collectionView) collectionView.addSubview(cycleView) collectionView.addSubview(gameView) collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) } } extension RecommendViewController{ fileprivate func loadData(){ recommendVM.requestData { self.collectionView.reloadData() self.gameView.groups = self.recommendVM.ancnorGroups } recommendVM.requestCycleData { self.cycleView.cycleModels = self.recommendVM.cycleModels } } } extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return recommendVM.ancnorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = recommendVM.ancnorGroups[section] return group.room_list!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let group = recommendVM.ancnorGroups[indexPath.section] let anchor = group.room_list?[indexPath.item] var cell : CollectionBaseCell! if indexPath.section == 1{ cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell }else{ cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell } cell.anchor = anchor return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let hearderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView hearderView.group = recommendVM.ancnorGroups[indexPath.section] return hearderView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) }else{ return CGSize(width: kItemW, height: kNormalItemH) } } }
mit
Daltron/BigBoard
Example/BigBoard/ExampleAddStockView.swift
1
4136
// // ExampleAddStockView.swift // BigBoard // // Created by Dalton Hinterscher on 5/20/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import SnapKit import ChameleonFramework protocol ExampleAddStockViewDelegate : class { func numberOfSearchResultStocks() -> Int func searchResultStockAtIndex(_ index:Int) -> BigBoardSearchResultStock func searchTermChanged(searchTerm:String) func stockResultSelectedAtIndex(_ index:Int) } class ExampleAddStockView: UIView, UITableViewDataSource, UITableViewDelegate { weak var delegate:ExampleAddStockViewDelegate? var searchTextField:UITextField! var stocksTableView:UITableView! init(delegate:ExampleAddStockViewDelegate) { super.init(frame: CGRect.zero) self.delegate = delegate self.backgroundColor = UIColor.white let searchBarView = UIView() addSubview(searchBarView) searchTextField = UITextField() searchTextField.borderStyle = .roundedRect searchTextField.textAlignment = .center searchTextField.placeholder = "Search:" searchTextField.addTarget(self, action: #selector(searchTermChanged), for: .allEditingEvents) searchBarView.addSubview(searchTextField) stocksTableView = UITableView(frame: CGRect.zero, style: .plain) stocksTableView.dataSource = self stocksTableView.delegate = self stocksTableView.rowHeight = 50.0 addSubview(stocksTableView) searchBarView.snp.makeConstraints { (make) in make.top.equalTo(self.snp.top) make.left.equalTo(self.snp.left) make.right.equalTo(self.snp.right) make.height.equalTo(50) } searchTextField.snp.makeConstraints { (make) in make.top.equalTo(searchBarView).offset(10) make.left.equalTo(searchBarView).offset(10) make.right.equalTo(searchBarView).offset(-10) make.bottom.equalTo(searchBarView).offset(-10) } stocksTableView.snp.makeConstraints { (make) in make.top.equalTo(searchBarView.snp.bottom) make.left.equalTo(self) make.right.equalTo(self) make.bottom.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func searchTermChanged() { delegate!.searchTermChanged(searchTerm: searchTextField.text!) } // MARK: UITableViewDataSource and UITableViewDataSource Implementation func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return delegate!.numberOfSearchResultStocks() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = "ExampleCell" var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as UITableViewCell? if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: reuseIdentifier) let exchangeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 25)) exchangeLabel.textAlignment = .right cell?.accessoryView = exchangeLabel } return cell! } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let stock = delegate!.searchResultStockAtIndex((indexPath as NSIndexPath).row) cell.textLabel?.text = stock.name! cell.detailTextLabel?.text = stock.symbol! let exchangeLabel = cell.accessoryView as! UILabel! exchangeLabel?.text = stock.exch! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) delegate!.stockResultSelectedAtIndex((indexPath as NSIndexPath).row) } }
mit
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletAuthentication/Models/Error/WalletRecoveryError.swift
1
385
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import WalletPayloadKit public enum WalletRecoveryError: LocalizedError, Equatable { case restoreFailure(WalletError) public var errorDescription: String? { switch self { case .restoreFailure(let walletError): return walletError.errorDescription } } }
lgpl-3.0
volodg/iAsync.network
Sources/NSError/NetworkError.swift
1
240
// // NetworkError.swift // iAsync_network // // Created by Vladimir Gorbenko on 18.08.14. // Copyright © 2014 EmbeddedSources. All rights reserved. // import Foundation import iAsync_utils public class NetworkError : UtilsError {}
mit
googlearchive/science-journal-ios
ScienceJournal/AppDelegateOpen.swift
1
2213
/* * Copyright 2019 Google LLC. All Rights Reserved. * * 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 /// A subclass of the AppDelegate allowing for customization of injectable classes. open class AppDelegateOpen: AppDelegate { open override var analyticsReporter: AnalyticsReporter { return _analyticsReporter } open override var feedbackReporter: FeedbackReporter { return _feedbackReporter } open override var fileSystemLayout: FileSystemLayout { return _fileSystemLayout } open override var accountsManager: AccountsManager { return _accountsManager } open override var drawerConfig: DrawerConfig { return _drawerConfig } open override var driveConstructor: DriveConstructor { return _driveConstructor } open override var commonUIComponents: CommonUIComponents { return _commonUIComponents } open override var networkAvailability: NetworkAvailability { return _networkAvailability } #if FEATURE_FIREBASE_RC open override var remoteConfigManager: RemoteConfigManager { return _remoteConfigManager } #endif private let _analyticsReporter = AnalyticsReporterOpen() private let _feedbackReporter = FeedbackReporterOpen() private let _fileSystemLayout = FileSystemLayout.production private let _accountsManager = AccountsManagerDisabled() private let _drawerConfig = DrawerConfigOpen() private let _driveConstructor = DriveConstructorDisabled() private let _commonUIComponents = CommonUIComponentsOpen() private let _networkAvailability = NetworkAvailabilityDisabled() #if FEATURE_FIREBASE_RC private let _remoteConfigManager = RemoteConfigManagerDisabled() #endif }
apache-2.0
googlearchive/science-journal-ios
ScienceJournalTests/Metadata/SensorTriggerEvaluatorTest.swift
1
7594
/* * Copyright 2019 Google LLC. All Rights Reserved. * * 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 XCTest @testable import third_party_sciencejournal_ios_ScienceJournalOpen class SensorTriggerEvaluatorTest: XCTestCase { func testShouldTriggerWithNoPreviousValue() { // Create a sensor trigger` with a value to trigger, and a sensor trigger evaluator with no // previous value. let sensorTrigger = SensorTrigger(sensorID: "sensorTriggerId") sensorTrigger.triggerInformation.valueToTrigger = 10 let sensorTriggerEvaluator = SensorTriggerEvaluator(sensorTrigger: sensorTrigger) // Set up a fake clock. let fakeLastUsed: Int64 = 12345 sensorTriggerEvaluator.clock = SettableClock(now: fakeLastUsed) XCTAssertNil(sensorTriggerEvaluator.previousValue, "The sensor trigger evaluator's previous value should be nil before calling " + "`shouldTrigger(withValue:)` for the first time.") let value = 10.0000000000001 XCTAssertFalse(sensorTriggerEvaluator.shouldTrigger(withValue: value), "If the sensor trigger evaluator has no previous value, this should be false.") XCTAssertEqual(sensorTriggerEvaluator.previousValue, value, "The sensor trigger evaluator's previous value should be equal to `value`.") XCTAssertEqual(sensorTriggerEvaluator.sensorTrigger.lastUsedDate.millisecondsSince1970, fakeLastUsed, "The sensor trigger's `lastUsedMs` should be equal to `fakeLastUsed`.") } func testShouldTriggerWhenAt() { // Create a sensor trigger to trigger when at a value. let sensorTrigger = SensorTrigger(sensorID: "sensorTriggerId") sensorTrigger.triggerInformation.triggerWhen = .triggerWhenAt sensorTrigger.triggerInformation.valueToTrigger = 10 let sensorTriggerEvaluator = SensorTriggerEvaluator(sensorTrigger: sensorTrigger) sensorTriggerEvaluator.previousValue = 11 XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 10.0000000000001), "If `value` is nearly equal to the `valueToTrigger`, this should be true.") XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 9), "If `value` crossed the threshold, this should be true.") XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 12), "If `value` crossed the threshold in the other direction, this should be true.") } func testShouldTriggerWhenDropsBelow() { // Create a sensor trigger to trigger when dropping below a value. let sensorTrigger = SensorTrigger(sensorID: "sensorTriggerId") sensorTrigger.triggerInformation.triggerWhen = .triggerWhenDropsBelow sensorTrigger.triggerInformation.valueToTrigger = 10 let sensorTriggerEvaluator = SensorTriggerEvaluator(sensorTrigger: sensorTrigger) sensorTriggerEvaluator.previousValue = 11 XCTAssertFalse(sensorTriggerEvaluator.shouldTrigger(withValue: 12), "If `value` is above `valueToTrigger`, this should be false.") XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 9), "If `value` drops below `valueToTrigger`, this should be true.") } func testShouldTriggerWhenRisesAbove() { // Create a sensor trigger to trigger when rising above `valueToTrigger`. let sensorTrigger = SensorTrigger(sensorID: "sensorTriggerId") sensorTrigger.triggerInformation.triggerWhen = .triggerWhenRisesAbove sensorTrigger.triggerInformation.valueToTrigger = 10 let sensorTriggerEvaluator = SensorTriggerEvaluator(sensorTrigger: sensorTrigger) sensorTriggerEvaluator.previousValue = 9 XCTAssertFalse(sensorTriggerEvaluator.shouldTrigger(withValue: 8), "If `value` is below `valueToTrigger`, this should be false.") XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 11), "If `value` rises above `valueToTrigger`, this should be true.") } func testShouldTriggerWhenBelow() { // Create a sensor trigger to trigger when below `valueToTrigger`. let sensorTrigger = SensorTrigger(sensorID: "sensorTriggerId") sensorTrigger.triggerInformation.triggerWhen = .triggerWhenBelow sensorTrigger.triggerInformation.valueToTrigger = 10 let sensorTriggerEvaluator = SensorTriggerEvaluator(sensorTrigger: sensorTrigger) sensorTriggerEvaluator.previousValue = 9 XCTAssertFalse(sensorTriggerEvaluator.shouldTrigger(withValue: 11), "If `value` is above `valueToTrigger`, this should be false.") XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 8), "If `value` is below `valueToTrigger`, this should be true.") XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 7), "Even when previous value is below `valueToTrigger`, if `value` is below " + "`valueToTrigger`, this should be true.") } func testShouldTriggerWhenAbove() { // Create a sensor trigger to trigger when above `valueToTrigger`. let sensorTrigger = SensorTrigger(sensorID: "sensorTriggerId") sensorTrigger.triggerInformation.triggerWhen = .triggerWhenAbove sensorTrigger.triggerInformation.valueToTrigger = 10 let sensorTriggerEvaluator = SensorTriggerEvaluator(sensorTrigger: sensorTrigger) sensorTriggerEvaluator.previousValue = 11 XCTAssertFalse(sensorTriggerEvaluator.shouldTrigger(withValue: 9), "If `value` is above `valueToTrigger`, this should be true.") XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 12), "If `value` is above `valueToTrigger`, this should be true.") XCTAssertTrue(sensorTriggerEvaluator.shouldTrigger(withValue: 14), "Even when previous value is above `valueToTrigger`, if `value` is above " + "`valueToTrigger`, this should be true.") } func testSensorTriggerEvaluatorsForSensorTriggers() { // Create some sensor triggers. let sensorTrigger1 = SensorTrigger(sensorID: "sensorTrigger1Id") let sensorTrigger2 = SensorTrigger(sensorID: "sensorTrigger2Id") let sensorTrigger3 = SensorTrigger(sensorID: "sensorTrigger3Id") let sensorTriggers = [sensorTrigger1, sensorTrigger2, sensorTrigger3] // Get sensor trigger evaluators for the `SensorTriggers`. let sensorTriggerEvaluators = SensorTriggerEvaluator.sensorTriggerEvaluators(for: sensorTriggers) XCTAssertEqual(sensorTriggers.count, sensorTriggerEvaluators.count, "There should be an equal `count` in `sensorTriggers` and " + "`sensorTriggerEvaluators`") // There should be a sensor trigger evaluator for each sensor trigger. for index in 0..<sensorTriggerEvaluators.endIndex { XCTAssertTrue(sensorTriggers[index] === sensorTriggerEvaluators[index].sensorTrigger, "The sensor trigger evaluator's sensor trigger should be equal to the " + "corresponding sensor trigger.") } } }
apache-2.0
quire-io/SwiftyChrono
Sources/Parsers/DE/DEMorgenTimeParser.swift
1
1624
// // DEMorgenTimeParser.swift // SwiftyChrono // // Created by Jerry Chen on 2/18/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation /* this is a white list for morning cases * e.g. * this morning => heute Morgen * tomorrow morning => Morgen früh * friday morning => Freitag Morgen * last morning => letzten Morgen */ private let PATTERN = "(\\W|^)((?:heute|letzten)\\s*Morgen|Morgen\\s*früh|\(DE_WEEKDAY_WORDS_PATTERN)\\s*Morgen)" private let timeMatch = 2 public class DEMorgenTimeParser: Parser { override var pattern: String { return PATTERN } override var language: Language { return .german } override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? { let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match) var result = ParsedResult(ref: ref, index: index, text: matchText) result.start.imply(.hour, to: opt[.morning] ?? 6) let time = match.string(from: text, atRangeIndex: timeMatch).lowercased() if time.hasPrefix("letzten") { result.start.imply(.day, to: ref.day - 1) } else if time.hasSuffix("früh") { result.start.imply(.day, to: ref.day + 1) } else { if let weekday = DE_WEEKDAY_OFFSET[time.substring(from: 0, to: time.count - "Morgen".count).trimmed()] { result.start.assign(.weekday, value: weekday) } } result.tags[.deMorgenTimeParser] = true return result } }
mit
nua-schroers/mvvm-frp
30_MVVM-App/MatchGame/MatchGame/Controller/MainViewController.swift
1
3323
// // ViewController.swift // MatchGame // // Created by Dr. Wolfram Schroers on 5/26/16. // Copyright © 2016 Wolfram Schroers. All rights reserved. // import UIKit /// The view controller of the first screen responsible for the game. class MainViewController: MVVMViewController, MainTakeAction { // MARK: The corresponding view model (view first) /// The main screen view model. var viewModel: MainViewModel // MARK: Lifecycle/workflow management required init?(coder aDecoder: NSCoder) { self.viewModel = MainViewModel() super.init(coder: aDecoder) self.viewModel.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.viewModel.viewWillAppear() } // MARK: Data Model -- THIS IS NO MORE! // MARK: User Interface /// The label at the top displaying the current game state. @IBOutlet weak var gameStateLabel: UILabel! /// The move report label beneath the game state label. @IBOutlet weak var moveReportLabel: UILabel! /// The graphical match pile. @IBOutlet weak var matchPileView: MatchPileView! /// The "Take 2" button. It can be disabled if needed. @IBOutlet weak var takeTwoButton: UIButton! /// The "Take 3" button. It can be disabled if needed. @IBOutlet weak var takeThreeButton: UIButton! /// Response to user tapping "Take 1". @IBAction func userTappedTakeOne(_ sender: AnyObject) { self.viewModel.userTappedTake(1) } /// Response to user tapping "Take 2". @IBAction func userTappedTakeTwo(_ sender: AnyObject) { self.viewModel.userTappedTake(2) } /// Response to user tapping "Take 3". @IBAction func userTappedTakeThree(_ sender: AnyObject) { self.viewModel.userTappedTake(3) } /// Response to user tapping "Info". @IBAction func userTappedInfo(_ sender: AnyObject) { self.viewModel.userTappedInfo() } // MARK: MainTakeAction func transitionToSettings() { // Instantiate the settings screen view controller and configure the UI transition. let settingsController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController settingsController.modalPresentationStyle = .currentContext settingsController.modalTransitionStyle = .flipHorizontal // Set the data context. settingsController.configure(self.viewModel.createContext(), contextDelegate: self.viewModel) // Perform the transition. self.present(settingsController, animated: true, completion: nil) } func updateLabelsAndButtonStates() { self.gameStateLabel.text = self.viewModel.gameState self.moveReportLabel.text = self.viewModel.moveReport self.takeTwoButton.isEnabled = self.viewModel.buttonTwoEnabled self.takeThreeButton.isEnabled = self.viewModel.buttonThreeEnabled } func setMatchesInPileView(_ count:Int) { self.matchPileView.setMatches(count) } func removeMatchesInPileView(_ count:Int) { self.matchPileView.removeMatches(count) } }
mit
FraGoTe/cat-years
Cat Years/ViewController.swift
1
860
// // ViewController.swift // Cat Years // // Created by Francis Gonzales Tello on 10/21/15. // Copyright © 2015 Francis Gonzales Tello. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var catYear: UITextField! @IBOutlet weak var resultLabel: UILabel! 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 findAge(sender: AnyObject) { var catAge = Int(catYear.text!)! catAge = catAge * 7 resultLabel.text = "Your cat age is " + String(catAge) + " in cat years" } }
mit
google/flatbuffers
swift/Sources/FlatBuffers/Constants.swift
2
3103
/* * Copyright 2021 Google Inc. All rights reserved. * * 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. */ #if !os(WASI) #if os(Linux) import CoreFoundation #else import Foundation #endif #else import SwiftOverlayShims #endif /// A boolean to see if the system is littleEndian let isLitteEndian: Bool = { let number: UInt32 = 0x12345678 return number == number.littleEndian }() /// Constant for the file id length let FileIdLength = 4 /// Type aliases public typealias Byte = UInt8 public typealias UOffset = UInt32 public typealias SOffset = Int32 public typealias VOffset = UInt16 /// Maximum size for a buffer public let FlatBufferMaxSize = UInt32 .max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1) /// Protocol that All Scalars should conform to /// /// Scalar is used to conform all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer. public protocol Scalar: Equatable { associatedtype NumericValue var convertedEndian: NumericValue { get } } extension Scalar where Self: Verifiable {} extension Scalar where Self: FixedWidthInteger { /// Converts the value from BigEndian to LittleEndian /// /// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet. public var convertedEndian: NumericValue { self as! Self.NumericValue } } extension Double: Scalar, Verifiable { public typealias NumericValue = UInt64 public var convertedEndian: UInt64 { bitPattern.littleEndian } } extension Float32: Scalar, Verifiable { public typealias NumericValue = UInt32 public var convertedEndian: UInt32 { bitPattern.littleEndian } } extension Bool: Scalar, Verifiable { public var convertedEndian: UInt8 { self == true ? 1 : 0 } public typealias NumericValue = UInt8 } extension Int: Scalar, Verifiable { public typealias NumericValue = Int } extension Int8: Scalar, Verifiable { public typealias NumericValue = Int8 } extension Int16: Scalar, Verifiable { public typealias NumericValue = Int16 } extension Int32: Scalar, Verifiable { public typealias NumericValue = Int32 } extension Int64: Scalar, Verifiable { public typealias NumericValue = Int64 } extension UInt8: Scalar, Verifiable { public typealias NumericValue = UInt8 } extension UInt16: Scalar, Verifiable { public typealias NumericValue = UInt16 } extension UInt32: Scalar, Verifiable { public typealias NumericValue = UInt32 } extension UInt64: Scalar, Verifiable { public typealias NumericValue = UInt64 } public func FlatBuffersVersion_22_11_23() {}
apache-2.0