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
hasanlsn/HAActionSheet
Example/HAActionSheet/AppDelegate.swift
1
2173
// // AppDelegate.swift // HAActionSheet // // Created by hasanlsn on 08/05/2017. // Copyright (c) 2017 hasanlsn. 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. 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:. } }
mit
Polidea/RxBluetoothKit
Source/CentralManagerRestoredState.swift
1
2942
import Foundation import CoreBluetooth /// It should be deleted when `RestoredState` will be deleted protocol CentralManagerRestoredStateType { var restoredStateData: [String: Any] { get } var centralManager: CentralManager { get } var peripherals: [Peripheral] { get } var scanOptions: [String: AnyObject]? { get } var services: [Service] { get } } /// Convenience class which helps reading state of restored CentralManager. public struct CentralManagerRestoredState: CentralManagerRestoredStateType { /// Restored state dictionary. public let restoredStateData: [String: Any] public unowned let centralManager: CentralManager /// Creates restored state information based on CoreBluetooth's dictionary /// - parameter restoredStateDictionary: Core Bluetooth's restored state data /// - parameter centralManager: `CentralManager` instance of which state has been restored. init(restoredStateDictionary: [String: Any], centralManager: CentralManager) { restoredStateData = restoredStateDictionary self.centralManager = centralManager } /// Array of `Peripheral` objects which have been restored. /// These are peripherals that were connected to the central manager (or had a connection pending) /// at the time the app was terminated by the system. public var peripherals: [Peripheral] { let objects = restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [AnyObject] guard let arrayOfAnyObjects = objects else { return [] } #if swift(>=4.1) let cbPeripherals = arrayOfAnyObjects.compactMap { $0 as? CBPeripheral } #else let cbPeripherals = arrayOfAnyObjects.flatMap { $0 as? CBPeripheral } #endif return cbPeripherals.map { centralManager.retrievePeripheral(for: $0) } } /// Dictionary that contains all of the peripheral scan options that were being used /// by the central manager at the time the app was terminated by the system. public var scanOptions: [String: AnyObject]? { return restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [String: AnyObject] } /// Array of `Service` objects which have been restored. /// These are all the services the central manager was scanning for at the time the app /// was terminated by the system. public var services: [Service] { let objects = restoredStateData[CBCentralManagerRestoredStateScanServicesKey] as? [AnyObject] guard let arrayOfAnyObjects = objects else { return [] } #if swift(>=4.1) let cbServices = arrayOfAnyObjects.compactMap { $0 as? CBService } #else let cbServices = arrayOfAnyObjects.flatMap { $0 as? CBService } #endif return cbServices.map { Service(peripheral: centralManager.retrievePeripheral(for: $0.peripheral), service: $0) } } }
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/03810-swift-typebase-getanyoptionalobjecttype.swift
11
299
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct g<T) { class A : a { deinit { deinit { } class A { var f1: String = a<b where I.h> { func a<h == F>(""""""""" func a proto
mit
austinzheng/swift-compiler-crashes
fixed/00477-no-stacktrace.swift
11
240
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSSet{{}protocol A{}{{}}init(array c){{{}}}}import Foundation
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/13680-swift-sourcemanager-getmessage.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 ( [ { protocol P { class d { func a { struct A { class case ,
mit
ericwastaken/Xcode_Playgrounds
Playgrounds/Binary Tree Search Implementation.playground/Contents.swift
1
2173
// Binary Search Tree // A node can contain at most 2 children // The tree is always in order public class BinarySearchTree<T>: CustomStringConvertible { var value: T var leftTree: BinarySearchTree<T>? var rightTree: BinarySearchTree<T>? init(_ value: T) { self.value = value } public var description: String { let value = "\(self.value)" let leftTree = self.leftTree == nil ? "nil" : "\(self.leftTree!)" let rightTree = self.rightTree == nil ? "nil" : "\(self.rightTree!)" return "\(value): [\(leftTree) , \(rightTree)]" } public var count: Int { var counter = 0 if let leftCount = self.leftTree?.count { counter += leftCount } if let rightCount = self.rightTree?.count { counter += rightCount } return counter + 1 // +1 for itself } } // Insert public func insert<T: Comparable>(intoTree: BinarySearchTree<T>, value: T) -> BinarySearchTree<T> { // decide if we go left or right if value < intoTree.value { if let leftTree = intoTree.leftTree { // We replace the left tree, with a future left tree (recursively) intoTree.leftTree = insert(intoTree: leftTree, value: value) } else { // no left tree, so insert into left let newNode = BinarySearchTree<T>(value) intoTree.leftTree = newNode return intoTree } } // We replace the right tree, with a future right tree (recursively) if let rightTree = intoTree.rightTree { // We replace the left tree, with a future left tree (recursively) intoTree.rightTree = insert(intoTree: rightTree, value: value) } else { // no left tree, so insert into left let newNode = BinarySearchTree<T>(value) intoTree.rightTree = newNode return intoTree } return intoTree } var myTree = BinarySearchTree<Int>(5) myTree = insert(intoTree: myTree, value: 7) myTree = insert(intoTree: myTree, value: 3) myTree = insert(intoTree: myTree, value: 13) print("myTree: \(myTree)")
unlicense
ThomasCle/Loggage
Loggage/LoggageTests/LogLevelTests.swift
1
1608
// // LogLevelTests.swift // Loggage // // Created by Thomas Kalhøj Clemensen on 24/08/2017. // Copyright © 2017 ThomasCle. All rights reserved. // import XCTest @testable import Loggage class LogLevelTests: 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 testLevel() { XCTAssert(LogLevel.verbose.rawValue == 0) XCTAssert(LogLevel.debug.rawValue == 1) XCTAssert(LogLevel.info.rawValue == 2) XCTAssert(LogLevel.todo.rawValue == 3) XCTAssert(LogLevel.warning.rawValue == 4) XCTAssert(LogLevel.error.rawValue == 5) } func testEmoji() { XCTAssert(LogLevel.verbose.emoji() == "🔊") XCTAssert(LogLevel.debug.emoji() == "🐞") XCTAssert(LogLevel.info.emoji() == "ℹ️") XCTAssert(LogLevel.todo.emoji() == "🛠") XCTAssert(LogLevel.warning.emoji() == "⚠️") XCTAssert(LogLevel.error.emoji() == "‼️") } func testName() { XCTAssert(LogLevel.verbose.name() == "Verbose") XCTAssert(LogLevel.debug.name() == "Debug") XCTAssert(LogLevel.info.name() == "Info") XCTAssert(LogLevel.todo.name() == "TODO") XCTAssert(LogLevel.warning.name() == "Warning") XCTAssert(LogLevel.error.name() == "Error") } }
mit
albinekcom/BitBay-Ticker-iOS
Codebase/Data Repository/Remote/RemoteDataRepository.swift
1
4303
import Foundation private enum Endpoint: String { case currencies = "https://raw.githubusercontent.com/albinekcom/Zonda-API-Tools/main/v1/currencies.json" case ticker = "https://api.zonda.exchange/rest/trading/ticker" case stats = "https://api.zonda.exchange/rest/trading/stats" var url: URL? { URL(string: rawValue) } } private enum RemoteDataRepositoryError: Error { case wrongURL } final class RemoteDataRepository { private let urlSession: URLSession private var cachedCurrenciesNamesAPIResponse: CurrenciesNamesAPIResponse? init(urlSession: URLSession = URLSession.shared) { self.urlSession = urlSession } func fetch() async throws -> [Ticker] { async let tickersValuesAPIResponse = fetch(TickersValuesAPIResponse.self, from: .ticker) async let tickersStatisticsAPIResponse = fetch(TickersStatisticsAPIResponse.self, from: .stats) let currenciesNamesAPIResponse: CurrenciesNamesAPIResponse if let cachedCurrenciesNamesAPIResponse = cachedCurrenciesNamesAPIResponse { currenciesNamesAPIResponse = cachedCurrenciesNamesAPIResponse } else { currenciesNamesAPIResponse = try await fetch(CurrenciesNamesAPIResponse.self, from: .currencies) cachedCurrenciesNamesAPIResponse = currenciesNamesAPIResponse } return try await tickers( tickersValuesAPIResponse: tickersValuesAPIResponse, tickersStatisticsAPIResponse: tickersStatisticsAPIResponse ) } // MARK: - Helpers private func fetch<T: Decodable>(_ type: T.Type, from endpoint: Endpoint) async throws -> T { guard let url = endpoint.url else { throw RemoteDataRepositoryError.wrongURL } return try JSONDecoder().decode( T.self, from: try await urlSession.data(from: url).0 ) } private func tickers(tickersValuesAPIResponse: TickersValuesAPIResponse, tickersStatisticsAPIResponse: TickersStatisticsAPIResponse) -> [Ticker] { tickersValuesAPIResponse.items.values.compactMap { guard let tickerStatisticsAPIResponseItem = tickersStatisticsAPIResponse.items[$0.market.code] else { return nil } return Ticker( tickerValuesAPIResponseItem: $0, tickerStatisticsAPIResponseItem: tickerStatisticsAPIResponseItem, firstCurrencyName: cachedCurrenciesNamesAPIResponse?.names[$0.market.first.currency.lowercased()], secondCurrencyName: cachedCurrenciesNamesAPIResponse?.names[$0.market.second.currency.lowercased()] ) } .sorted() } } private extension Ticker { init(tickerValuesAPIResponseItem: TickersValuesAPIResponse.Item, tickerStatisticsAPIResponseItem: TickersStatisticsAPIResponse.Item, firstCurrencyName: String?, secondCurrencyName: String?) { id = tickerValuesAPIResponseItem.market.code.lowercased() highestBid = tickerValuesAPIResponseItem.highestBid.double lowestAsk = tickerValuesAPIResponseItem.lowestAsk.double rate = tickerValuesAPIResponseItem.rate.double previousRate = tickerValuesAPIResponseItem.previousRate.double highestRate = tickerStatisticsAPIResponseItem.h.double lowestRate = tickerStatisticsAPIResponseItem.l.double volume = tickerStatisticsAPIResponseItem.v.double average = tickerStatisticsAPIResponseItem.r24h.double firstCurrency = .init( id: tickerValuesAPIResponseItem.market.first.currency.lowercased(), name: firstCurrencyName, precision: tickerValuesAPIResponseItem.market.first.scale ) secondCurrency = .init( id: tickerValuesAPIResponseItem.market.second.currency.lowercased(), name: secondCurrencyName, precision: tickerValuesAPIResponseItem.market.second.scale ) } } private extension Optional where Wrapped == String { var double: Double? { guard let self = self else { return nil } return Double(self) } }
mit
nanthi1990/SwiftCharts
SwiftCharts/ChartPoint/ChartPoint.swift
7
565
// // ChartPoint.swift // swift_charts // // Created by ischuetz on 01/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartPoint: Equatable { public let x: ChartAxisValue public let y: ChartAxisValue public init(x: ChartAxisValue, y: ChartAxisValue) { self.x = x self.y = y } public var text: String { return "\(self.x.text), \(self.y.text)" } } public func ==(lhs: ChartPoint, rhs: ChartPoint) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y }
apache-2.0
Syject/MyLessPass-iOS
LessPass/Model/Generator/LesspassData.swift
1
446
// // LesspassData.swift // LessPass // // Created by Dan Slupskiy on 11.01.17. // Copyright © 2017 Syject. All rights reserved. // import Foundation class LesspassData{ var site:String var login:String var masterPassword:String init(withSite site:String, login:String, andMasterPassword masterPassword:String) { self.site = site self.login = login self.masterPassword = masterPassword } }
gpl-3.0
wbaumann/SmartReceiptsiOS
SmartReceipts/Common/Exchange/ExchangeRateCalculator.swift
2
1052
// // ExchangeRateCalculator.swift // SmartReceipts // // Created by Bogdan Evsenev on 19/07/2019. // Copyright © 2019 Will Baumann. All rights reserved. // import Foundation import RxSwift class ExchangeRateCalculator { let exchangeRateUpdate = PublishSubject<Double>() let baseCurrencyPriceUpdate = PublishSubject<Double>() private let bag = DisposeBag() init(price: Double = 0, exchangeRate: Double = 0) { self.price = price self.exchangeRate = exchangeRate } var price: Double = 0 { didSet { let result = price*exchangeRate baseCurrencyPriceUpdate.onNext(result) } } var exchangeRate: Double = 0 { didSet { let result = price*exchangeRate baseCurrencyPriceUpdate.onNext(result) } } var baseCurrencyPrice: Double = 0 { didSet { if price == 0 { return } let result = baseCurrencyPrice/price exchangeRateUpdate.onNext(result) } } }
agpl-3.0
rnystrom/GitHawk
Classes/Issues/Comments/Markdown/ViewMarkdownViewController.swift
1
1548
// // ViewMarkdownViewController.swift // Freetime // // Created by Ryan Nystrom on 5/19/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import UIKit final class ViewMarkdownViewController: UIViewController { private let markdown: String private let textView = UITextView() init(markdown: String) { self.markdown = markdown super.init(nibName: nil, bundle: nil) title = NSLocalizedString("Markdown", comment: "") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem( barButtonSystemItem: .done, target: self, action: #selector(onDismiss) ) textView.isEditable = false textView.text = markdown textView.font = Styles.Text.code.preferredFont textView.textColor = Styles.Colors.Gray.dark.color textView.textContainerInset = UIEdgeInsets( top: Styles.Sizes.rowSpacing, left: Styles.Sizes.columnSpacing, bottom: Styles.Sizes.rowSpacing, right: Styles.Sizes.columnSpacing ) view.addSubview(textView) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() textView.frame = view.bounds } // MARK: Private API @objc func onDismiss() { dismiss(animated: trueUnlessReduceMotionEnabled) } }
mit
terflogag/OpenSourceController
Exemple/OpenSourceControllerDemo/AppDelegate.swift
1
2201
// // AppDelegate.swift // OpenSourceControllerDemo // // Created by Florian Gabach on 04/04/2017. // Copyright © 2017 OpenSourceController. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/19620-swift-constraints-constraintsystem-lookupmember.swift
10
228
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct S{ let a=b.h == a func b{ class b<T where f:a{ var:a
mit
yaobanglin/viossvc
viossvc/Scenes/Share/Tour/TourShareListViewController.swift
2
2791
// // ShareListViewController.swift // viossvc // // Created by yaowang on 2016/10/28. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit class TourShareListViewController: BasePageListTableViewController , OEZTableViewDelegate { // var listType:Int = 0; // var typeName: String var typeModel : TourShareTypeModel = TourShareTypeModel() // var typeNames:[String] = ["美食","住宿","景点","娱乐"]; override func viewDidLoad() { super.viewDidLoad(); // listType = listType < typeNames.count ? listType : 0 ; title = typeModel.type_title; tableView.registerNib(TourShareCell.self, forCellReuseIdentifier: "TourShareListCell"); switch typeModel.type_title { case "美食": MobClick.event(AppConst.Event.share_eat) break case "娱乐": MobClick.event(AppConst.Event.share_fun) break case "住宿": MobClick.event(AppConst.Event.share_hotel) break case "景点": MobClick.event(AppConst.Event.share_travel) break default: break } } override func isCalculateCellHeight() -> Bool { return true; } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view:TableViewHeaderView? = TableViewHeaderView.loadFromNib(); view?.titleLabel.text = typeModel.type_title + "分享"; return view; } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let model = dataSource?[indexPath.row] as? TourShareModel let viewController:TourShareDetailViewController = storyboardViewController() viewController.share_id = model!.share_id viewController.title = model!.share_theme self.navigationController?.pushViewController(viewController, animated: true); } func tableView(tableView: UITableView!, rowAtIndexPath indexPath: NSIndexPath!, didAction action: Int, data: AnyObject!) { if UInt(action) == AppConst.Action.CallPhone.rawValue { let model = self.tableView(tableView, cellDataForRowAtIndexPath: indexPath) as? TourShareModel if model?.telephone != nil { didActionTel(model!.telephone) } } } override func didRequest(pageIndex: Int) { let last_id:Int = pageIndex == 1 ? 0 : (dataSource?.last as! TourShareModel).share_id AppAPIHelper.tourShareAPI().list(last_id, count: AppConst.DefaultPageSize, type: typeModel.type_id, complete: completeBlockFunc(), error: errorBlockFunc()) } }
apache-2.0
SuPair/firefox-ios
AccountTests/LiveAccountTest.swift
4
7178
/* 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/. */ @testable import Account import Foundation import FxA import Shared import Deferred import SwiftyJSON import XCTest // Note: All live account tests have been disabled. Please see https://bugzilla.mozilla.org/show_bug.cgi?id=1332028. /* * A base test type for tests that need a live Firefox Account. */ open class LiveAccountTest: XCTestCase { lazy var signedInUser: JSON? = { if let path = Bundle(for: type(of: self)).path(forResource: "signedInUser.json", ofType: nil) { if let contents = try? String(contentsOfFile: path, encoding: .utf8) { let json = JSON(parseJSON: contents) if json.isError() { return nil } if let email = json["email"].string { return json } else { // This is the standard case: signedInUser.json is {}. return nil } } } XCTFail("Expected to read signedInUser.json!") return nil }() // It's not easy to have an optional resource, so we always include signedInUser.json in the test bundle. // If signedInUser.json contains an email address, we use that email address. // Since there's no way to get the corresponding password (from any client!), we assume that any // test account has password identical to its email address. fileprivate func withExistingAccount(_ mustBeVerified: Bool, completion: (Data, Data) -> Void) { // If we don't create at least one expectation, waitForExpectations fails. // So we unconditionally create one, even though the callback may not execute. self.expectation(description: "withExistingAccount").fulfill() if let json = self.signedInUser { if mustBeVerified { XCTAssertTrue(json["verified"].bool ?? false) } let email = json["email"].stringValue let password = json["password"].stringValue let emailUTF8 = email.utf8EncodedData let passwordUT8 = password.utf8EncodedData let stretchedPW = FxAClient10.quickStretchPW(emailUTF8, password: passwordUT8) completion(emailUTF8, stretchedPW) } else { // This is the standard case: signedInUser.json is {}. NSLog("Skipping test because signedInUser.json does not include email address.") } } func withVerifiedAccount(_ completion: (Data, Data) -> Void) { withExistingAccount(true, completion: completion) } // Helper function that waits for expectations to clear func withVerifiedAccountNoExpectations(_ completion: (Data, Data) -> Void) { withExistingAccount(true, completion: completion) self.waitForExpectations(timeout: 10, handler: nil) } func withCertificate(_ completion: @escaping (XCTestExpectation, Data, KeyPair, String) -> Void) { withVerifiedAccount { emailUTF8, quickStretchedPW in let expectation = self.expectation(description: "withCertificate") let keyPair = RSAKeyPair.generate(withModulusSize: 1024)! let client = FxAClient10() let login: Deferred<Maybe<FxALoginResponse>> = client.login(emailUTF8, quickStretchedPW: quickStretchedPW, getKeys: true) let sign: Deferred<Maybe<FxASignResponse>> = login.bind { (result: Maybe<FxALoginResponse>) in switch result { case let .failure(error): expectation.fulfill() return Deferred(value: .failure(error)) case let .success(loginResponse): return client.sign(loginResponse.sessionToken, publicKey: keyPair.publicKey) } } sign.upon { result in if let response = result.successValue { XCTAssertNotNil(response.certificate) completion(expectation, emailUTF8, keyPair, response.certificate) } else { XCTAssertEqual(result.failureValue!.description, "") expectation.fulfill() } } } } public enum AccountError: MaybeErrorType { case badParameters case noSignedInUser case unverifiedSignedInUser public var description: String { switch self { case .badParameters: return "Bad account parameters (email, password, or a derivative thereof)." case .noSignedInUser: return "No signedInUser.json (missing, no email, etc)." case .unverifiedSignedInUser: return "signedInUser.json describes an unverified account." } } } // Internal helper. func account(_ email: String, password: String, deviceName: String, configuration: FirefoxAccountConfiguration) -> Deferred<Maybe<FirefoxAccount>> { let client = FxAClient10(authEndpoint: configuration.authEndpointURL) let emailUTF8 = email.utf8EncodedData let passwordUTF8 = password.utf8EncodedData let quickStretchedPW = FxAClient10.quickStretchPW(emailUTF8, password: passwordUTF8) let login = client.login(emailUTF8, quickStretchedPW: quickStretchedPW, getKeys: true) return login.bind { result in if let response = result.successValue { let unwrapkB = FxAClient10.computeUnwrapKey(quickStretchedPW) return Deferred(value: Maybe(success: FirefoxAccount.from(configuration, andLoginResponse: response, unwrapkB: unwrapkB, deviceName: deviceName))) } else { return Deferred(value: Maybe(failure: result.failureValue!)) } } } func getTestAccount() -> Deferred<Maybe<FirefoxAccount>> { // TODO: Use signedInUser.json here. It's hard to include the same resource file in two Xcode targets. return self.account("998797987.sync@restmail.net", password: "998797987.sync@restmail.net", deviceName: "My iPhone", configuration: ProductionFirefoxAccountConfiguration()) } open func getAuthState(_ now: Timestamp) -> Deferred<Maybe<SyncAuthState>> { let account = self.getTestAccount() print("Got test account.") return account.map { result in print("Result was successful? \(result.isSuccess)") if let account = result.successValue { return Maybe(success: account.syncAuthState) } return Maybe(failure: result.failureValue!) } } open func syncAuthState(_ now: Timestamp) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> { return getAuthState(now).bind { result in if let authState = result.successValue { return authState.token(now, canBeExpired: false) } return Deferred(value: Maybe(failure: result.failureValue!)) } } }
mpl-2.0
SteveBarnegren/TweenKit
TweenKit/TweenKitTests/Action+Testable.swift
1
386
// // Action+Testable.swift // TweenKit // // Created by Steven Barnegren on 24/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import Foundation import TweenKit extension SchedulableAction { func simulateFullLifeCycle() { self.willBecomeActive() self.willBegin() self.didFinish() self.didBecomeInactive() } }
mit
nakajijapan/PhotoSlider
Sources/PhotoSlider/Classes/UIImage+PhotoSlider.swift
1
553
// // UIImage+PhotoSlider.swift // PhotoSlider // // Created by nakajijapan on 2016/09/29. // Copyright © 2016 nakajijapan. All rights reserved. // import UIKit extension UIView { func toImage() -> UIImage? { UIGraphicsBeginImageContextWithOptions(frame.size, false, 0.0) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: 0.0, y: 0.0) layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
mit
luoziyong/firefox-ios
Client/Frontend/Browser/TabManager.swift
1
34585
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Storage import Shared private let log = Logger.browserLogger protocol TabManagerDelegate: class { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) func tabManagerDidRestoreTabs(_ tabManager: TabManager) func tabManagerDidAddTabs(_ tabManager: TabManager) func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) } protocol TabManagerStateDelegate: class { func tabManagerWillStoreTabs(_ tabs: [Tab]) } // We can't use a WeakList here because this is a protocol. class WeakTabManagerDelegate { weak var value: TabManagerDelegate? init (value: TabManagerDelegate) { self.value = value } func get() -> TabManagerDelegate? { return value } } // TabManager must extend NSObjectProtocol in order to implement WKNavigationDelegate class TabManager: NSObject { fileprivate var delegates = [WeakTabManagerDelegate]() weak var stateDelegate: TabManagerStateDelegate? func addDelegate(_ delegate: TabManagerDelegate) { assert(Thread.isMainThread) delegates.append(WeakTabManagerDelegate(value: delegate)) } func removeDelegate(_ delegate: TabManagerDelegate) { assert(Thread.isMainThread) for i in 0 ..< delegates.count { let del = delegates[i] if delegate === del.get() || del.get() == nil { delegates.remove(at: i) return } } } fileprivate(set) var tabs = [Tab]() fileprivate var _selectedIndex = -1 fileprivate let navDelegate: TabManagerNavDelegate fileprivate(set) var isRestoring = false // A WKWebViewConfiguration used for normal tabs lazy fileprivate var configuration: WKWebViewConfiguration = { let configuration = WKWebViewConfiguration() configuration.processPool = WKProcessPool() configuration.preferences.javaScriptCanOpenWindowsAutomatically = !(self.prefs.boolForKey("blockPopups") ?? true) return configuration }() // A WKWebViewConfiguration used for private mode tabs lazy fileprivate var privateConfiguration: WKWebViewConfiguration = { let configuration = WKWebViewConfiguration() configuration.processPool = WKProcessPool() configuration.preferences.javaScriptCanOpenWindowsAutomatically = !(self.prefs.boolForKey("blockPopups") ?? true) configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent() return configuration }() fileprivate let imageStore: DiskImageStore? fileprivate let prefs: Prefs var selectedIndex: Int { return _selectedIndex } var tempTabs: [Tab]? var normalTabs: [Tab] { assert(Thread.isMainThread) return tabs.filter { !$0.isPrivate } } var privateTabs: [Tab] { assert(Thread.isMainThread) return tabs.filter { $0.isPrivate } } init(prefs: Prefs, imageStore: DiskImageStore?) { assert(Thread.isMainThread) self.prefs = prefs self.navDelegate = TabManagerNavDelegate() self.imageStore = imageStore super.init() addNavigationDelegate(self) NotificationCenter.default.addObserver(self, selector: #selector(TabManager.prefsDidChange), name: UserDefaults.didChangeNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } func addNavigationDelegate(_ delegate: WKNavigationDelegate) { assert(Thread.isMainThread) self.navDelegate.insert(delegate) } var count: Int { assert(Thread.isMainThread) return tabs.count } var selectedTab: Tab? { assert(Thread.isMainThread) if !(0..<count ~= _selectedIndex) { return nil } return tabs[_selectedIndex] } subscript(index: Int) -> Tab? { assert(Thread.isMainThread) if index >= tabs.count { return nil } return tabs[index] } subscript(webView: WKWebView) -> Tab? { assert(Thread.isMainThread) for tab in tabs where tab.webView === webView { return tab } return nil } func getTabFor(_ url: URL) -> Tab? { assert(Thread.isMainThread) for tab in tabs where tab.webView?.url == url { return tab } return nil } func selectTab(_ tab: Tab?, previous: Tab? = nil) { assert(Thread.isMainThread) let previous = previous ?? selectedTab if previous === tab { return } // Make sure to wipe the private tabs if the user has the pref turned on if shouldClearPrivateTabs(), !(tab?.isPrivate ?? false) { removeAllPrivateTabsAndNotify(false) } if let tab = tab { _selectedIndex = tabs.index(of: tab) ?? -1 } else { _selectedIndex = -1 } preserveTabs() assert(tab === selectedTab, "Expected tab is selected") selectedTab?.createWebview() delegates.forEach { $0.get()?.tabManager(self, didSelectedTabChange: tab, previous: previous) } } func shouldClearPrivateTabs() -> Bool { return prefs.boolForKey("settings.closePrivateTabs") ?? false } //Called by other classes to signal that they are entering/exiting private mode //This is called by TabTrayVC when the private mode button is pressed and BEFORE we've switched to the new mode func willSwitchTabMode() { if shouldClearPrivateTabs() && (selectedTab?.isPrivate ?? false) { removeAllPrivateTabsAndNotify(false) } } func expireSnackbars() { assert(Thread.isMainThread) for tab in tabs { tab.expireSnackbars() } } @discardableResult func addTab(_ request: URLRequest! = nil, configuration: WKWebViewConfiguration! = nil, afterTab: Tab? = nil, isPrivate: Bool) -> Tab { return self.addTab(request, configuration: configuration, afterTab: afterTab, flushToDisk: true, zombie: false, isPrivate: isPrivate) } func addTabAndSelect(_ request: URLRequest! = nil, configuration: WKWebViewConfiguration! = nil, afterTab: Tab? = nil, isPrivate: Bool) -> Tab { let tab = addTab(request, configuration: configuration, afterTab: afterTab, isPrivate: isPrivate) selectTab(tab) return tab } @discardableResult func addTabAndSelect(_ request: URLRequest! = nil, configuration: WKWebViewConfiguration! = nil, afterTab: Tab? = nil) -> Tab { let tab = addTab(request, configuration: configuration, afterTab: afterTab) selectTab(tab) return tab } // This method is duplicated to hide the flushToDisk option from consumers. @discardableResult func addTab(_ request: URLRequest! = nil, configuration: WKWebViewConfiguration! = nil, afterTab: Tab? = nil) -> Tab { return self.addTab(request, configuration: configuration, afterTab: afterTab, flushToDisk: true, zombie: false) } func addTabsForURLs(_ urls: [URL], zombie: Bool) { assert(Thread.isMainThread) if urls.isEmpty { return } var tab: Tab! for url in urls { tab = self.addTab(URLRequest(url: url), flushToDisk: false, zombie: zombie) } // Flush. storeChanges() // Select the most recent. self.selectTab(tab) // Notify that we bulk-loaded so we can adjust counts. delegates.forEach { $0.get()?.tabManagerDidAddTabs(self) } } fileprivate func addTab(_ request: URLRequest? = nil, configuration: WKWebViewConfiguration? = nil, afterTab: Tab? = nil, flushToDisk: Bool, zombie: Bool, isPrivate: Bool) -> Tab { assert(Thread.isMainThread) // Take the given configuration. Or if it was nil, take our default configuration for the current browsing mode. let configuration: WKWebViewConfiguration = configuration ?? (isPrivate ? privateConfiguration : self.configuration) let tab = Tab(configuration: configuration, isPrivate: isPrivate) configureTab(tab, request: request, afterTab: afterTab, flushToDisk: flushToDisk, zombie: zombie) return tab } fileprivate func addTab(_ request: URLRequest? = nil, configuration: WKWebViewConfiguration? = nil, afterTab: Tab? = nil, flushToDisk: Bool, zombie: Bool) -> Tab { assert(Thread.isMainThread) let tab = Tab(configuration: configuration ?? self.configuration) configureTab(tab, request: request, afterTab: afterTab, flushToDisk: flushToDisk, zombie: zombie) return tab } func moveTab(isPrivate privateMode: Bool, fromIndex visibleFromIndex: Int, toIndex visibleToIndex: Int) { assert(Thread.isMainThread) let currentTabs = privateMode ? privateTabs : normalTabs let fromIndex = tabs.index(of: currentTabs[visibleFromIndex]) ?? tabs.count - 1 let toIndex = tabs.index(of: currentTabs[visibleToIndex]) ?? tabs.count - 1 let previouslySelectedTab = selectedTab tabs.insert(tabs.remove(at: fromIndex), at: toIndex) if let previouslySelectedTab = previouslySelectedTab, let previousSelectedIndex = tabs.index(of: previouslySelectedTab) { _selectedIndex = previousSelectedIndex } storeChanges() } func configureTab(_ tab: Tab, request: URLRequest?, afterTab parent: Tab? = nil, flushToDisk: Bool, zombie: Bool) { assert(Thread.isMainThread) delegates.forEach { $0.get()?.tabManager(self, willAddTab: tab) } if parent == nil || parent?.isPrivate != tab.isPrivate { tabs.append(tab) } else if let parent = parent, var insertIndex = tabs.index(of: parent) { insertIndex += 1 while insertIndex < tabs.count && tabs[insertIndex].isDescendentOf(parent) { insertIndex += 1 } tab.parent = parent tabs.insert(tab, at: insertIndex) } delegates.forEach { $0.get()?.tabManager(self, didAddTab: tab) } if !zombie { tab.createWebview() } tab.navigationDelegate = self.navDelegate if let request = request { tab.loadRequest(request) } else { let newTabChoice = NewTabAccessors.getNewTabPage(prefs) switch newTabChoice { case .homePage: // We definitely have a homepage if we've got here // (so we can safely dereference it). let url = HomePageAccessors.getHomePage(prefs)! tab.loadRequest(URLRequest(url: url)) case .blankPage: // Do nothing: we're already seeing a blank page. break default: // The common case, where the NewTabPage enum defines // one of the about:home pages. if let url = newTabChoice.url { tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) tab.url = url } } } if flushToDisk { storeChanges() } } // This method is duplicated to hide the flushToDisk option from consumers. func removeTab(_ tab: Tab) { self.removeTab(tab, flushToDisk: true, notify: true) hideNetworkActivitySpinner() } /// - Parameter notify: if set to true, will call the delegate after the tab /// is removed. fileprivate func removeTab(_ tab: Tab, flushToDisk: Bool, notify: Bool) { assert(Thread.isMainThread) if tab.isPrivate { // Wipe clean data associated with this tab when it is removed. let dataTypes = Set([WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeIndexedDBDatabases]) tab.webView?.configuration.websiteDataStore.removeData(ofTypes: dataTypes, modifiedSince: Date.distantPast, completionHandler: {}) } let oldSelectedTab = selectedTab if notify { delegates.forEach { $0.get()?.tabManager(self, willRemoveTab: tab) } } // The index of the tab in its respective tab grouping. Used to figure out which tab is next var tabIndex: Int = -1 if let oldTab = oldSelectedTab { tabIndex = (tab.isPrivate ? privateTabs.index(of: oldTab) : normalTabs.index(of: oldTab)) ?? -1 } let prevCount = count if let removalIndex = tabs.index(where: { $0 === tab }) { tabs.remove(at: removalIndex) } let viableTabs: [Tab] = tab.isPrivate ? privateTabs : normalTabs //If the last item was deleted then select the last tab. Otherwise the _selectedIndex is already correct if let oldTab = oldSelectedTab, tab !== oldTab { _selectedIndex = tabs.index(of: oldTab) ?? -1 } else { if tabIndex == viableTabs.count { tabIndex -= 1 } if tabIndex < viableTabs.count && !viableTabs.isEmpty { _selectedIndex = tabs.index(of: viableTabs[tabIndex]) ?? -1 } else { _selectedIndex = -1 } } assert(count == prevCount - 1, "Make sure the tab count was actually removed") // There's still some time between this and the webView being destroyed. We don't want to pick up any stray events. tab.webView?.navigationDelegate = nil if notify { delegates.forEach { $0.get()?.tabManager(self, didRemoveTab: tab) } } if !tab.isPrivate && viableTabs.isEmpty { addTab() } // If the removed tab was selected, find the new tab to select. if selectedTab != nil { selectTab(selectedTab, previous: oldSelectedTab) } else { selectTab(tabs.last, previous: oldSelectedTab) } if flushToDisk { storeChanges() } } /// Removes all private tabs from the manager. /// - Parameter notify: if set to true, the delegate is called when a tab is /// removed. private func removeAllPrivateTabsAndNotify(_ notify: Bool) { // if there is a selected tab, it needs to be closed last // this is important for TopTabs as otherwise the selection of the new tab // causes problems as it may no longer be present. // without this we get a nasty crash guard let selectedTab = selectedTab, let _ = privateTabs.index(of: selectedTab) else { return privateTabs.forEach({ removeTab($0, flushToDisk: true, notify: notify) }) } let nonSelectedTabsForRemoval = privateTabs.filter { $0 != selectedTab } nonSelectedTabsForRemoval.forEach({ removeTab($0, flushToDisk: true, notify: notify) }) removeTab(selectedTab, flushToDisk: true, notify: notify) } func removeTabsWithUndoToast(_ tabs: [Tab]) { tempTabs = tabs var tabsCopy = tabs // Remove the current tab last to prevent switching tabs while removing tabs if let selectedTab = selectedTab { if let selectedIndex = tabsCopy.index(of: selectedTab) { let removed = tabsCopy.remove(at: selectedIndex) removeTabs(tabsCopy) removeTab(removed) } else { removeTabs(tabsCopy) } } for tab in tabs { tab.hideContent() } var toast: ButtonToast? if let numberOfTabs = tempTabs?.count, numberOfTabs > 0 { toast = ButtonToast(labelText: String.localizedStringWithFormat(Strings.TabsDeleteAllUndoTitle, numberOfTabs), buttonText: Strings.TabsDeleteAllUndoAction, completion: { buttonPressed in if buttonPressed { self.undoCloseTabs() self.storeChanges() for delegate in self.delegates { delegate.get()?.tabManagerDidAddTabs(self) } } self.eraseUndoCache() }) } delegates.forEach { $0.get()?.tabManagerDidRemoveAllTabs(self, toast: toast) } } func undoCloseTabs() { guard let tempTabs = self.tempTabs, tempTabs.count > 0 else { return } let tabsCopy = normalTabs restoreTabs(tempTabs) self.isRestoring = true for tab in tempTabs { tab.showContent(true) } if !tempTabs[0].isPrivate { removeTabs(tabsCopy) } selectTab(tempTabs.first) self.isRestoring = false delegates.forEach { $0.get()?.tabManagerDidRestoreTabs(self) } self.tempTabs?.removeAll() tabs.first?.createWebview() } func eraseUndoCache() { tempTabs?.removeAll() } func removeTabs(_ tabs: [Tab]) { for tab in tabs { self.removeTab(tab, flushToDisk: false, notify: true) } storeChanges() } func removeAll() { removeTabs(self.tabs) } func getIndex(_ tab: Tab) -> Int? { assert(Thread.isMainThread) for i in 0..<count where tabs[i] === tab { return i } assertionFailure("Tab not in tabs list") return nil } func getTabForURL(_ url: URL) -> Tab? { assert(Thread.isMainThread) return tabs.filter { $0.webView?.url == url } .first } func storeChanges() { stateDelegate?.tabManagerWillStoreTabs(normalTabs) // Also save (full) tab state to disk. preserveTabs() } func prefsDidChange() { DispatchQueue.main.async { let allowPopups = !(self.prefs.boolForKey("blockPopups") ?? true) // Each tab may have its own configuration, so we should tell each of them in turn. for tab in self.tabs { tab.webView?.configuration.preferences.javaScriptCanOpenWindowsAutomatically = allowPopups } // The default tab configurations also need to change. self.configuration.preferences.javaScriptCanOpenWindowsAutomatically = allowPopups self.privateConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = allowPopups } } func resetProcessPool() { assert(Thread.isMainThread) configuration.processPool = WKProcessPool() } } class SavedTab: NSObject, NSCoding { let isSelected: Bool let title: String? let isPrivate: Bool var sessionData: SessionData? var screenshotUUID: UUID? var faviconURL: String? var jsonDictionary: [String: AnyObject] { let title: String = self.title ?? "null" let faviconURL: String = self.faviconURL ?? "null" let uuid: String = self.screenshotUUID?.uuidString ?? "null" var json: [String: AnyObject] = [ "title": title as AnyObject, "isPrivate": String(self.isPrivate) as AnyObject, "isSelected": String(self.isSelected) as AnyObject, "faviconURL": faviconURL as AnyObject, "screenshotUUID": uuid as AnyObject ] if let sessionDataInfo = self.sessionData?.jsonDictionary { json["sessionData"] = sessionDataInfo as AnyObject? } return json } init?(tab: Tab, isSelected: Bool) { assert(Thread.isMainThread) self.screenshotUUID = tab.screenshotUUID as UUID? self.isSelected = isSelected self.title = tab.displayTitle self.isPrivate = tab.isPrivate self.faviconURL = tab.displayFavicon?.url super.init() if tab.sessionData == nil { let currentItem: WKBackForwardListItem! = tab.webView?.backForwardList.currentItem // Freshly created web views won't have any history entries at all. // If we have no history, abort. if currentItem == nil { return nil } let backList = tab.webView?.backForwardList.backList ?? [] let forwardList = tab.webView?.backForwardList.forwardList ?? [] let urls = (backList + [currentItem] + forwardList).map { $0.url } let currentPage = -forwardList.count self.sessionData = SessionData(currentPage: currentPage, urls: urls, lastUsedTime: tab.lastExecutedTime ?? Date.now()) } else { self.sessionData = tab.sessionData } } required init?(coder: NSCoder) { self.sessionData = coder.decodeObject(forKey: "sessionData") as? SessionData self.screenshotUUID = coder.decodeObject(forKey: "screenshotUUID") as? UUID self.isSelected = coder.decodeBool(forKey: "isSelected") self.title = coder.decodeObject(forKey: "title") as? String self.isPrivate = coder.decodeBool(forKey: "isPrivate") self.faviconURL = coder.decodeObject(forKey: "faviconURL") as? String } func encode(with coder: NSCoder) { coder.encode(sessionData, forKey: "sessionData") coder.encode(screenshotUUID, forKey: "screenshotUUID") coder.encode(isSelected, forKey: "isSelected") coder.encode(title, forKey: "title") coder.encode(isPrivate, forKey: "isPrivate") coder.encode(faviconURL, forKey: "faviconURL") } } extension TabManager { static fileprivate func tabsStateArchivePath() -> String { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] return URL(fileURLWithPath: documentsPath).appendingPathComponent("tabsState.archive").path } static func tabArchiveData() -> Data? { let tabStateArchivePath = tabsStateArchivePath() if FileManager.default.fileExists(atPath: tabStateArchivePath) { return (try? Data(contentsOf: URL(fileURLWithPath: tabStateArchivePath))) } else { return nil } } static func tabsToRestore() -> [SavedTab]? { if let tabData = tabArchiveData() { let unarchiver = NSKeyedUnarchiver(forReadingWith: tabData) return unarchiver.decodeObject(forKey: "tabs") as? [SavedTab] } else { return nil } } fileprivate func preserveTabsInternal() { assert(Thread.isMainThread) guard !isRestoring else { return } let path = TabManager.tabsStateArchivePath() var savedTabs = [SavedTab]() var savedUUIDs = Set<String>() for (tabIndex, tab) in tabs.enumerated() { if let savedTab = SavedTab(tab: tab, isSelected: tabIndex == selectedIndex) { savedTabs.append(savedTab) if let screenshot = tab.screenshot, let screenshotUUID = tab.screenshotUUID { savedUUIDs.insert(screenshotUUID.uuidString) imageStore?.put(screenshotUUID.uuidString, image: screenshot) } } } // Clean up any screenshots that are no longer associated with a tab. imageStore?.clearExcluding(savedUUIDs) let tabStateData = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: tabStateData) archiver.encode(savedTabs, forKey: "tabs") archiver.finishEncoding() tabStateData.write(toFile: path, atomically: true) } func preserveTabs() { // This is wrapped in an Objective-C @try/@catch handler because NSKeyedArchiver may throw exceptions which Swift cannot handle _ = Try(withTry: { () -> Void in self.preserveTabsInternal() }) { (exception) -> Void in print("Failed to preserve tabs: \(exception ??? "nil")") SentryIntegration.shared.send(message: "Failed to preserve tabs: \(exception ??? "nil")", tag: "TabManager", severity: .error) } } fileprivate func restoreTabsInternal() { log.debug("Restoring tabs.") guard let savedTabs = TabManager.tabsToRestore() else { log.debug("Nothing to restore.") return } var tabToSelect: Tab? for savedTab in savedTabs { // Provide an empty request to prevent a new tab from loading the home screen let tab = self.addTab(nil, configuration: nil, afterTab: nil, flushToDisk: false, zombie: true, isPrivate: savedTab.isPrivate) // Since this is a restored tab, reset the URL to be loaded as that will be handled by the SessionRestoreHandler tab.url = nil if let faviconURL = savedTab.faviconURL { let icon = Favicon(url: faviconURL, date: Date(), type: IconType.noneFound) icon.width = 1 tab.favicons.append(icon) } // Set the UUID for the tab, asynchronously fetch the UIImage, then store // the screenshot in the tab as long as long as a newer one hasn't been taken. if let screenshotUUID = savedTab.screenshotUUID, let imageStore = self.imageStore { tab.screenshotUUID = screenshotUUID imageStore.get(screenshotUUID.uuidString) >>== { screenshot in if tab.screenshotUUID == screenshotUUID { tab.setScreenshot(screenshot, revUUID: false) } } } if savedTab.isSelected { tabToSelect = tab } tab.sessionData = savedTab.sessionData tab.lastTitle = savedTab.title } if tabToSelect == nil { tabToSelect = tabs.first } log.debug("Done adding tabs.") // Only tell our delegates that we restored tabs if we actually restored a tab(s) if savedTabs.count > 0 { log.debug("Notifying delegates.") for delegate in delegates { delegate.get()?.tabManagerDidRestoreTabs(self) } } if let tab = tabToSelect { log.debug("Selecting a tab.") selectTab(tab) log.debug("Creating webview for selected tab.") tab.createWebview() } log.debug("Done.") } func restoreTabs() { isRestoring = true if count == 0 && !AppConstants.IsRunningTest && !DebugSettingsBundleOptions.skipSessionRestore { // This is wrapped in an Objective-C @try/@catch handler because NSKeyedUnarchiver may throw exceptions which Swift cannot handle _ = Try( withTry: { () -> Void in self.restoreTabsInternal() }, catch: { exception in print("Failed to restore tabs: \(exception ??? "nil")") SentryIntegration.shared.send(message: "Failed to restore tabs: \(exception ??? "nil")", tag: "TabManager", severity: .error) } ) } isRestoring = false // Always make sure there is a single normal tab. if normalTabs.isEmpty { let tab = addTab() if selectedTab == nil { selectTab(tab) } } } func restoreTabs(_ savedTabs: [Tab]) { isRestoring = true for tab in savedTabs { tabs.append(tab) tab.navigationDelegate = self.navDelegate for delegate in delegates { delegate.get()?.tabManager(self, didAddTab: tab) } } isRestoring = false } } extension TabManager : WKNavigationDelegate { func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { let isNoImageMode = self.prefs.boolForKey(PrefsKeys.KeyNoImageModeStatus) ?? false let tab = self[webView] tab?.setNoImageMode(isNoImageMode, force: false) let isNightMode = NightModeAccessors.isNightMode(self.prefs) tab?.setNightMode(isNightMode) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { hideNetworkActivitySpinner() // only store changes if this is not an error page // as we current handle tab restore as error page redirects then this ensures that we don't // call storeChanges unnecessarily on startup if let url = webView.url { if !url.isErrorPageURL { storeChanges() } } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { hideNetworkActivitySpinner() } func hideNetworkActivitySpinner() { for tab in tabs { if let tabWebView = tab.webView { // If we find one tab loading, we don't hide the spinner if tabWebView.isLoading { return } } } UIApplication.shared.isNetworkActivityIndicatorVisible = false } /// Called when the WKWebView's content process has gone away. If this happens for the currently selected tab /// then we immediately reload it. func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { if let tab = selectedTab, tab.webView == webView { webView.reload() } } } extension TabManager { class func tabRestorationDebugInfo() -> String { assert(Thread.isMainThread) let tabs = TabManager.tabsToRestore()?.map { $0.jsonDictionary } ?? [] do { let jsonData = try JSONSerialization.data(withJSONObject: tabs, options: [.prettyPrinted]) return String(data: jsonData, encoding: String.Encoding.utf8) ?? "" } catch _ { return "" } } } // WKNavigationDelegates must implement NSObjectProtocol class TabManagerNavDelegate: NSObject, WKNavigationDelegate { fileprivate var delegates = WeakList<WKNavigationDelegate>() func insert(_ delegate: WKNavigationDelegate) { delegates.insert(delegate) } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { for delegate in delegates { delegate.webView?(webView, didCommit: navigation) } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { for delegate in delegates { delegate.webView?(webView, didFail: navigation, withError: error) } } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { for delegate in delegates { delegate.webView?(webView, didFailProvisionalNavigation: navigation, withError: error) } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { for delegate in delegates { delegate.webView?(webView, didFinish: navigation) } } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let authenticatingDelegates = delegates.filter { wv in return wv.responds(to: #selector(WKNavigationDelegate.webView(_:didReceive:completionHandler:))) } guard let firstAuthenticatingDelegate = authenticatingDelegates.first else { return completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil) } firstAuthenticatingDelegate.webView?(webView, didReceive: challenge) { (disposition, credential) in completionHandler(disposition, credential) } } func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { for delegate in delegates { delegate.webView?(webView, didReceiveServerRedirectForProvisionalNavigation: navigation) } } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { for delegate in delegates { delegate.webView?(webView, didStartProvisionalNavigation: navigation) } } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { var res = WKNavigationActionPolicy.allow for delegate in delegates { delegate.webView?(webView, decidePolicyFor: navigationAction, decisionHandler: { policy in if policy == .cancel { res = policy } }) } decisionHandler(res) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { var res = WKNavigationResponsePolicy.allow for delegate in delegates { delegate.webView?(webView, decidePolicyFor: navigationResponse, decisionHandler: { policy in if policy == .cancel { res = policy } }) } decisionHandler(res) } }
mpl-2.0
APUtils/APExtensions
APExtensions/Classes/Core/_Extensions/_Foundation/NotificationCenter+Utils.swift
1
3658
// // NotificationCenter+Utils.swift // APExtensions // // Created by Anton Plebanovich on 8/15/17. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import Foundation // ******************************* MARK: - Day Start Notifications public extension Notification.Name { /// Post on 0:00:00 every day so app can refresh it's data. For example change `Today` to `Yesterday` date formatter string. static let DayDidStart = Notification.Name("DayDidStart") } private var dayTimer: Timer? private var fireDate: Date? public extension NotificationCenter { /// Start day notifications that post on 0:00:00 every day so app can refresh it's data. For example change `Today` to `Yesterday` date formatter string. func startDayNotifications() { guard fireDate == nil else { return } fireDate = Date.tomorrow // No need to start timer if application is not active, it'll be started when app becomes active if UIApplication.shared.applicationState == .active { startTimer() } g.sharedNotificationCenter.addObserver(self, selector: #selector(self.onDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil) g.sharedNotificationCenter.addObserver(self, selector: #selector(self.onWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil) } func stopDayNotifications() { g.sharedNotificationCenter.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) g.sharedNotificationCenter.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil) stopTimer() fireDate = nil } // ******************************* MARK: - Timer private func startTimer() { g.performInMain { guard let fireDate = fireDate else { return } dayTimer = Timer(fireAt: fireDate, interval: 0, target: self, selector: #selector(self.onTimer(_:)), userInfo: nil, repeats: false) RunLoop.main.add(dayTimer!, forMode: .default) } } private func restartTimer() { g.performInMain { self.stopTimer() fireDate = Date.tomorrow self.startTimer() } } private func stopTimer() { g.performInMain { dayTimer?.invalidate() dayTimer = nil } } @objc private func onTimer(_ timer: Timer) { g.sharedNotificationCenter.post(name: .DayDidStart, object: self) restartTimer() } // ******************************* MARK: - Notifications @objc private func onDidBecomeActive(_ notification: Notification) { if let fireDate = fireDate, fireDate < Date() { g.sharedNotificationCenter.post(name: .DayDidStart, object: self) } restartTimer() } @objc private func onWillResignActive(_ notification: Notification) { stopTimer() } } // ******************************* MARK: - Perform Once public extension NotificationCenter { /// Observes notification once and then removes observer. func observeOnce(forName: NSNotification.Name?, object: Any?, queue: OperationQueue?, using: @escaping (Notification) -> Void) { var token: NSObjectProtocol! token = addObserver(forName: forName, object: object, queue: queue, using: { [weak self] notification in if let token = token { self?.removeObserver(token) } using(notification) }) } }
mit
samantharachelb/todolist
todolist/Extensions/AddBordersToUIView.swift
1
994
// // AddBordersToUIView.swift // todolist // // Created by Samantha Emily-Rachel Belnavis on 2017-10-16. // Copyright © 2017 Samantha Emily-Rachel Belnavis. All rights reserved. // import Foundation import UIKit extension UIView { enum ViewSide { case Left, Right, Top, Bottom } func addBorder(toSide side: ViewSide, withColour color: CGColor, andThickness thickness: CGFloat) { let border = CALayer() border.backgroundColor = color switch side { case .Left: border.frame = CGRect(x: frame.minX, y: frame.minY, width: thickness, height: frame.height); break case .Right: border.frame = CGRect(x: frame.minX, y: frame.minY, width: thickness, height: frame.height); break case .Top: border.frame = CGRect(x: frame.minX, y: frame.minY, width: thickness, height: frame.height); break case .Bottom: border.frame = CGRect(x: frame.minX, y: frame.minY, width: thickness, height: frame.height); break } layer.addSublayer(border) } }
mit
edx/edx-app-ios
Pods/FBSDKLoginKit/FBSDKLoginKit/FBSDKLoginKit/Swift/LoginManager.swift
1
7534
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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. #if BUCK import FacebookCore #endif import FBSDKCoreKit import UIKit /// Login Result Block @available(tvOS, unavailable) public typealias LoginResultBlock = (LoginResult) -> Void /** Describes the result of a login attempt. */ @available(tvOS, unavailable) public enum LoginResult { /// User succesfully logged in. Contains granted, declined permissions and access token. case success(granted: Set<Permission>, declined: Set<Permission>, token: FBSDKCoreKit.AccessToken?) /// Login attempt was cancelled by the user. case cancelled /// Login attempt failed. case failed(Error) internal init(result: LoginManagerLoginResult?, error: Error?) { guard let result = result, error == nil else { self = .failed(error ?? LoginError(.unknown)) return } guard !result.isCancelled else { self = .cancelled return } let granted: Set<Permission> = Set(result.grantedPermissions.map { Permission(stringLiteral: $0) }) let declined: Set<Permission> = Set(result.declinedPermissions.map { Permission(stringLiteral: $0) }) self = .success(granted: granted, declined: declined, token: result.token) } } /** This class provides methods for logging the user in and out. It works directly with `AccessToken.current` and sets the "current" token upon successful authorizations (or sets `nil` in case of `logOut`). You should check `AccessToken.current` before calling `logIn()` to see if there is a cached token available (typically in your `viewDidLoad`). If you are managing your own token instances outside of `AccessToken.current`, you will need to set `current` before calling `logIn()` to authorize further permissions on your tokens. */ @available(tvOS, unavailable) public extension LoginManager { /** Initialize an instance of `LoginManager.` - parameter defaultAudience: Optional default audience to use. Default: `.Friends`. */ convenience init(defaultAudience: DefaultAudience = .friends) { self.init() self.defaultAudience = defaultAudience } /** Logs the user in or authorizes additional permissions. Use this method when asking for permissions. You should only ask for permissions when they are needed and the value should be explained to the user. You can inspect the result's `declinedPermissions` to also provide more information to the user if they decline permissions. This method will present a UI to the user. To reduce unnecessary app switching, you should typically check if `AccessToken.current` already contains the permissions you need. If it does, you probably do not need to call this method. You can only perform one login call at a time. Calling a login method before the completion handler is called on a previous login will result in an error. - parameter permissions: Array of read permissions. Default: `[.PublicProfile]` - parameter viewController: Optional view controller to present from. Default: topmost view controller. - parameter completion: Optional callback. */ func logIn( permissions: [Permission] = [.publicProfile], viewController: UIViewController? = nil, completion: LoginResultBlock? = nil ) { self.logIn(permissions: permissions.map { $0.name }, from: viewController, handler: sdkCompletion(completion)) } /** Logs the user in or authorizes additional permissions. Use this method when asking for permissions. You should only ask for permissions when they are needed and the value should be explained to the user. You can inspect the result's `declinedPermissions` to also provide more information to the user if they decline permissions. This method will present a UI to the user. To reduce unnecessary app switching, you should typically check if `AccessToken.current` already contains the permissions you need. If it does, you probably do not need to call this method. You can only perform one login call at a time. Calling a login method before the completion handler is called on a previous login will result in an error. - parameter viewController: Optional view controller to present from. Default: topmost view controller. - parameter configuration the login configuration to use. - parameter completion: Optional callback. */ func logIn( viewController: UIViewController? = nil, configuration: LoginConfiguration, completion: @escaping LoginResultBlock ) { let legacyCompletion = { (result: LoginManagerLoginResult?, error: Error?) in let result = LoginResult(result: result, error: error) completion(result) } self.__logIn(from: viewController, configuration: configuration, completion: legacyCompletion) } /** Logs the user in or authorizes additional permissions. Use this method when asking for permissions. You should only ask for permissions when they are needed and the value should be explained to the user. You can inspect the result's `declinedPermissions` to also provide more information to the user if they decline permissions. This method will present a UI to the user. To reduce unnecessary app switching, you should typically check if `AccessToken.current` already contains the permissions you need. If it does, you probably do not need to call this method. You can only perform one login call at a time. Calling a login method before the completion handler is called on a previous login will result in an error. - parameter configuration the login configuration to use. - parameter completion: Optional callback. */ func logIn( configuration: LoginConfiguration, completion: @escaping LoginResultBlock ) { let legacyCompletion = { (result: LoginManagerLoginResult?, error: Error?) in let result = LoginResult(result: result, error: error) completion(result) } self.__logIn(from: nil, configuration: configuration, completion: legacyCompletion) } private func sdkCompletion(_ completion: LoginResultBlock?) -> LoginManagerLoginResultBlock? { guard let original = completion else { return nil } return convertedResultHandler(original) } private func convertedResultHandler(_ original: @escaping LoginResultBlock) -> LoginManagerLoginResultBlock { return { (result: LoginManagerLoginResult?, error: Error?) in let result = LoginResult(result: result, error: error) original(result) } } }
apache-2.0
damicreabox/Git2Swift
Sources/Git2Swift/tree/Tree.swift
1
2214
// // Tree.swift // Git2Swift // // Created by Damien Giron on 01/08/2016. // // import Foundation import CLibgit2 /// Tree Definition public class Tree { let repository : Repository /// Internal libgit2 tree internal let tree : UnsafeMutablePointer<OpaquePointer?> /// Init with libgit2 tree /// /// - parameter repository: Git2Swift repository /// - parameter tree: Libgit2 tree pointer /// /// - returns: Tree init(repository: Repository, tree : UnsafeMutablePointer<OpaquePointer?>) { self.tree = tree self.repository = repository } deinit { if let ptr = tree.pointee { git_tree_free(ptr) } tree.deinitialize() tree.deallocate(capacity: 1) } /// Find entry by path. /// /// - parameter byPath: Path of file /// /// - throws: GitError /// /// - returns: TreeEntry or nil public func entry(byPath: String) throws -> TreeEntry? { // Entry let treeEntry = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) // Find tree entry let error = git_tree_entry_bypath(treeEntry, tree.pointee, byPath) switch error { case 0: return TreeEntry(pointer: treeEntry) case GIT_ENOTFOUND.rawValue: return nil default: throw GitError.unknownError(msg: "", code: error, desc: git_error_message()) } } /// Diff /// /// - parameter other: Other tree /// /// - returns: Diff public func diff(other: Tree) throws -> Diff { // Create diff let diff = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) // Create diff let error = git_diff_tree_to_tree(diff, repository.pointer.pointee, tree.pointee, other.tree.pointee, nil) if (error == 0) { return Diff(pointer: diff) } else { throw GitError.unknownError(msg: "diff", code: error, desc: git_error_message()) } } }
apache-2.0
ReSwift/ReSwift
ReSwift/CoreTypes/StoreSubscriber.swift
3
670
// // StoreSubscriber.swift // ReSwift // // Created by Benjamin Encz on 12/14/15. // Copyright © 2015 ReSwift Community. All rights reserved. // public protocol AnyStoreSubscriber: AnyObject { // swiftlint:disable:next identifier_name func _newState(state: Any) } public protocol StoreSubscriber: AnyStoreSubscriber { associatedtype StoreSubscriberStateType func newState(state: StoreSubscriberStateType) } extension StoreSubscriber { // swiftlint:disable:next identifier_name public func _newState(state: Any) { if let typedState = state as? StoreSubscriberStateType { newState(state: typedState) } } }
mit
SwiftKitz/Appz
Appz/Appz/Apps/Podcasts.swift
1
1009
// // Podcasts.swift // Appz // // Created by MARYAM ALJAME on 2/20/18. // Copyright © 2018 kitz. All rights reserved. // public extension Applications { struct Podcasts: ExternalApplication { public typealias ActionType = Applications.Podcasts.Action public let scheme = "podcasts:" public let fallbackURL = "https://itunes.apple.com/us/app/podcasts/id525463029?mt=8" public let appStoreId = "525463029" public init() {} } } // MARK: - Actions public extension Applications.Podcasts { enum Action { case open } } extension Applications.Podcasts.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) } } }
mit
swift-server/http
Sources/HTTP/PoCSocket/PoCSocket.swift
1
12565
// This source file is part of the Swift.org Server APIs open source project // // Copyright (c) 2017 Swift Server API project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // import Foundation import Dispatch import ServerSecurity ///:nodoc: public enum PoCSocketError: Error { case SocketOSError(errno: Int32) case InvalidSocketError case InvalidReadLengthError case InvalidWriteLengthError case InvalidBufferError } /// Simple Wrapper around the `socket(2)` functions we need for Proof of Concept testing /// Intentionally a thin layer over `recv(2)`/`send(2)` so uses the same argument types. /// Note that no method names here are the same as any system call names. /// This is because we expect the caller might need functionality we haven't implemented here. internal class PoCSocket: ConnectionDelegate { /// hold the file descriptor for the socket supplied by the OS. `-1` is invalid socket internal var socketfd: Int32 = -1 /// The TCP port the server is actually listening on. Set after system call completes internal var listeningPort: Int32 = -1 /// Track state between `listen(2)` and `shutdown(2)` private let _isListeningLock = DispatchSemaphore(value: 1) private var _isListening: Bool = false internal private(set) var isListening: Bool { get { _isListeningLock.wait() defer { _isListeningLock.signal() } return _isListening } set { _isListeningLock.wait() defer { _isListeningLock.signal() } _isListening = newValue } } /// Track state between `accept(2)/bind(2)` and `close(2)` private let _isConnectedLock = DispatchSemaphore(value: 1) private var _isConnected: Bool = false internal private(set) var isConnected: Bool { get { _isConnectedLock.wait() defer { _isConnectedLock.signal() } return _isConnected } set { _isConnectedLock.wait() defer { _isConnectedLock.signal() } _isConnected = newValue } } /// track whether a shutdown is in progress so we can suppress error messages private let _isShuttingDownLock = DispatchSemaphore(value: 1) private var _isShuttingDown: Bool = false private var isShuttingDown: Bool { get { _isShuttingDownLock.wait() defer { _isShuttingDownLock.signal() } return _isShuttingDown } set { _isShuttingDownLock.wait() defer { _isShuttingDownLock.signal() } _isShuttingDown = newValue } } /// Delegate that provides the TLS implementation public var TLSdelegate: TLSServiceDelegate? = nil /// Return the file descriptor as a connection endpoint for ConnectionDelegate. public var endpoint: ConnectionType { get { return ConnectionType.socket(self.socketfd) } } /// track whether a the socket has already been closed. private let _hasClosedLock = DispatchSemaphore(value: 1) private var _hasClosed: Bool = false private var hasClosed: Bool { get { _hasClosedLock.wait() defer { _hasClosedLock.signal() } return _hasClosed } set { _hasClosedLock.wait() defer { _hasClosedLock.signal() } _hasClosed = newValue } } /// Call recv(2) with buffer allocated by our caller and return the output /// /// - Parameters: /// - readBuffer: Buffer to read into. Note this needs to be `inout` because we're modfying it and we want Swift4+'s ownership checks to make sure no one else is at the same time /// - maxLength: Max length that can be read. Buffer *must* be at least this big!!! /// - Returns: Number of bytes read or -1 on failure as per `recv(2)` /// - Throws: PoCSocketError if sanity checks fail internal func socketRead(into readBuffer: inout UnsafeMutablePointer<Int8>, maxLength: Int) throws -> Int { if maxLength <= 0 || maxLength > Int(Int32.max) { throw PoCSocketError.InvalidReadLengthError } if socketfd <= 0 { throw PoCSocketError.InvalidSocketError } //Make sure no one passed a nil pointer to us let readBufferPointer: UnsafeMutablePointer<Int8>! = readBuffer if readBufferPointer == nil { throw PoCSocketError.InvalidBufferError } //Make sure data isn't re-used readBuffer.initialize(to: 0x0, count: maxLength) let read: Int if let tls = self.TLSdelegate { // HTTPS read = try tls.willReceive(into: readBuffer, bufSize: maxLength) } else { // HTTP read = recv(self.socketfd, readBuffer, maxLength, Int32(0)) } //Leave this as a local variable to facilitate Setting a Watchpoint in lldb return read } /// Pass buffer passed into to us into send(2). /// /// - Parameters: /// - buffer: buffer containing data to write. /// - bufSize: number of bytes to write. Buffer must be this long /// - Returns: number of bytes written or -1. See `send(2)` /// - Throws: PoCSocketError if sanity checks fail @discardableResult internal func socketWrite(from buffer: UnsafeRawPointer, bufSize: Int) throws -> Int { if socketfd <= 0 { throw PoCSocketError.InvalidSocketError } if bufSize < 0 || bufSize > Int(Int32.max) { throw PoCSocketError.InvalidWriteLengthError } // Make sure we weren't handed a nil buffer let writeBufferPointer: UnsafeRawPointer! = buffer if writeBufferPointer == nil { throw PoCSocketError.InvalidBufferError } let sent: Int if let tls = self.TLSdelegate { // HTTPS sent = try tls.willSend(buffer: buffer, bufSize: Int(bufSize)) } else { // HTTP sent = send(self.socketfd, buffer, Int(bufSize), Int32(0)) } //Leave this as a local variable to facilitate Setting a Watchpoint in lldb return sent } /// Calls `shutdown(2)` and `close(2)` on a socket internal func shutdownAndClose() { self.isShuttingDown = true if let tls = self.TLSdelegate { tls.willDestroy() } if socketfd < 1 { //Nothing to do. Maybe it was closed already return } if hasClosed { //Nothing to do. It was closed already return } if self.isListening || self.isConnected { _ = shutdown(self.socketfd, Int32(SHUT_RDWR)) self.isListening = false } self.isConnected = false close(self.socketfd) self.hasClosed = true } /// Thin wrapper around `accept(2)` /// /// - Returns: PoCSocket object for newly connected socket or nil if we've been told to shutdown /// - Throws: PoCSocketError on sanity check fails or if accept fails after several retries internal func acceptClientConnection() throws -> PoCSocket? { if socketfd <= 0 || !isListening { throw PoCSocketError.InvalidSocketError } let retVal = PoCSocket() var maxRetryCount = 100 var acceptFD: Int32 = -1 repeat { var acceptAddr = sockaddr_in() var addrSize = socklen_t(MemoryLayout<sockaddr_in>.size) acceptFD = withUnsafeMutablePointer(to: &acceptAddr) { pointer in return accept(self.socketfd, UnsafeMutableRawPointer(pointer).assumingMemoryBound(to: sockaddr.self), &addrSize) } if acceptFD < 0 && errno != EINTR { //fail if (isShuttingDown) { return nil } maxRetryCount = maxRetryCount - 1 print("Could not accept on socket \(socketfd). Error is \(errno). Will retry.") } } while acceptFD < 0 && maxRetryCount > 0 if acceptFD < 0 { throw PoCSocketError.SocketOSError(errno: errno) } retVal.isConnected = true retVal.socketfd = acceptFD // TLS delegate does post accept handling and verification if let tls = self.TLSdelegate { try tls.didAccept(connection: retVal) } return retVal } /// call `bind(2)` and `listen(2)` /// /// - Parameters: /// - port: `sin_port` value, see `bind(2)` /// - maxBacklogSize: backlog argument to `listen(2)` /// - Throws: PoCSocketError internal func bindAndListen(on port: Int = 0, maxBacklogSize: Int32 = 100) throws { #if os(Linux) socketfd = socket(Int32(AF_INET), Int32(SOCK_STREAM.rawValue), Int32(IPPROTO_TCP)) #else socketfd = socket(Int32(AF_INET), Int32(SOCK_STREAM), Int32(IPPROTO_TCP)) #endif if socketfd <= 0 { throw PoCSocketError.InvalidSocketError } // Initialize delegate if let tls = self.TLSdelegate { try tls.didCreateServer() } var on: Int32 = 1 // Allow address reuse if setsockopt(self.socketfd, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(MemoryLayout<Int32>.size)) < 0 { throw PoCSocketError.SocketOSError(errno: errno) } // Allow port reuse if setsockopt(self.socketfd, SOL_SOCKET, SO_REUSEPORT, &on, socklen_t(MemoryLayout<Int32>.size)) < 0 { throw PoCSocketError.SocketOSError(errno: errno) } #if os(Linux) var addr = sockaddr_in( sin_family: sa_family_t(AF_INET), sin_port: htons(UInt16(port)), sin_addr: in_addr(s_addr: in_addr_t(0)), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) #else var addr = sockaddr_in( sin_len: UInt8(MemoryLayout<sockaddr_in>.stride), sin_family: UInt8(AF_INET), sin_port: (Int(OSHostByteOrder()) != OSLittleEndian ? UInt16(port) : _OSSwapInt16(UInt16(port))), sin_addr: in_addr(s_addr: in_addr_t(0)), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) #endif _ = withUnsafePointer(to: &addr) { bind(self.socketfd, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size)) } _ = listen(self.socketfd, maxBacklogSize) isListening = true var addr_in = sockaddr_in() listeningPort = try withUnsafePointer(to: &addr_in) { pointer in var len = socklen_t(MemoryLayout<sockaddr_in>.size) if getsockname(socketfd, UnsafeMutablePointer(OpaquePointer(pointer)), &len) != 0 { throw PoCSocketError.SocketOSError(errno: errno) } #if os(Linux) return Int32(ntohs(addr_in.sin_port)) #else return Int32(Int(OSHostByteOrder()) != OSLittleEndian ? addr_in.sin_port.littleEndian : addr_in.sin_port.bigEndian) #endif } } /// Check to see if socket is being used /// /// - Returns: whether socket is listening or connected internal func isOpen() -> Bool { return isListening || isConnected } /// Sets the socket to Blocking or non-blocking mode. /// /// - Parameter mode: true for blocking, false for nonBlocking /// - Returns: `fcntl(2)` flags /// - Throws: PoCSocketError if `fcntl` fails @discardableResult internal func setBlocking(mode: Bool) throws -> Int32 { let flags = fcntl(self.socketfd, F_GETFL) if flags < 0 { //Failed throw PoCSocketError.SocketOSError(errno: errno) } let newFlags = mode ? flags & ~O_NONBLOCK : flags | O_NONBLOCK let result = fcntl(self.socketfd, F_SETFL, newFlags) if result < 0 { //Failed throw PoCSocketError.SocketOSError(errno: errno) } return result } }
apache-2.0
Headmast/openfights
MoneyHelper/Library/BaseClasses/Network/ServerPart/ServerRequests/ServerRequest.swift
1
9321
// // Serverrequest.swift // MoneyHelper // // Created by Kirill Klebanov on 16/09/2017. // Copyright © 2017 Surf. All rights reserved. // import Foundation import Alamofire @objc class ServerRequest: NSObject { typealias PerformedRequest = (DataRequest) -> Void typealias Completion = (ServerResponse) -> Void enum Method { case get case post case put case delete var alamofire: Alamofire.HTTPMethod { switch self { case .get: return .get case .post: return .post case .put: return .put case .delete: return .delete } } } enum Encoding { case defaultJson case defaultUrl case queryStringUrl var alamofire: Alamofire.ParameterEncoding { switch self { case .defaultJson: return JSONEncoding.default case .defaultUrl: return URLEncoding.default case .queryStringUrl: return URLEncoding.queryString } } } /// Метод API let path: String /// Результирующий URL запроса - включает baseUrl и path let url: URL /// Метод (get, post, delete...) let method: Method /// Токен для хедера let token: String? /// Хидеры запроса let headers: HTTPHeaders? /// Параметры запроса var parameters: ServerRequestParameter /// serverOnly by default var cachePolicy: CachePolicy let customEncoding: Encoding? fileprivate var currentRequest: DataRequest? = nil init(method: Method, relativeUrl: String, baseUrl: String, token: String? = nil, headers: HTTPHeaders? = nil, parameters: ServerRequestParameter, customEncoding: Encoding? = nil) { self.method = method self.token = token self.headers = headers self.path = relativeUrl self.url = (URL(string: baseUrl)?.appendingPathComponent(self.path))! self.parameters = parameters self.cachePolicy = .serverIfFailReadFromCahce self.customEncoding = customEncoding super.init() } func perform(with completion: @escaping (ServerResponse) -> Void) { let requests = self.createRequestWithPolicy(with: completion) switch self.parameters { case .simpleParams(let params): let request = self.createSingleParamRequest(params) requests.forEach({ $0(request) }) } } func createRequestWithPolicy(with completion: @escaping Completion) -> [PerformedRequest] { switch self.cachePolicy { case .cacheOnly: return [self.readFromCache(completion: completion)] case .serverOnly, .serverIfFailReadFromCahce: return [self.sendRequest(completion: completion)] case .firstCacheThenRefreshFromServer: let cacheRequest = self.readFromCache(completion: completion) let serverRequest = self.sendRequest(completion: completion) return [cacheRequest, serverRequest] } } /// Этот метод используется для отмены текущего запроса func cancel() { currentRequest?.cancel() } // MARK: - Helps /// Возвращает хедеры, которые необходимы для данного запроса. func createHeaders() -> HTTPHeaders { var headers: HTTPHeaders = self.headers ?? [:] if let tokenString = token { headers["Authorization"] = tokenString } headers ["Content-Type"] = "Application/json" return headers } } // MARK: - Work witch URLCache extension ServerRequest { /// Извлекает из кэш из URLCache для конкретного запроса func extractCachedUrlResponse() -> CachedURLResponse? { guard let urlRequest = self.currentRequest?.request else { return nil } if let response = URLCache.shared.cachedResponse(for: urlRequest) { return response } return nil } func extractCachedUrlResponse(request: URLRequest?) -> CachedURLResponse? { guard let urlRequest = request else { return nil } if let response = URLCache.shared.cachedResponse(for: urlRequest) { return response } return nil } /// Сохраняет запрос в кэш func store(cachedUrlResponse: CachedURLResponse, for request: URLRequest?) { guard let urlRequest = request else { return } URLCache.shared.storeCachedResponse(cachedUrlResponse, for: urlRequest) } } extension ServerRequest { enum MultipartRequestCompletion { case succes(DataRequest) case failure(ServerResponse) } func createSingleParamRequest(_ params: [String: Any]?) -> DataRequest { let headers = self.createHeaders() let manager = ServerRequestsManager.shared.manager let paramEncoding = {() -> ParameterEncoding in if let custom = self.customEncoding { return custom.alamofire } return self.method.alamofire == .get ? URLEncoding.default : JSONEncoding.default }() let request = manager.request( url, method: method.alamofire, parameters: params, encoding: paramEncoding, headers: headers ) return request } func createDataRequest() { } } // MARK: - Requests extension ServerRequest { func sendRequest(completion: @escaping Completion) -> PerformedRequest { let performRequest = { (request: DataRequest) -> Void in self.currentRequest = request request.response { afResponse in self.log(afResponse) var response = ServerResponse(dataResponse: afResponse, dataResult: .success(afResponse.data, false)) if (response.notModified || response.connectionFailed) && self.cachePolicy == .serverIfFailReadFromCahce { response = self.readCache(with: request.request, response: response) } if response.result.value != nil, let urlResponse = afResponse.response, let data = afResponse.data, self.cachePolicy != .serverOnly { self.store(cachedUrlResponse: CachedURLResponse(response: urlResponse, data: data, storagePolicy: .allowed), for: request.request) } completion(response) } } return performRequest } func readFromCache(completion: @escaping Completion) -> PerformedRequest { let performRequest = { (request: DataRequest) -> Void in completion(self.readCache(with: request.request)) } return performRequest } func readCache(with request: URLRequest?, response: ServerResponse? = nil) -> ServerResponse { let result = response ?? ServerResponse() if let cachedResponse = self.extractCachedUrlResponse(request: request), let resultResponse = cachedResponse.response as? HTTPURLResponse { result.httpResponse = resultResponse result.result = { () -> ResponseResult<Any> in do { let object = try JSONSerialization.jsonObject(with: cachedResponse.data, options: .allowFragments) return .success(object, true) } catch { return .failure(BaseCacheError.cantLoadFromCache) } }() } return result } } // MARK: - Supported methods extension ServerRequest { func log(_ afResponse: DefaultDataResponse) { #if DEBUG let url: String = afResponse.request?.url?.absoluteString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" let type: String = afResponse.request?.httpMethod ?? "" let headers: String = afResponse.request?.allHTTPHeaderFields?.description ?? "" let body = String(data: afResponse.request?.httpBody ?? Data(), encoding: String.Encoding.utf8) ?? "" let statusCode: String = "\(afResponse.response?.statusCode ?? 0)" let reponseHeaders: String = afResponse.response?.allHeaderFields.description ?? "" var responseBody: String = "" if let data = afResponse.data { responseBody = "\(String(data: data, encoding: .utf8) ?? "nil")" } debugPrint("URL: \(url)") debugPrint("REQUEST: \(type)") debugPrint("HEADERS: \(headers)") NSLog("BODY: %@", body) debugPrint("RESPONSE: \(statusCode)") debugPrint("HEADERS: \(reponseHeaders)") NSLog("BODY: %@", responseBody) debugPrint("TIMELINE: \(afResponse.timeline)") debugPrint("DiskCache: \(URLCache.shared.currentDiskUsage) of \(URLCache.shared.diskCapacity)") debugPrint("MemoryCache: \(URLCache.shared.currentMemoryUsage) of \(URLCache.shared.memoryCapacity)") #else #endif } }
apache-2.0
shorlander/firefox-ios
UITests/NavigationDelegateTests.swift
6
1447
/* 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 EarlGrey @testable import Client // WKWebView's WKNavigationDelegate is used for custom URL handling // such as telephone links, app store links, etc. class NavigationDelegateTests: KIFTestCase { fileprivate var webRoot: String! override func setUp() { super.setUp() webRoot = SimplePageServer.start() BrowserUtils.dismissFirstRunUI() } override func tearDown() { BrowserUtils.resetToAboutHome(tester()) BrowserUtils.clearPrivateData(tester: tester()) super.tearDown() } func enterUrl(url: String) { EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap()) EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_replaceText(url)) EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_typeText("\n")) } func testAppStoreLinkShowsConfirmation() { let url = "\(webRoot!)/navigationDelegate.html" enterUrl(url: url) tester().tapWebViewElementWithAccessibilityLabel("link") EarlGrey.select(elementWithMatcher: grey_accessibilityID("CancelOpenInAppStore")).perform(grey_tap()) } }
mpl-2.0
3lvis/Fragments
Source/Tailor.swift
2
1242
import UIKit class Tailor : UIViewController { init() { super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("Tailor doesn't support Storyboards or Interface Builder") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .whiteColor() let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) label.text = "Hi there, what are you doing to do today in this beautiful day?" label.font = UIFont.boldSystemFontOfSize(18.0) label.setTranslatesAutoresizingMaskIntoConstraints(false) label.backgroundColor = .redColor() self.view.addSubview(label) self.view.addConstraint( NSLayoutConstraint( item: label, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 1.0)) self.view.addConstraint( NSLayoutConstraint( item: label, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 0.05, constant: 0.0)) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } }
mit
christiankm/FinanceKit
Sources/FinanceKit/ExchangeRate.swift
1
496
// // FinanceKit // Copyright © 2022 Christian Mitteldorf. All rights reserved. // MIT license, see LICENSE file for details. // import Foundation /// Exchange rate is used to specify the relationship between the price of one currency to another, or other forms of trades. /// /// The exchange rate of Danish Kroner at a price of 620 compared to US Dollar at price 100 would be 0.161. /// `ExchangeRate` is simply a contextual typealias for `Double`. public typealias ExchangeRate = Double
mit
sotownsend/flok-apple
Pod/Classes/Drivers/Ping.swift
1
467
@objc class FlokPingModule : FlokModule { override var exports: [String] { return ["ping:", "ping1:", "ping2:"] } func ping(args: [AnyObject]) { engine.intDispatch("pong", args: nil) } func ping1(args: [AnyObject]) { engine.intDispatch("pong1", args: args) } func ping2(args: [AnyObject]) { engine.intDispatch("pong2", args: [args[0]]) engine.intDispatch("pong2", args: args) } }
mit
jtbandes/swift-compiler-crashes
crashes-fuzzing/27166-swift-typebase-isspecialized.swift
4
271
// 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 A{ protocol a protocol a{{}}struct B<T{func A{ class B{ struct d{ enum B<T:a { }} class d<f:T.a
mit
digdoritos/RestfulAPI-Example
RestfulAPI-Example/MemberViewController.swift
1
2502
// // MemberViewController.swift // RestfulAPI-Example // // Created by Chun-Tang Wang on 27/03/2017. // Copyright © 2017 Chun-Tang Wang. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import KeychainAccess class MemberViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var members = [Member]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) requestMembers() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func dismiss(_ sender: UIBarButtonItem) { dismissWithBackAnimation() } // MARK: - Data Request func requestMembers() { guard let token = TokenManager.keychain["token"] else { showAlert(title:"Warning", message: "Wrong session token") return } let api: Service = .getMember let headers: HTTPHeaders = [ "Authorization": token ] Alamofire.request(api.url(), method: api.method(), encoding: JSONEncoding.default, headers: headers) .validate() .responseJSON { response in switch response.result { case .success(let data): let json = JSON(data) self.members = Members(json: json["data"]).members self.tableView.reloadData() case .failure(let error): self.showAlert(title:"Error", message: error.localizedDescription) } } } } // MARK: - TableView Delegate extension MemberViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return members.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "MemberCell") else { return UITableViewCell() } cell.textLabel?.text = members[indexPath.row].name return cell } }
mit
mrdepth/Neocom
Legacy/Neocom/Neocom/WalletJournalPagePresenter.swift
2
2414
// // WalletJournalPagePresenter.swift // Neocom // // Created by Artem Shimanski on 11/12/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController import EVEAPI class WalletJournalPagePresenter: TreePresenter { typealias View = WalletJournalPageViewController typealias Interactor = WalletJournalPageInteractor struct Presentation { var sections: [Tree.Item.Section<Tree.Content.Section, Tree.Item.Row<ESI.Wallet.WalletJournalItem>>] var balance: String? } weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? required init(view: View) { self.view = view } func configure() { view?.tableView.register([Prototype.TreeSectionCell.default, Prototype.WalletJournalCell.default]) interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { let treeController = view?.treeController return DispatchQueue.global(qos: .utility).async { () -> Presentation in let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none dateFormatter.doesRelativeDateFormatting = true let items = content.value.walletJournal.sorted{$0.date > $1.date} let calendar = Calendar(identifier: .gregorian) let sections = Dictionary(grouping: items, by: { (i) -> Date in let components = calendar.dateComponents([.year, .month, .day], from: i.date) return calendar.date(from: components) ?? i.date }).sorted {$0.key > $1.key}.map { Tree.Item.Section(Tree.Content.Section(title: dateFormatter.string(from: $0.key).uppercased()), diffIdentifier: $0.key, treeController: treeController, children: $0.value.map{Tree.Item.Row($0)}) } let balance = content.value.balance.map {UnitFormatter.localizedString(from: $0, unit: .isk, style: .long)} return Presentation(sections: sections, balance: balance) } } }
lgpl-2.1
epaga/PenguinMath
PenguinRaceTests/PenguinRaceTests.swift
1
966
// // PenguinRaceTests.swift // PenguinRaceTests // // Created by John Goering on 21/06/15. // Copyright © 2015 John Goering. All rights reserved. // import XCTest class PenguinRaceTests: 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.measureBlock() { // Put the code you want to measure the time of here. } } }
apache-2.0
wyszo/TWCommonLib
TWCommonLib/TWCommonLib/StringExtensions.swift
1
491
import Foundation public extension String { /** Replaces multiple whitespaces in string with just one */ var condensedWhitespace: String { let components = self.components(separatedBy: CharacterSet.whitespacesAndNewlines) return components.filter { !$0.isEmpty }.joined(separator: " ") } var stringByRemovingHtmlTags: String { return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil); } }
mit
LeLuckyVint/MessageKit
Sources/Views/MessageInputBar.swift
1
18102
/* MIT License Copyright (c) 2017 MessageKit 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 open class MessageInputBar: UIView { public enum UIStackViewPosition { case left, right, bottom } // MARK: - Properties open weak var delegate: MessageInputBarDelegate? /// A background view that adds a blur effect. Shown when 'isTransparent' is set to TRUE. Hidden by default. open let blurView: UIView = { let blurEffect = UIBlurEffect(style: .extraLight) let view = UIVisualEffectView(effect: blurEffect) view.translatesAutoresizingMaskIntoConstraints = false view.isHidden = true return view }() /// When set to true, the blurView in the background is shown and the backgroundColor is set to .clear. Default is FALSE open var isTranslucent: Bool = false { didSet { blurView.isHidden = !isTranslucent backgroundColor = isTranslucent ? .clear : .white } } /// A boarder line anchored to the top of the view open let separatorLine = SeparatorLine() /** The InputStackView at the InputStackView.left position ## Important Notes ## 1. It's axis is initially set to .horizontal */ open let leftStackView = InputStackView(axis: .horizontal, spacing: 0) /** The InputStackView at the InputStackView.right position ## Important Notes ## 1. It's axis is initially set to .horizontal */ open let rightStackView = InputStackView(axis: .horizontal, spacing: 0) /** The InputStackView at the InputStackView.bottom position ## Important Notes ## 1. It's axis is initially set to .horizontal 2. It's spacing is initially set to 15 */ open let bottomStackView = InputStackView(axis: .horizontal, spacing: 15) open lazy var inputTextView: InputTextView = { [weak self] in let textView = InputTextView() textView.translatesAutoresizingMaskIntoConstraints = false textView.messageInputBar = self return textView }() /// The padding around the textView that separates it from the stackViews open var textViewPadding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8) { didSet { textViewLayoutSet?.bottom?.constant = -textViewPadding.bottom textViewLayoutSet?.left?.constant = textViewPadding.left textViewLayoutSet?.right?.constant = -textViewPadding.right bottomStackViewLayoutSet?.top?.constant = textViewPadding.bottom } } open var sendButton: InputBarButtonItem = { return InputBarButtonItem() .configure { $0.setSize(CGSize(width: 52, height: 28), animated: false) $0.isEnabled = false $0.title = "Send" $0.titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline) }.onTouchUpInside { $0.messageInputBar?.didSelectSendButton() } }() /// The anchor contants used by the UIStackViews and InputTextView to create padding within the InputBarAccessoryView open var padding: UIEdgeInsets = UIEdgeInsets(top: 6, left: 12, bottom: 6, right: 12) { didSet { updateViewContraints() } } open override var intrinsicContentSize: CGSize { let maxSize = CGSize(width: inputTextView.bounds.width, height: .greatestFiniteMagnitude) let sizeToFit = inputTextView.sizeThatFits(maxSize) var heightToFit = sizeToFit.height.rounded() + padding.top + padding.bottom if heightToFit >= maxHeight { if !isOverMaxHeight { textViewHeightAnchor?.isActive = true inputTextView.isScrollEnabled = true isOverMaxHeight = true } heightToFit = maxHeight } else { if isOverMaxHeight { textViewHeightAnchor?.isActive = false inputTextView.isScrollEnabled = false isOverMaxHeight = false } } inputTextView.invalidateIntrinsicContentSize() let size = CGSize(width: bounds.width, height: heightToFit) if previousIntrinsicContentSize != size { delegate?.messageInputBar(self, didChangeIntrinsicContentTo: size) } previousIntrinsicContentSize = size return size } private(set) var isOverMaxHeight = false /// The maximum intrinsicContentSize height. When reached the delegate 'didChangeIntrinsicContentTo' will be called. open var maxHeight: CGFloat = UIScreen.main.bounds.height / 3 { didSet { textViewHeightAnchor?.constant = maxHeight invalidateIntrinsicContentSize() } } /// The fixed widthAnchor constant of the leftStackView private(set) var leftStackViewWidthContant: CGFloat = 0 { didSet { leftStackViewLayoutSet?.width?.constant = leftStackViewWidthContant } } /// The fixed widthAnchor constant of the rightStackView private(set) var rightStackViewWidthContant: CGFloat = 52 { didSet { rightStackViewLayoutSet?.width?.constant = rightStackViewWidthContant } } /// The InputBarItems held in the leftStackView private(set) var leftStackViewItems: [InputBarButtonItem] = [] /// The InputBarItems held in the rightStackView private(set) var rightStackViewItems: [InputBarButtonItem] = [] /// The InputBarItems held in the bottomStackView private(set) var bottomStackViewItems: [InputBarButtonItem] = [] /// The InputBarItems held to make use of their hooks but they are not automatically added to a UIStackView open var nonStackViewItems: [InputBarButtonItem] = [] /// Returns a flatMap of all the items in each of the UIStackViews public var items: [InputBarButtonItem] { return [leftStackViewItems, rightStackViewItems, bottomStackViewItems, nonStackViewItems].flatMap { $0 } } // MARK: - Auto-Layout Management private var textViewLayoutSet: NSLayoutConstraintSet? private var textViewHeightAnchor: NSLayoutConstraint? private var leftStackViewLayoutSet: NSLayoutConstraintSet? private var rightStackViewLayoutSet: NSLayoutConstraintSet? private var bottomStackViewLayoutSet: NSLayoutConstraintSet? private var previousIntrinsicContentSize: CGSize? // MARK: - Initialization public convenience init() { self.init(frame: .zero) } public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Setup open func setup() { backgroundColor = .inputBarGray autoresizingMask = [.flexibleHeight] setupSubviews() setupConstraints() setupObservers() } private func setupSubviews() { addSubview(blurView) addSubview(inputTextView) addSubview(leftStackView) addSubview(rightStackView) addSubview(bottomStackView) addSubview(separatorLine) setStackViewItems([sendButton], forStack: .right, animated: false) } private func setupConstraints() { separatorLine.addConstraints(topAnchor, left: leftAnchor, right: rightAnchor, heightConstant: 0.5) blurView.fillSuperview() textViewLayoutSet = NSLayoutConstraintSet( top: inputTextView.topAnchor.constraint(equalTo: topAnchor, constant: padding.top), bottom: inputTextView.bottomAnchor.constraint(equalTo: bottomStackView.topAnchor, constant: -textViewPadding.bottom), left: inputTextView.leftAnchor.constraint(equalTo: leftStackView.rightAnchor, constant: textViewPadding.left), right: inputTextView.rightAnchor.constraint(equalTo: rightStackView.leftAnchor, constant: -textViewPadding.right) ).activate() textViewHeightAnchor = inputTextView.heightAnchor.constraint(equalToConstant: maxHeight) leftStackViewLayoutSet = NSLayoutConstraintSet( top: inputTextView.topAnchor.constraint(equalTo: topAnchor, constant: padding.top), bottom: leftStackView.bottomAnchor.constraint(equalTo: inputTextView.bottomAnchor, constant: 0), left: leftStackView.leftAnchor.constraint(equalTo: leftAnchor, constant: padding.left), width: leftStackView.widthAnchor.constraint(equalToConstant: leftStackViewWidthContant) ).activate() rightStackViewLayoutSet = NSLayoutConstraintSet( top: inputTextView.topAnchor.constraint(equalTo: topAnchor, constant: padding.top), bottom: rightStackView.bottomAnchor.constraint(equalTo: inputTextView.bottomAnchor, constant: 0), right: rightStackView.rightAnchor.constraint(equalTo: rightAnchor, constant: -padding.right), width: rightStackView.widthAnchor.constraint(equalToConstant: rightStackViewWidthContant) ).activate() bottomStackViewLayoutSet = NSLayoutConstraintSet( top: bottomStackView.topAnchor.constraint(equalTo: inputTextView.bottomAnchor), bottom: bottomStackView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor, constant: -padding.bottom), left: bottomStackView.leftAnchor.constraint(equalTo: leftAnchor, constant: padding.left), right: bottomStackView.rightAnchor.constraint(equalTo: rightAnchor, constant: -padding.right) ).activate() } private func updateViewContraints() { textViewLayoutSet?.top?.constant = padding.top leftStackViewLayoutSet?.top?.constant = padding.top leftStackViewLayoutSet?.left?.constant = padding.left rightStackViewLayoutSet?.top?.constant = padding.top rightStackViewLayoutSet?.right?.constant = -padding.right bottomStackViewLayoutSet?.left?.constant = padding.left bottomStackViewLayoutSet?.right?.constant = -padding.right bottomStackViewLayoutSet?.bottom?.constant = -padding.bottom } private func setupObservers() { NotificationCenter.default.addObserver(self, selector: #selector(MessageInputBar.orientationDidChange), name: .UIDeviceOrientationDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MessageInputBar.textViewDidChange), name: .UITextViewTextDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MessageInputBar.textViewDidBeginEditing), name: .UITextViewTextDidBeginEditing, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MessageInputBar.textViewDidEndEditing), name: .UITextViewTextDidEndEditing, object: nil) } // MARK: - Layout Helper Methods /// Layout the given UIStackView's /// /// - Parameter positions: The UIStackView's to layout public func layoutStackViews(_ positions: [InputStackView.Position] = [.left, .right, .bottom]) { for position in positions { switch position { case .left: leftStackView.setNeedsLayout() leftStackView.layoutIfNeeded() case .right: rightStackView.setNeedsLayout() rightStackView.layoutIfNeeded() case .bottom: bottomStackView.setNeedsLayout() bottomStackView.layoutIfNeeded() } } } /// Performs layout changes over the main thread /// /// - Parameters: /// - animated: If the layout should be animated /// - animations: Code internal func performLayout(_ animated: Bool, _ animations: @escaping () -> Void) { textViewLayoutSet?.deactivate() leftStackViewLayoutSet?.deactivate() rightStackViewLayoutSet?.deactivate() bottomStackViewLayoutSet?.deactivate() if animated { DispatchQueue.main.async { UIView.animate(withDuration: 0.3, animations: animations) } } else { UIView.performWithoutAnimation { animations() } } textViewLayoutSet?.activate() leftStackViewLayoutSet?.activate() rightStackViewLayoutSet?.activate() bottomStackViewLayoutSet?.activate() } // MARK: - UIStackView InputBarItem Methods /// Removes all of the arranged subviews from the UIStackView and adds the given items. Sets the inputBarAccessoryView property of the InputBarButtonItem /// /// - Parameters: /// - items: New UIStackView arranged views /// - position: The targeted UIStackView /// - animated: If the layout should be animated open func setStackViewItems(_ items: [InputBarButtonItem], forStack position: InputStackView.Position, animated: Bool) { func setNewItems() { switch position { case .left: leftStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } leftStackViewItems = items leftStackViewItems.forEach { $0.messageInputBar = self $0.parentStackViewPosition = position leftStackView.addArrangedSubview($0) } leftStackView.layoutIfNeeded() case .right: rightStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } rightStackViewItems = items rightStackViewItems.forEach { $0.messageInputBar = self $0.parentStackViewPosition = position rightStackView.addArrangedSubview($0) } rightStackView.layoutIfNeeded() case .bottom: bottomStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } bottomStackViewItems = items bottomStackViewItems.forEach { $0.messageInputBar = self $0.parentStackViewPosition = position bottomStackView.addArrangedSubview($0) } bottomStackView.layoutIfNeeded() } } performLayout(animated) { setNewItems() } } /// Sets the leftStackViewWidthConstant /// /// - Parameters: /// - newValue: New widthAnchor constant /// - animated: If the layout should be animated open func setLeftStackViewWidthConstant(to newValue: CGFloat, animated: Bool) { performLayout(animated) { self.leftStackViewWidthContant = newValue self.layoutStackViews([.left]) self.layoutIfNeeded() } } /// Sets the rightStackViewWidthConstant /// /// - Parameters: /// - newValue: New widthAnchor constant /// - animated: If the layout should be animated open func setRightStackViewWidthConstant(to newValue: CGFloat, animated: Bool) { performLayout(animated) { self.rightStackViewWidthContant = newValue self.layoutStackViews([.right]) self.layoutIfNeeded() } } // MARK: - Notifications/Hooks @objc open func orientationDidChange() { invalidateIntrinsicContentSize() } @objc open func textViewDidChange() { let trimmedText = inputTextView.text.trimmingCharacters(in: .whitespacesAndNewlines) sendButton.isEnabled = !trimmedText.isEmpty inputTextView.placeholderLabel.isHidden = !inputTextView.text.isEmpty items.forEach { $0.textViewDidChangeAction(with: inputTextView) } delegate?.messageInputBar(self, textViewTextDidChangeTo: trimmedText) invalidateIntrinsicContentSize() } @objc open func textViewDidBeginEditing() { self.items.forEach { $0.keyboardEditingBeginsAction() } } @objc open func textViewDidEndEditing() { self.items.forEach { $0.keyboardEditingEndsAction() } } // MARK: - User Actions open func didSelectSendButton() { delegate?.messageInputBar(self, didPressSendButtonWith: inputTextView.text) textViewDidChange() } }
mit
MoZhouqi/KMNavigationBarTransition
Example/SettingsViewController.swift
1
2086
// // SettingsViewController.swift // KMNavigationBarTransition // // Created by Zhouqi Mo on 1/1/16. // Copyright © 2017 Zhouqi Mo. All rights reserved. // import UIKit class SettingsViewController: UITableViewController { // MARK: Constants struct Constants { struct TableViewCell { static let Identifier = "Cell" } } // MARK: Properties var colorsData: (colorsArray: [NavigationBarBackgroundViewColor], selectedIndex: Int?)! var configurationBlock: ((_ color: NavigationBarBackgroundViewColor) -> Void)! var titleText = "" // MARK: View Life Cycle override func viewDidLoad() { title = titleText } } // MARK: - Table view data source extension SettingsViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return colorsData.colorsArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.TableViewCell.Identifier, for: indexPath) cell.textLabel?.text = colorsData.colorsArray[indexPath.row].rawValue cell.accessoryType = (indexPath.row == colorsData.selectedIndex) ? .checkmark : .none return cell } } // MARK: - Table view delegate extension SettingsViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let selectedIndex = colorsData.selectedIndex { tableView.cellForRow(at: IndexPath(row: selectedIndex, section: 0))?.accessoryType = .none } colorsData.selectedIndex = indexPath.row tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark tableView.deselectRow(at: indexPath, animated: true) configurationBlock?(colorsData.colorsArray[indexPath.row]) } }
mit
Ezfen/iOS.Apprentice.1-4
MyLocations/MyLocations/LocationsViewController.swift
1
7656
// // LocationsViewController.swift // MyLocations // // Created by ezfen on 16/8/22. // Copyright © 2016年 Ezfen Inc. All rights reserved. // import UIKit import CoreData import CoreLocation class LocationsViewController: UITableViewController { var managedObjectContext: NSManagedObjectContext! var locations = [Location]() lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest() let entity = NSEntityDescription.entityForName("Location", inManagedObjectContext: self.managedObjectContext) fetchRequest.entity = entity let sortDescription1 = NSSortDescriptor(key: "category", ascending: true) let sortDescription2 = NSSortDescriptor(key: "date", ascending: true) fetchRequest.sortDescriptors = [sortDescription1, sortDescription2] fetchRequest.fetchBatchSize = 20 let fetchResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "category", cacheName: "Locations") fetchResultsController.delegate = self return fetchResultsController }() override func viewDidLoad() { super.viewDidLoad() performFetch() navigationItem.rightBarButtonItem = editButtonItem() tableView.backgroundColor = UIColor.blackColor() tableView.separatorColor = UIColor(white: 1.0, alpha: 0.2) tableView.indicatorStyle = .White } func performFetch() { do { try fetchedResultsController.performFetch() } catch { fatalCoreDataError(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return fetchedResultsController.sections!.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let sectionInfo = fetchedResultsController.sections![section] return sectionInfo.name.uppercaseString } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath) as! LocationCell let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location cell.configureForLocation(location) return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location location.removePhotoFile() managedObjectContext.deleteObject(location) do { try managedObjectContext.save() } catch { fatalCoreDataError(error) } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "EditLocation" { let navigationController = segue.destinationViewController as! UINavigationController let controller = navigationController.topViewController as! LocationDetailsViewController controller.managedObjectContext = managedObjectContext if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) { let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location controller.locationToEdit = location } } } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let labelRect = CGRect(x: 15, y: tableView.sectionHeaderHeight - 14, width: 300, height: 14) let label = UILabel(frame: labelRect) label.font = UIFont.boldSystemFontOfSize(11) label.text = tableView.dataSource!.tableView!(tableView, titleForFooterInSection: section) label.textColor = UIColor(white: 1.0, alpha: 0.4) label.backgroundColor = UIColor.clearColor() let separatorRect = CGRect(x: 15, y: tableView.sectionHeaderHeight - 0.5, width: tableView.bounds.size.width - 15, height: 0.5) let separator = UIView(frame: separatorRect) separator.backgroundColor = tableView.separatorColor let viewRect = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.sectionHeaderHeight) let view = UIView(frame: viewRect) view.backgroundColor = UIColor(white: 0, alpha: 0.85) view.addSubview(label) view.addSubview(separator) return view } deinit { fetchedResultsController.delegate = nil } } extension LocationsViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { print("*** controllerWillChangeContent") tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: print("*** NSFetchResultsChangeInsert (object)") tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: print("*** NSFetchResultsChangeDelete (object)") tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: print("*** NSFetchResultsChangeUpdate (object)") if let cell = tableView.cellForRowAtIndexPath(indexPath!) as? LocationCell { let location = controller.objectAtIndexPath(indexPath!) as! Location cell.configureForLocation(location) } case .Move: print("*** NSFetchResultsChangeMove (object)") tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: print("*** NSFetchResultsChangeInsert (section)") tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: print("*** NSFetchResultsChangeDelete (section)") tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Update: print("*** NSFetchResultsChangeUpdate (section)") case .Move: print("*** NSFetchResultsChangeMove (section)") } } func controllerDidChangeContent(controller: NSFetchedResultsController) { print("*** controllerDidChangeContent") tableView.endUpdates() } }
mit
chenchangqing/learniosRAC
FRP-Swift/FRP-Swift/ViewModels/FRPPhotoViewModel.swift
1
2601
// // FRPPhotoViewModel.swift // FRP-Swift // // Created by green on 15/9/4. // Copyright (c) 2015年 green. All rights reserved. // import UIKit import ReactiveViewModel import ReactiveCocoa class FRPPhotoViewModel: ImageViewModel { let photoModelDataSourceProtocol = FRPPhotoModelDataSource.shareInstance() var searchFullsizedURLCommand :RACCommand! var errorMsg : String = "" var isLoading : Bool = false init(photoModel:FRPPhotoModel) { super.init(urlString: nil,model:photoModel,isNeedCompress:false) // 初始化command searchFullsizedURLCommand = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in self.setValue(true, forKey: "isLoading") if let identifier=(self.model as! FRPPhotoModel).identifier { return self.photoModelDataSourceProtocol.searchFullsizedURL(identifier) } else { return RACSignal.empty() } }) // 错误处理 searchFullsizedURLCommand.errors.subscribeNextAs { (error:NSError) -> () in self.setValue(false, forKey: "isLoading") self.setValue(error.localizedDescription, forKey: "errorMsg") } downloadImageCommand.errors.subscribeNextAs { (error:NSError) -> () in self.setValue(false, forKey: "isLoading") self.setValue(error.localizedDescription, forKey: "errorMsg") } // 更新大图URLString searchFullsizedURLCommand.executionSignals.switchToLatest() // .takeUntil(didBecomeInactiveSignal.skip(1)) .subscribeNext({ (any:AnyObject!) -> Void in // 更新图片 self.urlString = any as? String self.downloadImageCommand.execute(nil) }, completed: { () -> Void in println("searchFullsizedURLCommand completed") }) downloadImageCommand.executionSignals.switchToLatest() // .takeUntil(didBecomeInactiveSignal.skip(1)) .subscribeNext({ (any:AnyObject!) -> Void in self.setValue(false, forKey: "isLoading") }, completed: { () -> Void in self.setValue(false, forKey: "isLoading") }) // 激活后开始查询 didBecomeActiveSignal.subscribeNext { (any:AnyObject!) -> Void in searchFullsizedURLCommand.execute(nil) } } }
gpl-2.0
buddies2705/eddystone
tools/ios-eddystone-scanner-sample/EddystoneScannerSampleSwift/ViewController.swift
13
1297
// Copyright 2015 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. import UIKit class ViewController: UIViewController, BeaconScannerDelegate { var beaconScanner: BeaconScanner! override func viewDidLoad() { super.viewDidLoad() self.beaconScanner = BeaconScanner() self.beaconScanner!.delegate = self self.beaconScanner!.startScanning() } func didFindBeacon(beaconScanner: BeaconScanner, beaconInfo: BeaconInfo) { NSLog("FIND: %@", beaconInfo.description) } func didLoseBeacon(beaconScanner: BeaconScanner, beaconInfo: BeaconInfo) { NSLog("LOST: %@", beaconInfo.description) } func didUpdateBeacon(beaconScanner: BeaconScanner, beaconInfo: BeaconInfo) { NSLog("UPDATE: %@", beaconInfo.description) } }
apache-2.0
br1sk/brisk-ios
Brisk iOS/App/StatusDisplay.swift
1
1102
import UIKit import SVProgressHUD protocol StatusDisplay { func showLoading() func showSuccess(message: String, autoDismissAfter delay: TimeInterval) func showError(title: String?, message: String, dismissButtonTitle: String?, completion: (() -> Void)?) func hideLoading() } extension StatusDisplay where Self: UIViewController { func showLoading() { SVProgressHUD.show() } func showSuccess(message: String, autoDismissAfter delay: TimeInterval = 3.0) { SVProgressHUD.setMinimumDismissTimeInterval(delay) SVProgressHUD.showSuccess(withStatus: message) } func showError(title: String? = Localizable.Global.error.localized, message: String, dismissButtonTitle: String? = Localizable.Global.dismiss.localized, completion: (() -> Void)? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: dismissButtonTitle, style: .cancel, handler: nil)) present(alert, animated: true, completion: completion) } func hideLoading() { SVProgressHUD.dismiss() } }
mit
luckymore0520/leetcode
Multiply Strings.playground/Contents.swift
1
2895
//: Playground - noun: a place where people can play import UIKit //Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. // //Note: // //The length of both num1 and num2 is < 110. //Both num1 and num2 contains only digits 0-9. //Both num1 and num2 does not contain any leading zero. extension Character { var asciiValue: UInt32? { return String(self).unicodeScalars.filter{$0.isASCII}.first?.value } } class Solution { func multiply(_ num1: String, _ num2: String) -> String { if (num1 == "0" || num2 == "0") { return "0" } let num1 = getNumArray(num1) let num2 = getNumArray(num2) let short = num1.count > num2.count ? num2: num1 let long = short == num1 ? num2 : num1 var result:[Int] = [] var zeros:[Int] = [] for num in short.reversed() { var tmp = multiply(long, multiper: num) tmp += zeros print(tmp) result = add(result, tmp) zeros.append(0) } let resultString = result.reduce("") { (str, next) -> String in "\(str)\(next)" } return resultString } func add(_ num1:[Int],_ num2:[Int]) -> [Int] { var i = 0 var add = 0 var result:[Int] = [] let num1Count = num1.count let num2Count = num2.count while i < num1Count && i < num2Count { let eachResult = num1[num1Count - i - 1] + num2[num2Count - i - 1] + add add = eachResult / 10 result.insert(eachResult % 10, at: 0) i += 1 } while i < num1Count { let eachResult = num1[num1Count - i - 1] + add add = eachResult / 10 result.insert(eachResult % 10, at: 0) i += 1 } while i < num2Count { let eachResult = num2[num2Count - i - 1] + add add = eachResult / 10 result.insert(eachResult % 10, at: 0) i += 1 } if (add > 0) { result.insert(add, at: 0) } return result } func multiply(_ num:[Int], multiper:Int) -> [Int] { var result:[Int] = [] var add = 0 for eachNum in num.reversed() { let eachResult = eachNum * multiper + add result.insert(eachResult % 10, at: 0) add = eachResult / 10 } if (add > 0) { result.insert(add, at: 0) } return result } func getNumArray(_ num:String) -> [Int] { var array:[Int] = [] for char in num.characters { let ascii = Int(char.asciiValue!) array.append(ascii - 48) } return array } } let solution = Solution() solution.multiply("0", "456")
mit
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/SecurityResultCallbackImpl.swift
1
4638
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Interface for Managing the Security result callback Auto-generated implementation of ISecurityResultCallback specification. */ public class SecurityResultCallbackImpl : BaseCallbackImpl, ISecurityResultCallback { /** Constructor with callback id. @param id The id of the callback. */ public override init(id : Int64) { super.init(id: id) } /** No data received - error condition, not authorized . @param error Error values @since v2.0 */ public func onError(error : ISecurityResultCallbackError) { let param0 : String = "Adaptive.ISecurityResultCallbackError.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(error.toString())\\\"}\"))" var callbackId : Int64 = -1 if (getId() != nil) { callbackId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleSecurityResultCallbackError( \(callbackId), \(param0))") } /** Correct data received. @param keyValues key and values @since v2.0 */ public func onResult(keyValues : [SecureKeyPair]) { let param0Array : NSMutableString = NSMutableString() param0Array.appendString("[") for (index,obj) in keyValues.enumerate() { param0Array.appendString("Adaptive.SecureKeyPair.toObject(JSON.parse(\"\(JSONUtil.escapeString(SecureKeyPair.Serializer.toJSON(obj)))\"))") if index < keyValues.count-1 { param0Array.appendString(", ") } } param0Array.appendString("]") let param0 : String = param0Array as String var callbackId : Int64 = -1 if (getId() != nil) { callbackId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleSecurityResultCallbackResult( \(callbackId), \(param0))") } /** Data received with warning - ie Found entries with existing key and values have been overriden @param keyValues key and values @param warning Warning values @since v2.0 */ public func onWarning(keyValues : [SecureKeyPair], warning : ISecurityResultCallbackWarning) { let param0Array : NSMutableString = NSMutableString() param0Array.appendString("[") for (index,obj) in keyValues.enumerate() { param0Array.appendString("Adaptive.SecureKeyPair.toObject(JSON.parse(\"\(JSONUtil.escapeString(SecureKeyPair.Serializer.toJSON(obj)))\"))") if index < keyValues.count-1 { param0Array.appendString(", ") } } param0Array.appendString("]") let param0 : String = param0Array as String let param1 : String = "Adaptive.ISecurityResultCallbackWarning.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(warning.toString())\\\"}\"))" var callbackId : Int64 = -1 if (getId() != nil) { callbackId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleSecurityResultCallbackWarning( \(callbackId), \(param0), \(param1))") } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
huangboju/Moots
Examples/UITextField_Demo/TextField/ViewController.swift
1
4146
// // ViewController.swift // TextField // // Created by 伯驹 黄 on 2016/10/12. // Copyright © 2016年 伯驹 黄. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { fileprivate lazy var textField: UITextField = { let textField = UITextField(frame: CGRect(x: 100, y: 100, width: 100, height: 44)) textField.setValue(UIColor.yellow, forKeyPath: "_placeholderLabel.textColor") textField.text = "有光标无键盘" textField.placeholder = "13423143214" return textField }() fileprivate lazy var button: UIButton = { let button = UIButton(type: .custom) button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) return button }() private lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.frame, style: .grouped) tableView.dataSource = self return tableView }() fileprivate lazy var cursorView: UIView = { let cursorView = UIView(frame: CGRect(x: 15, y: 10, width: 2, height: 24)) cursorView.backgroundColor = UIColor.blue cursorView.layer.add(self.opacityForever_Animation(), forKey: nil) return cursorView }() var animation: CABasicAnimation { let animation = CABasicAnimation(keyPath: "opacity") animation.duration = 0.4 animation.autoreverses = true animation.repeatCount = HUGE animation.isRemovedOnCompletion = false animation.fromValue = NSNumber(value: 1.0) animation.toValue = NSNumber(value: 0.0) return animation } func opacityForever_Animation() -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "opacity")//必须写opacity才行。 animation.fromValue = NSNumber(value: 1.0) animation.toValue = NSNumber(value: 0.0) // animation.autoreverses = true animation.duration = 0.8 animation.repeatCount = MAXFLOAT animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.removed animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)///没有的话是均匀的动画。 return animation } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(calueChange), name: UITextField.textDidBeginEditingNotification, object: nil) view.addSubview(tableView) } @objc func buttonAction() { textField.inputView = nil textField.reloadInputViews() // 重载输入视图 } @objc func calueChange() { tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .none) } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .value1, reuseIdentifier: "cell") cell.textLabel?.text = indexPath.row.description if indexPath == IndexPath(row: 0, section: 0) { textField.inputView = UIView() textField.becomeFirstResponder() textField.removeFromSuperview() button.removeFromSuperview() cell.textLabel?.sizeToFit() textField.frame = CGRect(x: 15 + cell.textLabel!.frame.width, y: 0, width: view.frame.width - 30, height: 44) textField.backgroundColor = UIColor.red cell.contentView.addSubview(textField) button.frame = textField.frame cell.contentView.addSubview(button) } else if indexPath == IndexPath(row: 1, section: 0) { cursorView.removeFromSuperview() cell.textLabel?.text = "假光标" cell.contentView.addSubview(cursorView) } return cell } func numberOfSections(in tableView: UITableView) -> Int { return 2 } }
mit
charmaex/photo-table
PhotoTable/Pics.swift
1
1175
// // Pics.swift // PhotoTable // // Created by Jan Dammshäuser on 14.02.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import Foundation import UIKit class Pics: NSObject, NSCoding { private var _img: String! private var _title: String! private var _desc: String! var img: String { return _img } var title: String { return _title } var desc: String { return _desc } init(img: String, title: String, description: String) { _img = img _title = title _desc = description } override init() { } convenience required init?(coder aDecoder: NSCoder) { self.init() self._img = aDecoder.decodeObjectForKey("img") as? String self._title = aDecoder.decodeObjectForKey("title") as? String self._desc = aDecoder.decodeObjectForKey("desc") as? String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self._img, forKey: "img") aCoder.encodeObject(self._title, forKey: "title") aCoder.encodeObject(self._desc, forKey: "desc") } }
gpl-3.0
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/DiffableDatasource/TableDiffableVC.swift
1
4423
// // TableDiffable.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2022/6/19. // Copyright © 2022 伯驹 黄. All rights reserved. // import Foundation enum ContactSection: CaseIterable { case favourite case all } // MARK:- Item model struct Contact: Hashable { var id: Int? var firstName: String? var lastName: String? var dateOfBirth: Date? } class TableDiffableVC: UIViewController { private lazy var tableView: UITableView = { let tableView = UITableView() return tableView }() let reuseIdentifier = "TableViewCell" private var dataSource: UITableViewDiffableDataSource<ContactSection, Contact>? // MARK:- View life cycle methods override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalToSuperview() } customiseTableview() } // MARK:- Custom methods /**Customise tableview */ func customiseTableview() { title = NSLocalizedString("Contact list", comment: "Contact list screen title") tableView.register(UITableViewCell.self, forCellReuseIdentifier: "TableViewCell") createContactDataSource() updateTableViewModels() } /**Create mock data and update into tableview */ func updateTableViewModels() { let model1 = Contact(id: 1, firstName: "Contact 1", lastName: "Contact 1", dateOfBirth: nil) let model2 = Contact(id: 2, firstName: "Contact 2", lastName: "Contact 2", dateOfBirth: nil) let model3 = Contact(id: 3, firstName: "Contact 3", lastName: "Contact 3", dateOfBirth: nil) let model4 = Contact(id: 4, firstName: "Contact 4", lastName: "Contact 4", dateOfBirth: nil) let model5 = Contact(id: 5, firstName: "Contact 5", lastName: "Contact 5", dateOfBirth: nil) let models = [model1, model2, model3, model4, model5] update(models, animate: true) } /**Define diffable datasource for tableview with the help of cell provider and assign datasource to tablview */ func createContactDataSource() { dataSource = UITableViewDiffableDataSource(tableView: tableView, cellProvider: { tableView, indexPath, contact in let cell = tableView.dequeueReusableCell(withIdentifier: self.reuseIdentifier, for: indexPath) cell.textLabel?.text = contact.firstName cell.detailTextLabel?.text = contact.lastName return cell }) tableView.dataSource = dataSource } /**Create an empty new snapshot and add contact into that and apply updated snapshot into tableview's datasource */ func add(_ contact: Contact, animate: Bool = true) { guard let dataSource = self.dataSource else { return } var snapshot = NSDiffableDataSourceSnapshot<ContactSection, Contact>() snapshot.appendSections([ContactSection.all]) snapshot.appendItems([contact], toSection: ContactSection.all) dataSource.apply(snapshot, animatingDifferences: animate, completion: nil) } /**Update the contact list into current snapshot and apply updated snapshot into tableview's datasource */ func update(_ contactList: [Contact], animate: Bool = true) { guard let dataSource = self.dataSource else { return } var snapshot = dataSource.snapshot() snapshot.appendSections([ContactSection.all]) snapshot.appendItems(contactList, toSection: ContactSection.all) dataSource.apply(snapshot, animatingDifferences: animate, completion: nil) } /**Delete the contact from current snapshot and apply updated snapshot into tableview's datasource */ func remove(_ contact: Contact, animate: Bool = true) { guard let dataSource = self.dataSource else { return } var snapshot = dataSource.snapshot() snapshot.deleteItems([contact]) dataSource.apply(snapshot, animatingDifferences: animate, completion: nil) } } // MARK:- UITableViewDelegate methods extension TableDiffableVC: UITableViewDelegate { /**We can define delegate methods while using diffable datasource in tableview. For confirming that,I will just printed the sample text. */ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("Cell selected") } }
mit
Valbrand/tibei
Sources/Tibei/client/TibeiServiceBrowser.swift
1
1802
// // GameControllerClient.swift // connectivityTest // // Created by Daniel de Jesus Oliveira on 15/11/2016. // Copyright © 2016 Daniel de Jesus Oliveira. All rights reserved. // import UIKit class TibeiServiceBrowser: NSObject { let serviceBrowser: NetServiceBrowser = NetServiceBrowser() var inputStream: InputStream? var outputStream: OutputStream? var isBrowsing: Bool = false var delegate: TibeiServiceBrowserDelegate? override init() { super.init() self.serviceBrowser.includesPeerToPeer = true self.serviceBrowser.delegate = self } func startBrowsing(forServiceType serviceIdentifier: String) { self.serviceBrowser.searchForServices(ofType: "\(serviceIdentifier)._tcp", inDomain: "local") } func stopBrowsing() { self.serviceBrowser.stop() } } extension TibeiServiceBrowser: NetServiceBrowserDelegate { func netServiceBrowserWillSearch(_ browser: NetServiceBrowser) { self.isBrowsing = true } func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser) { self.isBrowsing = false } func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) { self.delegate?.gameControllerServiceBrowser(self, raisedErrors: errorDict) } func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) { self.delegate?.gameControllerServiceBrowser(self, foundService: service, moreComing: moreComing) } func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) { self.delegate?.gameControllerServiceBrowser(self, removedService: service, moreComing: moreComing) } }
mit
AvdLee/ALReactiveCocoaExtension
Pod/Classes/SignalProducer+Helper.swift
1
2691
// // SignalProducer+Helper.swift // Pods // // Created by Antoine van der Lee on 15/01/16. // // import Foundation import ReactiveSwift import enum Result.NoError public enum ALCastError : Error { case couldNotCastToType } private extension SignalProducerProtocol { func mapToType<U>() -> SignalProducer<U, ALCastError> { return flatMapError({ (_) -> SignalProducer<Value, ALCastError> in return SignalProducer(error: ALCastError.couldNotCastToType) }).flatMap(.concat) { object -> SignalProducer<U, ALCastError> in if let castedObject = object as? U { return SignalProducer(value: castedObject) } else { return SignalProducer(error: ALCastError.couldNotCastToType) } } } } public extension SignalProducerProtocol { @available(*, deprecated, renamed: "onStarting(_:)") open func onStarted(_ callback:@escaping () -> ()) -> SignalProducer<Value, Error> { return onStarting(callback) } open func onStarting(_ callback:@escaping () -> ()) -> SignalProducer<Value, Error> { return self.on(starting: callback) } open func onError(_ callback:@escaping (_ error:Error) -> () ) -> SignalProducer<Value, Error> { return self.on(failed: { (error) -> () in callback(error) }) } open func onNext(_ nextClosure:@escaping (Value) -> ()) -> SignalProducer<Value, Error> { return self.on(value: nextClosure) } open func onCompleted(_ nextClosure:@escaping () -> ()) -> SignalProducer<Value, Error> { return self.on(completed: nextClosure) } open func onNextAs<U>(_ nextClosure:@escaping (U) -> ()) -> SignalProducer<U, ALCastError> { return self.mapToType().on(value: nextClosure) } /// This function ignores any parsing errors open func startWithNextAs<U>(_ nextClosure:@escaping (U) -> ()) -> Disposable { return mapToType() .flatMapError { (object) -> SignalProducer<U, NoError> in return SignalProducer.empty }.startWithValues(nextClosure) } public func flatMapErrorToNSError() -> SignalProducer<Value, NSError> { return flatMapError({ SignalProducer(error: $0 as NSError) }) } } public extension SignalProducer { public func ignoreError() -> SignalProducer<Value, NoError> { return flatMapError { _ in SignalProducer<Value, NoError>.empty } } } public extension Signal { func toSignalProducer() -> SignalProducer<Value, Error> { return SignalProducer(self) } }
mit
mightydeveloper/swift
validation-test/compiler_crashers/26226-swift-constraints-constraintsystem-assignfixedtype.swift
9
281
// 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 struct B{let n=[]struct Q<T where g:a{struct c{{}func a{(a
apache-2.0
mmrmmlrr/ExamMaster
ExamMaster/Exam Creation Flow/Options Picker/ExamOptionsPickerViewController.swift
1
1712
// // ExamOptionsPickerViewController.swift // ExamMaster // // Created by aleksey on 28.02.16. // Copyright © 2016 aleksey chernish. All rights reserved. // import Foundation import ModelsTreeKit class ExamOptionsPickerViewController: UIViewController, ModelApplicable { @IBOutlet private weak var questionsCountLabel: UILabel! @IBOutlet private weak var timeLimitLabel: UILabel! @IBOutlet private weak var questionsCountSlider: UISlider! @IBOutlet private weak var switch1: UISwitch! @IBOutlet private weak var switch2: UISwitch! @IBOutlet private weak var timeLimitSlider: UISlider! @IBOutlet private weak var boundLabel: UILabel! weak var model: ExamOptionsPickerModel! override func viewDidLoad() { super.viewDidLoad() (switch1.onSignal && switch2.onSignal).map { $0 ? "ON" : "OFF" }.bindTo(keyPath: "text", of: boundLabel) model.questionsCountChangeSignal.subscribeNext { [weak self] in self?.questionsCountLabel.text = "Questions: \($0)" self?.questionsCountSlider.value = Float($0) }.ownedBy(self) model.timeLimitChangeSignal.subscribeNext { [weak self] in self?.timeLimitLabel.text = "Time limit: \(Int($0)) min" self?.timeLimitSlider.value = Float($0) }.ownedBy(self) questionsCountSlider.valueSignal.map { Int($0) }.subscribeNext { [weak self] in self?.model.applyQuestionsCount($0) }.ownedBy(self) timeLimitSlider.valueSignal.map { NSTimeInterval($0) }.subscribeNext { [weak self] in self?.model.applyTimeLimit($0) }.ownedBy(self) } @IBAction private func confirm(sender: AnyObject?) { model.confirmExamCreation() } }
mit
niunaruto/DeDaoAppSwift
testSwift/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift
33
1095
// // UIDatePicker+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/31/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) import RxSwift import UIKit extension Reactive where Base: UIDatePicker { /// Reactive wrapper for `date` property. public var date: ControlProperty<Date> { return value } /// Reactive wrapper for `date` property. public var value: ControlProperty<Date> { return base.rx.controlPropertyWithDefaultEvents( getter: { datePicker in datePicker.date }, setter: { datePicker, value in datePicker.date = value } ) } /// Reactive wrapper for `countDownDuration` property. public var countDownDuration: ControlProperty<TimeInterval> { return base.rx.controlPropertyWithDefaultEvents( getter: { datePicker in datePicker.countDownDuration }, setter: { datePicker, value in datePicker.countDownDuration = value } ) } } #endif
mit
u10int/Kinetic
Pod/Classes/Easing.swift
1
10208
// // Easing.swift // Kinetic // // Created by Nicholas Shipes on 12/18/15. // Copyright © 2015 Urban10 Interactive, LLC. All rights reserved. // import UIKit public protocol FloatingPointMath: FloatingPoint { var sine: Self { get } var cosine: Self { get } var powerOfTwo: Self { get } } extension Float: FloatingPointMath { public var sine: Float { return sin(self) } public var cosine: Float { return cos(self) } public var powerOfTwo: Float { return pow(2, self) } } extension Double: FloatingPointMath { public var sine: Double { return sin(self) } public var cosine: Double { return cos(self) } public var powerOfTwo: Double { return pow(2, self) } } public protocol TimingFunction { func solve(_ x: Double) -> Double } struct TimingFunctionSolver: TimingFunction { var solver: (Double) -> Double init(solver: @escaping (Double) -> Double) { self.solver = solver } func solve(_ x: Double) -> Double { return solver(x) } } public protocol EasingType { var timingFunction: TimingFunction { get } } public struct Linear: EasingType { public var timingFunction: TimingFunction { return TimingFunctionSolver(solver: { (x) -> Double in return x }) } } public struct Bezier: EasingType { private var bezier: UnitBezier public init(_ p1x: Double, _ p1y: Double, _ p2x: Double, _ p2y: Double) { self.bezier = UnitBezier(p1x, p1y, p2x, p2y) } public var timingFunction: TimingFunction { return TimingFunctionSolver(solver: { (x) -> Double in return self.bezier.solve(x) }) } } public enum Quadratic: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return x * x } case .easeOut: fn = { (x) -> Double in return -x * (x - 2) } case .easeInOut: fn = { (x) -> Double in if x < 1 / 2 { return 2 * x * x } else { return (-2 * x * x) + (4 * x) - 1 } } } return TimingFunctionSolver(solver: fn) } } public enum Cubic: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return x * x * x } case .easeOut: fn = { (x) -> Double in let p = x - 1 return p * p * p + 1 } case .easeInOut: fn = { (x) -> Double in if x < 1 / 2 { return 4 * x * x * x } else { let f = 2 * x - 2 return 1 / 2 * f * f * f + 1 } } } return TimingFunctionSolver(solver: fn) } } public enum Quartic: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return x * x * x * x } case .easeOut: fn = { (x) -> Double in let f = x - 1 return f * f * f * (1 - x) + 1 } case .easeInOut: fn = { (x) -> Double in if x < 1 / 2 { return 8 * x * x * x * x } else { let f = x - 1 return -8 * f * f * f * f + 1 } } } return TimingFunctionSolver(solver: fn) } } public enum Quintic: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return x * x * x * x * x } case .easeOut: fn = { (x) -> Double in let f = x - 1 return f * f * f * f * f + 1 } case .easeInOut: fn = { (x) -> Double in if x < 1 / 2 { return 16 * x * x * x * x * x } else { let f = 2 * x - 2 return 1 / 2 * f * f * f * f * f + 1 } } } return TimingFunctionSolver(solver: fn) } } public enum Sine: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return ((x - 1) * Double.pi / 2).sine + 1 } case .easeOut: fn = { (x) -> Double in return (x * Double.pi / 2).sine } case .easeInOut: fn = { (x) -> Double in return 1 / 2 * (1 - (x * Double.pi).cosine) } } return TimingFunctionSolver(solver: fn) } } public enum Circular: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return 1 - sqrt(1 - x * x) } case .easeOut: fn = { (x) -> Double in return sqrt((2 - x) * x) } case .easeInOut: fn = { (x) -> Double in if x < 1 / 2 { let h = 1 - sqrt(1 - 4 * x * x) return 1 / 2 * h } else { let f = -(2 * x - 3) * (2 * x - 1) let g = sqrt(f) return 1 / 2 * (g + 1) } } } return TimingFunctionSolver(solver: fn) } } public enum Exponential: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return x == 0 ? x : (10 * (x - 1)).powerOfTwo } case .easeOut: fn = { (x) -> Double in return x == 1 ? x : 1 - (-10 * x).powerOfTwo } case .easeInOut: fn = { (x) -> Double in if x == 0 || x == 1 { return x } if x < 1 / 2 { return 1 / 2 * (20 * x - 10).powerOfTwo } else { let h = (-20 * x + 10).powerOfTwo return -1 / 2 * h + 1 } } } return TimingFunctionSolver(solver: fn) } } public enum Elastic: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return (13 * Double.pi / 2 * x).sine * (10 * (x - 1)).powerOfTwo } case .easeOut: fn = { (x) -> Double in let f = (-13 * Double.pi / 2 * (x + 1)).sine let g = (-10 * x).powerOfTwo return f * g + 1 } case .easeInOut: fn = { (x) -> Double in if x < 1 / 2 { let f = ((13 * Double.pi / 2) * 2 * x).sine return 1 / 2 * f * (10 * ((2 * x) - 1)).powerOfTwo } else { let h = (2 * x - 1) + 1 let f = (-13 * Double.pi / 2 * h).sine let g = (-10 * (2 * x - 1)).powerOfTwo return 1 / 2 * (f * g + 2) } } } return TimingFunctionSolver(solver: fn) } } public enum Back: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = { (x) -> Double in return x * x * x - x * (x * Double.pi).sine } case .easeOut: fn = { (x) -> Double in let f = 1 - x return 1 - ( f * f * f - f * (f * Double.pi).sine) } case .easeInOut: fn = { (x) -> Double in if x < 1 / 2 { let f = 2 * x return 1 / 2 * (f * f * f - f * (f * Double.pi).sine) } else { let f = 1 - (2 * x - 1) let g = (f * Double.pi).sine let h = f * f * f - f * g return 1 / 2 * (1 - h ) + 1 / 2 } } } return TimingFunctionSolver(solver: fn) } } public enum Bounce: EasingType { case easeIn case easeOut case easeInOut public var timingFunction: TimingFunction { var fn: (Double) -> Double switch self { case .easeIn: fn = easeIn case .easeOut: fn = easeOut case .easeInOut: fn = { (x) -> Double in if x < 1 / 2 { return 1 / 2 * self.easeIn(2 * x) } else { let f = self.easeOut(x * 2 - 1) + 1 return 1 / 2 * f } } } return TimingFunctionSolver(solver: fn) } private func easeIn<T: FloatingPoint>(_ x: T) -> T { return 1 - easeOut(1 - x) } private func easeOut<T: FloatingPoint>(_ x: T) -> T { if x < 4 / 11 { return (121 * x * x) / 16 } else if x < 8 / 11 { let f = (363 / 40) * x * x let g = (99 / 10) * x return f - g + (17 / 5) } else if x < 9 / 10 { let f = (4356 / 361) * x * x let g = (35442 / 1805) * x return f - g + 16061 / 1805 } else { let f = (54 / 5) * x * x return f - ((513 / 25) * x) + 268 / 25 } } } // MARK: - Unit Bezier // // This implementation is based on WebCore Bezier implmentation // http://opensource.apple.com/source/WebCore/WebCore-955.66/platform/graphics/UnitBezier.h private let epsilon: Double = 1.0 / 1000 private struct UnitBezier { public var p1x: Double public var p1y: Double public var p2x: Double public var p2y: Double init(_ p1x: Double, _ p1y: Double, _ p2x: Double, _ p2y: Double) { self.p1x = p1x self.p1y = p1y self.p2x = p2x self.p2y = p2y } func solve(_ x: Double) -> Double { return UnitBezierSover(bezier: self).solve(x) } } private struct UnitBezierSover { var ax: Double var ay: Double var bx: Double var by: Double var cx: Double var cy: Double init(bezier: UnitBezier) { self.init(p1x: bezier.p1x, p1y: bezier.p1y, p2x: bezier.p2x, p2y: bezier.p2y) } init(p1x: Double, p1y: Double, p2x: Double, p2y: Double) { cx = 3 * p1x bx = 3 * (p2x - p1x) - cx ax = 1 - cx - bx cy = 3 * p1y by = 3 * (p2y - p1y) - cy ay = 1.0 - cy - by } func sampleCurveX(_ t: Double) -> Double { return ((ax * t + bx) * t + cx) * t } func sampleCurveY(_ t: Double) -> Double { return ((ay * t + by) * t + cy) * t } func sampleCurveDerivativeX(_ t: Double) -> Double { return (3.0 * ax * t + 2.0 * bx) * t + cx } func solveCurveX(_ x: Double) -> Double { var t0, t1, t2, x2, d2: Double // first try a few iterations of Newton's method -- normally very fast t2 = x for _ in 0..<8 { x2 = sampleCurveX(t2) - x if fabs(x2) < epsilon { return t2 } d2 = sampleCurveDerivativeX(t2) if fabs(x2) < 1e-6 { break } t2 = t2 - x2 / d2 } // fall back to the bisection method for reliability t0 = 0 t1 = 1 t2 = x if t2 < t0 { return t0 } if t2 > t1 { return t1 } while t0 < t1 { x2 = sampleCurveX(t2) if fabs(x2 - x) < epsilon { return t2 } if x > x2 { t0 = t2 } else { t1 = t2 } t2 = (t1 - t0) * 0.5 + t0 } // failure return t2 } func solve(_ x: Double) -> Double { return sampleCurveY(solveCurveX(x)) } }
mit
wistia/WistiaKit
Example/Tests/WistiaAPIUploadTests.swift
1
1692
// // WistiaAPIUploadTests.swift // WistiaKit // // Created by Daniel Spinosa on 11/18/16. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest import WistiaKitCore import WistiaKit class WistiaAPIUploadTests: XCTestCase { let unlimitedAPI = WistiaAPI(apiToken:"1511ac67c0213610d9370ef12349c6ac828a18f6405154207b44f3a7e3a29e93") let limitedAPI = WistiaAPI(apiToken: "dcb0e1179609d1da5cf1698797fdb205ff783d428414bab13ec042102e53e159") let fileURL = Bundle(for: WistiaAPIUploadTests.self).url(forResource: "clipXS", withExtension: "m4v")! func testSuccessfulUpload() { let expectation = self.expectation(description: "file uploaded") unlimitedAPI.upload(fileURL: fileURL, intoProject: nil, name: nil, description: nil, contactID: nil, progressHandler: nil) { media, error in XCTAssert(error == nil && media != nil) self.unlimitedAPI.deleteMedia(forHash: media!.hashedID) { media, error in } expectation.fulfill() } waitForExpectations(timeout: 20, handler: nil) } func testVideoLimitUpload() { let expectation = self.expectation(description: "file upload fails with VideoLimit") limitedAPI.upload(fileURL: fileURL, intoProject: nil, name: nil, description: nil, contactID: nil, progressHandler: nil) { media, error in XCTAssert(media == nil && error != nil) switch error! { case .VideoLimit(_): expectation.fulfill() default: XCTAssert(false, "Expected VideoLimit Error") } } waitForExpectations(timeout: 3, handler: nil) } }
mit
optimizely/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/Flush.swift
1
6864
// // Flush.swift // Mixpanel // // Created by Yarden Eitan on 6/3/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation protocol FlushDelegate { func flush(completion: (() -> Void)?) func updateQueue(_ queue: Queue, type: FlushType) #if os(iOS) func updateNetworkActivityIndicator(_ on: Bool) #endif // os(iOS) } class Flush: AppLifecycle { var timer: Timer? var delegate: FlushDelegate? var useIPAddressForGeoLocation = true var flushRequest: FlushRequest var flushOnBackground = true var _flushInterval = 0.0 private let flushIntervalReadWriteLock: DispatchQueue var flushInterval: Double { set { flushIntervalReadWriteLock.sync(flags: .barrier, execute: { _flushInterval = newValue }) delegate?.flush(completion: nil) startFlushTimer() } get { flushIntervalReadWriteLock.sync { return _flushInterval } } } required init(basePathIdentifier: String) { self.flushRequest = FlushRequest(basePathIdentifier: basePathIdentifier) flushIntervalReadWriteLock = DispatchQueue(label: "com.mixpanel.flush_interval.lock", qos: .utility, attributes: .concurrent) } func flushEventsQueue(_ eventsQueue: Queue, automaticEventsEnabled: Bool?) -> Queue? { let (automaticEventsQueue, eventsQueue) = orderAutomaticEvents(queue: eventsQueue, automaticEventsEnabled: automaticEventsEnabled) var mutableEventsQueue = flushQueue(type: .events, queue: eventsQueue) if let automaticEventsQueue = automaticEventsQueue { mutableEventsQueue?.append(contentsOf: automaticEventsQueue) } return mutableEventsQueue } func orderAutomaticEvents(queue: Queue, automaticEventsEnabled: Bool?) -> (automaticEventQueue: Queue?, eventsQueue: Queue) { var eventsQueue = queue if automaticEventsEnabled == nil || !automaticEventsEnabled! { var discardedItems = Queue() for (i, ev) in eventsQueue.enumerated().reversed() { if let eventName = ev["event"] as? String, eventName.hasPrefix("$ae_") { discardedItems.append(ev) eventsQueue.remove(at: i) } } if automaticEventsEnabled == nil { return (discardedItems, eventsQueue) } } return (nil, eventsQueue) } func flushPeopleQueue(_ peopleQueue: Queue) -> Queue? { return flushQueue(type: .people, queue: peopleQueue) } func flushGroupsQueue(_ groupsQueue: Queue) -> Queue? { return flushQueue(type: .groups, queue: groupsQueue) } func flushQueue(type: FlushType, queue: Queue) -> Queue? { if flushRequest.requestNotAllowed() { return queue } return flushQueueInBatches(queue, type: type) } func startFlushTimer() { stopFlushTimer() if flushInterval > 0 { DispatchQueue.main.async() { [weak self] in guard let self = self else { return } self.timer = Timer.scheduledTimer(timeInterval: self.flushInterval, target: self, selector: #selector(self.flushSelector), userInfo: nil, repeats: true) } } } @objc func flushSelector() { delegate?.flush(completion: nil) } func stopFlushTimer() { if let timer = timer { DispatchQueue.main.async() { [weak self, timer] in timer.invalidate() self?.timer = nil } } } func flushQueueInBatches(_ queue: Queue, type: FlushType) -> Queue { var mutableQueue = queue while !mutableQueue.isEmpty { var shouldContinue = false let batchSize = min(mutableQueue.count, APIConstants.batchSize) let range = 0..<batchSize let batch = Array(mutableQueue[range]) // Log data payload sent Logger.debug(message: "Sending batch of data") Logger.debug(message: batch as Any) let requestData = JSONHandler.encodeAPIData(batch) if let requestData = requestData { let semaphore = DispatchSemaphore(value: 0) #if os(iOS) if !MixpanelInstance.isiOSAppExtension() { delegate?.updateNetworkActivityIndicator(true) } #endif // os(iOS) var shadowQueue = mutableQueue flushRequest.sendRequest(requestData, type: type, useIP: useIPAddressForGeoLocation, completion: { [weak self, semaphore, range] success in #if os(iOS) if !MixpanelInstance.isiOSAppExtension() { guard let self = self else { return } self.delegate?.updateNetworkActivityIndicator(false) } #endif // os(iOS) if success { if let lastIndex = range.last, shadowQueue.count - 1 > lastIndex { shadowQueue.removeSubrange(range) } else { shadowQueue.removeAll() } self?.delegate?.updateQueue(shadowQueue, type: type) } shouldContinue = success semaphore.signal() }) _ = semaphore.wait(timeout: DispatchTime.distantFuture) mutableQueue = shadowQueue } if !shouldContinue { break } } return mutableQueue } // MARK: - Lifecycle func applicationDidBecomeActive() { startFlushTimer() } func applicationWillResignActive() { stopFlushTimer() } }
apache-2.0
hdoria/HDNTextField
Example/HDNTextField/ViewController.swift
1
510
// // ViewController.swift // HDNTextField // // Created by Hugo Doria on 07/08/2016. // Copyright (c) 2016 Hugo Doria. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
sstanic/Shopfred
Shopfred/Shopfred/Model/ShoppingSpace+CoreDataClass.swift
1
684
// // ShoppingSpace+CoreDataClass.swift // Shopfred // // Created by Sascha Stanic on 6/24/17. // Copyright © 2017 Sascha Stanic. All rights reserved. // import Foundation import CoreData @objc(ShoppingSpace) public class ShoppingSpace: NSManagedObject { convenience init(name: String, context: NSManagedObjectContext) { if let ent = NSEntityDescription.entity(forEntityName: "ShoppingSpace", in: context) { self.init(entity: ent, insertInto: context) self.id = "sf-" + UUID().uuidString.lowercased() self.name = name } else { fatalError("Unable to find Entity name!") } } }
mit
brentdax/swift
test/decl/var/behaviors.swift
10
8683
// RUN: %target-typecheck-verify-swift -enable-experimental-property-behaviors -module-name Main // REQUIRES: property_behavior_value_substitution protocol behavior { associatedtype Value } extension behavior { var value: Value { fatalError("") } } struct NotABehavior {} var test1: Int __behavior behavior var test2: String __behavior Main.behavior // expected-error@+1{{property behavior name must refer to a protocol}} var test5: String __behavior NotABehavior struct Concrete { var test: String __behavior behavior static var test: String __behavior behavior } protocol Proto { } extension Proto { var test: String __behavior behavior static var test: String __behavior behavior } struct Generic<T> { var test: String __behavior behavior static var test: String __behavior behavior } protocol SelfRequirement {} protocol ValueRequirement {} protocol constraints: SelfRequirement { associatedtype Value: ValueRequirement } extension constraints { var value: Value { fatalError("") } } struct VR: ValueRequirement {} struct GVR<T>: ValueRequirement {} struct NVR {} // expected-error@+3{{property behavior 'constraints' can only be used on instance properties because it has 'Self' requirements}} // expected-error@+2{{type 'NVR' does not conform to protocol 'ValueRequirement'}} // expected-note@+1{{behavior 'constraints' requires property type to conform to protocol 'ValueRequirement'}} var a: NVR __behavior constraints // expected-error@+1{{property behavior 'constraints' can only be used on instance properties because it has 'Self' requirements}} var b: VR __behavior constraints struct SR: SelfRequirement { // expected-error@+2{{type 'NVR' does not conform to protocol 'ValueRequirement'}} // expected-note@+1{{behavior 'constraints' requires property type to conform to protocol 'ValueRequirement'}} var a: NVR __behavior constraints var b: VR __behavior constraints // expected-error@+3{{property behavior 'constraints' can only be used on instance properties because it has 'Self' requirements}} // expected-error@+2{{type 'NVR' does not conform to protocol 'ValueRequirement'}} // expected-note@+1{{behavior 'constraints' requires property type to conform to protocol 'ValueRequirement'}} static var a: NVR __behavior constraints // expected-error@+1{{property behavior 'constraints' can only be used on instance properties because it has 'Self' requirements}} static var b: VR __behavior constraints } // expected-error@+1 * {{type 'NSR' does not conform to protocol 'SelfRequirement'}} struct NSR { // expected-note@+3{{conformance to 'SelfRequirement' required to contain an instance property with behavior 'constraints'}} // expected-error@+2{{type 'NVR' does not conform to protocol 'ValueRequirement'}} // expected-note@+1{{behavior 'constraints' requires property type to conform to protocol 'ValueRequirement'}} var a: NVR __behavior constraints // expected-note@+1{{conformance to 'SelfRequirement' required to contain an instance property with behavior 'constraints'}} var b: VR __behavior constraints } struct GSR<T>: SelfRequirement { var a: VR __behavior constraints var b: GVR<T> __behavior constraints } extension GSR where T: ValueRequirement { var c: T __behavior constraints } protocol nonBehaviorReqt { associatedtype Value func notBehaviorRelated() // expected-note{{declared here}} } extension nonBehaviorReqt { var value: Value { fatalError("") } } // expected-error@+1{{behavior protocol 'nonBehaviorReqt' has non-behavior requirement 'notBehaviorRelated'}} var x: Int __behavior nonBehaviorReqt protocol hasStorage { associatedtype Value var storage: Value? { get set } } extension hasStorage { static func initStorage() -> Value? { return nil } // Overloads that should be disregarded static func initStorage() -> Value { fatalError("") } static func initStorage(_: String) -> Value? { fatalError("") } var value: Value { fatalError("") } } var tuple = (0,0) var storage1: Int __behavior hasStorage // expected-error {{not supported}} struct Foo<T> { static var staticStorage1: T __behavior hasStorage // expected-error{{static stored properties not supported in generic types}} var storage2: T __behavior hasStorage // FIXME: Hack because we can't find the synthesized associated type witness // during witness matching. typealias Value = T func foo<U>(_: U) { var storage1: T __behavior hasStorage // expected-error {{not supported}} var storage2: U __behavior hasStorage // expected-error {{not supported}} _ = storage1 _ = storage2 } } struct Foo2<T> { var storage3: Int = 0 // expected-error {{initializer expression provided, but property behavior 'hasStorage' does not use it}} __behavior hasStorage var (storage4, storage5) = tuple // expected-error* {{initializer expression provided, but property behavior 'hasStorage' does not use it}} __behavior hasStorage // FIXME: Hack because we can't find the synthesized associated type witness // during witness matching. typealias Value = Int } extension Foo { static var y: T __behavior hasStorage // expected-error{{static stored properties not supported in generic types}} var y: T __behavior hasStorage // expected-error {{extensions must not contain stored properties}} } protocol storageWithoutInit { associatedtype Value var storage: Value { get set } } extension storageWithoutInit { var value: Value { fatalError("") } func initStorage() -> Int { fatalError("signature is wrong") } // expected-note * {{found this candidate}} } struct Bar { var x: Int __behavior storageWithoutInit // expected-error {{property behavior protocol has a 'storage' requirement but does not have a static 'initStorage' method with the expected type '() -> Self.Value'}} } class Bas { var x: Int __behavior storageWithoutInit // expected-error {{property behavior protocol has a 'storage' requirement but does not have a static 'initStorage' method with the expected type '() -> Self.Value'}} } protocol valueTypeMismatch { associatedtype Value } extension valueTypeMismatch { var value: Value? { fatalError("") } // expected-note {{'value' property declared here}} } var x: Int __behavior valueTypeMismatch // expected-error {{property behavior 'valueTypeMismatch' provides 'value' property implementation with type 'Int?' that doesn't match type 'x' of declared property 'Int'}} protocol getset { associatedtype Value } extension getset { var value: Value { get { } set { } } } var testGetset: Int __behavior getset class C<T> { var testGetset: T __behavior getset static var testGetset: T __behavior getset } struct S<T> { var testGetset: T __behavior getset static var testGetset: T __behavior getset } protocol parameterized { associatedtype Value func parameter() -> Value } extension parameterized { var value: Value { get { } set { } } } struct TestParameters { var hasParameter: Int __behavior parameterized { 0 } var (sharedParameter1, sharedParameter2): (Int,Int) __behavior parameterized { 0 } // expected-error {{multiple variables is not supported}} expected-error{{sharedParameter2}} var missingParameter: Int __behavior parameterized // expected-error{{requires a parameter}} var invalidParameter: Int __behavior parameterized { 5.5 } // expected-error{{cannot convert return expression of type 'Double' to return type 'Int'}} } // TODO var globalParameter: Int __behavior parameterized { 0 } // expected-error{{not supported}} protocol noParameter { associatedtype Value } extension noParameter { var value: Value { get { } set { } } } var hasNoParameter: Int __behavior noParameter var hasUnwantedParameter: Int __behavior noParameter { 0 } // expected-error{{parameter expression provided, but property behavior 'noParameter' does not use it}} protocol storageWithInitialValue { associatedtype Value var storage: Value? { get set } } extension storageWithInitialValue { var value: Value { get { } } static func initStorage(_ x: Value) -> Value? { return nil } } struct TestStorageWithInitialValue { var x: Int __behavior storageWithInitialValue // Would require DI var y = 0 __behavior storageWithInitialValue var z: Int = 5.5 __behavior storageWithInitialValue // expected-error {{cannot convert value of type 'Double' to type 'Int' in coercion}} var (a, b) = tuple __behavior storageWithInitialValue // expected-error* {{do not support destructuring}} // FIXME: Hack because we can't find the synthesized associated type witness // during witness matching. typealias Value = Int }
apache-2.0
onebytegone/actionable
ActionableTests/ActionableTests.swift
1
1134
// // ActionableTests.swift // ActionableTests // // Created by Ethan Smith on 5/18/15. // Copyright (c) 2015 Ethan Smith. All rights reserved. // import Foundation import XCTest class ActionableTests: XCTestCase { func testLifecycle() { var calledCount = 0; let actionable = Actionable() let wrapper = actionable.on("myEvent", handler: { calledCount += 1 }) actionable.trigger("otherEvent") XCTAssertEqual(0, calledCount) actionable.trigger("myEvent") XCTAssertEqual(1, calledCount) actionable.trigger("myEvent") XCTAssertEqual(2, calledCount) actionable.off("myEvent", wrapper: wrapper) actionable.trigger("myEvent") XCTAssertEqual(2, calledCount) } func testLifecycleWithArgs() { var calledCount = 0; let actionable = Actionable() let wrapper = actionable.on("add") { (value: Any?) -> () in calledCount += value as! Int } actionable.trigger("add", data: 1) XCTAssertEqual(1, calledCount) actionable.trigger("add", data: 10) XCTAssertEqual(11, calledCount) } }
mit
tardieu/swift
validation-test/compiler_crashers_fixed/27693-swift-constraints-constraintsystem-opengeneric.swift
65
492
// 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 import b : } struct B<T where h:e:A {class A{ class B{ struct Q{" { func b<T {let a = b init(
apache-2.0
apple/swift-package-manager
Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyPlugin/Plugins/MyPlugin/plugin.swift
2
623
import PackagePlugin import Foundation @main struct MyPlugin: CommandPlugin { func performCommand(context: PluginContext, arguments: [String]) async throws { for name in ["RemoteTool", "LocalTool", "ImpliedLocalTool"] { let tool = try context.tool(named: name) print("tool path is \(tool.path)") do { let process = Process() process.executableURL = URL(fileURLWithPath: tool.path.string) try process.run() } catch { print("error: \(error)") } } } }
apache-2.0
NordicSemiconductor/IOS-Pods-DFU-Library
iOSDFULibrary/Classes/Utilities/Streams/DFUStreamBin.swift
1
3353
/* * Copyright (c) 2019, Nordic Semiconductor * 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 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 Foundation internal class DFUStreamBin : DFUStream { private(set) var currentPart = 1 private(set) var parts = 1 private(set) var currentPartType: UInt8 = 0 /// Firmware binaries. private var binaries: Data /// The init packet content. private var initPacketBinaries: Data? private var firmwareSize: UInt32 = 0 var size: DFUFirmwareSize { switch currentPartType { case FIRMWARE_TYPE_SOFTDEVICE: return DFUFirmwareSize(softdevice: firmwareSize, bootloader: 0, application: 0) case FIRMWARE_TYPE_BOOTLOADER: return DFUFirmwareSize(softdevice: 0, bootloader: firmwareSize, application: 0) // case FIRMWARE_TYPE_APPLICATION: default: return DFUFirmwareSize(softdevice: 0, bootloader: 0, application: firmwareSize) } } var currentPartSize: DFUFirmwareSize { return size } init(urlToBinFile: URL, urlToDatFile: URL?, type: DFUFirmwareType) { binaries = try! Data(contentsOf: urlToBinFile) firmwareSize = UInt32(binaries.count) if let dat = urlToDatFile { initPacketBinaries = try? Data(contentsOf: dat) } currentPartType = type.rawValue } init(binFile: Data, datFile: Data?, type: DFUFirmwareType) { binaries = binFile firmwareSize = UInt32(binaries.count) initPacketBinaries = datFile currentPartType = type.rawValue } var data: Data { return binaries } var initPacket: Data? { return initPacketBinaries } func hasNextPart() -> Bool { return false } func switchToNextPart() { // Do nothing. } }
bsd-3-clause
ingresse/ios-sdk
IngresseSDK/Services/UserTickets/Responses/UserWalletTicket.swift
1
1738
// // Copyright © 2020 Ingresse. All rights reserved. // public struct UserWalletTicket: Decodable { public let id: Int public let guestTypeId: Int? public let ticketTypeId: Int? public let itemType: String? public let price: Double? public let tax: Double? public let sessions: Self.Sessions? public let title: String? public let type: String? public let eventId: Int? public let eventTitle: String? public let eventVenue: Self.Venue? public let transactionId: String? public let desc: String? public let sequence: String? public let code: String? public let checked: Bool? public let receivedFrom: Self.Transfer? public let transferredTo: Self.Transfer? public let currentHolder: Self.Transfer? public let live: Self.Live? public let transferable: Bool? public let isResalable: Bool? public let resalableUrl: String? public let isTransferable: Bool? public let isTransferCancelable: Bool? public let isReturnable: Bool? enum CodingKeys: String, CodingKey { case id case guestTypeId case ticketTypeId case itemType case price case tax case sessions case title case type case eventId case eventTitle case eventVenue case transactionId case desc = "description" case sequence case code case checked case receivedFrom case transferredTo = "transferedTo" case currentHolder case live case transferable case isResalable case resalableUrl case isTransferable case isTransferCancelable case isReturnable } }
mit
fitpay/fitpay-ios-sdk
FitpaySDK/PaymentDevice/EventListeners/FitpayBlockEventListener.swift
1
762
import Foundation open class FitpayBlockEventListener { public typealias BlockCompletion = (_ event: FitpayEvent) -> Void var blockCompletion: BlockCompletion var completionQueue: DispatchQueue private var isValid = true public init(completion: @escaping BlockCompletion, queue: DispatchQueue = DispatchQueue.main) { self.blockCompletion = completion self.completionQueue = queue } } extension FitpayBlockEventListener: FitpayEventListener { public func dispatchEvent(_ event: FitpayEvent) { guard isValid else { return } completionQueue.async { self.blockCompletion(event) } } public func invalidate() { isValid = false } }
mit
cubixlabs/GIST-Framework
GISTFramework/Classes/GISTCore/GISTUtility.swift
1
12524
// // GISTUtility.swift // GISTFramework // // Created by Shoaib Abdul on 07/09/2016. // Copyright © 2016 Social Cubix. All rights reserved. // import UIKit import PhoneNumberKit /// Class for Utility methods. public class GISTUtility: NSObject { //MARK: - Properties @nonobjc static var bundle:Bundle? { let frameworkBundle = Bundle(for: GISTUtility.self); if let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("GISTFrameworkBundle.bundle") { return Bundle(url: bundleURL); } else { return nil; } } //P.E. @nonobjc static var screenHeight:CGFloat { if #available(iOS 11.0, *) { let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first let topInset:CGFloat = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0 guard topInset >= 44 else { return UIScreen.main.bounds.height } let bottomInset:CGFloat = 34;//rootView.safeAreaInsets.bottom return UIScreen.main.bounds.height - topInset - bottomInset; } else { return UIScreen.main.bounds.height; } } //F.E. @nonobjc public static let deviceRatio:CGFloat = screenHeight / 736.0; @nonobjc public static let deviceRatioWN:CGFloat = (UIScreen.main.bounds.height - 64.0) / (736.0 - 64.0); // Ratio with Navigation /// Bool flag for device type. @nonobjc public static let isIPad:Bool = UIDevice.current.userInterfaceIdiom == .pad; ///Bool flag for if the device has nodge @nonobjc public static var hasNotch:Bool { get { if #available(iOS 11.0, *) { // with notch: 44.0 on iPhone X, XS, XS Max, XR. // without notch: 24.0 on iPad Pro 12.9" 3rd generation, 20.0 on iPhone 8 on iOS 12+. let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first return window?.safeAreaInsets.bottom ?? 0 > 0 } return false } } /// Flag to check user interfce layout direction @nonobjc public static var isRTL:Bool { get { return GIST_CONFIG.isRTL; } } //P.E. //MARK: - Methods /// Function to delay a particular action. /// /// - Parameters: /// - delay: Delay Time in double. /// - closure: Closure to call after delay. public class func delay(_ delay:Double, closure:@escaping () -> Void) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } //F.E. /// Native Phone Call /// /// - Parameter number: a valid phone number public class func nativePhoneCall(at number:String) { let phoneNumber: String = "tel://\(number.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))"; if let phoneURL:URL = URL(string: phoneNumber), UIApplication.shared.canOpenURL(phoneURL) { if #available(iOS 10.0, *) { UIApplication.shared.open(phoneURL, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(phoneURL); } } } //F.E. /// Calculate Age /// /// - Parameter birthday: Date of birth /// - Returns: age public class func calculateAge (_ dateOfBirth: Date) -> Int { let calendar : Calendar = Calendar.current let unitFlags : NSCalendar.Unit = [NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day] let dateComponentNow : DateComponents = (calendar as NSCalendar).components(unitFlags, from: Date()) let dateComponentBirth : DateComponents = (calendar as NSCalendar).components(unitFlags, from: dateOfBirth) if ((dateComponentNow.month! < dateComponentBirth.month!) || ((dateComponentNow.month! == dateComponentBirth.month!) && (dateComponentNow.day! < dateComponentBirth.day!)) ) { return dateComponentNow.year! - dateComponentBirth.year! - 1 } else { return dateComponentNow.year! - dateComponentBirth.year! } }//F.E. /// Converts value to (value * device ratio) considering navigtion bar fixed height. /// /// - Parameter value: Value /// - Returns: Device specific ratio * value public class func convertToRatioSizedForNavi(_ value:CGFloat) ->CGFloat { return self.convertToRatio(value, sizedForIPad: false, sizedForNavi:true); // Explicit true for Sized For Navi } //F.E. /// Converts value to (value * device ratio). /// /// - Parameters: /// - value: Value /// - sizedForIPad: Bool flag for sizedForIPad /// - sizedForNavi: Bool flag for sizedForNavi /// - Returns: Device specific ratio * value public class func convertToRatio(_ value:CGFloat, sizedForIPad:Bool = false, sizedForNavi:Bool = false) -> CGFloat { /* iPhone6 Hight:667 ===== 0.90625 iPhone5 Hight:568 ====== 0.77173913043478 iPhone4S Hight:480 iPAd Hight:1024 ===== 1.39130434782609 (height/736.0) */ if (GISTConfig.shared.convertToRatio == false || (GISTUtility.isIPad && !sizedForIPad)) { return value; } if (sizedForNavi) { return value * GISTUtility.deviceRatioWN; // With Navigation } return value * GISTUtility.deviceRatio; } //F.E. /// Converts CGPoint to (point * device ratio). /// /// - Parameters: /// - value: CGPoint value /// - sizedForIPad: Bool flag for sizedForIPad /// - Returns: Device specific ratio * point public class func convertPointToRatio(_ value:CGPoint, sizedForIPad:Bool = false) ->CGPoint { return CGPoint(x:self.convertToRatio(value.x, sizedForIPad: sizedForIPad), y:self.convertToRatio(value.y, sizedForIPad: sizedForIPad)); } //F.E. /// Converts CGSize to (size * device ratio). /// /// - Parameters: /// - value: CGSize value /// - sizedForIPad: Bool flag for sizedForIPad /// - Returns: Device specific ratio * size public class func convertSizeToRatio(_ value:CGSize, sizedForIPad:Bool = false) ->CGSize { return CGSize(width:self.convertToRatio(value.width, sizedForIPad: sizedForIPad), height:self.convertToRatio(value.height, sizedForIPad: sizedForIPad)); } //F.E. /// Validate String for Empty /// /// - Parameter text: String /// - Returns: Bool whether the string is empty or not. public class func isEmpty(_ text:String?)->Bool { guard (text != nil) else { return true; } return (text!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == ""); } //F.E. /// Validate String for email regex. /// /// - Parameter text: Sting /// - Returns: Bool whether the string is a valid email or not. public class func isValidEmail(_ text:String?)->Bool { guard (text != nil) else { return false; } let emailRegex:String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex) return predicate.evaluate(with: text!); } //F.E. /// Validate String for URL regex. /// /// - Parameter text: Sting /// - Returns: Bool whether the string is a valid URL or not. public class func isValidUrl(_ text:String?) -> Bool { guard (text != nil) else { return false; } let regexURL: String = "(http://|https://)?((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+" let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", regexURL) return predicate.evaluate(with: text) } //F.E. /// Validate String for Phone Number regex. /// /// - Parameter text: Sting /// - Returns: Bool whether the string is a valid phone number or not. public class func isValidPhoneNo(_ text:String?, withRegion region: String = PhoneNumberKit.defaultRegionCode()) -> Bool { return self.validatePhoneNumber(text, withRegion:region) != nil; } //F.E. public class func validatePhoneNumber(_ text:String?, withRegion region: String = PhoneNumberKit.defaultRegionCode()) -> PhoneNumber? { guard (text != nil) else { return nil; } let kit = PhoneNumberKit() var pNumber:String = text! if pNumber.hasPrefix("0") { pNumber.remove(at: pNumber.startIndex); } do { let phoneNumber:PhoneNumber = try kit.parse(pNumber, withRegion:region); print("numberString: \(phoneNumber.numberString) countryCode: \(phoneNumber.countryCode) leadingZero: \(phoneNumber.leadingZero) nationalNumber: \(phoneNumber.nationalNumber) numberExtension: \(String(describing: phoneNumber.numberExtension)) type: \(phoneNumber.type)") return phoneNumber; } catch { } return nil; } //F.E. /// Validate String for number. /// /// - Parameter text: Sting /// - Returns: Bool whether the string is a valid number or not. public class func isNumeric(_ text:String?) -> Bool { guard (text != nil) else { return false; } return Double(text!) != nil; } //F.E. /// Validate String for alphabetic. /// /// - Parameter text: Sting /// - Returns: Bool whether the string is a valid alphabetic string or not. public class func isAlphabetic(_ text:String?) -> Bool { guard (text != nil) else { return false; } let regexURL: String = ".*[^A-Za-z ].*" let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", regexURL) return predicate.evaluate(with: text) } //F.E. /// Validate String for minimum character limit. /// /// - Parameter text: String /// - Parameter noOfChar: Int /// - Returns: Bool whether the string is a valid number of characters. public class func isValidForMinChar(_ text:String?, noOfChar:Int) -> Bool { guard (text != nil) else { return false; } return (text!.count >= noOfChar); } //F.E. /// Validate String for maximum character limit. /// /// - Parameter text: String? /// - Parameter noOfChar: Int /// - Returns: Bool whether the string is a valid number of characters. public class func isValidForMaxChar(_ text:String?, noOfChar:Int) -> Bool { guard (text != nil) else { return false; } return (text!.count <= noOfChar); } //F.E. /// Validate String for mininum value entered. /// /// - Parameter text: String? /// - Parameter value: Int /// - Returns: Bool whether the string is valid. public class func isValidForMinValue(_ text:String?, value:Int) -> Bool { guard (text != nil) else { return false; } let amount:Int = Int(text!) ?? 0; return amount >= value; } //F.E. /// Validate String for mininum value entered. /// /// - Parameter text: String /// - Parameter value: Int /// - Returns: Bool whether the string is valid. public class func isValidForMaxValue(_ text:String?, value:Int) -> Bool { guard (text != nil) else { return false; } let amount:Int = Int(text!) ?? 0; return amount <= value; } //F.E. /// Validate String for a regex. /// /// - Parameters: /// - text: String /// - regex: Ragex String /// - Returns: Bool whether the string is a valid regex string. public class func isValidForRegex(_ text:String?, regex:String) -> Bool { guard (text != nil) else { return false; } let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", regex) return predicate.evaluate(with: text!); } //F.E. } //CLS END
agpl-3.0
jindulys/HackerRankSolutions
Sources/ZenefitsContest.swift
1
14383
// // ZenefitsContest.swift // HRSwift // // Created by yansong li on 2015-11-20. // Copyright © 2015 yansong li. All rights reserved. // import Foundation // This one scored 65.0, due to time out // Need to optimize this solution // Question 1 class bobCandyShop { let cashes = [1, 2, 5, 10, 20, 50, 100] var combinations = [[Int]]() func getNumOfCost(cost:Int, start:Int, valueList:[Int]) -> Void { // This way to get rid of redundant cost let length = cashes.count if cost == 0 { combinations.append(valueList) } for i in start..<length { if cost < cashes[i] { return } self.getNumOfCost(cost - cashes[i], start: i, valueList: valueList+[cashes[i]]) } } // Editorial Solution // https://www.hackerrank.com/contests/zenhacks/challenges/candy-shop/editorial func call(i:Int, n:Int) -> Int { if n < 0 { return 0 } if n == 0 { return 1 } if i == 7{ return 0 } var ans = 0 ans += call(i, n: n-cashes[i]) + call(i+1, n: n) return ans } func solution() -> Void { let cost = Int(getLine())! //getNumOfCost(cost, start: 0, valueList: []) //print(combinations.count) print(call(0, n: cost)) } } // Question 2 class EncryptionModule { let p: String let ePrime: String var shiftCounts: [Int:Int] init(p:String, ep:String) { self.p = p self.ePrime = ep shiftCounts = [Int: Int]() } // wrong one because I forgot to count recycle of shift // func calculateShifting() -> Void { // for (i, c) in p.characters.enumerate() { // let currentDetectIndex = ePrime.characters.startIndex.advancedBy(i) // let characterToCompare = ePrime.characters[currentDetectIndex] // let toCompare = characterToCompare.unicodeScalarCodePoint() // let compared = c.unicodeScalarCodePoint() // if let val = shiftCounts[toCompare - compared] { // shiftCounts[toCompare - compared] = val + 1 // } else { // shiftCounts[toCompare - compared] = 1 // } // } // var minimal = Int.min // for (_, counts) in shiftCounts { // if minimal < counts { // minimal = counts // } // } // print(shiftCounts) // print(p.characters.count - minimal) // } func calculateShifting() -> Void { for (i, c) in p.characters.enumerate() { let currentDetectIndex = ePrime.characters.startIndex.advancedBy(i) let characterToCompare = ePrime.characters[currentDetectIndex] let toCompare = characterToCompare.unicodeScalarCodePoint() let compared = c.unicodeScalarCodePoint() if let val = shiftCounts[toCompare - compared] { shiftCounts[toCompare - compared] = val + 1 } else { shiftCounts[toCompare - compared] = 1 } } var final = [Int: Int]() for (k, v) in shiftCounts { print("key:\(k), value:\(v)") let reverseKey = k > 0 ? k-26 : 26+k if let _ = final[k] { continue } if let _ = final[reverseKey] { continue } var countTotal = v if let val = shiftCounts[reverseKey] { countTotal += val } final[k] = countTotal } var minimal = Int.min for (_, counts) in final { if minimal < counts { minimal = counts } } print(final) print(p.characters.count - minimal) } } // Question 3 class jarjarBinks { // This question want me to find pair of shoes that matches func getPairOfShoes(pairs:[(String, String)]) -> Void { var matches = [String:[String:Int]]() for (des, type) in pairs { if var savedType = matches[des] { if let typeCount = savedType[type] { savedType[type] = typeCount + 1 } else { savedType[type] = 1 } matches[des] = savedType } else { matches[des] = [type: 1] } } var totalMatches = 0 for (_, savedType) in matches { if savedType.keys.count == 2 { var lessCount = Int.max for (_, count) in savedType { if count < lessCount { lessCount = count } } totalMatches += lessCount } } print(totalMatches) } func solution() -> Void { let N = Int(getLine())! var inputs = [(String, String)]() for _ in 0..<N { let currentInput = getLine() let splitted = currentInput.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let des = splitted[0] + splitted[1] + splitted[2] let type = splitted[3] inputs.append((des, type)) } getPairOfShoes(inputs) } func test() -> Void { let myPairs = [("nike4blue","L"),("adidas4green","L"),("nike4blue","R")] getPairOfShoes(myPairs) } } // Question 4 class PrimeTargets { var currentPrimes = [Int]() func solution() -> Void { let N = Int(getLine())! let inputs = getLine().componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).map{Int($0)!} getPrimesSumBetter(inputs,count: N) } // This solution has time out func getPrimesSum(inputs:[Int], count:Int) -> Void { let primes = getPrimes(count) var total = 0 for i in 0..<count { for j in primes { if i + j < count { // valid index total += inputs[i+j] - inputs[i] } } } print(total) } // Find another solution that could improve time efficiency /* The idea behind this is to count the position in the prime, so we could directly get the num of this value be minused times and minus others time To find the position of some index we could use binary search Already improve score from 33.3 to 66.6 the limitation now is how to fast generate prime */ func getPrimesSumBetter(inputs:[Int], count:Int) -> Void { let primes = getPrimes(count) currentPrimes = primes var total = 0 for i in 0..<count { let minusPartCount = (count-1) - i let plusPartCount = i let minusCount = binarySearchLessOrEqualIndex(minusPartCount) let plusCount = binarySearchLessOrEqualIndex(plusPartCount) total = total + inputs[i] * plusCount - inputs[i] * minusCount } print(total) } func getPrimes(length:Int) -> [Int] { // Here the length means how many elements we have // This prime finder is a specific one because we want to find gap that is prime // so we start from 3 var primes = [Int]() if length < 3 { return primes } // here since we want to find gap, length should not be included, start from 2 since 2 is the smallest prime for i in 2..<length { var currentIsPrime = true // check prime is general, we should use count from 2 to sqrt(i) to see whether or not it // could be divided. let higherBounder = sqrt(Double(i)) let intHigher = Int(higherBounder) if intHigher >= 2 { for j in 2...intHigher { if i % j == 0 { currentIsPrime = false break } } } if currentIsPrime { primes.append(i) } } return primes } func binarySearchLessOrEqualIndex(target:Int) -> Int { var lowerIndex = 0 var higherIndex = currentPrimes.count - 1 var indexToCheck = (higherIndex + lowerIndex) / 2 while lowerIndex <= higherIndex { if currentPrimes[indexToCheck] == target { return indexToCheck + 1 } else if (currentPrimes[indexToCheck] < target) { lowerIndex = indexToCheck + 1 indexToCheck = (higherIndex + lowerIndex) / 2 } else { higherIndex = indexToCheck - 1 indexToCheck = (higherIndex + lowerIndex) / 2 } } // At this point our lower exceed higher return higherIndex + 1 } func test() -> Void { getPrimesSumBetter([2, 4, 6, 8, 10, 12, 14], count: 7) } } // Question 9 // https://www.hackerrank.com/contests/zenhacks/challenges/zenland class BattleOfRyloth { // required person at Node[i] var required = [Int](count: 100000, repeatedValue: 0) // available person at Node[i] var available = [Int](count: 100000, repeatedValue: 0) // degree of node i in given tree var degree = [Int](count: 100000, repeatedValue: 0) // Adjacency list of Node var graph = [[Int]](count: 100000, repeatedValue: []) // Queue to store all the leaves var leafNodes = Queue<Int>() // Used LinkedListQueue to try to improve performance, failed var leafNodes2 = LinkedListQueue<Int>() func solution() { let numberOfNodes = Int(getLine())! for i in 0..<numberOfNodes { let infoArray = getLineToArray().map {Int($0)!} available[i] = infoArray[0] required[i] = infoArray[1] } for _ in 0..<numberOfNodes-1 { let edge = getLineToArray().map {Int($0)!} degree[edge[0]] += 1; degree[edge[1]] += 1; graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) } // save leaf to leafQueue for i in 0..<numberOfNodes { if degree[i] == 1 { leafNodes.enqueue(i) } } var answer = 0 while !leafNodes.isEmpty { let currentLeaf = leafNodes.dequeue()! as Int // Maybe negative let extraPersonCount = available[currentLeaf] - required[currentLeaf] // delete current leaf node from tree degree[currentLeaf] = 0 for i in 0..<graph[currentLeaf].count { let adjacentNode = graph[currentLeaf][i] if degree[adjacentNode] == 0 { continue } degree[adjacentNode] -= 1 if degree[adjacentNode] == 1 { leafNodes.enqueue(adjacentNode) } available[adjacentNode] += extraPersonCount answer += abs(extraPersonCount) } } print(answer) } func solution2() { let numberOfNodes = Int(getLine())! for i in 0..<numberOfNodes { let infoArray = getLineToArray().map {Int($0)!} available[i] = infoArray[0] required[i] = infoArray[1] } for _ in 0..<numberOfNodes-1 { let edge = getLineToArray().map {Int($0)!} degree[edge[0]] += 1; degree[edge[1]] += 1; graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) } // save leaf to leafQueue for i in 0..<numberOfNodes { if degree[i] == 1 { leafNodes2.enqueue(i) } } var answer = 0 while !leafNodes2.isEmpty() { let currentLeaf = leafNodes2.dequeue()! as Int // Maybe negative let extraPersonCount = available[currentLeaf] - required[currentLeaf] // delete current leaf node from tree degree[currentLeaf] = 0 for i in 0..<graph[currentLeaf].count { let adjacentNode = graph[currentLeaf][i] if degree[adjacentNode] == 0 { continue } degree[adjacentNode]-- if degree[adjacentNode] == 1 { leafNodes2.enqueue(adjacentNode) } available[adjacentNode] += extraPersonCount answer += abs(extraPersonCount) } } print(answer) } func solution3() { let numberOfNodes = Int(getLine())! for i in 0..<numberOfNodes { let infoArray = getLineToArray().map {Int($0)!} available[i] = infoArray[0] required[i] = infoArray[1] } for _ in 0..<numberOfNodes-1 { let edge = getLineToArray().map {Int($0)!} graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) } var seq: [Int] = [Int](count: numberOfNodes, repeatedValue: 0) var p: [Int] = [Int](count: numberOfNodes, repeatedValue: 0) seq[0] = 0 p[0] = -1 var top = 1 for i in SRange(end: numberOfNodes - 1) { let now = seq[i] for j in graph[now] { if j != p[now] { p[j] = now seq[top] = j top += 1 } } } var answer = 0 for i in SRange(start: numberOfNodes-1, end: 0, step: -1) { let x = seq[i] answer += abs(available[x] - required[x]) available[p[x]] += available[x] - required[x] } print(answer) } }
mit
Incipia/Goalie
PaintCode/GoalieSpeechBubbleKit.swift
1
5420
// // File.swift // Goalie // // Created by Gregory Klein on 1/7/16. // Copyright © 2016 Incipia. All rights reserved. // import Foundation struct GoalieSpeechBubbleKit { static func drawBubbleWithColor(_ color: UIColor, tailDirection: BubbleTailDirection, inFrame frame: CGRect) { switch tailDirection { case .left: _drawBubblePointingLeft(frame: frame, withColor: color) case .right: _drawBubblePointingRight(frame: frame, withColor: color) } } fileprivate static func _drawBubblePointingLeft(frame: CGRect = CGRect(x: 0, y: 0, width: 180, height: 87), withColor color: UIColor) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Shadow Declarations let speechBubbleShadow = NSShadow() speechBubbleShadow.shadowColor = UIColor.black.withAlphaComponent(0.2) speechBubbleShadow.shadowOffset = CGSize(width: 0.1, height: 3.1) speechBubbleShadow.shadowBlurRadius = 5 //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: frame.minX + 17.65, y: frame.maxY - 22.55)) bezierPath.addLine(to: CGPoint(x: frame.minX + 24.15, y: frame.maxY - 22.55)) bezierPath.addLine(to: CGPoint(x: frame.minX + 24.15, y: frame.maxY - 12)) bezierPath.addLine(to: CGPoint(x: frame.minX + 38.05, y: frame.maxY - 22.55)) bezierPath.addLine(to: CGPoint(x: frame.maxX - 18.95, y: frame.maxY - 22.55)) bezierPath.addCurve(to: CGPoint(x: frame.maxX - 15.45, y: frame.maxY - 26.05), controlPoint1: CGPoint(x: frame.maxX - 17.05, y: frame.maxY - 22.55), controlPoint2: CGPoint(x: frame.maxX - 15.45, y: frame.maxY - 24.1)) bezierPath.addLine(to: CGPoint(x: frame.maxX - 14.3, y: frame.minY + 8.5)) bezierPath.addCurve(to: CGPoint(x: frame.maxX - 17.8, y: frame.minY + 5), controlPoint1: CGPoint(x: frame.maxX - 14.3, y: frame.minY + 6.6), controlPoint2: CGPoint(x: frame.maxX - 15.85, y: frame.minY + 5)) bezierPath.addLine(to: CGPoint(x: frame.minX + 16.5, y: frame.minY + 5)) bezierPath.addCurve(to: CGPoint(x: frame.minX + 13, y: frame.minY + 8.5), controlPoint1: CGPoint(x: frame.minX + 14.6, y: frame.minY + 5), controlPoint2: CGPoint(x: frame.minX + 13, y: frame.minY + 6.55)) bezierPath.addLine(to: CGPoint(x: frame.minX + 14.15, y: frame.maxY - 26.05)) bezierPath.addCurve(to: CGPoint(x: frame.minX + 17.65, y: frame.maxY - 22.55), controlPoint1: CGPoint(x: frame.minX + 14.2, y: frame.maxY - 24.15), controlPoint2: CGPoint(x: frame.minX + 15.75, y: frame.maxY - 22.55)) bezierPath.close() bezierPath.miterLimit = 4; context!.saveGState() context!.setShadow(offset: speechBubbleShadow.shadowOffset, blur: speechBubbleShadow.shadowBlurRadius, color: (speechBubbleShadow.shadowColor as! UIColor).cgColor) color.setFill() bezierPath.fill() context!.restoreGState() } fileprivate static func _drawBubblePointingRight(frame: CGRect = CGRect(x: 0, y: 0, width: 180, height: 87), withColor color: UIColor) { //// General Declarations //// General Declarations let context = UIGraphicsGetCurrentContext() //// Shadow Declarations let speechBubbleShadow = NSShadow() speechBubbleShadow.shadowColor = UIColor.black.withAlphaComponent(0.2) speechBubbleShadow.shadowOffset = CGSize(width: 0.1, height: 3.1) speechBubbleShadow.shadowBlurRadius = 5 //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: frame.minX + 17.65, y: frame.maxY - 22.55)) bezierPath.addLine(to: CGPoint(x: frame.maxX - 39.35, y: frame.maxY - 22.55)) bezierPath.addLine(to: CGPoint(x: frame.maxX - 25.45, y: frame.maxY - 12)) bezierPath.addLine(to: CGPoint(x: frame.maxX - 25.45, y: frame.maxY - 22.55)) bezierPath.addLine(to: CGPoint(x: frame.maxX - 18.95, y: frame.maxY - 22.55)) bezierPath.addCurve(to: CGPoint(x: frame.maxX - 15.45, y: frame.maxY - 26.05), controlPoint1: CGPoint(x: frame.maxX - 17.05, y: frame.maxY - 22.55), controlPoint2: CGPoint(x: frame.maxX - 15.45, y: frame.maxY - 24.1)) bezierPath.addLine(to: CGPoint(x: frame.maxX - 14.3, y: frame.minY + 8.5)) bezierPath.addCurve(to: CGPoint(x: frame.maxX - 17.8, y: frame.minY + 5), controlPoint1: CGPoint(x: frame.maxX - 14.3, y: frame.minY + 6.6), controlPoint2: CGPoint(x: frame.maxX - 15.85, y: frame.minY + 5)) bezierPath.addLine(to: CGPoint(x: frame.minX + 16.5, y: frame.minY + 5)) bezierPath.addCurve(to: CGPoint(x: frame.minX + 13, y: frame.minY + 8.5), controlPoint1: CGPoint(x: frame.minX + 14.6, y: frame.minY + 5), controlPoint2: CGPoint(x: frame.minX + 13, y: frame.minY + 6.55)) bezierPath.addLine(to: CGPoint(x: frame.minX + 14.15, y: frame.maxY - 26.05)) bezierPath.addCurve(to: CGPoint(x: frame.minX + 17.65, y: frame.maxY - 22.55), controlPoint1: CGPoint(x: frame.minX + 14.2, y: frame.maxY - 24.15), controlPoint2: CGPoint(x: frame.minX + 15.75, y: frame.maxY - 22.55)) bezierPath.close() bezierPath.miterLimit = 4; context!.saveGState() context!.setShadow(offset: speechBubbleShadow.shadowOffset, blur: speechBubbleShadow.shadowBlurRadius, color: (speechBubbleShadow.shadowColor as! UIColor).cgColor) color.setFill() bezierPath.fill() context!.restoreGState() } }
apache-2.0
dehesa/Metal
books/05 - Lighting/Sources/iOS/MasterController.swift
1
384
import UIKit import MetalKit final class MasterController: UIViewController { private var _renderer: TeapotRenderer! override var prefersStatusBarHidden: Bool { true } override func viewDidLoad() { super.viewDidLoad() let metalView = self.view as! MTKView self._renderer = try! TeapotRenderer(view: metalView) metalView.delegate = self._renderer } }
mit
uasys/swift
validation-test/compiler_crashers_2_fixed/0002-rdar19792768.swift
38
411
// RUN: %target-swift-frontend %s -emit-silgen // rdar://problem/19792768 public func foo< Expected : Sequence, Actual : Sequence, T : Comparable where Expected.Iterator.Element == Actual.Iterator.Element, Expected.Iterator.Element == (T, T) >(_ expected: Expected, _ actual: Actual) {} func f() { foo( [ (10, 1010), (20, 1020), (30, 1030) ], [ (10, 1010), (20, 1020), (30, 1030) ]) }
apache-2.0
CoderLala/DouYZBTest
DouYZB/DouYZB/Classes/Tools/Extension/NSDate-Extension.swift
1
369
// // NSDate-Extension.swift // DouYZB // // Created by 黄金英 on 17/2/7. // Copyright © 2017年 黄金英. All rights reserved. // import Foundation extension Date{ static func getCurrentTime() -> String { let nowDate = Date() let timeInteval = Int(nowDate.timeIntervalSince1970) return "\(timeInteval)" } }
mit
apple/swift
validation-test/compiler_crashers_fixed/26028-swift-parser-skipsingle.swift
65
573
// 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 class A{ enum S{ { (( { {{ { { {( { { ({{ {{{ { { { {{ { { { { { { { { ( {{ { { { { { { { { {{ { { { {( ({ (( {{ {{ { { { { { { { {{ {{ {{{ { { { { ( { {" deinit{ class case,
apache-2.0
apple/swift
test/SourceKit/CodeFormat/indent-trailing/trailing-func.swift
22
148
func foo() -> Int { // RUN: %sourcekitd-test -req=format -line=2 -length=1 %s | %FileCheck --strict-whitespace %s // CHECK: key.sourcetext: " "
apache-2.0
hooman/swift
test/Distributed/Runtime/distributed_actor_identity.swift
1
1463
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -Xfrontend -enable-experimental-distributed -parse-as-library) // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime import StdlibUnittest import _Distributed @available(SwiftStdlib 5.5, *) struct ActorAddress: ActorIdentity, CustomStringConvertible { let id: String var description: Swift.String { "ActorAddress(id: \(id))" } } @main struct Main { static func main() async { if #available(SwiftStdlib 5.5, *) { let ActorIdentityTests = TestSuite("ActorIdentity") ActorIdentityTests.test("equality") { let a = ActorAddress(id: "a") let b = ActorAddress(id: "b") let anyA = AnyActorIdentity(a) let anyB = AnyActorIdentity(b) expectEqual(a, a) expectEqual(anyA, anyA) expectNotEqual(a, b) expectNotEqual(anyA, anyB) } ActorIdentityTests.test("hash") { let a = ActorAddress(id: "a") let b = ActorAddress(id: "b") let anyA = AnyActorIdentity(a) let anyB = AnyActorIdentity(b) expectEqual(a.hashValue, a.hashValue) expectEqual(anyA.hashValue, anyA.hashValue) expectNotEqual(a.hashValue, b.hashValue) expectNotEqual(anyA.hashValue, anyB.hashValue) } } await runAllTestsAsync() } }
apache-2.0
dietcoke27/TableVector
Example/TableVector/ViewController.swift
1
11983
// // ViewController.swift // TableVector // // Created by Cole Kurkowski on 2/3/16. // Copyright © 2016 Cole Kurkowski. All rights reserved. // import UIKit import TableVector final class ViewController: UITableViewController, TableVectorDelegate { typealias VectorType = TableVector<Container> var tableVector: VectorType! var reader: FileReader! var buffer: VectorBuffer<Container>! var filterString: String? var shouldSleep = true var shouldReadFile = true override func viewDidLoad() { super.viewDidLoad() let compare = { (lhs: T, rhs: T) -> Bool in return lhs.string.caseInsensitiveCompare(rhs.string) == .orderedAscending } let sectionMember = { (elem: T, rep: T) -> Bool in let elemChar = elem.string.substring(to: elem.string.characters.index(after: elem.string.startIndex)) let repChar = rep.string.substring(to: rep.string.characters.index(after: rep.string.startIndex)) return elemChar.caseInsensitiveCompare(repChar) == .orderedSame } let sectionCompare = { (lhs: T, rhs: T) -> Bool in let elemChar = lhs.string.substring(to: lhs.string.characters.index(after: lhs.string.startIndex)) let repChar = rhs.string.substring(to: rhs.string.characters.index(after: rhs.string.startIndex)) return elemChar.caseInsensitiveCompare(repChar) == .orderedAscending } self.tableVector = VectorType(delegate: self, comparator: compare, sectionClosure: sectionMember, sectionComparator: sectionCompare) self.buffer = VectorBuffer(vector: self.tableVector) self.tableVector.suspendDelegateCalls = true if self.shouldReadFile { self.reader = FileReader() self.reader.vc = self } self.tableView.allowsMultipleSelection = false let button = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(ViewController.filterButton(sender:))) let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.addButton(sender:))) self.navigationItem.rightBarButtonItems = [addButton, button] self.tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "header") } func addButton(sender: Any?) { let alert = UIAlertController(title: "Add", message: nil, preferredStyle: .alert) alert.addTextField(configurationHandler: nil) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Add", style: .default, handler: {[weak alert] (action) in if let text = alert?.textFields?.first { let container = Container(string: text.text ?? "") self.tableVector.insert(container) } })) self.present(alert, animated: true, completion: nil) } func filterButton(sender: Any?) { let alert = UIAlertController(title: "Filter", message: nil, preferredStyle: .alert) alert.addTextField { (field) in field.text = self.filterString } alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: {[weak alert] (action) in if let textField = alert?.textFields?.first, let text = textField.text { if text == "" { self.tableVector.removeFilter() } else { if let previousFilter = self.filterString, text.contains(previousFilter) { self.tableVector.refineFilter{ (container) -> Bool in return container.string.contains(text) || text.contains(container.string) } } else { if self.filterString != nil { self.tableVector.removeFilter() } self.tableVector.filter(predicate: { (container) -> Bool in return container.string.contains(text) || text.contains(container.string) }) } } self.filterString = text } else { self.tableVector.removeFilter() } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } override func viewWillAppear(_ animated: Bool) { self.tableVector.suspendDelegateCalls = false } override func viewDidAppear(_ animated: Bool) { if !(self.reader?.started ?? true) { self.reader.startReader() } let timer = Timer(timeInterval: 1, target: self, selector: #selector(ViewController.timerUpdate(_:)), userInfo: nil, repeats: true) RunLoop.main.add(timer, forMode: .commonModes) } @objc func timerUpdate(_ sender: Any) { DispatchQueue.global(qos: .background).async { var total = 0 for section in 0..<(self.tableVector.sectionCount) { total += self.tableVector.countForSection(section) } var secondTotal = 0 for section in 0..<(self.tableView.numberOfSections) { secondTotal += self.tableView.numberOfRows(inSection: section) } DispatchQueue.main.async { self.title = "\(total) | \(secondTotal)" } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let str = self.tableVector.representative(at: section)?.string if let str = str { let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") let char = str.substring(to: str.characters.index(after: str.startIndex)) header?.textLabel?.text = char.uppercased() return header } else { return nil } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if self.tableView(tableView, numberOfRowsInSection: section) == 0 { return 0 } return 28 } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { self.tableVector.remove(at: indexPath) } } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .delete } func elementChangedForVector(_ vector: VectorType, changes: ElementChangeType<Container>, atIndexPaths: [IndexPath]) { switch changes { case .inserted: var newSections = [Int]() for path in atIndexPaths { if self.tableView.numberOfRows(inSection: path.section) == 0 { newSections.append(path.section) } } self.tableView.insertRows(at: atIndexPaths, with: .automatic) if newSections.count > 0 { self.tableView.reloadSections(IndexSet(newSections), with: .automatic) } case .removed, .filteredOut: var emptySections = [Int]() self.tableView.deleteRows(at: atIndexPaths, with: .automatic) for path in atIndexPaths { if self.tableView.numberOfRows(inSection: path.section) == 0 { emptySections.append(path.section) } } if emptySections.count > 0 { self.tableView.reloadSections(IndexSet(emptySections), with: .automatic) } case .updated: break } } func refresh(sections: IndexSet, inVector: VectorType) { UIView.transition(with: self.tableView, duration: 0.5, options: .transitionCrossDissolve, animations: { self.tableView.reloadData() }, completion: nil) } func sectionChangedForVector(_ vector: VectorType, change: SectionChangeType, atIndex: Int) { if case .inserted = change { self.tableView.insertSections(IndexSet(integer: atIndex), with: .automatic) } } override func numberOfSections(in tableView: UITableView) -> Int { let c = self.tableVector.sectionCount return c } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let c = self.tableVector.countForSection(section) return c } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let container = self.tableVector[indexPath]! cell.textLabel?.text = container.string return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? DetailViewController { if let path = self.tableView.indexPathForSelectedRow { vc.container = self.tableVector[path] } } } } class FileReader { private var filename = "american" private var fileHandle: FileHandle? weak var vc: ViewController! let queue = DispatchQueue(label: "filereader", attributes: .concurrent, target: .global(qos: .background)) let group = DispatchGroup() let sem = DispatchSemaphore(value: 0) var started = false func startReader() { started = true self.queue.async { self.readWholeFile() } } private func readWholeFile() { if let path = Bundle.main.path(forResource: self.filename, ofType: nil) { var count = 0 do { let str = try String(contentsOfFile: path) let components = str.components(separatedBy: "\n") for comp in components { weak var vc = self.vc self.queue.async(group: self.group) { let contain = Container(string: comp) if vc?.shouldSleep ?? false { let slp = arc4random_uniform(10) sleep(slp) } vc?.buffer.append(contain) } count += 1 if count >= 50 { self.group.notify(queue: self.queue) { count = 0 self.sem.signal() } self.sem.wait() } } } catch { } } } } class Container: CustomStringConvertible { let string: String var description: String { get { return self.string } } init(string: String) { self.string = string } }
mit
krzysztofzablocki/Sourcery
Sourcery/Utils/FolderWatcher.swift
1
4706
// // FolderWatcher.swift // Sourcery // // Created by Krzysztof Zabłocki on 24/12/2016. // Copyright © 2016 Pixle. All rights reserved. // import Foundation public enum FolderWatcher { struct Event { let path: String let flags: Flag struct Flag: OptionSet { let rawValue: FSEventStreamEventFlags init(rawValue: FSEventStreamEventFlags) { self.rawValue = rawValue } init(_ value: Int) { self.rawValue = FSEventStreamEventFlags(value) } static let isDirectory = Flag(kFSEventStreamEventFlagItemIsDir) static let isFile = Flag(kFSEventStreamEventFlagItemIsFile) static let created = Flag(kFSEventStreamEventFlagItemCreated) static let modified = Flag(kFSEventStreamEventFlagItemModified) static let removed = Flag(kFSEventStreamEventFlagItemRemoved) static let renamed = Flag(kFSEventStreamEventFlagItemRenamed) static let isHardlink = Flag(kFSEventStreamEventFlagItemIsHardlink) static let isLastHardlink = Flag(kFSEventStreamEventFlagItemIsLastHardlink) static let isSymlink = Flag(kFSEventStreamEventFlagItemIsSymlink) static let changeOwner = Flag(kFSEventStreamEventFlagItemChangeOwner) static let finderInfoModified = Flag(kFSEventStreamEventFlagItemFinderInfoMod) static let inodeMetaModified = Flag(kFSEventStreamEventFlagItemInodeMetaMod) static let xattrsModified = Flag(kFSEventStreamEventFlagItemXattrMod) var description: String { var names: [String] = [] if self.contains(.isDirectory) { names.append("isDir") } if self.contains(.isFile) { names.append("isFile") } if self.contains(.created) { names.append("created") } if self.contains(.modified) { names.append("modified") } if self.contains(.removed) { names.append("removed") } if self.contains(.renamed) { names.append("renamed") } if self.contains(.isHardlink) { names.append("isHardlink") } if self.contains(.isLastHardlink) { names.append("isLastHardlink") } if self.contains(.isSymlink) { names.append("isSymlink") } if self.contains(.changeOwner) { names.append("changeOwner") } if self.contains(.finderInfoModified) { names.append("finderInfoModified") } if self.contains(.inodeMetaModified) { names.append("inodeMetaModified") } if self.contains(.xattrsModified) { names.append("xattrsModified") } return names.joined(separator: ", ") } } } public class Local { private let path: String private var stream: FSEventStreamRef! private let closure: (_ events: [Event]) -> Void /// Creates folder watcher. /// /// - Parameters: /// - path: Path to observe /// - latency: Latency to use /// - closure: Callback closure init(path: String, latency: TimeInterval = 1/60, closure: @escaping (_ events: [Event]) -> Void) { self.path = path self.closure = closure func handler(_ stream: ConstFSEventStreamRef, clientCallbackInfo: UnsafeMutableRawPointer?, numEvents: Int, eventPaths: UnsafeMutableRawPointer, eventFlags: UnsafePointer<FSEventStreamEventFlags>, eventIDs: UnsafePointer<FSEventStreamEventId>) { let eventStream = unsafeBitCast(clientCallbackInfo, to: Local.self) let paths = unsafeBitCast(eventPaths, to: NSArray.self) let events = (0..<numEvents).compactMap { idx in return (paths[idx] as? String).flatMap { Event(path: $0, flags: Event.Flag(rawValue: eventFlags[idx])) } } eventStream.closure(events) } var context = FSEventStreamContext() context.info = unsafeBitCast(self, to: UnsafeMutableRawPointer.self) let flags = UInt32(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents) stream = FSEventStreamCreate(nil, handler, &context, [path] as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, flags) FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue) FSEventStreamStart(stream) } deinit { FSEventStreamStop(stream) FSEventStreamInvalidate(stream) FSEventStreamRelease(stream) } } }
mit
powerytg/Accented
Accented/UI/Gallery/UserGalleryListViewController.swift
1
4531
// // UserGalleryListViewController.swift // Accented // // User gallery list page // // Created by You, Tiangong on 9/1/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class UserGalleryListViewController: UIViewController, InfiniteLoadingViewControllerDelegate, MenuDelegate { private let headerCompressionStart : CGFloat = 50 private let headerCompressionDist : CGFloat = 200 private var streamViewController : UserGalleryListStreamViewController! private var user : UserModel private var backButton = UIButton(type: .custom) private var headerView : UserHeaderSectionView! private var backgroundView : DetailBackgroundView! private let displayStyles = [MenuItem(action: .None, text: "Display As Groups"), MenuItem(action: .None, text: "Display As List")] // Menu private var menu = [MenuItem(action : .Home, text: "Home")] private var menuBar : CompactMenuBar! init(user : UserModel) { // Get an updated copy of user profile self.user = StorageService.sharedInstance.getUserProfile(userId: user.userId)! super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = ThemeManager.sharedInstance.currentTheme.rootViewBackgroundColor backgroundView = DetailBackgroundView(frame: self.view.bounds) self.view.insertSubview(backgroundView, at: 0) // Header view headerView = UserHeaderSectionView(user) view.addSubview(headerView) // Stream controller createStreamViewController() // Back button self.view.addSubview(backButton) backButton.setImage(UIImage(named: "DetailBackButton"), for: .normal) backButton.addTarget(self, action: #selector(backButtonDidTap(_:)), for: .touchUpInside) backButton.sizeToFit() // Create a menu menuBar = CompactMenuBar(menu) menuBar.delegate = self view.addSubview(menuBar) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() backgroundView.frame = view.bounds streamViewController.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height - CompactMenuBar.defaultHeight) streamViewController.view.setNeedsLayout() var f = headerView.frame f.size.width = view.bounds.size.width headerView.frame = f headerView.setNeedsLayout() f = backButton.frame f.origin.x = 10 f.origin.y = 30 backButton.frame = f f = menuBar.frame f.origin.x = 0 f.origin.y = view.bounds.height - CompactMenuBar.defaultHeight f.size.width = view.bounds.width f.size.height = CompactMenuBar.defaultHeight menuBar.frame = f } private func createStreamViewController() { streamViewController = UserGalleryListStreamViewController(user : user) addChildViewController(streamViewController) streamViewController.delegate = self self.view.insertSubview(streamViewController.view, at: 1) streamViewController.view.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height) streamViewController.didMove(toParentViewController: self) } // MARK: - Events @objc private func backButtonDidTap(_ sender : UIButton) { _ = self.navigationController?.popViewController(animated: true) } // MARK: - InfiniteLoadingViewControllerDelegate func collectionViewContentOffsetDidChange(_ contentOffset: CGFloat) { var dist = contentOffset - headerCompressionStart dist = min(headerCompressionDist, max(0, dist)) headerView.alpha = 1 - (dist / headerCompressionDist) // Apply background effects backgroundView.applyScrollingAnimation(contentOffset) } // MARK : - MenuDelegate func didSelectMenuItem(_ menuItem: MenuItem) { if menuItem.action == .Home { NavigationService.sharedInstance.popToRootController(animated: true) } } }
mit
shuoli84/RxSwift
RxExample/RxExample/Examples/PartialUpdates/PartialUpdatesViewController.swift
2
7831
// // PartialUpdatesViewController.swift // RxExample // // Created by Krunoslav Zaher on 6/8/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa import CoreData let generateCustomSize = true let runAutomatically = false let useAnimatedUpdateForCollectionView = false class PartialUpdatesViewController : ViewController { @IBOutlet weak var reloadTableViewOutlet: UITableView! @IBOutlet weak var partialUpdatesTableViewOutlet: UITableView! @IBOutlet weak var partialUpdatesCollectionViewOutlet: UICollectionView! var moc: NSManagedObjectContext! var child: NSManagedObjectContext! var timer: NSTimer? = nil static let initialValue: [HashableSectionModel<String, Int>] = [ NumberSection(model: "section 1", items: [1, 2, 3]), NumberSection(model: "section 2", items: [4, 5, 6]), NumberSection(model: "section 3", items: [7, 8, 9]), NumberSection(model: "section 4", items: [10, 11, 12]), NumberSection(model: "section 5", items: [13, 14, 15]), NumberSection(model: "section 6", items: [16, 17, 18]), NumberSection(model: "section 7", items: [19, 20, 21]), NumberSection(model: "section 8", items: [22, 23, 24]), NumberSection(model: "section 9", items: [25, 26, 27]), NumberSection(model: "section 10", items: [28, 29, 30]) ] static let firstChange: [HashableSectionModel<String, Int>]? = nil var generator = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: initialValue) var sections = Variable([NumberSection]()) let disposeBag = DisposeBag() func skinTableViewDataSource(dataSource: RxTableViewSectionedDataSource<NumberSection>) { dataSource.cellFactory = { (tv, ip, i) in let cell = tv.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell ?? UITableViewCell(style:.Default, reuseIdentifier: "Cell") cell.textLabel!.text = "\(i)" return cell } dataSource.titleForHeaderInSection = { [unowned dataSource] (section: Int) -> String in return dataSource.sectionAtIndex(section).model } } func skinCollectionViewDataSource(dataSource: RxCollectionViewSectionedDataSource<NumberSection>) { dataSource.cellFactory = { [unowned dataSource] (cv, ip, i) in let cell = cv.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: ip) as! NumberCell cell.value!.text = "\(i)" return cell } dataSource.supplementaryViewFactory = { [unowned dataSource] (cv, kind, ip) in let section = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Section", forIndexPath: ip) as! NumberSectionView section.value!.text = "\(dataSource.sectionAtIndex(ip.section).model)" return section } } override func viewDidLoad() { super.viewDidLoad() // For UICollectionView, if another animation starts before previous one is finished, it will sometimes crash :( // It's not deterministic (because Randomizer generates deterministic updates), and if you click fast // It sometimes will and sometimes wont crash, depending on tapping speed. // I guess you can maybe try some tricks with timeout, hard to tell :( That's on Apple side. if generateCustomSize { let nSections = 10 let nItems = 100 var sections = [HashableSectionModel<String, Int>]() for i in 0 ..< nSections { sections.append(HashableSectionModel(model: "Section \(i + 1)", items: Array(i * nItems ..< (i + 1) * nItems))) } generator = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: sections) } #if runAutomatically timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: "randomize", userInfo: nil, repeats: true) #endif self.sections.next(generator.sections) let tvAnimatedDataSource = RxTableViewSectionedAnimatedDataSource<NumberSection>() let reloadDataSource = RxTableViewSectionedReloadDataSource<NumberSection>() skinTableViewDataSource(tvAnimatedDataSource) skinTableViewDataSource(reloadDataSource) let newSections = self.sections >- skip(1) let initialState = [Changeset.initialValue(self.sections.value)] // reactive data sources let updates = zip(self.sections, newSections) { (old, new) in return differentiate(old, new) } >- startWith(initialState) updates >- partialUpdatesTableViewOutlet.rx_subscribeWithReactiveDataSource(tvAnimatedDataSource) >- disposeBag.addDisposable self.sections >- reloadTableViewOutlet.rx_subscribeWithReactiveDataSource(reloadDataSource) >- disposeBag.addDisposable // Collection view logic works, but when clicking fast because of internal bugs // collection view will sometimes get confused. I know what you are thinking, // but this is really not a bug in the algorithm. The generated changes are // pseudorandom, and crash happens depending on clicking speed. // // More info in `RxDataSourceStarterKit/README.md` // // If you want, turn this to true, just click slow :) // // While `useAnimatedUpdateForCollectionView` is false, you can click as fast as // you want, table view doesn't seem to have same issues like collection view. #if useAnimatedUpdateForCollectionView let cvAnimatedDataSource = RxCollectionViewSectionedAnimatedDataSource<NumberSection>() skinCollectionViewDataSource(cvAnimatedDataSource) updates >- partialUpdatesCollectionViewOutlet.rx_subscribeWithReactiveDataSource(cvAnimatedDataSource) >- disposeBag.addDisposable #else let cvReloadDataSource = RxCollectionViewSectionedReloadDataSource<NumberSection>() skinCollectionViewDataSource(cvReloadDataSource) self.sections >- partialUpdatesCollectionViewOutlet.rx_subscribeWithReactiveDataSource(cvReloadDataSource) >- disposeBag.addDisposable #endif // touches partialUpdatesCollectionViewOutlet.rx_itemSelected >- subscribeNext { [unowned self] i in println("Let me guess, it's .... It's \(self.generator.sections[i.section].items[i.item]), isn't it? Yeah, I've got it.") } >- disposeBag.addDisposable merge(from([partialUpdatesTableViewOutlet.rx_itemSelected, reloadTableViewOutlet.rx_itemSelected])) >- subscribeNext { [unowned self] i in println("I have a feeling it's .... \(self.generator.sections[i.section].items[i.item])?") } >- disposeBag.addDisposable } override func viewWillDisappear(animated: Bool) { self.timer?.invalidate() } @IBAction func randomize() { generator.randomize() var values = generator.sections // useful for debugging if PartialUpdatesViewController.firstChange != nil { values = PartialUpdatesViewController.firstChange! } //println(values) sections.next(values) } }
mit
AceWangLei/BYWeiBo
BYWeiBo/UILabel+Extension.swift
1
359
// // UILabel+Extension.swift // BYWeiBo // // Created by wanglei on 16/1/26. // Copyright © 2016年 lit. All rights reserved. // import UIKit extension UILabel { convenience init(textColor: UIColor, fontSize: CGFloat) { self.init() self.textColor = textColor self.font = UIFont.systemFontOfSize(fontSize) } }
apache-2.0
edopelawi/CascadingTableDelegate
Example/CascadingTableDelegate/RowTableDelegates/DestinationReviewUserRowDelegate.swift
1
2072
// // DestinationReviewUserRowDelegate.swift // CascadingTableDelegate // // Created by Ricardo Pramana Suranta on 11/2/16. // Copyright © 2016 Ricardo Pramana Suranta. All rights reserved. // import Foundation import CascadingTableDelegate struct DestinationReviewUserRowViewModel { let userName: String let userReview: String let rating: Int } class DestinationReviewUserRowDelegate: CascadingBareTableDelegate { /// Cell identifier that will be used by this instance. Kindly register this on section-level delegate that will use this class' instance. static let cellIdentifier = DestinationReviewUserCell.nibIdentifier() fileprivate var viewModel: DestinationReviewUserRowViewModel? convenience init(viewModel: DestinationReviewUserRowViewModel) { self.init(index: 0, childDelegates: []) self.viewModel = viewModel } } extension DestinationReviewUserRowDelegate { @objc override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = DestinationReviewUserRowDelegate.cellIdentifier return tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) } @objc func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat { let userReview = viewModel?.userReview ?? "" return DestinationReviewUserCell.preferredHeight(userReview: userReview) } @objc func tableView(_ tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: IndexPath) -> CGFloat { return DestinationReviewUserCell.preferredHeight(userReview: "") } @objc func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) { guard let cell = cell as? DestinationReviewUserCell, let viewModel = viewModel else { return } cell.configure( userName: viewModel.userName, userReview: viewModel.userReview, rating: viewModel.rating ) let lastRow = (index + 1) == parentDelegate?.childDelegates.count cell.hideBottomBorder = lastRow } }
mit
aryaxt/SwiftInjection
SwiftInjectionExample/SwiftInjectionExample/AppDelegate.swift
1
2242
// // AppDelegate.swift // SwiftInjectionExample // // Created by Aryan Ghassemi on 4/23/16. // Copyright © 2016 Aryan Ghassemi. All rights reserved. // import UIKit import SwiftInjection @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? override init() { super.init() DIContainer.instance.addModule(AppModule()) } fileprivate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } internal 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. } internal 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. } internal 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. } internal 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. } internal func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
WhisperSystems/Signal-iOS
SignalServiceKit/src/Util/SwiftSingletons.swift
1
958
// // Copyright (c) 2018 Open Whisper Systems. All rights reserved. // import Foundation public class SwiftSingletons: NSObject { public static let shared = SwiftSingletons() private var classSet = Set<String>() private override init() { super.init() } public func register(_ singleton: AnyObject) { guard !CurrentAppContext().isRunningTests else { return } guard _isDebugAssertConfiguration() else { return } let singletonClassName = String(describing: type(of: singleton)) guard !classSet.contains(singletonClassName) else { owsFailDebug("Duplicate singleton: \(singletonClassName).") return } Logger.verbose("Registering singleton: \(singletonClassName).") classSet.insert(singletonClassName) } public static func register(_ singleton: AnyObject) { shared.register(singleton) } }
gpl-3.0
djwbrown/swift
stdlib/public/SDK/Foundation/Codable.swift
2
2897
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Errors //===----------------------------------------------------------------------===// // Both of these error types bridge to NSError, and through the entry points they use, no further work is needed to make them localized. extension EncodingError : LocalizedError {} extension DecodingError : LocalizedError {} //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// internal extension DecodingError { /// Returns a `.typeMismatch` error describing the expected type. /// /// - parameter path: The path of `CodingKey`s taken to decode a value of this type. /// - parameter expectation: The type expected to be encountered. /// - parameter reality: The value that was encountered instead of the expected type. /// - returns: A `DecodingError` with the appropriate path and debug description. internal static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError { let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead." return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description)) } /// Returns a description of the type of `value` appropriate for an error message. /// /// - parameter value: The value whose type to describe. /// - returns: A string describing `value`. /// - precondition: `value` is one of the types below. fileprivate static func _typeDescription(of value: Any) -> String { if value is NSNull { return "a null value" } else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ { return "a number" } else if value is String { return "a string/data" } else if value is [Any] { return "an array" } else if value is [String : Any] { return "a dictionary" } else { // This should never happen -- we somehow have a non-JSON type here. preconditionFailure("Invalid storage type \(type(of: value)).") } } }
apache-2.0
MillmanY/MMPlayerView
MMPlayerView/Classes/Item/SRTInfo.swift
1
555
// // SRTInfo.swift // MMPlayerView // // Created by Millman on 2019/12/13. // import Foundation public struct SRTInfo: Equatable { public let index: Int public let timeRange: ClosedRange<TimeInterval> public let text: String static func emptyInfo() -> Self { return SRTInfo(index: -1, timeRange: 0...0, text: "") } public static func == (lhs: Self, rhs: Self) -> Bool { return (lhs.index == rhs.index && lhs.timeRange == rhs.timeRange && lhs.text == rhs.text) } }
mit
nathawes/swift
test/SymbolGraph/Symbols/Mixins/Availability/Inherited/MessageFilled.swift
20
1314
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -module-name MessageFilled -emit-module -emit-module-path %t/ // RUN: %target-swift-symbolgraph-extract -module-name MessageFilled -I %t -pretty-print -output-dir %t // RUN: %FileCheck %s --input-file %t/MessageFilled.symbols.json // RUN: %FileCheck %s --input-file %t/MessageFilled.symbols.json --check-prefix=TRANSITIVE // REQUIRES: OS=macosx @available(macOS, deprecated, message: "S message") public struct S { @available(macOS, deprecated) public func foo() {} } // A child never inherits its parent's availability message because it // may not make sense 100% of the time. // CHECK-LABEL: "precise": "s:13MessageFilled1SV3fooyyF", // CHECK: "availability": [ // CHECK-NEXT: { // CHECK-NEXT: "domain": "macOS", // CHECK-NEXT: "isUnconditionallyDeprecated": true // CHECK-NEXT: } @available(macOS, deprecated, message: "Outer message") public struct Outer { public struct Inner { // TRANSITIVE-LABEL: "precise": "s:13MessageFilled5OuterV5InnerV3fooyyF" // TRANSITIVE: "availability": [ // TRANSITIVE-NEXT: { // TRANSITIVE-NEXT: "domain": "macOS", // TRANSITIVE-NEXT: "isUnconditionallyDeprecated": true // TRANSITIVE-NEXT: } @available(macOS, deprecated) public func foo() {} } }
apache-2.0
roambotics/swift
test/Interop/SwiftToCxx/expose-attr/expose-swift-decls-to-cxx.swift
2
4318
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -module-name Expose -enable-experimental-cxx-interop -clang-header-expose-decls=has-expose-attr -emit-clang-header-path %t/expose.h // RUN: %FileCheck %s < %t/expose.h // RUN: %check-interop-cxx-header-in-clang(%t/expose.h -Wno-error=unused-function) // RUN: %target-swift-frontend %s -typecheck -module-name Expose -enable-experimental-cxx-interop-in-clang-header -clang-header-expose-decls=has-expose-attr -emit-clang-header-path %t/expose.h // RUN: %FileCheck %s < %t/expose.h // RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -emit-module -module-name Expose -o %t // RUN: %target-swift-frontend -parse-as-library %t/Expose.swiftmodule -typecheck -module-name Expose -enable-experimental-cxx-interop -clang-header-expose-decls=has-expose-attr -emit-clang-header-path %t/expose.h // RUN: %FileCheck %s < %t/expose.h // RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -enable-library-evolution -typecheck -emit-module-interface-path %t/Expose.swiftinterface -module-name Expose // RUN: %target-swift-frontend -parse-as-library %t/Expose.swiftinterface -enable-library-evolution -disable-objc-attr-requires-foundation-module -typecheck -module-name Expose -enable-experimental-cxx-interop -clang-header-expose-decls=has-expose-attr -emit-clang-header-path %t/expose.h // RUN: %FileCheck %s < %t/expose.h @_expose(Cxx) public func exposed1() { } public func exposed2NotExposed() { } @_expose(Cxx) public func exposed3() { } @_expose(Cxx, "exposed4") public func exposed4Renamed() { } @_expose(Cxx) public struct ExposedStruct { public var x: Int public func method() {} } public struct NotExposedStruct { public var x: Int } @_expose(Cxx, "ExposedStruct2") public struct ExposedStructRenamed { public var y: Int @_expose(Cxx) public init() { y = 42; prop = 0; prop2 = 0; } @_expose(Cxx, "initWithValue") public init(why x: Int) { y = x; prop = 0; prop2 = 0; } @_expose(Cxx, "renamedProp") public var prop: Int @_expose(Cxx, "prop3") public let prop2: Int @_expose(Cxx, "renamedMethod") public func method() {} public func getNonExposedStruct() -> NotExposedStruct { return NotExposedStruct(x: 2) } // FIXME: if 'getNonExposedStruct' has explicit @_expose we should error in Sema. public func passNonExposedStruct(_ x: NotExposedStruct) { } // FIXME: if 'passNonExposedStruct' has explicit @_expose we should error in Sema. } @_expose(Cxx) public final class ExposedClass { public func method() {} } // CHECK: class ExposedClass final // CHECK: class ExposedStruct final { // CHECK: class ExposedStruct2 final { // CHECK: ExposedStruct2(ExposedStruct2 &&) // CHECK-NEXT: swift::Int getY() const; // CHECK-NEXT: void setY(swift::Int value); // CHECK-NEXT: static inline ExposedStruct2 init(); // CHECK-NEXT: static inline ExposedStruct2 initWithValue(swift::Int x); // CHECK-NEXT: swift::Int getRenamedProp() const; // CHECK-NEXT: void setRenamedProp(swift::Int value); // CHECK-NEXT: swift::Int getProp3() const; // CHECK-NEXT: void renamedMethod() const; // CHECK-NEXT: private: // CHECK: inline void exposed1() noexcept { // CHECK-NEXT: return _impl::$s6Expose8exposed1yyF(); // CHECK-NEXT: } // CHECK-EMPTY: // CHECK-EMPTY: // CHECK-NEXT: inline void exposed3() noexcept { // CHECK-NEXT: return _impl::$s6Expose8exposed3yyF(); // CHECK-NEXT: } // CHECK-EMPTY: // CHECK-EMPTY: // CHECK-NEXT: inline void exposed4() noexcept { // CHECK-NEXT: return _impl::$s6Expose15exposed4RenamedyyF(); // CHECK-NEXT: } // CHECK: void ExposedClass::method() // CHECK: swift::Int ExposedStruct::getX() const { // CHECK: void ExposedStruct::setX(swift::Int value) { // CHECK: void ExposedStruct::method() const { // CHECK: swift::Int ExposedStruct2::getY() const { // CHECK: void ExposedStruct2::setY(swift::Int value) { // CHECK: ExposedStruct2 ExposedStruct2::init() { // CHECK: ExposedStruct2 ExposedStruct2::initWithValue(swift::Int x) { // CHECK: swift::Int ExposedStruct2::getRenamedProp() const { // CHECK: void ExposedStruct2::setRenamedProp(swift::Int value) { // CHECK: swift::Int ExposedStruct2::getProp3() const { // CHECK: void ExposedStruct2::renamedMethod() const { // CHECK-NOT: NonExposedStruct
apache-2.0
stephencelis/SQLite.swift
Sources/SQLite/Typed/CustomFunctions.swift
1
8237
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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 extension Connection { /// Creates or redefines a custom SQL function. /// /// - Parameters: /// /// - function: The name of the function to create or redefine. /// /// - deterministic: Whether or not the function is deterministic (_i.e._ /// the function always returns the same result for a given input). /// /// Default: `false` /// /// - block: A block of code to run when the function is called. /// The assigned types must be explicit. /// /// - Returns: A closure returning an SQL expression to call the function. func createFunction<Z: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z) throws -> () -> Expression<Z> { let fn = try createFunction(function, 0, deterministic) { _ in block() } return { fn([]) } } func createFunction<Z: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z?) throws -> () -> Expression<Z?> { let fn = try createFunction(function, 0, deterministic) { _ in block() } return { fn([]) } } // MARK: - func createFunction<Z: Value, A: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z) throws -> (Expression<A>) -> Expression<Z> { let fn = try createFunction(function, 1, deterministic) { args in block(value(args[0])) } return { arg in fn([arg]) } } func createFunction<Z: Value, A: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z) throws -> (Expression<A?>) -> Expression<Z> { let fn = try createFunction(function, 1, deterministic) { args in block(args[0].map(value)) } return { arg in fn([arg]) } } func createFunction<Z: Value, A: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z?) throws -> (Expression<A>) -> Expression<Z?> { let fn = try createFunction(function, 1, deterministic) { args in block(value(args[0])) } return { arg in fn([arg]) } } func createFunction<Z: Value, A: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z?) throws -> (Expression<A?>) -> Expression<Z?> { let fn = try createFunction(function, 1, deterministic) { args in block(args[0].map(value)) } return { arg in fn([arg]) } } // MARK: - func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B) -> Z) throws -> (Expression<A>, Expression<B>) -> Expression<Z> { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), value(args[1])) } return { a, b in fn([a, b]) } } func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B) -> Z) throws -> (Expression<A?>, Expression<B>) -> Expression<Z> { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), value(args[1])) } return { a, b in fn([a, b]) } } func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B?) -> Z) throws -> (Expression<A>, Expression<B?>) -> Expression<Z> { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), args[1].map(value)) } return { a, b in fn([a, b]) } } func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B) -> Z?) throws -> (Expression<A>, Expression<B>) -> Expression<Z?> { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), value(args[1])) } return { a, b in fn([a, b]) } } func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B?) -> Z) throws -> (Expression<A?>, Expression<B?>) -> Expression<Z> { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), args[1].map(value)) } return { a, b in fn([a, b]) } } func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B) -> Z?) throws -> (Expression<A?>, Expression<B>) -> Expression<Z?> { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), value(args[1])) } return { a, b in fn([a, b]) } } func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B?) -> Z?) throws -> (Expression<A>, Expression<B?>) -> Expression<Z?> { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), args[1].map(value)) } return { a, b in fn([a, b]) } } func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B?) -> Z?) throws -> (Expression<A?>, Expression<B?>) -> Expression<Z?> { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), args[1].map(value)) } return { a, b in fn([a, b]) } } // MARK: - fileprivate func createFunction<Z: Value>(_ function: String, _ argumentCount: UInt, _ deterministic: Bool, _ block: @escaping ([Binding?]) -> Z) throws -> ([Expressible]) -> Expression<Z> { createFunction(function, argumentCount: argumentCount, deterministic: deterministic) { arguments in block(arguments).datatypeValue } return { arguments in function.quote().wrap(", ".join(arguments)) } } fileprivate func createFunction<Z: Value>(_ function: String, _ argumentCount: UInt, _ deterministic: Bool, _ block: @escaping ([Binding?]) -> Z?) throws -> ([Expressible]) -> Expression<Z?> { createFunction(function, argumentCount: argumentCount, deterministic: deterministic) { arguments in block(arguments)?.datatypeValue } return { arguments in function.quote().wrap(", ".join(arguments)) } } }
mit
wavecos/curso_ios_3
Playgrounds/Condicionales.playground/section-1.swift
1
537
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var saludo = "Hola Mundo" let edadJuan = 21 let edadAna = 34 let edadMaria = 1 if edadJuan > 20 { println("Juan es Mayor de edad") } else { println("Debe ir a dormir") } if edadMaria > edadAna { println("Maria es mamá de Ana") } else if edadAna < edadJuan { println("Ana es la hermana menor de Juán") } else { println("todos son menores") } if edadJuan > 20 && edadAna > 20 { println("Juan y Ana son adultos") }
apache-2.0
motoom/ios-apps
TraceMaze/TraceMaze/Maze.swift
1
3779
import Foundation /* struct PhysicsCategory { static let None : UInt32 = 0 static let All : UInt32 = UInt32.max static let Monster : UInt32 = 0b1 // 1 static let Projectile: UInt32 = 0b10 // 2 } */ let WALLNORTH = 1 // Walls let WALLEAST = 2 let WALLSOUTH = 4 let WALLWEST = 8 let VISITED = 16 // Used during maze generation let NORTH = 0 let EAST = 1 let SOUTH = 2 let WEST = 3 class Maze { var rowcount: Int = 0 var colcount: Int = 0 var cells: Array<Array<Int>> // Wall bits for NORTH, EAST, SOUTH, WEST let wallbit = [WALLNORTH, WALLEAST, WALLSOUTH, WALLWEST] // Coordinate offsets for NORTH, EAST, SOUTH, WEST let drow = [-1, 0, 1, 0] let dcol = [0, 1, 0, -1] // Directions opposite of NORTH, EAST, SOUTH, WEST let opposite = [SOUTH, WEST, NORTH, EAST] init(_ rowcount: Int, _ colcount: Int) { self.rowcount = rowcount self.colcount = colcount // See http://stackoverflow.com/questions/25127700/two-dimensional-array-in-swift cells = Array(count: rowcount, repeatedValue: Array(count: colcount, repeatedValue: 0)) generate() } func generateStep(row: Int, _ col: Int) { var directions = [NORTH, EAST, SOUTH, WEST] // Randomize the directions, so the path will meander. for a in 0 ..< 4 { let b = Int(arc4random() & 3) (directions[a], directions[b]) = (directions[b], directions[a]) } // Iterate over the directions. for dir in 0 ..< 4 { // Determine the coordinates of the cell in that direction. let direction = directions[dir] let newrow = row + drow[direction] let newcol = col + dcol[direction] // Decide if the cell is valid or not. Skip cells outside the maze. if newrow < 0 || newrow >= rowcount { continue } if newcol < 0 || newcol >= colcount { continue } // New cell must not have been previously visited. if cells[newrow][newcol] & VISITED != 0 { continue } // Cut down the walls. cells[row][col] &= ~wallbit[direction] cells[row][col] |= VISITED cells[newrow][newcol] &= ~wallbit[opposite[direction]] cells[newrow][newcol] |= VISITED generateStep(newrow, newcol) } } // Maze generation according to http://weblog.jamisbuck.org/2010/12/27/maze-generation-recursive-backtracking func generate() { // Start with all walls up, also clears 'visited' bit. for r in 0 ..< rowcount { for c in 0 ..< colcount { cells[r][c] = WALLNORTH|WALLEAST|WALLSOUTH|WALLWEST } } // ...and generate the maze from the middle. generateStep(rowcount / 2, colcount / 2) } func asciiRepresentation() -> String { var s = " " for _ in 0 ..< self.colcount * 2 - 1 { s += "_" } s += "\n" for r in 0 ..< self.rowcount { s += "|" for c in 0 ..< self.colcount { if cells[r][c] & WALLSOUTH != 0 { if cells[r][c] & WALLEAST != 0 { s += "_|" // └├┤└┐┣╋━┃ } else { s += "__" } } else { if cells[r][c] & WALLEAST != 0 { s += " |" } else { s += " " } } } s += "\n" } return s } }
mit
godlift/XWSwiftRefresh
XWSwiftRefresh/Helper/UIViewExtension-XW.swift
2
1703
// // UIViewExtension-XW.swift // 01-drawingBoard // // Created by Xiong Wei on 15/8/8. // Copyright © 2015年 Xiong Wei. All rights reserved. // 增加frame 快速访问计算属性 import UIKit extension UIView { var xw_x:CGFloat { get{ //写下面这句不会进入 死循环 // let a = self.xw_x return self.frame.origin.x } set { self.frame.origin.x = newValue // 写下面这句不会死循环 //self.frame.origin.x = x } } var xw_y:CGFloat { get{ return self.frame.origin.y } set { self.frame.origin.y = newValue } } var xw_width:CGFloat { get{ return self.frame.size.width } set { self.frame.size.width = newValue } } var xw_height:CGFloat { get{ return self.frame.size.height } set { self.frame.size.height = newValue } } var xw_size:CGSize { get { return self.frame.size } set { self.frame.size = newValue } } var xw_origin:CGPoint { get { return self.frame.origin } set { self.frame.origin = newValue } } var xw_centerX:CGFloat { get{ return self.center.x } set { self.center.x = newValue } } var xw_centerY:CGFloat { get{ return self.center.y } set { self.center.y = newValue } } }
mit
richardpiazza/XCServerCoreData
Sources/IntegrationIssues.swift
1
8246
import Foundation import CoreData import CodeQuickKit import XCServerAPI public class IntegrationIssues: NSManagedObject { public convenience init?(managedObjectContext: NSManagedObjectContext, integration: Integration) { self.init(managedObjectContext: managedObjectContext) self.integration = integration } public func update(withIntegrationIssues issues: XCServerClient.Issues) { guard let moc = self.managedObjectContext else { Log.warn("\(#function) failed; MOC is nil") return } // Build Service Errors if let set = self.buildServiceErrors { for issue in set { issue.inverseBuildServiceErrors = nil moc.delete(issue) } } if let buildServiceErrors = issues.buildServiceErrors { for error in buildServiceErrors { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: error) issue.inverseBuildServiceErrors = self } } } // Build Service Warnings if let set = self.buildServiceWarnings { for issue in set { issue.inverseBuildServiceWarnings = nil moc.delete(issue) } } if let buildServiceWarnings = issues.buildServiceWarnings { for warning in buildServiceWarnings { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: warning) issue.inverseBuildServiceWarnings = self } } } // Errors if let errors = issues.errors { if let set = self.unresolvedErrors { for issue in set { issue.inverseUnresolvedErrors = nil moc.delete(issue) } } if let set = self.resolvedErrors { for issue in set { issue.inverseResolvedErrors = nil moc.delete(issue) } } if let set = self.freshErrors { for issue in set { issue.inverseFreshErrors = nil moc.delete(issue) } } for unresolvedIssue in errors.unresolvedIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: unresolvedIssue) issue.inverseUnresolvedErrors = self } } for resolvedIssue in errors.resolvedIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: resolvedIssue) issue.inverseResolvedErrors = self } } for freshIssue in errors.freshIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: freshIssue) issue.inverseFreshErrors = self } } } // Warnings if let warnings = issues.warnings { if let set = self.unresolvedWarnings { for issue in set { issue.inverseUnresolvedWarnings = nil moc.delete(issue) } } if let set = self.resolvedWarnings { for issue in set { issue.inverseResolvedWarnings = nil moc.delete(issue) } } if let set = self.freshWarnings { for issue in set { issue.inverseFreshWarnings = nil moc.delete(issue) } } for unresolvedIssue in warnings.unresolvedIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: unresolvedIssue) issue.inverseUnresolvedWarnings = self } } for resolvedIssue in warnings.resolvedIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: resolvedIssue) issue.inverseResolvedWarnings = self } } for freshIssue in warnings.freshIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: freshIssue) issue.inverseFreshWarnings = self } } } // Analyzer Warnings if let analyzerWarnings = issues.analyzerWarnings { if let set = self.unresolvedAnalyzerWarnings { for issue in set { issue.inverseUnresolvedAnalyzerWarnings = nil moc.delete(issue) } } if let set = self.resolvedAnalyzerWarnings { for issue in set { issue.inverseResolvedAnalyzerWarnings = nil moc.delete(issue) } } if let set = self.freshAnalyzerWarnings { for issue in set { issue.inverseFreshAnalyserWarnings = nil moc.delete(issue) } } for unresolvedIssue in analyzerWarnings.unresolvedIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: unresolvedIssue) issue.inverseUnresolvedAnalyzerWarnings = self } } for resolvedIssue in analyzerWarnings.resolvedIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: resolvedIssue) issue.inverseResolvedAnalyzerWarnings = self } } for freshIssue in analyzerWarnings.freshIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: freshIssue) issue.inverseFreshAnalyserWarnings = self } } } // Test Failures if let testFailures = issues.testFailures { if let set = self.unresolvedTestFailures { for issue in set { issue.inverseUnresolvedTestFailures = nil moc.delete(issue) } } if let set = self.resolvedTestFailures { for issue in set { issue.inverseResolvedTestFailures = nil moc.delete(issue) } } if let set = self.freshTestFailures { for issue in set { issue.inverseFreshTestFailures = nil moc.delete(issue) } } for unresolvedIssue in testFailures.unresolvedIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: unresolvedIssue) issue.inverseUnresolvedTestFailures = self } } for resolvedIssue in testFailures.resolvedIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: resolvedIssue) issue.inverseResolvedAnalyzerWarnings = self } } for freshIssue in testFailures.freshIssues { if let issue = Issue(managedObjectContext: moc) { issue.update(withIssue: freshIssue) issue.inverseFreshTestFailures = self } } } } }
mit
CoderYLiu/30DaysOfSwift
Project 07 - PullToRefresh/PullToRefresh/ViewController.swift
1
3070
// // ViewController.swift // PullToRefresh <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/13. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit class ViewController: UITableViewController { let cellIdentifer = "NewCellIdentifier" let favoriteEmoji = ["🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆"] let newFavoriteEmoji = ["🏃🏃🏃🏃🏃", "💩💩💩💩💩", "👸👸👸👸👸", "🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆" ] var emojiData = [String]() override func viewDidLoad() { super.viewDidLoad() emojiData = favoriteEmoji self.tableView.backgroundColor = UIColor(red:0.092, green:0.096, blue:0.116, alpha:1) self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifer) self.refreshControl = UIRefreshControl() self.refreshControl!.addTarget(self, action: #selector(ViewController.didRoadEmoji), for: .valueChanged) self.refreshControl!.backgroundColor = UIColor(red:0.113, green:0.113, blue:0.145, alpha:1) let attributes = [NSForegroundColorAttributeName: UIColor.white] self.refreshControl!.attributedTitle = NSAttributedString(string: "Last updated on \(Date())", attributes: attributes) self.refreshControl!.tintColor = UIColor.white self.title = "emoji" self.navigationController?.navigationBar.barStyle = UIBarStyle.blackTranslucent self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 60.0 self.tableView.tableFooterView = UIView(frame: CGRect.zero) self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none } override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return emojiData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifer)! as UITableViewCell cell.textLabel?.text = self.emojiData[indexPath.row]; cell.textLabel?.textAlignment = NSTextAlignment.center cell.textLabel?.font = UIFont.systemFont(ofSize: 50.0) cell.backgroundColor = UIColor.clear cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } // MARK: - RoadEmoji func didRoadEmoji() { self.emojiData = newFavoriteEmoji self.tableView.reloadData() self.refreshControl!.endRefreshing() } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/01832-swift-lexer-leximpl.swift
11
563
// 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 " var d { protocol b : A { typealias A : C<T }() -> Void>() -> <I : c { public var d == c<T>((self.e: Any, x } case .Type) { } }(T>(.c(c: String { func b: b[T] return x }
apache-2.0
kstaring/swift
stdlib/public/SDK/AppKit/NSError.swift
3
10044
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import AppKit extension CocoaError.Code { public static var textReadInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } public static var textWriteInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } public static var serviceApplicationNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } public static var serviceApplicationLaunchFailed: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } public static var serviceRequestTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } public static var serviceInvalidPasteboardData: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } public static var serviceMalformedServiceDictionary: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } public static var serviceMiscellaneous: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } public static var sharingServiceNotConfigured: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } // Names deprecated late in Swift 3 extension CocoaError.Code { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var textReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var textWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var serviceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var serviceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var serviceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var serviceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var serviceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var serviceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var sharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError { public static var textReadInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } public static var textWriteInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } public static var serviceApplicationNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } public static var serviceApplicationLaunchFailed: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } public static var serviceRequestTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } public static var serviceInvalidPasteboardData: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } public static var serviceMalformedServiceDictionary: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } public static var serviceMiscellaneous: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } public static var sharingServiceNotConfigured: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } // Names deprecated late in Swift 3 extension CocoaError { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var textReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var textWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var serviceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var serviceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var serviceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var serviceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var serviceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var serviceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var sharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError { public var isServiceError: Bool { return code.rawValue >= 66560 && code.rawValue <= 66817 } public var isSharingServiceError: Bool { return code.rawValue >= 67072 && code.rawValue <= 67327 } public var isTextReadWriteError: Bool { return code.rawValue >= 65792 && code.rawValue <= 66303 } } extension CocoaError { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var TextReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var ServiceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var ServiceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var ServiceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var ServiceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var ServiceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var ServiceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var SharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError.Code { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var TextReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var ServiceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var ServiceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var ServiceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var ServiceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var ServiceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var ServiceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var SharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } }
apache-2.0
mleiv/MEGameTracker
MEGameTracker/Views/Shepard Tab/Shepard Split View/ShepardSplitViewController.swift
1
762
// // ShepardSplitViewController.swift // MEGameTracker // // Created by Emily Ivie on 2/22/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit public final class ShepardSplitViewController: UIViewController, MESplitViewController { @IBOutlet weak public var mainPlaceholder: IBIncludedSubThing? @IBOutlet weak public var detailBorderLeftView: UIView? @IBOutlet weak public var detailPlaceholder: IBIncludedSubThing? public var ferriedSegue: FerriedPrepareForSegueClosure? public var dontSplitViewInPage = false @IBAction public func closeDetailStoryboard(_ sender: AnyObject?) { closeDetailStoryboard() } override public func prepare(for segue: UIStoryboardSegue, sender: Any?) { ferriedSegue?(segue.destination) } }
mit
uber/RIBs
ios/RIBs/Classes/PresentableInteractor.swift
1
1283
// // Copyright (c) 2017. Uber Technologies // // 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 /// Base class of an `Interactor` that actually has an associated `Presenter` and `View`. open class PresentableInteractor<PresenterType>: Interactor { /// The `Presenter` associated with this `Interactor`. public let presenter: PresenterType /// Initializer. /// /// - note: This holds a strong reference to the given `Presenter`. /// /// - parameter presenter: The presenter associated with this `Interactor`. public init(presenter: PresenterType) { self.presenter = presenter } // MARK: - Private deinit { LeakDetector.instance.expectDeallocate(object: presenter as AnyObject) } }
apache-2.0
jengelsma/cis657-summer2016-class-demos
Lecture04-StopWatch-Demo/Lecture04-StopWatch-DemoTests/Lecture04_StopWatch_DemoTests.swift
1
1054
// // Lecture04_StopWatch_DemoTests.swift // Lecture04-StopWatch-DemoTests // // Created by Jonathan Engelsma on 5/19/16. // Copyright © 2016 Jonathan Engelsma. All rights reserved. // import XCTest @testable import Lecture04_StopWatch_Demo class Lecture04_StopWatch_DemoTests: 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.measureBlock { // Put the code you want to measure the time of here. } } }
mit
headione/criticalmaps-ios
CriticalMapsKit/Tests/SettingsFeatureTests/SettingsViewSnapshotTests.swift
1
576
import SettingsFeature import TestHelper import XCTest class SettingsViewSnapshotTests: XCTestCase { func test_settingsView_light() { let settingsView = SettingsView( store: .init( initialState: .init(), reducer: settingsReducer, environment: SettingsEnvironment( uiApplicationClient: .noop, setUserInterfaceStyle: { _ in .none }, fileClient: .noop, backgroundQueue: .immediate, mainQueue: .immediate ) ) ) assertScreenSnapshot(settingsView, sloppy: true) } }
mit
pluralsight/PSOperations
PSOperationsAppForTestsTests/PSOperationsAppForTestsTests.swift
1
1493
import PSOperations import XCTest class PSOperationsAppForTestsTests: XCTestCase { /* This test only exhibits the problem when run in an app container, thus, it is part of a test suite that is part of an application. When you have many (less than the tested amount) operations that have dependencies often a crash occurs when all operations in the dependency chain are completed. This problem is not limited to PSOperations. If you adapt this test to use NSOperationQueue and NSBlockOperation (or some other NSOperation, doesn't matter) This same crash will occur. While meeting expectations is important the real test is whether or not it crashes when the last operation finishes */ func testDependantOpsCrash() { let queue = PSOperations.OperationQueue() let opcount = 5_000 var ops: [PSOperations.Operation] = [] for _ in 0..<opcount { let exp = expectation(description: "block should finish") let block = PSOperations.BlockOperation { finish in // NSLog("op: \(i): opcount: queue: \(queue.operationCount)") exp.fulfill() finish() } ops.append(block) } for index in 1..<opcount { let op1 = ops[index] op1.addDependency(ops[index - 1]) } queue.addOperations(ops, waitUntilFinished: false) waitForExpectations(timeout: 60 * 3, handler: nil) } }
apache-2.0
MaddTheSane/WWDC
WWDC/DownloadListProgressCellView.swift
10
915
// // DownloadListProgressCellView.swift // WWDC // // Created by Ruslan Alikhamov on 26/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa class DownloadListCellView: NSTableCellView { weak var item: AnyObject? var cancelBlock: ((AnyObject?, DownloadListCellView) -> Void)? var started: Bool = false @IBOutlet weak var progressIndicator: NSProgressIndicator! @IBOutlet weak var statusLabel: NSTextField! @IBOutlet weak var cancelButton: NSButton! @IBAction func cancelBtnPressed(sender: NSButton) { if let block = self.cancelBlock { block(self.item, self) } } override func awakeFromNib() { super.awakeFromNib() self.progressIndicator.indeterminate = true self.progressIndicator.startAnimation(nil) } func startProgress() { if (self.started) { return } self.progressIndicator.indeterminate = false self.started = true } }
bsd-2-clause
Fidetro/SwiftFFDB
Sources/FMDBConnection.swift
1
5593
// // FMDBConnection.swift // Swift-FFDB // // Created by Fidetro on 2017/10/14. // Copyright © 2017年 Fidetro. All rights reserved. // import FMDB public struct FMDBConnection:FFDBConnection { public typealias T = FMDatabase public static let share = FMDBConnection() public static var databasePath : String? private init() {} public func executeDBQuery<R:Decodable>(db:FMDatabase?, return type: R.Type, sql: String, values: [Any]?, completion: QueryResult?) throws { if let db = db { try db.executeDBQuery(return: type, sql: sql, values: values, completion: completion) } else { try database().executeDBQuery(return: type, sql: sql, values: values, completion: completion) } } public func executeDBUpdate(db:FMDatabase?, sql: String, values: [Any]?, completion: UpdateResult?) throws { if let db = db { try db.executeDBUpdate(sql: sql, values: values, completion: completion) } else { try database().executeDBUpdate(sql: sql, values: values, completion: completion) } } /// Get databaseContentFileURL /// /// - Returns: databaseURL public func databasePathURL() -> URL { if let databasePath = FMDBConnection.databasePath { return URL(fileURLWithPath: databasePath) } let executableFile = (Bundle.main.object(forInfoDictionaryKey: kCFBundleExecutableKey as String) as! String) let fileURL = try! FileManager.default .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent(executableFile+".sqlite") return fileURL } public func database() -> T { let database = FMDatabase(url: databasePathURL()) return database } public func findNewColumns(_ table:FFObject.Type) -> [String]? { var newColumns = [String]() for column in table.columnsOfSelf() { let result = columnExists(column, inTableWithName: table.tableName()) if result == false { newColumns.append(column) } } guard newColumns.count != 0 else { return nil } return newColumns } private func columnExists(_ columnName: String, inTableWithName: String) -> Bool { let database = self.database() guard database.open() else { debugPrintLog("Unable to open database") return false } let result = database.columnExists(columnName, inTableWithName: inTableWithName) return result } } extension FMDatabase { func executeDBUpdate(sql:String,values:[Any]?,completion:UpdateResult?) throws { guard open() else { debugPrintLog("Unable to open database") if let completion = completion { completion(false) } return } guard var values = values else { try self.executeUpdate(sql, values: nil) if let completion = completion { completion(true) } return } values = values.map { (ele) -> Any in if let data = ele as? Data { return data.base64EncodedString() }else if let json = ele as? [String:Any] { do{ return try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted).base64EncodedString() }catch{ debugPrintLog("\(error)") assertionFailure() } } return ele } try self.executeUpdate(sql, values: values) if let completion = completion { completion(true) } } func executeDBQuery<T:Decodable>(return type:T.Type, sql:String, values:[Any]?,completion: QueryResult?) throws { guard self.open() else { debugPrintLog("Unable to open database") if let completion = completion { completion(nil) } return } let result = try self.executeQuery(sql, values: values) var modelArray = Array<Decodable>() while result.next() { if let dict = result.resultDictionary { let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) do{ let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 decoder.dataDecodingStrategy = .base64 let model = try decoder.decode(type, from: jsonData) modelArray.append(model) }catch{ debugPrintLog(error) assertionFailure("check you func columntype,func customColumnsType,property type") } } } guard modelArray.count != 0 else { if let completion = completion { completion(nil) } return } if let completion = completion { completion(modelArray) } } }
apache-2.0