repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
22377832/ccyswift
CrashDemo/CrashDemo/AppDelegate.swift
1
5048
// // AppDelegate.swift // CrashDemo // // Created by sks on 17/2/27. // Copyright © 2017年 chen. All rights reserved. // import UIKit import CoreData import KSCrash @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let installation = KSCrashInstallationStandard.sharedInstance() installation?.url = URL(string: "https://collector.bughd.com/kscrash?key=0ecffa01cdcb0a7a1922cc15f7fa38f6") installation?.install() installation?.sendAllReports(completion: nil) BugHD.handleCrash(withKey: "0ecffa01cdcb0a7a1922cc15f7fa38f6") BugHD.setCustomizeValue(UIDevice.current.name, forKey: "DeviceName") return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "CrashDemo") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
6ec4c13fc7fc59a06d1cfa732b1edebf
48.460784
285
0.68662
5.531798
false
false
false
false
googlemaps/maps-sdk-for-ios-samples
GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/MapLayerViewController.swift
1
2544
// Copyright 2020 Google LLC. All rights reserved. // // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF // ANY KIND, either express or implied. See the License for the specific language governing // permissions and limitations under the License. import GoogleMaps import UIKit class MapLayerViewController: UIViewController { private let duration: TimeInterval = 2 private lazy var mapView: GMSMapView = { let camera = GMSCameraPosition(target: .victoria, zoom: 4) return GMSMapView(frame: .zero, camera: camera) }() override func loadView() { mapView.isMyLocationEnabled = true view = mapView navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Fly to My Location", style: .plain, target: self, action: #selector(tapMyLocation)) } @objc func tapMyLocation() { guard let location = mapView.myLocation, CLLocationCoordinate2DIsValid(location.coordinate) else { return } mapView.layer.cameraLatitude = location.coordinate.latitude mapView.layer.cameraLongitude = location.coordinate.longitude mapView.layer.cameraBearing = 0 // Access the GMSMapLayer directly to modify the following properties with a // specified timing function and duration. addMapViewAnimation(key: kGMSLayerCameraLatitudeKey, toValue: location.coordinate.latitude) addMapViewAnimation(key: kGMSLayerCameraLongitudeKey, toValue: location.coordinate.longitude) addMapViewAnimation(key: kGMSLayerCameraBearingKey, toValue: 0) // Fly out to the minimum zoom and then zoom back to the current zoom! let keyFrameAnimation = CAKeyframeAnimation(keyPath: kGMSLayerCameraZoomLevelKey) keyFrameAnimation.duration = duration let zoom = mapView.camera.zoom keyFrameAnimation.values = [zoom, kGMSMinZoomLevel, zoom] mapView.layer.add(keyFrameAnimation, forKey: kGMSLayerCameraZoomLevelKey) } func addMapViewAnimation(key: String, toValue: Double) { let animation = CABasicAnimation(keyPath: key) animation.duration = duration animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) animation.toValue = toValue mapView.layer.add(animation, forKey: key) } }
apache-2.0
3e877af3a0c4feb2e8fdcf615ef79eac
39.380952
97
0.755896
4.676471
false
false
false
false
gtranchedone/FlickrParty
FlickrPartyTests/PhotoTests.swift
1
4660
// // PhotoTests.swift // FlickrParty // // Created by Gianluca Tranchedone on 04/05/2015. // Copyright (c) 2015 Gianluca Tranchedone. All rights reserved. // import UIKit import XCTest import FlickrParty class PhotoTests: 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 testTwoDifferentPhotosAreNotEqual() { let photo1 = Photo(identifier: "photo1", title: "", details: "", ownerName: "", imageURL: NSURL(string: "apple.com")!, thumbnailURL: NSURL(string: "apple.com")!) let photo2 = Photo(identifier: "photo2", title: "", details: "", ownerName: "", imageURL: NSURL(string: "apple.com")!, thumbnailURL: NSURL(string: "apple.com")!) XCTAssertNotEqual(photo1, photo2, "Two different Photos are believed to be equal") } func testTwoPhotosAreEqualIfIdentifiersAreEqual() { let photo1 = Photo(identifier: "photo", title: "", details: "", ownerName: "", imageURL: NSURL(string: "apple.com")!, thumbnailURL: NSURL(string: "apple.com")!) let photo2 = Photo(identifier: "photo", title: "", details: "", ownerName: "", imageURL: NSURL(string: "apple.com")!, thumbnailURL: NSURL(string: "apple.com")!) XCTAssertEqual(photo1, photo2, "Two supposedly equal Photos aren't recognized as equal") } func testPhotoCanBeConvertedToDictionary() { let photo = makePhoto() let dictionaryValue = photo.dictionaryValue() let expectedDictionary = makePhotoDictionary() XCTAssertEqual(expectedDictionary, dictionaryValue) } func testPhotoWithNoURLsCanBeConvertedToDictionary() { let photo = makePhotoWithNoURLs() let dictionaryValue = photo.dictionaryValue() let expectedDictionary = makePhotoDictionaryWithNoURLs() XCTAssertEqual(expectedDictionary, dictionaryValue) } func testPhotoCanBePrintedInConsoleWithMeaningfulDescription() { let photo = makePhoto() let dictionaryValue = photo.dictionaryValue() XCTAssertEqual(photo.description, dictionaryValue.description) } func testPhotoImplementsDataRepresentableProtocolCorrectly() { let photo = makePhoto() let dataValue = photo.asData() let dictionaryValue = photo.dictionaryValue() let dataAsDictionary = try! NSJSONSerialization.JSONObjectWithData(dataValue, options: NSJSONReadingOptions.AllowFragments) as? [String : String] XCTAssertEqual(dictionaryValue, dataAsDictionary!, "Photo doesn't implement the DataRepresentable protocol correctly") } func testPhotoImplementsDataConvertibleProtocolCorrectly() { let photo = makePhoto() var photoDictionary = makePhotoDictionary() photoDictionary["description"] = photoDictionary["details"] let photoDictionaryData = try! NSJSONSerialization.dataWithJSONObject(photoDictionary, options: NSJSONWritingOptions.PrettyPrinted) let convertedPhoto = Photo.convertFromData(photoDictionaryData) XCTAssertEqual(photo, convertedPhoto!, "Photo doesn't implement the DataRepresentable protocol correctly") } private func makePhoto() -> Photo { let imageURL = NSURL(string: "https://apple.com/imageURL.jpg") let thumbnailURL = NSURL(string: "https://apple.com/thumbnailURL.jpg") let photo = Photo(identifier: "123", title: "Photo 123", details: "Some Description", ownerName: "Some Owner", imageURL: imageURL, thumbnailURL: thumbnailURL) return photo } private func makePhotoWithNoURLs() -> Photo { let photo = Photo(identifier: "123", title: "Photo 123", details: "Some Description", ownerName: "Some Owner") return photo } private func makePhotoDictionary() -> [String: String] { return ["identifier": "123", "title": "Photo 123", "details": "Some Description", "ownerName": "Some Owner", "imageURL": "https://apple.com/imageURL.jpg", "thumbnailURL": "https://apple.com/thumbnailURL.jpg"] } private func makePhotoDictionaryWithNoURLs() -> [String: String] { return ["identifier": "123", "title": "Photo 123", "details": "Some Description", "ownerName": "Some Owner", "imageURL": "", "thumbnailURL": ""] } }
mit
b2a7420b81db9f4c124adb484727fe1d
43.807692
169
0.666738
4.957447
false
true
false
false
andreaperizzato/CoreStore
CoreStoreDemo/CoreStoreDemo/List and Object Observers Demo/ListObserverDemoViewController.swift
3
9080
// // ListObserverDemoViewController.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/05/02. // Copyright (c) 2015 John Rommel Estropia. All rights reserved. // import UIKit import CoreStore private struct Static { enum Filter: String { case All = "All Colors" case Light = "Light Colors" case Dark = "Dark Colors" func next() -> Filter { switch self { case All: return .Light case Light: return .Dark case Dark: return .All } } func whereClause() -> Where { switch self { case .All: return Where(true) case .Light: return Where("brightness >= 0.9") case .Dark: return Where("brightness <= 0.4") } } } static var filter = Filter.All { didSet { self.palettes.refetch(self.filter.whereClause()) } } static let palettes: ListMonitor<Palette> = { try! CoreStore.addSQLiteStoreAndWait( fileName: "ColorsDemo.sqlite", configuration: "ObservingDemo", resetStoreOnModelMismatch: true ) return CoreStore.monitorSectionedList( From(Palette), SectionBy("colorName"), OrderBy(.Ascending("hue")) ) }() } // MARK: - ListObserverDemoViewController class ListObserverDemoViewController: UITableViewController, ListSectionObserver { // MARK: NSObject deinit { Static.palettes.removeObserver(self) } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() let navigationItem = self.navigationItem navigationItem.leftBarButtonItems = [ self.editButtonItem(), UIBarButtonItem( barButtonSystemItem: .Trash, target: self, action: "resetBarButtonItemTouched:" ) ] let filterBarButton = UIBarButtonItem( title: Static.filter.rawValue, style: .Plain, target: self, action: "filterBarButtonItemTouched:" ) navigationItem.rightBarButtonItems = [ UIBarButtonItem( barButtonSystemItem: .Add, target: self, action: "addBarButtonItemTouched:" ), filterBarButton ] self.filterBarButton = filterBarButton Static.palettes.addObserver(self) self.setTableEnabled(!Static.palettes.isPendingRefetch) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) switch (segue.identifier, segue.destinationViewController, sender) { case (.Some("ObjectObserverDemoViewController"), let destinationViewController as ObjectObserverDemoViewController, let palette as Palette): destinationViewController.palette = palette default: break } } // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return Static.palettes.numberOfSections() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Static.palettes.numberOfObjectsInSection(section) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PaletteTableViewCell") as! PaletteTableViewCell let palette = Static.palettes[indexPath] cell.colorView?.backgroundColor = palette.color cell.label?.text = palette.colorText return cell } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) self.performSegueWithIdentifier( "ObjectObserverDemoViewController", sender: Static.palettes[indexPath] ) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { switch editingStyle { case .Delete: let palette = Static.palettes[indexPath] CoreStore.beginAsynchronous{ (transaction) -> Void in transaction.delete(palette) transaction.commit { (result) -> Void in } } default: break } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return Static.palettes.sectionInfoAtIndex(section).name } // MARK: ListObserver func listMonitorWillChange(monitor: ListMonitor<Palette>) { self.tableView.beginUpdates() } func listMonitorDidChange(monitor: ListMonitor<Palette>) { self.tableView.endUpdates() } func listMonitorWillRefetch(monitor: ListMonitor<Palette>) { self.setTableEnabled(false) } func listMonitorDidRefetch(monitor: ListMonitor<Palette>) { self.filterBarButton?.title = Static.filter.rawValue self.tableView.reloadData() self.setTableEnabled(true) } // MARK: ListObjectObserver func listMonitor(monitor: ListMonitor<Palette>, didInsertObject object: Palette, toIndexPath indexPath: NSIndexPath) { self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } func listMonitor(monitor: ListMonitor<Palette>, didDeleteObject object: Palette, fromIndexPath indexPath: NSIndexPath) { self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } func listMonitor(monitor: ListMonitor<Palette>, didUpdateObject object: Palette, atIndexPath indexPath: NSIndexPath) { if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? PaletteTableViewCell { let palette = Static.palettes[indexPath] cell.colorView?.backgroundColor = palette.color cell.label?.text = palette.colorText } } func listMonitor(monitor: ListMonitor<Palette>, didMoveObject object: Palette, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { self.tableView.deleteRowsAtIndexPaths([fromIndexPath], withRowAnimation: .Automatic) self.tableView.insertRowsAtIndexPaths([toIndexPath], withRowAnimation: .Automatic) } // MARK: ListSectionObserver func listMonitor(monitor: ListMonitor<Palette>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int) { self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic) } func listMonitor(monitor: ListMonitor<Palette>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int) { self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic) } // MARK: Private private var filterBarButton: UIBarButtonItem? @IBAction private dynamic func resetBarButtonItemTouched(sender: AnyObject?) { CoreStore.beginAsynchronous { (transaction) -> Void in transaction.deleteAll(From(Palette)) transaction.commit() } } @IBAction private dynamic func filterBarButtonItemTouched(sender: AnyObject?) { Static.filter = Static.filter.next() } @IBAction private dynamic func addBarButtonItemTouched(sender: AnyObject?) { CoreStore.beginAsynchronous { (transaction) -> Void in let palette = transaction.create(Into(Palette)) palette.setInitialValues() transaction.commit() } } private func setTableEnabled(enabled: Bool) { UIView.animateWithDuration( 0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in if let tableView = self.tableView { tableView.alpha = enabled ? 1.0 : 0.5 tableView.userInteractionEnabled = enabled } }, completion: nil ) } }
mit
261e5a9cb707a16e1364da2fa67fc105
28.868421
157
0.598678
6.106254
false
false
false
false
nathawes/swift
test/Profiler/coverage_closures.swift
19
2348
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sil -module-name coverage_closures %s | %FileCheck %s // RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-ir %s func bar(arr: [(Int32) -> Int32]) { // CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 (Swift.Int32) -> Swift.Int32 in coverage_closures.bar // CHECK-NEXT: [[@LINE+1]]:13 -> [[@LINE+1]]:42 : 0 for a in [{ (b : Int32) -> Int32 in b }] { a(0) } } func foo() { // CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo() // CHECK-NEXT: [[@LINE+1]]:12 -> [[@LINE+1]]:59 : 0 let c1 = { (i1 : Int32, i2 : Int32) -> Bool in i1 < i2 } // CHECK-LABEL: sil_coverage_map {{.*}}// f1 #1 ((Swift.Int32, Swift.Int32) -> Swift.Bool) -> Swift.Bool in coverage_closures.foo() // CHECK-NEXT: [[@LINE+1]]:55 -> {{.*}}:4 : 0 func f1(_ closure : (Int32, Int32) -> Bool) -> Bool { // CHECK-LABEL: sil_coverage_map {{.*}}// implicit closure #1 () throws -> Swift.Bool in f1 // CHECK-NEXT: [[@LINE+1]]:29 -> [[@LINE+1]]:42 : 0 return closure(0, 1) && closure(1, 0) } f1(c1) // CHECK-LABEL: sil_coverage_map {{.*}}// closure #2 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo() // CHECK-NEXT: [[@LINE+1]]:6 -> [[@LINE+1]]:27 : 0 f1 { i1, i2 in i1 > i2 } // CHECK-LABEL: sil_coverage_map {{.*}}// closure #3 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo() // CHECK-NEXT: [[@LINE+3]]:6 -> [[@LINE+3]]:48 : 0 // CHECK-LABEL: sil_coverage_map {{.*}}// implicit closure #1 () throws -> {{.*}} in coverage_closures.foo // CHECK-NEXT: [[@LINE+1]]:36 -> [[@LINE+1]]:46 : 0 f1 { left, right in left == 0 || right == 1 } } // SR-2615: Display coverage for implicit member initializers without crashing struct C1 { // CHECK-LABEL: sil_coverage_map{{.*}}// variable initialization expression of coverage_closures.C1 // CHECK-NEXT: [[@LINE+1]]:24 -> [[@LINE+1]]:34 : 0 private var errors = [String]() } // rdar://39200851: Closure in init method covered twice class C2 { init() { // CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 () -> () in coverage_closures.C2.init() // CHECK-NEXT: [[@LINE+2]]:13 -> [[@LINE+4]]:6 : 0 // CHECK-NEXT: } let _ = { () in print("hello") } } }
apache-2.0
7c63678f2e257b7b2935d84acfadacc1
40.928571
160
0.598382
2.987277
false
false
false
false
synchromation/Buildasaur
BuildaKit/SyncerManager.swift
2
4660
// // SyncerManager.swift // Buildasaur // // Created by Honza Dvorsky on 10/3/15. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import ReactiveCocoa import XcodeServerSDK import BuildaHeartbeatKit import BuildaUtils //owns running syncers and their children, manages starting/stopping them, //creating them from configurations public class SyncerManager { public let storageManager: StorageManager public let factory: SyncerFactoryType public let loginItem: LoginItem public let syncersProducer: SignalProducer<[HDGitHubXCBotSyncer], NoError> public let projectsProducer: SignalProducer<[Project], NoError> public let serversProducer: SignalProducer<[XcodeServer], NoError> public let buildTemplatesProducer: SignalProducer<[BuildTemplate], NoError> public let triggerProducer: SignalProducer<[Trigger], NoError> public var syncers: [HDGitHubXCBotSyncer] private var configTriplets: SignalProducer<[ConfigTriplet], NoError> private var heartbeatManager: HeartbeatManager! public init(storageManager: StorageManager, factory: SyncerFactoryType, loginItem: LoginItem) { self.storageManager = storageManager self.loginItem = loginItem self.factory = factory self.syncers = [] let configTriplets = SyncerProducerFactory.createTripletsProducer(storageManager) self.configTriplets = configTriplets let syncersProducer = SyncerProducerFactory.createSyncersProducer(factory, triplets: configTriplets) self.syncersProducer = syncersProducer let justProjects = storageManager.projectConfigs.producer.map { $0.map { $0.1 } } let justServers = storageManager.serverConfigs.producer.map { $0.map { $0.1 } } let justBuildTemplates = storageManager.buildTemplates.producer.map { $0.map { $0.1 } } let justTriggerConfigs = storageManager.triggerConfigs.producer.map { $0.map { $0.1 } } self.projectsProducer = SyncerProducerFactory.createProjectsProducer(factory, configs: justProjects) self.serversProducer = SyncerProducerFactory.createServersProducer(factory, configs: justServers) self.buildTemplatesProducer = SyncerProducerFactory.createBuildTemplateProducer(factory, templates: justBuildTemplates) self.triggerProducer = SyncerProducerFactory.createTriggersProducer(factory, configs: justTriggerConfigs) syncersProducer.startWithNext { [weak self] in self?.syncers = $0 } self.checkForAutostart() self.setupHeartbeatManager() } private func setupHeartbeatManager() { if let heartbeatOptOut = self.storageManager.config.value["heartbeat_opt_out"] as? Bool where heartbeatOptOut { Log.info("User opted out of anonymous heartbeat") } else { Log.info("Will send anonymous heartbeat. To opt out add `\"heartbeat_opt_out\" = true` to ~/Library/Application Support/Buildasaur/Config.json") self.heartbeatManager = HeartbeatManager(server: "https://builda-ekg.herokuapp.com") self.heartbeatManager.delegate = self self.heartbeatManager.start() } } private func checkForAutostart() { guard let autostart = self.storageManager.config.value["autostart"] as? Bool where autostart else { return } self.syncers.forEach { $0.active = true } } public func xcodeServerWithRef(ref: RefType) -> SignalProducer<XcodeServer?, NoError> { return self.serversProducer.map { allServers -> XcodeServer? in return allServers.filter { $0.config.id == ref }.first } } public func projectWithRef(ref: RefType) -> SignalProducer<Project?, NoError> { return self.projectsProducer.map { allProjects -> Project? in return allProjects.filter { $0.config.value.id == ref }.first } } public func syncerWithRef(ref: RefType) -> SignalProducer<HDGitHubXCBotSyncer?, NoError> { return self.syncersProducer.map { allSyncers -> HDGitHubXCBotSyncer? in return allSyncers.filter { $0.config.value.id == ref }.first } } deinit { self.stopSyncers() } public func startSyncers() { self.syncers.forEach { $0.active = true } } public func stopSyncers() { self.syncers.forEach { $0.active = false } } } extension SyncerManager: HeartbeatManagerDelegate { public func numberOfRunningSyncers() -> Int { return self.syncers.filter { $0.active }.count } }
mit
4cb858c8812a16f84df4d02dc95aec57
38.820513
156
0.690921
4.868339
false
true
false
false
vbudhram/firefox-ios
Storage/SQL/BrowserDB.swift
2
8598
/* 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 XCGLogger import Deferred import Shared private let log = Logger.syncLogger public typealias Args = [Any?] open class BrowserDB { fileprivate let db: SwiftData // SQLITE_MAX_VARIABLE_NUMBER = 999 by default. This controls how many ?s can // appear in a query string. open static let MaxVariableNumber = 999 public init(filename: String, secretKey: String? = nil, schema: Schema, files: FileAccessor) { log.debug("Initializing BrowserDB: \(filename).") let file = URL(fileURLWithPath: (try! files.getAndEnsureDirectory())).appendingPathComponent(filename).path if AppConstants.BuildChannel == .developer && secretKey != nil { log.debug("Will attempt to use encrypted DB: \(file) with secret = \(secretKey ?? "nil")") } self.db = SwiftData(filename: file, key: secretKey, prevKey: nil, schema: schema, files: files) } // Remove the DB op from the queue (by marking it cancelled), and if it is already running tell sqlite to cancel it. // At any point the operation could complete on another thread, so it is held weakly. // Swift compiler bug: failing to compile WeakRef<Cancellable> here. public func cancel(databaseOperation: WeakRef<AnyObject>) { weak var databaseOperation = databaseOperation.value as? Cancellable db.suspendQueue() defer { db.resumeQueue() } databaseOperation?.cancel() if databaseOperation?.running ?? false { db.cancel() } } // For testing purposes or other cases where we want to ensure that this `BrowserDB` // instance has been initialized (schema is created/updated). public func touch() -> Success { return withConnection { connection -> Void in guard let _ = connection as? ConcreteSQLiteDBConnection else { throw DatabaseError(description: "Could not establish a database connection") } } } /* * Opening a WAL-using database with a hot journal cannot complete in read-only mode. * The supported mechanism for a read-only query against a WAL-using SQLite database is to use PRAGMA query_only, * but this isn't all that useful for us, because we have a mixed read/write workload. */ @discardableResult func withConnection<T>(flags: SwiftData.Flags = .readWriteCreate, _ callback: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> { return db.withConnection(flags, callback) } func transaction<T>(_ callback: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> { return db.transaction(callback) } @discardableResult func vacuum() -> Success { log.debug("Vacuuming a BrowserDB.") return withConnection({ connection -> Void in try connection.vacuum() }) } @discardableResult func checkpoint() -> Success { log.debug("Checkpointing a BrowserDB.") return transaction { connection in connection.checkpoint() } } public class func varlist(_ count: Int) -> String { return "(" + Array(repeating: "?", count: count).joined(separator: ", ") + ")" } enum InsertOperation: String { case Insert = "INSERT" case Replace = "REPLACE" case InsertOrIgnore = "INSERT OR IGNORE" case InsertOrReplace = "INSERT OR REPLACE" case InsertOrRollback = "INSERT OR ROLLBACK" case InsertOrAbort = "INSERT OR ABORT" case InsertOrFail = "INSERT OR FAIL" } /** * Insert multiple sets of values into the given table. * * Assumptions: * 1. The table exists and contains the provided columns. * 2. Every item in `values` is the same length. * 3. That length is the same as the length of `columns`. * 4. Every value in each element of `values` is non-nil. * * If there are too many items to insert, multiple individual queries will run * in sequence. * * A failure anywhere in the sequence will cause immediate return of failure, but * will not roll back — use a transaction if you need one. */ func bulkInsert(_ table: String, op: InsertOperation, columns: [String], values: [Args]) -> Success { // Note that there's a limit to how many ?s can be in a single query! // So here we execute 999 / (columns * rows) insertions per query. // Note that we can't use variables for the column names, so those don't affect the count. if values.isEmpty { log.debug("No values to insert.") return succeed() } let variablesPerRow = columns.count // Sanity check. assert(values[0].count == variablesPerRow) let cols = columns.joined(separator: ", ") let queryStart = "\(op.rawValue) INTO \(table) (\(cols)) VALUES " let varString = BrowserDB.varlist(variablesPerRow) let insertChunk: ([Args]) -> Success = { vals -> Success in let valuesString = Array(repeating: varString, count: vals.count).joined(separator: ", ") let args: Args = vals.flatMap { $0 } return self.run(queryStart + valuesString, withArgs: args) } let rowCount = values.count if (variablesPerRow * rowCount) < BrowserDB.MaxVariableNumber { return insertChunk(values) } log.debug("Splitting bulk insert across multiple runs. I hope you started a transaction!") let rowsPerInsert = (999 / variablesPerRow) let chunks = chunk(values, by: rowsPerInsert) log.debug("Inserting in \(chunks.count) chunks.") // There's no real reason why we can't pass the ArraySlice here, except that I don't // want to keep fighting Swift. return walk(chunks, f: { insertChunk(Array($0)) }) } func write(_ sql: String, withArgs args: Args? = nil) -> Deferred<Maybe<Int>> { return withConnection { connection -> Int in try connection.executeChange(sql, withArgs: args) let modified = connection.numberOfRowsModified log.debug("Modified rows: \(modified).") return modified } } public func forceClose() { db.forceClose() } public func reopenIfClosed() { db.reopenIfClosed() } func run(_ sql: String, withArgs args: Args? = nil) -> Success { return run([(sql, args)]) } func run(_ commands: [String]) -> Success { return run(commands.map { (sql: $0, args: nil) }) } /** * Runs an array of SQL commands. Note: These will all run in order in a transaction and will block * the caller's thread until they've finished. If any of them fail the operation will abort (no more * commands will be run) and the transaction will roll back, returning a DatabaseError. */ func run(_ commands: [(sql: String, args: Args?)]) -> Success { if commands.isEmpty { return succeed() } return transaction { connection -> Void in for (sql, args) in commands { try connection.executeChange(sql, withArgs: args) } } } func runQuery<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>> { return withConnection { connection -> Cursor<T> in connection.executeQuery(sql, factory: factory, withArgs: args) } } func runQueryUnsafe<T, U>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T, block: @escaping (Cursor<T>) throws -> U) -> Deferred<Maybe<U>> { return withConnection { connection -> U in let cursor = connection.executeQueryUnsafe(sql, factory: factory, withArgs: args) defer { cursor.close() } return try block(cursor) } } func queryReturnsResults(_ sql: String, args: Args? = nil) -> Deferred<Maybe<Bool>> { return runQuery(sql, args: args, factory: { _ in true }) >>== { deferMaybe($0[0] ?? false) } } func queryReturnsNoResults(_ sql: String, args: Args? = nil) -> Deferred<Maybe<Bool>> { return runQuery(sql, args: nil, factory: { _ in false }) >>== { deferMaybe($0[0] ?? true) } } }
mpl-2.0
a33a95cbe71b7a21e28e2cec1df230d1
37.375
182
0.62343
4.565056
false
false
false
false
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/ListViewController/View/ListViewCell.swift
1
3409
// // ListViewCell.swift // XMLYDemo // // Created by xiudou on 2016/12/27. // Copyright © 2016年 CoderST. All rights reserved. // import UIKit class ListViewCell: UICollectionViewCell { fileprivate lazy var iconImageView : UIImageView = { let iconImageView = UIImageView() iconImageView.contentMode = .scaleAspectFill iconImageView.clipsToBounds = true return iconImageView }() fileprivate lazy var titleLabel : UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: 14) titleLabel.numberOfLines = 2 return titleLabel }() fileprivate lazy var firstLabel : UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: 12) return titleLabel }() fileprivate lazy var twoLabel : UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: 12) return titleLabel }() fileprivate lazy var lineView : UIView = { let lineView = UIView() lineView.backgroundColor = UIColor.gray.withAlphaComponent(0.5) return lineView }() var listModel : ListModel?{ didSet{ guard let listModel = listModel else { return } iconImageView.sd_setImage( with: URL(string: listModel.coverPath ), placeholderImage: UIImage(named: "placeholder_image")) titleLabel.text = listModel.title firstLabel.text = listModel.firstKResults.first?.title if listModel.firstKResults.count > 1 { twoLabel.text = listModel.firstKResults[1].title } } } override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = UIColor.white contentView.addSubview(iconImageView) contentView.addSubview(titleLabel) contentView.addSubview(firstLabel) contentView.addSubview(twoLabel) contentView.addSubview(lineView) iconImageView.snp.makeConstraints { (make) in make.top.equalTo(contentView).offset(10) make.left.equalTo(contentView).offset(10) make.bottom.equalTo(contentView).offset(-10) make.width.equalTo(contentView.bounds.height - 20) } titleLabel.snp.makeConstraints { (make) in make.left.equalTo(iconImageView.snp.right).offset(10) make.right.equalTo(contentView.snp.right).offset(-10) make.top.equalTo(iconImageView) } firstLabel.snp.makeConstraints { (make) in make.left.equalTo(titleLabel) make.right.equalTo(titleLabel) make.top.equalTo(titleLabel.snp.bottom).offset(5) } twoLabel.snp.makeConstraints { (make) in make.left.equalTo(titleLabel) make.right.equalTo(titleLabel) make.top.equalTo(firstLabel.snp.bottom).offset(5) } lineView.snp.makeConstraints { (make) in make.left.equalTo(titleLabel) make.right.bottom.equalTo(contentView) make.height.equalTo(0.5) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
4db65386d44ea72f0c2d3572a6e116cb
30.537037
134
0.603641
4.929088
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/Mesh/ControlPanel/Gen3SetupControlPanelCellType.swift
1
12567
// // Created by Raimundas Sakalauskas on 2019-04-17. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation enum Gen3SetupControlPanelCellType { case name case notes case wifi case cellular case ethernet case mesh case documentation case unclaim case actionNewWifi case actionManageWifi case actionChangeSimStatus case actionChangeDataLimit case actionChangePinsStatus case actionPromoteToGateway case actionDemoteFromGateway case meshInfoNetworkName case meshInfoNetworkID case meshInfoNetworkExtPanID case meshInfoNetworkPanID case meshInfoNetworkChannel case meshInfoNetworkDeviceCount case meshInfoDeviceRole case wifiInfoSSID case wifiInfoChannel case wifiInfoRSSI case actionLeaveMeshNetwork case actionAddToMeshNetwork func getCellTitle(context: Gen3SetupContext) -> String { switch self { case .name: return Gen3SetupStrings.ControlPanel.Root.Name case .notes: return Gen3SetupStrings.ControlPanel.Root.Notes case .wifi: return Gen3SetupStrings.ControlPanel.Root.Wifi case .cellular: return Gen3SetupStrings.ControlPanel.Root.Cellular case .ethernet: return Gen3SetupStrings.ControlPanel.Root.Ethernet case .mesh: return Gen3SetupStrings.ControlPanel.Root.Mesh case .documentation: return Gen3SetupStrings.ControlPanel.Root.Documentation case .unclaim: return Gen3SetupStrings.ControlPanel.Root.UnclaimDevice case .actionNewWifi: return Gen3SetupStrings.ControlPanel.Wifi.AddNewWifi case .actionManageWifi: return Gen3SetupStrings.ControlPanel.Wifi.ManageWifi case .wifiInfoSSID: return Gen3SetupStrings.ControlPanel.Wifi.SSID case .wifiInfoChannel: return Gen3SetupStrings.ControlPanel.Wifi.Channel case .wifiInfoRSSI: return Gen3SetupStrings.ControlPanel.Wifi.RSSI case .actionChangeSimStatus: return Gen3SetupStrings.ControlPanel.Cellular.ChangeSimStatus case .actionChangeDataLimit: return Gen3SetupStrings.ControlPanel.Cellular.ChangeDataLimit case .actionChangePinsStatus: return Gen3SetupStrings.ControlPanel.Ethernet.ChangePinsStatus case .meshInfoNetworkName: return Gen3SetupStrings.ControlPanel.Mesh.NetworkName case .meshInfoNetworkID: return Gen3SetupStrings.ControlPanel.Mesh.NetworkID case .meshInfoNetworkExtPanID: return Gen3SetupStrings.ControlPanel.Mesh.NetworkExtPanID case .meshInfoNetworkPanID: return Gen3SetupStrings.ControlPanel.Mesh.NetworkPanID case .meshInfoNetworkChannel: return Gen3SetupStrings.ControlPanel.Mesh.NetworkChannel case .meshInfoNetworkDeviceCount: return Gen3SetupStrings.ControlPanel.Mesh.DeviceCount case .meshInfoDeviceRole: return Gen3SetupStrings.ControlPanel.Mesh.DeviceRole case .actionLeaveMeshNetwork: return Gen3SetupStrings.ControlPanel.Mesh.LeaveNetwork case .actionAddToMeshNetwork: return Gen3SetupStrings.ControlPanel.Mesh.AddToNetwork case .actionPromoteToGateway: return Gen3SetupStrings.ControlPanel.Mesh.PromoteToGateway case .actionDemoteFromGateway: return Gen3SetupStrings.ControlPanel.Mesh.DemoteFromGateway } } func getCellDetails(context: Gen3SetupContext) -> String? { switch self { case .actionChangeSimStatus: if context.targetDevice.sim!.status! == .activate { return Gen3SetupStrings.ControlPanel.Cellular.Active } else if (context.targetDevice.sim!.status! == .inactiveDataLimitReached) { return Gen3SetupStrings.ControlPanel.Cellular.Paused } else if (context.targetDevice.sim!.status! == .inactiveNeverActivated) { return Gen3SetupStrings.ControlPanel.Cellular.NeverActivated } else { return Gen3SetupStrings.ControlPanel.Cellular.Inactive } case .actionChangePinsStatus: return context.targetDevice.ethernetDetectionFeature! ? Gen3SetupStrings.ControlPanel.Ethernet.Active : Gen3SetupStrings.ControlPanel.Ethernet.Inactive case .actionChangeDataLimit: return context.targetDevice.sim!.dataLimit! > -1 ? Gen3SetupStrings.ControlPanel.Cellular.DataLimit.DataLimitValue.replacingOccurrences(of: "{{dataLimit}}", with: String(context.targetDevice.sim!.dataLimit!)) : Gen3SetupStrings.ControlPanel.Cellular.DataLimit.DataLimitValueNone case .name: return context.targetDevice.name case .notes: return context.targetDevice.notes case .meshInfoNetworkName: if let _ = context.targetDevice.meshNetworkInfo { return context.targetDevice.meshNetworkInfo!.name } else { return Gen3SetupStrings.ControlPanel.Mesh.NoNetworkInfo } case .meshInfoNetworkID: return context.targetDevice.meshNetworkInfo!.networkID case .meshInfoNetworkExtPanID: return context.targetDevice.meshNetworkInfo!.extPanID case .meshInfoNetworkPanID: return String(context.targetDevice.meshNetworkInfo!.panID) case .meshInfoNetworkChannel: return String(context.targetDevice.meshNetworkInfo!.channel) case .meshInfoNetworkDeviceCount: if let apiNetworks = context.apiNetworks { for network in apiNetworks { if (context.targetDevice.meshNetworkInfo!.networkID == network.id) { return String(network.deviceCount) } } } return nil case .meshInfoDeviceRole: //BUG: fix a bug where this is called for device that has no network role return (context.targetDevice.networkRole ?? .node) == .gateway ? Gen3SetupStrings.ControlPanel.Mesh.DeviceRoleGateway : Gen3SetupStrings.ControlPanel.Mesh.DeviceRoleNode case .wifiInfoSSID: if let _ = context.targetDevice.wifiNetworkInfo { return context.targetDevice.wifiNetworkInfo!.ssid } else { return Gen3SetupStrings.ControlPanel.Wifi.NoNetworkInfo } case .wifiInfoChannel: return String(context.targetDevice.wifiNetworkInfo!.channel) case .wifiInfoRSSI: return String(context.targetDevice.wifiNetworkInfo!.rssi) default: return nil } } func getCellEnabled(context: Gen3SetupContext) -> Bool { switch self { case .actionChangeSimStatus: return false case .meshInfoNetworkName, .meshInfoNetworkID, .meshInfoNetworkExtPanID, .meshInfoNetworkPanID, .meshInfoNetworkPanID, .meshInfoNetworkChannel, .meshInfoDeviceRole, .meshInfoNetworkDeviceCount: return false case .wifiInfoChannel, .wifiInfoRSSI, .wifiInfoSSID: return false case .actionChangeDataLimit: return context.targetDevice.sim!.dataLimit! > -1 default: return true } } func getIcon(context: Gen3SetupContext) -> UIImage? { switch self { case .wifi: return UIImage(named: "Gen3SetupWifiIcon") case .cellular: return UIImage(named: "Gen3SetupCellularIcon") case .ethernet: return UIImage(named: "Gen3SetupEthernetIcon") case .mesh: return UIImage(named: "Gen3SetupMeshIcon") default: return nil } } func getDisclosureIndicator(context: Gen3SetupContext) -> UITableViewCell.AccessoryType { switch self { case .unclaim, .actionLeaveMeshNetwork: return .none case .meshInfoNetworkName, .meshInfoNetworkID, .meshInfoNetworkExtPanID, .meshInfoNetworkPanID, .meshInfoNetworkPanID, .meshInfoNetworkChannel, .meshInfoNetworkDeviceCount, .meshInfoDeviceRole: return .none case .wifiInfoChannel, .wifiInfoRSSI, .wifiInfoSSID: return .none case .actionChangeSimStatus: return .none default: return .disclosureIndicator } } static func prepareTableView(_ tableView: UITableView) { tableView.register(UINib.init(nibName: "Gen3SetupBasicCell", bundle: nil), forCellReuseIdentifier: "Gen3SetupBasicCell") tableView.register(UINib.init(nibName: "Gen3SetupBasicIconCell", bundle: nil), forCellReuseIdentifier: "Gen3SetupBasicIconCell") tableView.register(UINib.init(nibName: "Gen3SetupButtonCell", bundle: nil), forCellReuseIdentifier: "Gen3SetupButtonCell") tableView.register(UINib.init(nibName: "Gen3SetupSubtitleCell", bundle: nil), forCellReuseIdentifier: "Gen3SetupSubtitleCell") tableView.register(UINib.init(nibName: "Gen3SetupHorizontalDetailCell", bundle: nil), forCellReuseIdentifier: "Gen3SetupHorizontalDetailCell") } func getConfiguredCell(_ tableView: UITableView, context: Gen3SetupContext) -> Gen3SetupCell { let image = self.getIcon(context: context) let detail = self.getCellDetails(context: context) let enabled = self.getCellEnabled(context: context) let accessoryType = self.getDisclosureIndicator(context: context) var cell:Gen3SetupCell! = nil if (self == .unclaim || self == .actionLeaveMeshNetwork) { cell = tableView.dequeueReusableCell(withIdentifier: "Gen3SetupButtonCell") as! Gen3SetupCell cell.cellTitleLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: enabled ? ParticleStyle.RedTextColor : ParticleStyle.DetailsTextColor) } else if (self == .actionChangeSimStatus || self == .actionChangePinsStatus) { cell = tableView.dequeueReusableCell(withIdentifier: "Gen3SetupSubtitleCell") as! Gen3SetupCell cell.cellTitleLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor) cell.cellSubtitleLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.SmallSize, color: ParticleStyle.PrimaryTextColor) cell.cellSubtitleLabel.text = detail } else if image != nil { cell = tableView.dequeueReusableCell(withIdentifier: "Gen3SetupBasicIconCell") as! Gen3SetupCell cell.cellTitleLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: enabled ? ParticleStyle.PrimaryTextColor : ParticleStyle.DetailsTextColor) } else if detail != nil { cell = tableView.dequeueReusableCell(withIdentifier: "Gen3SetupHorizontalDetailCell") as! Gen3SetupCell cell.cellTitleLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: enabled ? ParticleStyle.PrimaryTextColor : ParticleStyle.DetailsTextColor) cell.cellDetailLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: ParticleStyle.DetailsTextColor) cell.cellDetailLabel.text = detail } else { cell = tableView.dequeueReusableCell(withIdentifier: "Gen3SetupBasicCell") as! Gen3SetupCell cell.cellTitleLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: enabled ? ParticleStyle.PrimaryTextColor : ParticleStyle.DetailsTextColor) } cell.tintColor = ParticleStyle.DisclosureIndicatorColor cell.accessoryType = accessoryType cell.cellTitleLabel.text = self.getCellTitle(context: context) cell.cellIconImageView?.image = image return cell } }
apache-2.0
bcc433da4c4495e612dcae83500425bb
45.032967
294
0.662847
5.625336
false
false
false
false
the-grid/Portal
PortalTests/Networking/Resources/Site/UpdateSiteSpec.swift
1
1591
import Mockingjay import MockingjayMatchers import Nimble import Portal import Quick import Result class UpdateSiteSpec: QuickSpec { override func spec() { describe("updating a site") { it("should result in Success") { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.protocolClasses = [MockingjayProtocol.self] as [AnyClass] + configuration.protocolClasses! let token = "token" let client = APIClient(token: token, configuration: configuration) let id = siteModel.id.UUIDString.lowercaseString let matcher = api(.PUT, "https://api.thegrid.io/site/\(id)", token: token, body: updatedSiteResponseBody) let builder = http(200) self.stub(matcher, builder: builder) let error = NSError(domain: "io.thegrid.PortalTests", code: 0, userInfo: [ NSLocalizedDescriptionKey: "Unexpected request." ]) self.stub(everything, builder: failure(error)) var responseValue: Void? var responseError: NSError? client.updateSite(updatedSiteModel) { result in responseValue = result.value responseError = result.error } expect(responseValue).toEventually(beVoid()) expect(responseError).toEventually(beNil()) } } } }
mit
2e4ad0ac7614efb6db33e2ea5bc53f9b
38.775
142
0.564425
5.806569
false
true
false
false
gscalzo/PrettyWeather
PrettyWeather/WeatherHourForecastView.swift
1
2788
// // WeatherHourForecastView.swift // PrettyWeather // // Created by Giordano Scalzo on 04/02/2015. // Copyright (c) 2015 Effective Code. All rights reserved. // import Cartography import WeatherIconsKit class WeatherHourForecastView: UIView { private var didSetupConstraints = false private let iconLabel = UILabel() private let hourLabel = UILabel() private let tempsLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() style() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { if didSetupConstraints { super.updateConstraints() return } layoutView() super.updateConstraints() didSetupConstraints = true } } // MARK: Setup private extension WeatherHourForecastView{ func setup(){ addSubview(iconLabel) addSubview(hourLabel) addSubview(tempsLabel) } } // MARK: Layout private extension WeatherHourForecastView{ func layoutView() { layout(iconLabel) { view in view.center == view.superview!.center view.height == 50 } layout(hourLabel) { view in view.centerX == view.superview!.centerX view.top == view.superview!.top } layout(tempsLabel) { view in view.centerX == view.superview!.centerX view.bottom == view.superview!.bottom } } } // MARK: Style private extension WeatherHourForecastView{ func style(){ iconLabel.textColor = UIColor.whiteColor() hourLabel.font = UIFont.latoFontOfSize(20) hourLabel.textColor = UIColor.whiteColor() tempsLabel.font = UIFont.latoFontOfSize(20) tempsLabel.textColor = UIColor.whiteColor() } } // MARK: Render extension WeatherHourForecastView{ func render(weatherCondition: WeatherCondition){ var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" hourLabel.text = dateFormatter.stringFromDate(weatherCondition.time) iconLabel.attributedText = iconStringFromIcon(weatherCondition.icon!, 30) var usesMetric = false if let localeSystem = NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem) as? Bool { usesMetric = localeSystem } if usesMetric { tempsLabel.text = "\(weatherCondition.minTempCelsius.roundToInt())° \(weatherCondition.maxTempCelsius.roundToInt())°" } else { tempsLabel.text = "\(weatherCondition.minTempFahrenheit.roundToInt())° \(weatherCondition.maxTempFahrenheit.roundToInt())°" } } }
mit
46a410d92cb4cb8cda437b01d5f68787
27.701031
135
0.641523
5.007194
false
false
false
false
moosichu/hac-website
Sources/HaCWebsiteLib/Views/Hackathons/CountDownTimer.swift
2
1470
import HaCTML import Foundation /* A count down timer for an event alongside a count down message. The two necessary things for this are a startDate and and endDate. You can also set custom messages. They will show different things based on whether the timer is counting-down to the start of the event, to the end of the event, or if the event is over. */ struct CountDownTimer : Nodeable { let startDate : Date let endDate : Date let id = "CountDownTimer\(UUID().description)" let preId = "CountDownTimerPre\(UUID().description)" // the id of the countdown message let beforeEventMessage = "Time left to start" let duringEventMessage = "Time remaining" let afterEventMessage = "Time's up!" var node: Node { return Fragment( El.Div[Attr.className => "CountDownTimer"].containing( El.Div[ Attr.className => "CountDownTimer__pre", Attr.id => preId ].containing(""), El.Div[ Attr.className => "CountDownTimer_time", Attr.id => id ].containing("YOU SHOULD SEE THE TIME REMAINING HERE"), Script( file: "Hackathons/CountDownTimer.js", definitions: [ "startDate": startDate, "endDate": endDate, "id": id, "preId": preId, "beforeEventMessage": beforeEventMessage, "duringEventMessage": duringEventMessage, "afterEventMessage" : afterEventMessage ] ) ) ) } }
mit
c219fcd8fa50279d9c091e2ef8659b38
30.956522
89
0.640816
4.495413
false
false
false
false
XCEssentials/FunctionalState
Sources/Dispatch/SomeState.swift
2
2714
/* MIT License Copyright (c) 2016 Maxim Khatskevich ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** Special container object that represents a single state, does not contain metadata about 'Subject' type. */ public struct SomeState { /** Internal state identifier that helps to distinguish one state from another. It is supposed to be unique per stateful object, regardless of the rest of the state internal member values. */ let identifier: StateIdentifier /** Closure that must be called to apply this state (when this state is NOT current yet, or current state is undefined yet, to make it current). */ let onSet: SomeMutationWithCompletion /** Closure that must be called to apply this state when this state IS already current. This might be useful to update some parameters that the state captures from the outer scope when gets called/created, while entire state stays the same. */ let onUpdate: SomeMutationWithCompletion? //--- /** The only designated constructor, intentionally inaccessible from outer scope to make the static `state(...)` functions of `Stateful` protocol exclusive way of defining states for a given class. */ init( identifier: String, onSet: @escaping SomeMutationWithCompletion, onUpdate: SomeMutationWithCompletion? ) { self.identifier = identifier self.onSet = onSet self.onUpdate = onUpdate } } //--- extension SomeState: Equatable { public static func == (left: SomeState, right: SomeState) -> Bool { return left.identifier == right.identifier } }
mit
591c732ca97d2b42db9684b870a120af
34.710526
241
0.721813
5.063433
false
false
false
false
coach-plus/ios
Pods/RxSwift/RxSwift/Observables/Do.swift
6
5342
// // Do.swift // RxSwift // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onNext: Action to invoke for each element in the observable sequence. - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter afterError: Action to invoke after errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. - returns: The source sequence with the side-effecting behavior applied. */ public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, afterError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Observable<Element> { return Do(source: self.asObservable(), eventHandler: { e in switch e { case .next(let element): try onNext?(element) case .error(let e): try onError?(e) case .completed: try onCompleted?() } }, afterEventHandler: { e in switch e { case .next(let element): try afterNext?(element) case .error(let e): try afterError?(e) case .completed: try afterCompleted?() } }, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) } } final private class DoSink<Observer: ObserverType>: Sink<Observer>, ObserverType { typealias Element = Observer.Element typealias EventHandler = (Event<Element>) throws -> Void typealias AfterEventHandler = (Event<Element>) throws -> Void private let _eventHandler: EventHandler private let _afterEventHandler: AfterEventHandler init(eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, observer: Observer, cancel: Cancelable) { self._eventHandler = eventHandler self._afterEventHandler = afterEventHandler super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { do { try self._eventHandler(event) self.forwardOn(event) try self._afterEventHandler(event) if event.isStopEvent { self.dispose() } } catch let error { self.forwardOn(.error(error)) self.dispose() } } } final private class Do<Element>: Producer<Element> { typealias EventHandler = (Event<Element>) throws -> Void typealias AfterEventHandler = (Event<Element>) throws -> Void private let _source: Observable<Element> private let _eventHandler: EventHandler private let _afterEventHandler: AfterEventHandler private let _onSubscribe: (() -> Void)? private let _onSubscribed: (() -> Void)? private let _onDispose: (() -> Void)? init(source: Observable<Element>, eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, onSubscribe: (() -> Void)?, onSubscribed: (() -> Void)?, onDispose: (() -> Void)?) { self._source = source self._eventHandler = eventHandler self._afterEventHandler = afterEventHandler self._onSubscribe = onSubscribe self._onSubscribed = onSubscribed self._onDispose = onDispose } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { self._onSubscribe?() let sink = DoSink(eventHandler: self._eventHandler, afterEventHandler: self._afterEventHandler, observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) self._onSubscribed?() let onDispose = self._onDispose let allSubscriptions = Disposables.create { subscription.dispose() onDispose?() } return (sink: sink, subscription: allSubscriptions) } }
mit
b536aec869f12e941656a40c83211c7b
46.6875
394
0.646883
5.277668
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/SavedArticlesFetcherProgressManager.swift
4
2691
/* This class is responsible for updating SavedArticlesFetcher's 'progress' object - both setting it and updating its unit counts when appropriate. It does so while being minimally invasive to SavedArticlesFetcher, observing only the SavedArticlesFetcher's 'fetchesInProcessCount'. Remember that SavedArticlesFetcher's 'progress' object is not re-used (per Apple's NSProgress docs), so you'll need to observe it to know when it gets re-set, and you'll then have to observe any properties you are interested in of the re-set progress. */ @objcMembers class SavedArticlesFetcherProgressManager: NSObject { private var fetchesInProcessCountObservation: NSKeyValueObservation? weak var delegate: SavedArticlesFetcher? = nil @objc(initWithDelegate:) public required init(with delegate: SavedArticlesFetcher) { self.delegate = delegate super.init() setup() } private func resetProgress() { self.delegate?.progress = Progress.discreteProgress(totalUnitCount: -1) } private func setup(){ self.resetProgress() fetchesInProcessCountObservation = self.delegate?.observe(\SavedArticlesFetcher.fetchesInProcessCount, options: [.new, .old]) { [weak self] (fetcher, change) in if let newValue = change.newValue?.int64Value, let oldValue = change.oldValue?.int64Value, let progress = self?.delegate?.progress { // Advance totalUnitCount if new units were added let deltaValue = newValue - oldValue let wereNewUnitsAdded = deltaValue > 0 if wereNewUnitsAdded { progress.totalUnitCount = progress.totalUnitCount + deltaValue } // Update completedUnitCount let unitsRemaining = progress.totalUnitCount - newValue progress.completedUnitCount = unitsRemaining // Reset on finish let wereAllUnitsCompleted = newValue == 0 && oldValue > 0 if wereAllUnitsCompleted { // "NSProgress objects cannot be reused. Once they’re done, they’re done. Once they’re cancelled, they’re cancelled. If you need to reuse an NSProgress, instead make a new instance and provide a mechanism so the client of your progress knows that the object has been replaced, like a notification." ( Source: https://developer.apple.com/videos/play/wwdc2015/232/ by way of https://stinkykitten.com/index.php/2017/08/13/nsprogress/ ) self?.resetProgress() } } } } }
mit
1647a86e233cfc8a66303c47c2d63015
54.895833
531
0.655982
5.366
false
false
false
false
ShengQiangLiu/arcgis-runtime-samples-ios
GeometrySample/swift/GeometrySample/Controllers/UnionDifferenceViewController.swift
4
5773
// // Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // import UIKit import ArcGIS class UnionDifferenceViewController: UIViewController, AGSMapViewLayerDelegate { @IBOutlet weak var toolbar:UIToolbar! @IBOutlet weak var mapView:AGSMapView! @IBOutlet weak var addButton:UIBarButtonItem! @IBOutlet weak var resetButton:UIBarButtonItem! @IBOutlet weak var segmentedControl:UISegmentedControl! @IBOutlet weak var userInstructions:UILabel! var sketchLayer:AGSSketchGraphicsLayer! var graphicsLayer:AGSGraphicsLayer! var unionGraphic:AGSGraphic! var differenceGraphic:AGSGraphic! override func viewDidLoad() { super.viewDidLoad() self.mapView.showMagnifierOnTapAndHold = true self.mapView.enableWrapAround() self.mapView.layerDelegate = self // Load a tiled map service let mapUrl = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer") let tiledLyr = AGSTiledMapServiceLayer(URL: mapUrl) self.mapView.addMapLayer(tiledLyr, withName:"Tiled Layer") // Symbols to display geometries let lineSymbol = AGSSimpleLineSymbol() lineSymbol.color = UIColor.yellowColor() lineSymbol.width = 4 let pointSymbol = AGSSimpleMarkerSymbol() pointSymbol.color = UIColor.redColor() pointSymbol.style = .Circle let innerSymbol = AGSSimpleFillSymbol() innerSymbol.color = UIColor.redColor().colorWithAlphaComponent(0.40) innerSymbol.outline = nil let compositeSymbol = AGSCompositeSymbol() compositeSymbol.addSymbol(lineSymbol) compositeSymbol.addSymbol(pointSymbol) compositeSymbol.addSymbol(innerSymbol) // A renderer for the graphics layer let simpleRenderer = AGSSimpleRenderer(symbol: compositeSymbol) // Create and add a graphics layer to the map self.graphicsLayer = AGSGraphicsLayer() self.graphicsLayer.renderer = simpleRenderer self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer") self.userInstructions.text = "Draw two intersecting polygons by tapping on the map" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - AGSMapView delegate func mapViewDidLoad(mapView: AGSMapView!) { // Create a sketch layer and add it to the map self.sketchLayer = AGSSketchGraphicsLayer() self.sketchLayer.geometry = AGSMutablePolygon(spatialReference: self.mapView.spatialReference) self.mapView.addMapLayer(self.sketchLayer, withName:"Sketch layer") self.mapView.touchDelegate = self.sketchLayer } //MARK: - Toolbar actions @IBAction func add() { //Get the geometry of the sketch layer let sketchGeometry = self.sketchLayer.geometry.copy() as! AGSGeometry //Create the graphic and add it to the graphics layer let graphic = AGSGraphic(geometry: sketchGeometry, symbol:nil, attributes:nil) self.graphicsLayer.addGraphic(graphic) self.sketchLayer.clear() // If we have two graphics if self.graphicsLayer.graphics.count == 2 { self.addButton.enabled = false let geometryEngine = AGSGeometryEngine() // Get the geometries from the graphics layer let geometry1 = self.graphicsLayer.graphics[0].geometry let geometry2 = self.graphicsLayer.graphics[1].geometry // Make a new graphic with the difference of the two geometries let differenceGeometry = geometryEngine.differenceOfGeometry(geometry1, andGeometry:geometry2) self.differenceGraphic = AGSGraphic(geometry: differenceGeometry, symbol:nil, attributes:nil) let geometries = [geometry1,geometry2] // Make a new graphic with the union of the geometries self.unionGraphic = AGSGraphic(geometry: geometryEngine.unionGeometries(geometries), symbol:nil, attributes:nil) self.unionDifference(self.segmentedControl) self.userInstructions.text = "Toggle union and difference" } } @IBAction func reset() { self.graphicsLayer.removeAllGraphics() self.sketchLayer.clear() self.unionGraphic = nil self.differenceGraphic = nil self.addButton.enabled = true self.userInstructions.text = "Draw two intersecting polygons by tapping on the map" } @IBAction func unionDifference(segmentedControl:UISegmentedControl) { // Set the graphic for the selected operation if self.unionGraphic != nil && self.differenceGraphic != nil { if segmentedControl.selectedSegmentIndex == 0 { self.graphicsLayer.removeAllGraphics() self.graphicsLayer.addGraphic(self.unionGraphic) } else { self.graphicsLayer.removeAllGraphics() self.graphicsLayer.addGraphic(self.differenceGraphic) } } } }
apache-2.0
ed8cd9763098cb18437a46b5799a4b41
37.231788
130
0.662221
5.310948
false
false
false
false
silence0201/Swift-Study
Swifter/37GCDDelay.playground/Contents.swift
1
1732
//: Playground - noun: a place where people can play import Foundation import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true // 创建目标队列 let workingQueue = DispatchQueue(label: "my_queue") // 派发到刚创建的队列中,GCD 会负责进行线程调度 workingQueue.async { // 在 workingQueue 中异步进行 print("努力工作") Thread.sleep(forTimeInterval: 2) // 模拟两秒的执行时间 DispatchQueue.main.async { // 返回到主线程更新 UI print("结束工作,更新 UI") } } let time: TimeInterval = 2.0 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) { print("2 秒后输出") } import Foundation typealias Task = (_ cancel : Bool) -> Void func delay(_ time: TimeInterval, task: @escaping ()->()) -> Task? { func dispatch_later(block: @escaping ()->()) { let t = DispatchTime.now() + time DispatchQueue.main.asyncAfter(deadline: t, execute: block) } var closure: (()->Void)? = task var result: Task? let delayedClosure: Task = { cancel in if let internalClosure = closure { if (cancel == false) { DispatchQueue.main.async(execute: internalClosure) } } closure = nil result = nil } result = delayedClosure dispatch_later { if let delayedClosure = result { delayedClosure(false) } } return result; } func cancel(_ task: Task?) { task?(true) } delay(2) { print("2 秒后输出") } let task = delay(5) { print("拨打 110") } // 仔细想一想.. // 还是取消为妙.. cancel(task)
mit
fc98ad0aa92d8ad8e963a4c104014203
18.625
68
0.590446
3.792271
false
false
false
false
cliffpanos/True-Pass-iOS
iOSApp/CheckIn/Constructive Controllers/LoginViewController.swift
1
7516
// // LoginViewController.swift // True Pass // // Created by Cliff Panos on 4/1/17. // Copyright © 2017 Clifford Panos. All rights reserved. // import UIKit class LoginViewController: ManagedViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var primaryView: UIView! @IBOutlet weak var titleStackView: UIStackView! @IBOutlet weak var loginTitle: UILabel! var textFieldSelected: Bool = false var textFieldManager: CPTextFieldManager! let feedbackGenerator = UINotificationFeedbackGenerator() static var preFilledEmail: String? override func viewDidLoad() { super.viewDidLoad() textFieldManager = CPTextFieldManager(textFields: [emailTextField, passwordTextField], in: self) textFieldManager.setupTextFields(withAccessory: .done) textFieldManager.setFinalReturn(keyType: .go) { self.signInPressed(Int(0)) } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) setNeedsStatusBarAppearanceUpdate() passwordTextField.text = "" if let email = LoginViewController.preFilledEmail { emailTextField.text = email LoginViewController.preFilledEmail = nil passwordTextField.becomeFirstResponder() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //Check to see if an information controller or version update controller should be shown let firstLaunchedEver = C.getFromUserDefaults(withKey: Shared.FIRST_LAUNCH_OF_APP_EVER) as? Bool ?? true if firstLaunchedEver { self.performSegue(withIdentifier: "toTruePassInfo", sender: nil) C.persistUsingUserDefaults(false, forKey: Shared.FIRST_LAUNCH_OF_APP_EVER) } } //MARK: Sign-in & Account Creation ------------------------------------------ : @IBAction func signInPressed(_ sender: Any) { feedbackGenerator.prepare() guard let email = emailTextField.text?.trimmingCharacters(in: .whitespaces), let password = passwordTextField.text?.trimmingCharacters(in: .whitespaces) else { self.showSimpleAlert("Incomplete Fields", message: "Surprise! You need to enter both an email and a password to log in.") return } Accounts.shared.standardLogin(withEmail: email, password: password, completion: { success in if success { //CHECK TO SEE IF EMAIL IS VERIFIED if let current = Accounts.shared.current, !current.isEmailVerified { self.showOptionsAlert("Email Not Yet Verified", message: "For your security, you must verify your email address before logging into your account", left: "Send Email Again", right: "OK", handlerOne: { current.sendEmailVerification(completion: { error in if let error = error { self.showSimpleAlert("Error While Resending Email", message: error.localizedDescription) } else { self.showSimpleAlert("Verification Email Sent", message: nil) } }) }) self.feedbackGenerator.notificationOccurred(.warning) return // ! -- CRITICAL -- !// } //RETRIEVE important account info to be saved in Core Data let newUserService = FirebaseService(entity: FirebaseEntity.TPUser) newUserService.retrieveData(forIdentifier: Accounts.shared.current!.uid) { object in let newUser = object as! TPUser Accounts.saveToUserDefaults(user: newUser, updateImage: true) //At this point, the user is about to be logged in self.feedbackGenerator.notificationOccurred(.success) self.loginTitle.text = "Success" self.animateOff() } } else { self.shakeTextFields() self.feedbackGenerator.notificationOccurred(.error) } }) } @IBAction func newAccount(_ sender: Any) { let vc = C.storyboard.instantiateViewController(withIdentifier: "newAccountViewController") self.view.endEditing(true) self.navigationController?.pushViewController(vc, animated: true) } //MARK: - Animations ---------------------- : func shakeTextFields() { let animation = CABasicAnimation(keyPath: "transform.translation.x") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.repeatCount = 3 animation.duration = 0.08 animation.autoreverses = true animation.byValue = 9 //how much it moves self.passwordTextField.layer.add(animation, forKey: "position") self.emailTextField.layer.add(animation, forKey: "position") } override func keyboardWillShow(notification: Notification) { guard !textFieldSelected else { return } UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.68, initialSpringVelocity: 4, options: .curveEaseIn, animations: { self.primaryView.transform = CGAffineTransform(translationX: 0, y: -75) }, completion: {_ in self.textFieldSelected = true }) } override func keyboardWillHide(notification: Notification) { guard textFieldSelected else { return } UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.68, initialSpringVelocity: 4, options: .curveEaseIn, animations: { self.primaryView.transform = CGAffineTransform(translationX: 0, y: 0) }, completion: {_ in self.textFieldSelected = false }) } func dismissKeyboard() { self.view.endEditing(true) } func animateOff() { dismissKeyboard() UIView.animate(withDuration: 0.7, delay: 0.5, usingSpringWithDamping: 0.7, initialSpringVelocity: 2.5, options: .curveEaseOut, animations: { self.primaryView.transform = CGAffineTransform(translationX: 0, y: UIScreen.main.bounds.height) self.titleStackView.transform = CGAffineTransform(translationX: 0, y: -150) }, completion: {_ in self.textFieldSelected = false C.userIsLoggedIn = true let tabBarController = C.storyboard.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController // self.present(tabBarController, animated: true, completion: { // // // }) C.appDelegate.window!.rootViewController = tabBarController C.appDelegate.tabBarController = tabBarController C.appDelegate.tabBarController.selectedIndex = 0 }) } }
apache-2.0
91151c7cf8b3d04c2d22d09b15f2464d
37.737113
219
0.600665
5.599851
false
false
false
false
kiancheong/Alamofire
Source/Alamofire.swift
11
12558
// // Alamofire.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // MARK: - URLStringConvertible /** Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ public protocol URLStringConvertible { /** A URL that conforms to RFC 2396. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. See https://tools.ietf.org/html/rfc2396 See https://tools.ietf.org/html/rfc1738 See https://tools.ietf.org/html/rfc1808 */ var URLString: String { get } } extension String: URLStringConvertible { public var URLString: String { return self } } extension NSURL: URLStringConvertible { public var URLString: String { return absoluteString } } extension NSURLComponents: URLStringConvertible { public var URLString: String { return URL!.URLString } } extension NSURLRequest: URLStringConvertible { public var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible /** Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. */ public protocol URLRequestConvertible { /// The URL request. var URLRequest: NSMutableURLRequest { get } } extension NSURLRequest: URLRequestConvertible { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } // MARK: - Convenience func URLRequest( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil) -> NSMutableURLRequest { let mutableURLRequest: NSMutableURLRequest if let request = URLString as? NSMutableURLRequest { mutableURLRequest = request } else if let request = URLString as? NSURLRequest { mutableURLRequest = request.URLRequest } else { mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) } mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return mutableURLRequest } // MARK: - Request Methods /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { return Manager.sharedInstance.request( method, URLString, parameters: parameters, encoding: encoding, headers: headers ) } /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { return Manager.sharedInstance.request(URLRequest.URLRequest) } // MARK: - Upload Methods // MARK: File /** Creates an upload request using the shared manager instance for the specified method, URL string, and file. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) } /** Creates an upload request using the shared manager instance for the specified URL request and file. - parameter URLRequest: The URL request. - parameter file: The file to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return Manager.sharedInstance.upload(URLRequest, file: file) } // MARK: Data /** Creates an upload request using the shared manager instance for the specified method, URL string, and data. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) } /** Creates an upload request using the shared manager instance for the specified URL request and data. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return Manager.sharedInstance.upload(URLRequest, data: data) } // MARK: Stream /** Creates an upload request using the shared manager instance for the specified method, URL string, and stream. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) } /** Creates an upload request using the shared manager instance for the specified URL request and stream. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(URLRequest, stream: stream) } // MARK: MultipartFormData /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( method, URLString, headers: headers, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( URLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } // MARK: - Download Methods // MARK: URL Request /** Creates a download request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download( method, URLString, parameters: parameters, encoding: encoding, headers: headers, destination: destination ) } /** Creates a download request using the shared manager instance for the specified URL request. - parameter URLRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(URLRequest, destination: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(data, destination: destination) }
mit
43a180f28e57926f493197eeb9d3e7f2
33.03252
117
0.709269
5.0232
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/SlidingPlayerController.swift
1
3028
// // SlidingPlayerController.swift // MrGreen // // Created by Benzi on 15/08/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import SpriteKit class SlidingPlayerController: PlayerController { //var hatTilted = false private var slideActivated = false func doSlide() { // if slideActivated { return } // slideActivated = true // let playerSprite = world.sprite.get(world.mainPlayer).node // let slideEffect = entitySprite("slide_effect_\(Direction.Name[moveDirection]!)") // slideEffect.size = playerSprite.size // var targetPosition = CGPointZero // let offsetAmount:CGFloat = slideEffect.size.width * 0.95 // // offset the position based on direction // switch moveDirection { // case Direction.Down: // slideEffect.position = CGPointMake(0.0, +offsetAmount) // case Direction.Up: // slideEffect.position = CGPointMake(0.0, -offsetAmount) // case Direction.Left: // slideEffect.position = CGPointMake(+offsetAmount, 0.0) // case Direction.Right: // slideEffect.position = CGPointMake(-offsetAmount, 0.0) // default: break // } // slideEffect.zPosition = playerSprite.zPosition - 1.0 // slideEffect.name = "slide_effect" // playerSprite.addChild(slideEffect) } func endSlide() { // slideActivated = false // let playerSprite = world.sprite.get(world.mainPlayer).node // let slideEffect = playerSprite.childNodeWithName("slide_effect")! // slideEffect.removeFromParent() } override init(world: WorldMapper, moveDirection: UInt) { super.init(world: world, moveDirection: moveDirection) super.name = "SlidingPlayerController" add(SlidePlayerAction(entity: world.mainPlayer, world: world, direction: moveDirection)) } override func begin() { super.begin() world.eventBus.raise(GameEvent.SlideStarted, data: world.mainPlayer) } override func end() { //if slideActivated { endSlide() } world.eventBus.raise(GameEvent.SlideCompleted, data: nil) // // check if we need to remove the slide behaviour // // slide mode // if world.slide.belongsTo(world.mainPlayer) { // let slide = world.slide.get(world.mainPlayer) // switch slide.duration { // case .Infinite: // world.eventBus.raise(GameEvent.SlideCompleted, data: slide) // case let .TurnBased(moves): // slide.duration = .TurnBased(moves-1) // world.eventBus.raise(GameEvent.SlideCompleted, data: slide) // if (moves-1) <= 0 { // world.eventBus.raise(GameEvent.SlideDeactivated, data: slide) // world.manager.removeComponent(world.mainPlayer, c: slide) // } // } // } super.end() } }
isc
fb9729d570c3e3b77304152645d6fc01
35.059524
96
0.606341
4.356835
false
false
false
false
ello/ello-ios
Specs/Helpers/SpecsTrackingAgent.swift
1
908
//// /// SpecsTrackingAgent.swift // @testable import Ello class SpecsTrackingAgent: AnalyticsAgent { var resetCalled = false var lastEvent = "" var lastUserId: String? = "" var lastTraits: [String: Any]? var lastScreenTitle = "" var lastProperties: [String: Any]? func identify(_ userId: String?, traits: [String: Any]?) { lastUserId = userId lastTraits = traits } func track(_ event: String) { lastEvent = event } func track(_ event: String, properties: [String: Any]?) { lastEvent = event lastProperties = properties } func screen(_ screenTitle: String) { lastScreenTitle = screenTitle } func screen(_ screenTitle: String, properties: [String: Any]?) { lastScreenTitle = screenTitle lastProperties = properties } func reset() { resetCalled = true } }
mit
be7d89d94e877222d281f0553606c648
20.619048
68
0.604626
4.49505
false
false
false
false
plivesey/SwiftGen
swiftgen-cli/storyboards.swift
1
1679
// // SwiftGen // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Commander import PathKit import GenumKit let storyboardsCommand = command( outputOption, templateOption(prefix: "storyboards"), templatePathOption, Option<String>("sceneEnumName", "StoryboardScene", flag: "e", description: "The name of the enum to generate for Scenes"), Option<String>("segueEnumName", "StoryboardSegue", flag: "g", description: "The name of the enum to generate for Segues"), VariadicOption<String>("import", [], description: "Additional imports to be added to the generated file"), VariadicArgument<Path>("PATH", description: "Directory to scan for .storyboard files. Can also be a path to a single .storyboard", validator: pathsExist) ) { output, templateName, templatePath, sceneEnumName, segueEnumName, extraImports, paths in let parser = StoryboardParser() do { for path in paths { if path.extension == "storyboard" { try parser.addStoryboard(at: path) } else { try parser.parseDirectory(at: path) } } let templateRealPath = try findTemplate( prefix: "storyboards", templateShortName: templateName, templateFullPath: templatePath ) let template = try GenumTemplate(templateString: templateRealPath.read(), environment: genumEnvironment()) let context = parser.stencilContext( sceneEnumName: sceneEnumName, segueEnumName: segueEnumName, extraImports: extraImports ) let rendered = try template.render(context) output.write(content: rendered, onlyIfChanged: true) } catch { printError(string: "error: \(error.localizedDescription)") } }
mit
bc6554e5cf84407b56e131dfc6e7969f
33.265306
110
0.711138
4.465426
false
false
false
false
qvacua/vimr
VimR/VimR/MainWindowReducer.swift
1
2308
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Foundation final class MainWindowReducer: ReducerType { typealias StateType = MainWindow.State typealias ActionType = UuidAction<MainWindow.Action> func typedReduce(_ tuple: ReduceTuple) -> ReduceTuple { var state = tuple.state switch tuple.action.payload { case let .frameChanged(to: frame): state.frame = frame case let .cd(to: cwd): if state.cwd != cwd { state.cwd = cwd } case let .setBufferList(buffers): state.buffers = buffers case let .newCurrentBuffer(buffer): state.currentBuffer = buffer case let .setDirtyStatus(status): // When I gt or w around, we change tab somehow... Dunno why... if status == tuple.state.isDirty { return tuple } state.isDirty = status case let .focus(view): state.viewToBeFocused = view case let .setState(for: tool, with: workspaceTool): state.tools[tool] = WorkspaceToolState( location: workspaceTool.location, dimension: workspaceTool.dimension, open: workspaceTool.isSelected ) if workspaceTool.isSelected { state.tools .filter { $0 != tool && $1.location == workspaceTool.location } .forEach { state.tools[$0.0]?.open = false } } case let .setToolsState(tools): state.orderedTools = [] tools.forEach { toolPair in let toolId = toolPair.0 let tool = toolPair.1 state.tools[toolId] = WorkspaceToolState( location: tool.location, dimension: tool.dimension, open: tool.isSelected ) if tool.isSelected { state.tools .filter { $0 != toolId && $1.location == tool.location } .forEach { state.tools[$0.0]?.open = false } } state.orderedTools.append(toolId) } case let .toggleAllTools(value): state.isAllToolsVisible = value case let .toggleToolButtons(value): state.isToolButtonsVisible = value case let .setTheme(theme): state.appearance.theme = Marked(theme) case .makeSessionTemporary: state.isTemporarySession = true default: return tuple } return (state, tuple.action, true) } }
mit
1a69af1684b0bc2bbbd92dfaa2c5703e
24.086957
73
0.616984
4.227106
false
false
false
false
mako2x/JPHoliday
JPHoliday/DateUtil.swift
1
3001
// // DateUtil.swift // JPHoliday // // Created by Komatsu, Makoto a | Mako | NEWSD on 10/12/15. // Copyright © 2015 mako2x. All rights reserved. // import Foundation /** * 日付の計算を行うクラス */ struct DateUtil { /** 指定の年月日の曜日を取得する - parameter year: 年 - parameter month: 月 - parameter day: 日 - returns: 曜日 */ static func calcWeekday(year year: Int, month: Int, day: Int) -> Int { let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! cal.locale = NSLocale(localeIdentifier: "en_US") let comp = NSDateComponents() comp.year = year comp.month = month comp.day = day let date = cal.dateFromComponents(comp)! return cal.components(NSCalendarUnit.Weekday, fromDate: date).weekday } /** 国民の休日と振替え休日を追加する - parameter orignalHolidays: 追加前の休日の配列 - returns: 追加後の休日の配列 */ static func addNationalAndSubstituteHolidays(orignalHolidays: [Holiday]) -> [Holiday] { return addNatinalHolidays(addSubstituteHolidays(orignalHolidays)) } /** 国民の休日を追加する - parameter orignalHolidays: 追加前の休日の配列 - returns: 追加後の休日の配列 */ private static func addNatinalHolidays(orignalHolidays: [Holiday]) -> [Holiday] { var holidays = [Holiday]() for h in orignalHolidays { let d = Date(year: h.year, month: h.month, day: h.day) if h.year >= 1986 && d.dateByAddingDays(-2).isContainedInHolidays(holidays) { let dateBefore1Day = d.dateByAddingDays(-1) if !dateBefore1Day.isContainedInHolidays(holidays) { let nationalHoliday = Holiday(name: "国民の休日", year: dateBefore1Day.year, month: dateBefore1Day.month, day: dateBefore1Day.day) holidays.append(nationalHoliday) } } holidays.append(h) } return holidays } /** 振替休日を追加する - parameter orignalHolidays: 追加前の休日の配列 - returns: 追加後の休日の配列 */ private static func addSubstituteHolidays(orignalHolidays: [Holiday]) -> [Holiday] { var holidays = [Holiday]() for h in orignalHolidays { holidays.append(h) if h.year < 1973 || (h.year == 1973 && h.month < 4) || h.weekday != 1 { continue } var d = Date(year: h.year, month: h.month, day: h.day) while d.isContainedInHolidays(orignalHolidays) { d = d.dateByAddingDays(1) } holidays.append(Holiday(name: "振替休日", year: d.year, month: d.month, day: d.day)) } return holidays } }
mit
be7b160883bac3866914ab1ca3e18d01
27.894737
145
0.576166
4.02346
false
false
false
false
zwaldowski/ParksAndRecreation
Latest/Keyboard Layout Guide/KeyboardLayoutGuide/KeyboardLayoutGuide.swift
1
8424
// // KeyboardLayoutGuide.swift // KeyboardLayoutGuide // // Created by Zachary Waldowski on 8/23/15. // Copyright © 2015-2016. Licensed under MIT. Some rights reserved. // import UIKit /// A keyboard layout guide may be used as an item in Auto Layout or for its /// layout anchors. public final class KeyboardLayoutGuide: UILayoutGuide { private static let didUpdate = Notification.Name(rawValue: "KeyboardLayoutGuideDidUpdateNotification") // MARK: Lifecycle private let notificationCenter: NotificationCenter private func commonInit() { notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardWillShow, object: nil) notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardWillHide, object: nil) notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardDidChangeFrame, object: nil) notificationCenter.addObserver(self, selector: #selector(noteAncestorGuideUpdate), name: KeyboardLayoutGuide.didUpdate, object: nil) notificationCenter.addObserver(self, selector: #selector(noteTextFieldDidEndEditing), name: .UITextFieldTextDidEndEditing, object: nil) } public required init?(coder aDecoder: NSCoder) { self.notificationCenter = .default super.init(coder: aDecoder) commonInit() } fileprivate init(notificationCenter: NotificationCenter) { self.notificationCenter = notificationCenter super.init() commonInit() } override convenience init() { self.init(notificationCenter: .default) } // MARK: Public API /// If assigned, the `contentInsets` of the view will be adjusted to match /// the keyboard insets. /// /// It is not necessary to track the scroll view that is managed as the /// primary view of a `UITableViewController` or /// `UICollectionViewController`. public weak var adjustContentInsetsInScrollView: UIScrollView? // MARK: Actions private var keyboardBottomConstraint: NSLayoutConstraint? private var lastScrollViewInsetDelta: CGFloat = 0 private var currentAnimator: UIViewPropertyAnimator? override public var owningView: UIView? { didSet { guard owningView !== oldValue else { return } keyboardBottomConstraint?.isActive = false keyboardBottomConstraint = nil guard let view = owningView else { return } NSLayoutConstraint.activate([ leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: trailingAnchor), topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), view.safeAreaLayoutGuide.bottomAnchor.constraint(greaterThanOrEqualTo: bottomAnchor), { let constraint = view.bottomAnchor.constraint(equalTo: bottomAnchor) constraint.priority = UILayoutPriority(rawValue: 999.5) self.keyboardBottomConstraint = constraint return constraint }() ]) } } private func update(for info: KeyboardInfo, in view: UIView, animatingWith animator: UIViewPropertyAnimator?) { keyboardBottomConstraint?.constant = info.overlap(in: view) if let animator = animator, !view.isEffectivelyDisappearing { animator.addAnimations { info.adjustForOverlap(in: self.adjustContentInsetsInScrollView, lastAppliedInset: &self.lastScrollViewInsetDelta) view.layoutIfNeeded() } } else { info.adjustForOverlap(in: adjustContentInsetsInScrollView, lastAppliedInset: &lastScrollViewInsetDelta) } } // MARK: - Notifications @objc private func noteUpdateKeyboard(_ note: Notification) { let info = KeyboardInfo(userInfo: note.userInfo) guard let view = owningView else { return } let animator = currentAnimator ?? { UIView.performWithoutAnimation(view.layoutIfNeeded) let animator = info.makeAnimator() animator.addCompletion { [weak self] _ in self?.currentAnimator = nil } self.currentAnimator = animator return animator }() update(for: info, in: view, animatingWith: animator) NotificationCenter.default.post(name: KeyboardLayoutGuide.didUpdate, object: self, userInfo: note.userInfo) animator.startAnimation() } @objc private func noteAncestorGuideUpdate(note: Notification) { guard let view = owningView, let ancestor = note.object as? KeyboardLayoutGuide, let ancestorView = ancestor.owningView, view !== ancestorView, view.isDescendant(of: ancestorView) else { return } let info = KeyboardInfo(userInfo: note.userInfo) update(for: info, in: view, animatingWith: ancestor.currentAnimator) } // <rdar://problem/30978412> UITextField contents animate in when layout performed during editing end @objc private func noteTextFieldDidEndEditing(_ note: Notification) { guard let view = owningView, let textField = note.object as? UITextField, view !== textField, textField.isDescendant(of: view), !view.isEffectivelyDisappearing else { return } UIView.performWithoutAnimation(textField.layoutIfNeeded) } } // MARK: - UIViewController extension UIViewController { private static var keyboardLayoutGuideKey = false /// For unit testing purposes only. @nonobjc internal func makeKeyboardLayoutGuide(notificationCenter: NotificationCenter) -> KeyboardLayoutGuide { assert(isViewLoaded, "This layout guide should not be accessed before the view is loaded.") let guide = KeyboardLayoutGuide(notificationCenter: notificationCenter) view.addLayoutGuide(guide) return guide } /// A keyboard layout guide is a rectangle in the layout system representing /// the area on screen not currently occupied by the keyboard; thus, it is a /// simplified model for performing layout by avoiding the keyboard. /// /// Normally, the guide is a rectangle matching the safe area of a view /// controller's view. When the keyboard is active, its bottom contracts to /// account for the keyboard. This change is animated alongside the keyboard /// animation. /// /// - seealso: KeyboardLayoutGuide @nonobjc public var keyboardLayoutGuide: KeyboardLayoutGuide { if let guide = objc_getAssociatedObject(self, &UIViewController.keyboardLayoutGuideKey) as? KeyboardLayoutGuide { return guide } let guide = makeKeyboardLayoutGuide(notificationCenter: .default) objc_setAssociatedObject(self, &UIViewController.keyboardLayoutGuideKey, guide, .OBJC_ASSOCIATION_ASSIGN) return guide } } // MARK: - private struct KeyboardInfo { let userInfo: [AnyHashable: Any]? func makeAnimator() -> UIViewPropertyAnimator { let duration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval) ?? 0.25 return UIViewPropertyAnimator(duration: duration, timingParameters: UISpringTimingParameters()) } func overlap(in view: UIView) -> CGFloat { guard let endFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect, view.canBeObscuredByKeyboard else { return 0 } let intersection = view.convert(endFrame, from: UIScreen.main.coordinateSpace).intersection(view.bounds) guard !intersection.isNull, intersection.maxY == view.bounds.maxY else { return 0 } var height = intersection.height if let scrollView = view as? UIScrollView, scrollView.contentInsetAdjustmentBehavior != .never { height -= view.safeAreaInsets.bottom } return max(height, 0) } func adjustForOverlap(in scrollView: UIScrollView?, lastAppliedInset: inout CGFloat) { guard let scrollView = scrollView else { return } let newOverlap = overlap(in: scrollView) let delta = newOverlap - lastAppliedInset lastAppliedInset = newOverlap scrollView.scrollIndicatorInsets.bottom += delta scrollView.contentInset.bottom += delta } }
mit
f7566d013cfcc608578962ea3a162622
37.99537
143
0.691915
5.490874
false
false
false
false
zisko/swift
test/SILGen/enum_resilience.swift
1
3471
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s import resilient_enum // Resilient enums are always address-only, and switches must include // a default case // CHECK-LABEL: sil hidden @$S15enum_resilience15resilientSwitchyy0c1_A06MediumOF : $@convention(thin) (@in Medium) -> () // CHECK: [[BOX:%.*]] = alloc_stack $Medium // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]] // CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5 // CHECK: bb1: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb3: // CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: [[INDIRECT:%.*]] = load [take] [[INDIRECT_ADDR]] // CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]] // CHECK-NEXT: destroy_value [[INDIRECT]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb4: // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb5: // CHECK-NEXT: unreachable // CHECK: bb6: // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] func resilientSwitch(_ m: Medium) { switch m { case .Paper: () case .Canvas: () case .Pamphlet: () case .Postcard: () } } // Indirect enums are still address-only, because the discriminator is stored // as part of the value, so we cannot resiliently make assumptions about the // enum's size // CHECK-LABEL: sil hidden @$S15enum_resilience21indirectResilientEnumyy010resilient_A016IndirectApproachOF : $@convention(thin) (@in IndirectApproach) -> () func indirectResilientEnum(_ ia: IndirectApproach) {} public enum MyResilientEnum { case kevin case loki } // CHECK-LABEL: sil @$S15enum_resilience15resilientSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in MyResilientEnum) -> () // CHECK: switch_enum_addr %2 : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2 // // CHECK: return public func resilientSwitch(_ e: MyResilientEnum) { switch e { case .kevin: () case .loki: () } } // Inlineable functions must lower the switch as if it came from outside the module // CHECK-LABEL: sil [serialized] @$S15enum_resilience16inlineableSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in MyResilientEnum) -> () // CHECK: switch_enum_addr %2 : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2, default bb3 // CHECK: return @_inlineable public func inlineableSwitch(_ e: MyResilientEnum) { switch e { case .kevin: () case .loki: () } }
apache-2.0
2dc9c468d1cb2809213d6f1405b5a624
41.851852
209
0.677615
3.474474
false
false
false
false
chaoyang805/DoubanMovie
DoubanMovie/RealmHelper.swift
1
5448
/* * Copyright 2016 chaoyang805 [email protected] * * 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 import RealmSwift class RealmHelper: NSObject { private(set) var realm: Realm override init() { let migrationBlock: MigrationBlock = { (migration, oldSchemaVersion) in if oldSchemaVersion == 1 { migration.enumerateObjects(ofType: DoubanMovie.className(), { (oldObject, newObject) in newObject!["collectDate"] = NSDate() }) } if oldSchemaVersion == 2 { migration.enumerateObjects(ofType: DoubanMovie.className(), { (oldObject, newObject) in if let directors = oldObject?["directors"] as? List<DoubanCelebrity> { newObject!["directorsDescription"] = (directors.reduce("") { $0 + "/" + $1.name }.stringByRemoveFirstCharacter() as AnyObject) } if let casts = oldObject?["casts"] as? List<DoubanCelebrity> { newObject!["castsDescription"] = (casts.reduce("") { $0 + "/" + $1.name }.stringByRemoveFirstCharacter() as AnyObject) } }) } } let config = Realm.Configuration(inMemoryIdentifier: nil, encryptionKey: nil, readOnly: false, schemaVersion: 3, migrationBlock: migrationBlock, deleteRealmIfMigrationNeeded: false, objectTypes: nil) // Realm.Configuration(inMemoryIdentifier: nil, encryptionKey: nil, readOnly: false, schemaVersion: 1, migrationBlock: nil, deleteRealmIfMigrationNeeded: true, objectTypes: nil) Realm.Configuration.defaultConfiguration = config realm = try! Realm() super.init() } func getRealmLocation() { NSLog("realm path: \(realm.configuration.fileURL)") } /** 添加电影到收藏里 - parameter movie: 要添加的电影对象 - parameter copy: 是否拷贝对象,如果拷贝的话,当删除后仍然可以访问原来的对象 */ func addFavoriteMovie(_ movie: DoubanMovie, copy: Bool = false) { realm.beginWrite() realm.add(copy ? movie.copy() as! DoubanMovie : movie, update: true) do { try realm.commitWrite() } catch { NSLog("error occured while add movie \(error)") realm.cancelWrite() } } /** 添加多个电影到收藏里 - parameter movies: 要添加的所有电影 */ func addFavoriteMovies(movies: [DoubanMovie]) { realm.beginWrite() realm.add(movies, update: true) do { try realm.commitWrite() } catch { NSLog("error occured while add movies \(error)") realm.cancelWrite() } } /** 从数据库中删除一条电影 - parameter movie: 要删除的电影 - returns: 删除是否成功 */ func deleteMovieFromFavorite(_ movie: DoubanMovie) { do { try realm.write { realm.delete(movie) } } catch { NSLog("error occured while delete a movie \(error)") realm.cancelWrite() } } /** 根据提供的id从数据库中删除一个电影条目 - parameter id: 电影的id */ func deleteMovieById(id: String) { guard let movieToDel = realm.objects(DoubanMovie.self).filter("id = %s", id).first else { return } deleteMovieFromFavorite(movieToDel) } /** 通过id 获得对应的电影条目 - parameter id: 电影id - parameter completion: 查询完成的回调 */ func getFavoriteMovie(byId id: String, completion: ((DoubanMovie?) -> Void)?) { let movie = self.realm.objects(DoubanMovie.self).filter("id = %s", id).first completion?(movie) } /** 获得所有收藏的电影 - returns: 返回当前所有收藏 */ func getAllFavoriteMovies(completion: ((Results<DoubanMovie>) -> Void)?) { let results = self.realm.objects(DoubanMovie.self) completion?(results) } /** 某个电影条目是否已经收藏 - parameter id: 电影的id - returns: 如果存在则返回true */ func movieExists(id: String) -> Bool { let exists = realm.objects(DoubanMovie.self).filter("id = %s", id).count > 0 return exists } func updateMovieInfo(updateBlock: ()-> Void) { realm.beginWrite() updateBlock() do { try realm.commitWrite() } catch { NSLog("error occured while delete a movie \(error)") realm.cancelWrite() } } }
apache-2.0
f4680429f6f27bd8f09187fd49800223
28.744186
207
0.568608
4.663628
false
false
false
false
lorentey/swift
validation-test/Reflection/reflect_Enum_TwoCaseTwoPayloads.swift
3
18813
// RUN: %empty-directory(%t) // RUN: %target-build-swift -g -lswiftSwiftReflectionTest %s -o %t/reflect_Enum_TwoCaseTwoPayloads // RUN: %target-codesign %t/reflect_Enum_TwoCaseTwoPayloads // RUN: %target-run %target-swift-reflection-test %t/reflect_Enum_TwoCaseTwoPayloads | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test import SwiftReflectionTest struct Marker { let value = 1 let extra = 2 } enum TwoCaseTwoPayloadsEnum { case valid(Marker) case invalid(Int) } class ClassWithTwoCaseTwoPayloadsEnum { var e1: TwoCaseTwoPayloadsEnum? var e2: TwoCaseTwoPayloadsEnum = .valid(Marker()) var e3: TwoCaseTwoPayloadsEnum = .invalid(7) var e4: TwoCaseTwoPayloadsEnum? = .valid(Marker()) var e5: TwoCaseTwoPayloadsEnum? = .invalid(7) var e6: TwoCaseTwoPayloadsEnum?? } reflect(object: ClassWithTwoCaseTwoPayloadsEnum()) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Enum_TwoCaseTwoPayloads.ClassWithTwoCaseTwoPayloadsEnum) // CHECK-64: Type info: // CHECK-64: (class_instance size=153 alignment=8 stride=160 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=e1 offset=16 // CHECK-64: (single_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-64: (field name=some offset=0 // CHECK-64: (multi_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-64: (field name=valid offset=0 // CHECK-64: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64: (field name=extra offset=8 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (field name=invalid offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))))) // CHECK-64: (field name=e2 offset=40 // CHECK-64: (multi_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-64: (field name=valid offset=0 // CHECK-64: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64: (field name=extra offset=8 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (field name=invalid offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (field name=e3 offset=64 // CHECK-64: (multi_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-64: (field name=valid offset=0 // CHECK-64: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64: (field name=extra offset=8 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (field name=invalid offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (field name=e4 offset=88 // CHECK-64: (single_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-64: (field name=some offset=0 // CHECK-64: (multi_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-64: (field name=valid offset=0 // CHECK-64: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64: (field name=extra offset=8 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (field name=invalid offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))))) // CHECK-64: (field name=e5 offset=112 // CHECK-64: (single_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-64: (field name=some offset=0 // CHECK-64: (multi_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-64: (field name=valid offset=0 // CHECK-64: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64: (field name=extra offset=8 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (field name=invalid offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))))) // CHECK-64: (field name=e6 offset=136 // CHECK-64: (single_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=252 bitwise_takable=1 // CHECK-64: (field name=some offset=0 // CHECK-64: (single_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-64: (field name=some offset=0 // CHECK-64: (multi_payload_enum size=17 alignment=8 stride=24 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-64: (field name=valid offset=0 // CHECK-64: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64: (field name=extra offset=8 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (field name=invalid offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Enum_TwoCaseTwoPayloads.ClassWithTwoCaseTwoPayloadsEnum) // CHECK-32: Type info: // CHECK-32: (class_instance size=77 alignment=4 stride=80 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=e1 offset=8 // CHECK-32: (single_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-32: (field name=some offset=0 // CHECK-32: (multi_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-32: (field name=valid offset=0 // CHECK-32: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32: (field name=extra offset=4 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (field name=invalid offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))))) // CHECK-32: (field name=e2 offset=20 // CHECK-32: (multi_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-32: (field name=valid offset=0 // CHECK-32: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32: (field name=extra offset=4 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (field name=invalid offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (field name=e3 offset=32 // CHECK-32: (multi_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-32: (field name=valid offset=0 // CHECK-32: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32: (field name=extra offset=4 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (field name=invalid offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (field name=e4 offset=44 // CHECK-32: (single_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-32: (field name=some offset=0 // CHECK-32: (multi_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-32: (field name=valid offset=0 // CHECK-32: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32: (field name=extra offset=4 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (field name=invalid offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))))) // CHECK-32: (field name=e5 offset=56 // CHECK-32: (single_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-32: (field name=some offset=0 // CHECK-32: (multi_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-32: (field name=valid offset=0 // CHECK-32: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32: (field name=extra offset=4 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (field name=invalid offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))))) // CHECK-32: (field name=e6 offset=68 // CHECK-32: (single_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=252 bitwise_takable=1 // CHECK-32: (field name=some offset=0 // CHECK-32: (single_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-32: (field name=some offset=0 // CHECK-32: (multi_payload_enum size=9 alignment=4 stride=12 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-32: (field name=valid offset=0 // CHECK-32: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32: (field name=extra offset=4 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (field name=invalid offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
54d0f23d96bef4d157602224465f0d76
69.992453
137
0.636315
3.503352
false
false
false
false
joeytat/JWStarRating
Classes/JWStarRatingView.swift
1
1523
// // JWStarRatingView.swift // WapaKit // // Created by Joey on 1/21/15. // Copyright (c) 2015 Joeytat. All rights reserved. // import UIKit @IBDesignable class JWStarRatingView: UIView { @IBInspectable var starColor: UIColor = UIColor(red: 200.0/255.0, green: 200.0/255.0, blue: 200.0/255.0, alpha: 1) @IBInspectable var starHighlightColor: UIColor = UIColor(red: 88.0/255.0, green: 88.0/255.0, blue: 88.0/255.0, alpha: 1) @IBInspectable var starCount:Int = 5 @IBInspectable var spaceBetweenStar:CGFloat = 10.0 #if TARGET_INTERFACE_BUILDER override func willMoveToSuperview(newSuperview: UIView?) { let starRating = JWStarRating(frame: self.bounds, starCount: self.starCount, starColor: self.starColor, starHighlightColor: self.starHighlightColor, spaceBetweenStar: self.spaceBetweenStar) addSubview(starRating) } #else override func awakeFromNib() { super.awakeFromNib() let starRating = JWStarRating(frame: self.bounds, starCount: self.starCount, starColor: self.starColor, starHighlightColor: self.starHighlightColor, spaceBetweenStar: self.spaceBetweenStar) starRating.addTarget(self, action: #selector(JWStarRatingView.valueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged) addSubview(starRating) } #endif func valueChanged(starRating:JWStarRating){ // Do something with the value... print("Value changed \(starRating.ratedStarIndex)") } }
mit
b8575ecaee10c7bc98f54d45634cf95a
38.051282
197
0.701248
4.116216
false
false
false
false
Jasonbit/YamlSwift
YamlTests/YamlTests.swift
1
16599
import Yaml import XCTest class YamlTests: XCTestCase { func testNull() { XCTAssert(Yaml.load("# comment line").value! == .Null) XCTAssert(Yaml.load("").value! == .Null) XCTAssert(Yaml.load("null").value! == .Null) XCTAssert(Yaml.load("Null").value! == nil) XCTAssert(Yaml.load("NULL").value! == nil) XCTAssert(Yaml.load("~").value! == nil) XCTAssert(Yaml.load("NuLL").value! == "NuLL") XCTAssert(Yaml.load("null#").value! == "null#") XCTAssert(Yaml.load("null#string").value! == "null#string") XCTAssert(Yaml.load("null #comment").value! == nil) let value: Yaml = nil XCTAssert(value == nil) } func testBool() { XCTAssert(Yaml.load("true").value! == .Bool(true)) XCTAssert(Yaml.load("True").value!.bool == true) XCTAssert(Yaml.load("TRUE").value! == true) XCTAssert(Yaml.load("trUE").value! == "trUE") XCTAssert(Yaml.load("true#").value! == "true#") XCTAssert(Yaml.load("true#string").value! == "true#string") XCTAssert(Yaml.load("true #comment").value! == true) XCTAssert(Yaml.load("true #").value! == true) XCTAssert(Yaml.load("true ").value! == true) XCTAssert(Yaml.load("true\n").value! == true) XCTAssert(Yaml.load("true \n").value! == true) XCTAssert(true == Yaml.load("\ntrue \n").value!) XCTAssert(Yaml.load("false").value! == .Bool(false)) XCTAssert(Yaml.load("False").value!.bool == false) XCTAssert(Yaml.load("FALSE").value! == false) XCTAssert(Yaml.load("faLSE").value! == "faLSE") XCTAssert(Yaml.load("false#").value! == "false#") XCTAssert(Yaml.load("false#string").value! == "false#string") XCTAssert(Yaml.load("false #comment").value! == false) XCTAssert(Yaml.load("false #").value! == false) XCTAssert(Yaml.load("false ").value! == false) XCTAssert(Yaml.load("false\n").value! == false) XCTAssert(Yaml.load("false \n").value! == false) XCTAssert(false == Yaml.load("\nfalse \n").value!) let value: Yaml = true XCTAssert(value == true) XCTAssert(value.bool == true) } func testInt() { XCTAssert(Yaml.load("0").value! == .Int(0)) XCTAssert(Yaml.load("+0").value!.int == 0) XCTAssert(Yaml.load("-0").value! == 0) XCTAssert(Yaml.load("2").value! == 2) XCTAssert(Yaml.load("+2").value! == 2) XCTAssert(Yaml.load("-2").value! == -2) XCTAssert(Yaml.load("00123").value! == 123) XCTAssert(Yaml.load("+00123").value! == 123) XCTAssert(Yaml.load("-00123").value! == -123) XCTAssert(Yaml.load("0o10").value! == 8) XCTAssert(Yaml.load("0o010").value! == 8) XCTAssert(Yaml.load("0o0010").value! == 8) XCTAssert(Yaml.load("0x10").value! == 16) XCTAssert(Yaml.load("0x1a").value! == 26) XCTAssert(Yaml.load("0x01a").value! == 26) XCTAssert(Yaml.load("0x001a").value! == 26) XCTAssert(Yaml.load("10:10").value! == 610) XCTAssert(Yaml.load("10:10:10").value! == 36610) XCTAssert(Yaml.load("2").value! == 2) XCTAssert(Yaml.load("2.0").value! == 2) XCTAssert(Yaml.load("2.5").value! != 2) XCTAssert(Yaml.load("2.5").value!.int == nil) let value1: Yaml = 2 XCTAssert(value1 == 2) XCTAssert(value1.int == 2) let value2: Yaml = -2 XCTAssert(value2 == -2) XCTAssert(-value2 == 2) XCTAssert(-value2 == value1) } func testDouble() { XCTAssert(Yaml.load(".inf").value! == .Double(Double.infinity)) XCTAssert(Yaml.load(".Inf").value!.double == Double.infinity) XCTAssert(Yaml.load(".INF").value!.double == Double.infinity) XCTAssert(Yaml.load(".iNf").value! == ".iNf") XCTAssert(Yaml.load(".inf#").value! == ".inf#") XCTAssert(Yaml.load(".inf# string").value! == ".inf# string") XCTAssert(Yaml.load(".inf # comment").value!.double == Double.infinity) XCTAssert(Yaml.load(".inf .inf").value! == ".inf .inf") XCTAssert(Yaml.load("+.inf # comment").value!.double == Double.infinity) XCTAssert(Yaml.load("-.inf").value! == .Double(-Double.infinity)) XCTAssert(Yaml.load("-.Inf").value!.double == -Double.infinity) XCTAssert(Yaml.load("-.INF").value!.double == -Double.infinity) XCTAssert(Yaml.load("-.iNf").value! == "-.iNf") XCTAssert(Yaml.load("-.inf#").value! == "-.inf#") XCTAssert(Yaml.load("-.inf# string").value! == "-.inf# string") XCTAssert(Yaml.load("-.inf # comment").value!.double == -Double.infinity) XCTAssert(Yaml.load("-.inf -.inf").value! == "-.inf -.inf") XCTAssert(Yaml.load(".nan").value! != .Double(Double.NaN)) XCTAssert(Yaml.load(".nan").value!.double!.isNaN) XCTAssert(Yaml.load(".NaN").value!.double!.isNaN) XCTAssert(Yaml.load(".NAN").value!.double!.isNaN) XCTAssert(Yaml.load(".Nan").value!.double == nil) XCTAssert(Yaml.load(".nan#").value! == ".nan#") XCTAssert(Yaml.load(".nan# string").value! == ".nan# string") XCTAssert(Yaml.load(".nan # comment").value!.double!.isNaN) XCTAssert(Yaml.load(".nan .nan").value! == ".nan .nan") XCTAssert(Yaml.load("0.").value! == .Double(0)) XCTAssert(Yaml.load(".0").value!.double == 0) XCTAssert(Yaml.load("+0.").value! == 0) XCTAssert(Yaml.load("+.0").value! == 0) XCTAssert(Yaml.load("+.").value! != 0) XCTAssert(Yaml.load("-0.").value! == 0) XCTAssert(Yaml.load("-.0").value! == 0) XCTAssert(Yaml.load("-.").value! != 0) XCTAssert(Yaml.load("2.").value! == 2) XCTAssert(Yaml.load(".2").value! == 0.2) XCTAssert(Yaml.load("+2.").value! == 2) XCTAssert(Yaml.load("+.2").value! == 0.2) XCTAssert(Yaml.load("-2.").value! == -2) XCTAssert(Yaml.load("-.2").value! == -0.2) XCTAssert(Yaml.load("1.23015e+3").value! == 1.23015e+3) XCTAssert(Yaml.load("12.3015e+02").value! == 12.3015e+02) XCTAssert(Yaml.load("1230.15").value! == 1230.15) XCTAssert(Yaml.load("+1.23015e+3").value! == 1.23015e+3) XCTAssert(Yaml.load("+12.3015e+02").value! == 12.3015e+02) XCTAssert(Yaml.load("+1230.15").value! == 1230.15) XCTAssert(Yaml.load("-1.23015e+3").value! == -1.23015e+3) XCTAssert(Yaml.load("-12.3015e+02").value! == -12.3015e+02) XCTAssert(Yaml.load("-1230.15").value! == -1230.15) XCTAssert(Yaml.load("-01230.15").value! == -1230.15) XCTAssert(Yaml.load("-12.3015e02").value! == -12.3015e+02) XCTAssert(Yaml.load("2").value! == 2.0) XCTAssert(Yaml.load("2.0").value! == 2.0) XCTAssert(Yaml.load("2.5").value! == 2.5) XCTAssert(Yaml.load("2.5").value!.int == nil) let value1: Yaml = 0.2 XCTAssert(value1 == 0.2) XCTAssert(value1.double == 0.2) let value2: Yaml = -0.2 XCTAssert(value2 == -0.2) XCTAssert(-value2 == 0.2) XCTAssert(-value2 == value1) } func testString () { XCTAssert(Yaml.load("Behrang").value! == .String("Behrang")) XCTAssert(Yaml.load("\"Behrang\"").value! == .String("Behrang")) XCTAssert(Yaml.load("\"B\\\"ehran\\\"g\"").value! == .String("B\"ehran\"g")) XCTAssert(Yaml.load("Behrang Noruzi Niya").value!.string == "Behrang Noruzi Niya") XCTAssert(Yaml.load("Radin Noruzi Niya").value! == "Radin Noruzi Niya") XCTAssert(Yaml.load("|").value! == "") XCTAssert(Yaml.load("| ").value! == "") XCTAssert(Yaml.load("| # comment").value! == "") XCTAssert(Yaml.load("| # comment\n").value! == "") XCTAssert(Yaml.load("|\nRadin").error != nil) XCTAssert(Yaml.load("|\n Radin").value! == "Radin") XCTAssert(Yaml.load("| \n Radin").value! == "Radin") XCTAssert(Yaml.load("| # comment\n Radin").value! == "Radin") XCTAssert(Yaml.load("|\n Radin").value! == "Radin") XCTAssert(Yaml.load("|2\n Radin").value! == "Radin") XCTAssert(Yaml.load("|1\n Radin").value! == " Radin") XCTAssert(Yaml.load("|1\n\n Radin").value! == "\n Radin") XCTAssert(Yaml.load("|\n\n Radin").value! == "\nRadin") XCTAssert(Yaml.load("|3\n\n Radin").value == nil) XCTAssert(Yaml.load("|3\n \n Radin").value == nil) XCTAssert(Yaml.load("|3\n \n Radin").value! == "\nRadin") XCTAssert(Yaml.load("|\n \n\n \n Radin\n\n \n\n Noruzi Niya").value! == "\n\n\nRadin\n\n\n\nNoruzi Niya") XCTAssert(Yaml.load("|\n \n\n \n Radin\n\n \n\n Noruzi Niya\n #1").value! == "\n\n\nRadin\n\n\n\nNoruzi Niya\n#1") XCTAssert(Yaml.load("|\n \n\n \n Radin\n\n \n\n Noruzi Niya\n #1" + "\n # Comment").value! == "\n\n\nRadin\n\n\n\nNoruzi Niya\n#1\n") XCTAssert(Yaml.load("|\n Radin\n").value! == "Radin\n") XCTAssert(Yaml.load("|\n Radin\n\n").value! == "Radin\n") XCTAssert(Yaml.load("|\n Radin\n \n ").value! == "Radin\n") XCTAssert(Yaml.load("|\n Radin\n \n ").value! == "Radin\n") XCTAssert(Yaml.load("|-\n Radin\n \n ").value! == "Radin") XCTAssert(Yaml.load("|+\n Radin\n").value! == "Radin\n") XCTAssert(Yaml.load("|+\n Radin\n\n").value! == "Radin\n\n") XCTAssert(Yaml.load("|+\n Radin\n \n ").value! == "Radin\n\n") XCTAssert(Yaml.load("|+\n Radin\n \n ").value! == "Radin\n \n ") XCTAssert(Yaml.load("|2+\n Radin\n \n ").value! == "Radin\n\n") XCTAssert(Yaml.load("|+2\n Radin\n \n ").value! == "Radin\n\n") XCTAssert(Yaml.load("|-2\n Radin\n \n ").value! == "Radin") XCTAssert(Yaml.load("|2-\n Radin\n \n ").value! == "Radin") XCTAssert(Yaml.load("|22\n Radin\n \n ").error != nil) XCTAssert(Yaml.load("|--\n Radin\n \n ").error != nil) XCTAssert(Yaml.load(">+\n trimmed\n \n \n\n as\n space\n\n \n").value! == "trimmed\n\n\nas space\n\n \n") XCTAssert(Yaml.load(">-\n trimmed\n \n \n\n as\n space").value! == "trimmed\n\n\nas space") XCTAssert(Yaml.load(">\n foo \n \n \t bar\n\n baz\n").value! == "foo \n\n\t bar\n\nbaz\n") XCTAssert(Yaml.load(">\n \n Behrang").error != nil) XCTAssert(Yaml.load(">\n \n Behrang").value! == "\nBehrang") XCTAssert(Yaml.load(">\n\n folded\n line\n\n next\n line\n * bullet\n\n" + " * list\n * lines\n\n last\n line\n\n# Comment").value! == .String("\nfolded line\nnext line\n * bullet\n\n * list\n * lines" + "\n\nlast line\n")) XCTAssert(Yaml.load("\"\n foo \n \n \t bar\n\n baz\n\"").value! == " foo\nbar\nbaz ") XCTAssert(Yaml.load("\"folded \nto a space,\t\n \nto a line feed," + " or \t\\\n \\ \tnon-content\"").value! == "folded to a space,\nto a line feed, or \t \tnon-content") XCTAssert(Yaml.load("\" 1st non-empty\n\n 2nd non-empty" + " \n\t3rd non-empty \"").value! == " 1st non-empty\n2nd non-empty 3rd non-empty ") XCTAssert(Yaml.load("'here''s to \"quotes\"'").value! == "here's to \"quotes\"") XCTAssert(Yaml.load("' 1st non-empty\n\n 2nd non-empty" + " \n\t3rd non-empty '").value! == " 1st non-empty\n2nd non-empty 3rd non-empty ") XCTAssert(Yaml.load("x\n y\nz").value! == "x y z") XCTAssert(Yaml.load(" x\ny\n z").value! == "x y z") XCTAssert(Yaml.load("a: x\n y\n z").value! == ["a": "x y z"]) XCTAssert(Yaml.load("a: x\ny\n z").error != nil) XCTAssert(Yaml.load("- a: x\n y\n z").value! == [["a": "x y z"]]) XCTAssert(Yaml.load("- a:\n x\n y\n z").value! == [["a": "x y z"]]) XCTAssert(Yaml.load("- a: \n x\n y\n z").value! == [["a": "x y z"]]) XCTAssert(Yaml.load("- a: # comment\n x\n y\n z").value! == [["a": "x y z"]]) let value1: Yaml = "Radin" XCTAssert(value1 == "Radin") XCTAssert(value1.string == "Radin") let value2 = Yaml.load( "# Outside flow collection:\n" + "- ::vector\n" + "- \": - ()\"\n" + "- Up, up, and away!\n" + "- -123\n" + "- http://example.com/foo#bar\n" + "# Inside flow collection:\n" + "- [ ::vector,\n" + " \": - ()\",\n" + " \"Up, up and away!\",\n" + " -123,\n" + " http://example.com/foo#bar ]\n" ).value! XCTAssert(value2.count == 6) XCTAssert(value2[0] == "::vector") XCTAssert(value2[5][0] == "::vector") XCTAssert(value2[5][4] == "http://example.com/foo#bar") } func testFlowSeq () { XCTAssert(Yaml.load("[]").value! == .Array([])) XCTAssert(Yaml.load("[]").value!.count == 0) XCTAssert(Yaml.load("[ true ]").value! == [Yaml.Bool(true)]) XCTAssert(Yaml.load("[ true ]").value! == .Array([true])) XCTAssert(Yaml.load("[ true ]").value! == [true]) XCTAssert(Yaml.load("[ true ]").value![0] == true) XCTAssert(Yaml.load("[true, false, true]").value! == [true, false, true]) XCTAssert(Yaml.load("[Behrang, Radin]").value! == ["Behrang", "Radin"]) XCTAssert(Yaml.load("[true, [false, true]]").value! == [true, [false, true]]) XCTAssert(Yaml.load("[true, true ,false, false , false]").value! == [true, true, false, false, false]) XCTAssert(Yaml.load("[true, .NaN]").value! != [true, .Double(Double.NaN)]) XCTAssert(Yaml.load("[~, null, TRUE, False, .INF, -.inf, 0, 123, -456" + ", 0o74, 0xFf, 1.23, -4.5]").value! == [nil, nil, true, false, .Double(Double.infinity), .Double(-Double.infinity), 0, 123, -456, 60, 255, 1.23, -4.5]) XCTAssert(Yaml.load("x:\n y:\n z: [\n1]").error != nil) XCTAssert(Yaml.load("x:\n y:\n z: [\n 1]").error != nil) XCTAssert(Yaml.load("x:\n y:\n z: [\n 1]").value! == ["x": ["y": ["z": [1]]]]) } func testBlockSeq () { XCTAssert(Yaml.load("- 1\n- 2").value! == [1, 2]) XCTAssert(Yaml.load("- 1\n- 2").value![1] == 2) XCTAssert(Yaml.load("- x: 1").value! == [["x": 1]]) XCTAssert(Yaml.load("- x: 1\n y: 2").value![0] == ["x": 1, "y": 2]) XCTAssert(Yaml.load("- 1\n \n- x: 1\n y: 2").value! == [1, ["x": 1, "y": 2]]) XCTAssert(Yaml.load("- x:\n - y: 1").value! == [["x": [["y": 1]]]]) } func testFlowMap () { XCTAssert(Yaml.load("{}").value! == [:]) XCTAssert(Yaml.load("{x: 1}").value! == ["x": 1]) XCTAssert(Yaml.load("{x: 1, x: 2}").error != nil) XCTAssert(Yaml.load("{x: 1}").value!["x"] == 1) XCTAssert(Yaml.load("{x:1}").error != nil) XCTAssert(Yaml.load("{\"x\":1}").value!["x"] == 1) XCTAssert(Yaml.load("{\"x\":1, 'y': true}").value!["y"] == true) XCTAssert(Yaml.load("{\"x\":1, 'y': true, z: null}").value!["z"] == nil) XCTAssert(Yaml.load("{first name: \"Behrang\"," + " last name: 'Noruzi Niya'}").value! == ["first name": "Behrang", "last name": "Noruzi Niya"]) XCTAssert(Yaml.load("{fn: Behrang, ln: Noruzi Niya}").value!["ln"] == "Noruzi Niya") XCTAssert(Yaml.load("{fn: Behrang\n ,\nln: Noruzi Niya}").value!["ln"] == "Noruzi Niya") } func testBlockMap () { XCTAssert(Yaml.load("x: 1\ny: 2").value! == .Dictionary([.String("x"): .Int(1), .String("y"): .Int(2)])) XCTAssert(Yaml.load("x: 1\nx: 2").error != nil) XCTAssert(Yaml.load("x: 1\n? y\n: 2").value! == ["x": 1, "y": 2]) XCTAssert(Yaml.load("x: 1\n? x\n: 2").error != nil) XCTAssert(Yaml.load("x: 1\n? y\n:\n2").error != nil) XCTAssert(Yaml.load("x: 1\n? y\n:\n 2").value! == ["x": 1, "y": 2]) XCTAssert(Yaml.load("x: 1\n? y").value! == ["x": 1, "y": nil]) XCTAssert(Yaml.load("? y").value! == ["y": nil]) XCTAssert(Yaml.load(" \n \n \n \n\nx: 1 \n \ny: 2" + "\n \n \n ").value!["y"] == 2) XCTAssert(Yaml.load("x:\n a: 1 # comment \n b: 2\ny: " + "\n c: 3\n ").value!["y"]["c"] == 3) XCTAssert(Yaml.load("# comment \n\n # x\n # y \n \n x: 1" + " \n y: 2").value! == ["x": 1, "y": 2]) } func testDirectives () { XCTAssert(Yaml.load("%YAML 1.2\n1").error != nil) XCTAssert(Yaml.load("%YAML 1.2\n---1").value! == 1) XCTAssert(Yaml.load("%YAML 1.2 #\n---1").value! == 1) XCTAssert(Yaml.load("%YAML 1.2\n%YAML 1.2\n---1").error != nil) XCTAssert(Yaml.load("%YAML 1.0\n---1").error != nil) XCTAssert(Yaml.load("%YAML 1\n---1").error != nil) XCTAssert(Yaml.load("%YAML 1.3\n---1").error != nil) XCTAssert(Yaml.load("%YAML \n---1").error != nil) } func testReserves () { XCTAssert(Yaml.load("`reserved").error != nil) XCTAssert(Yaml.load("@behrangn").error != nil) XCTAssert(Yaml.load("twitter handle: @behrangn").error != nil) } func testAliases () { XCTAssert(Yaml.load("x: &a 1\ny: *a").value! == ["x": 1, "y": 1]) XCTAssert(Yaml.loadMultiple("x: &a 1\ny: *a\n---\nx: *a").error != nil) XCTAssert(Yaml.load("x: *a").error != nil) } func testUnicodeSurrogates() { XCTAssert(Yaml.load("x: Dog‼🐶\ny: 𝒂𝑡").value! == ["x": "Dog‼🐶", "y": "𝒂𝑡"]) } }
mit
9fdf15e59d0ad891bb25078f001f1cb2
45.175487
85
0.558364
2.957538
false
false
false
false
patrickmontalto/SwiftNetworking
SwiftNetworking/Classes/NetworkClient.swift
1
3657
// // NetworkClient.swift // Pods // // Created by Patrick on 4/4/17. // // import Foundation /// Abstract networking client. open class NetworkClient { typealias JSONDictionary = [String: Any] // MARK: - Types enum Method: String { case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case delete = "DELETE" case connect = "CONNECT" case options = "OPTIONS" case trace = "TRACE" case patch = "PATCH" var acceptsBody: Bool { switch self { case .post, .put, .patch: return true default: return false } } } enum Error: Swift.Error { case unknown } // MARK: - Properties public let baseURL: URL public let session: URLSession // MARK: - Initializers public init(baseURL: URL, session: URLSession = URLSession.shared) { self.baseURL = baseURL self.session = session } // MARK: - Requests /// Build a URLRequest based on the baseURL of the NetworkClient. /// /// - parameter method: HTTP method /// - parameter path: path component /// - parameter queryItems: optional array of query items /// - parameter parameters: optional JSONDictionary of params /// - returns: Expected URLRequest func buildRequest(method: Method = .get, path: String, queryItems: [URLQueryItem] = [], parameters: JSONDictionary? = nil) -> URLRequest { // Create url with path component var url = baseURL.appendingPathComponent(path) // Apply query parameters to url if !queryItems.isEmpty, var components = URLComponents(url: url, resolvingAgainstBaseURL: true) { components.queryItems = queryItems if let modifiedURL = components.url { url = modifiedURL } } // Create request var request = URLRequest(url: url) request.httpMethod = method.rawValue // Add defaults request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // Add body if let parameters = parameters, method.acceptsBody, let body = try? JSONSerialization.data(withJSONObject: parameters, options: []) { request.httpBody = body } return request } /// Build and send a URLRequest (raw network result) /// /// - parameter method: HTTP method /// - parameter path: path component /// - parameter queryItems: optional array of query items /// - parameter parameters: optional JSONDictionary of params /// - parameter completion: completion block called containing a Result object func request(method: Method = .get, path: String, queryItems: [URLQueryItem] = [], parameters: JSONDictionary? = nil, completion: ((NetworkResult) -> Void)? = nil) { // Make request let request = buildRequest(method: method, path: path, queryItems: queryItems, parameters: parameters) // Send request session.dataTask(with: request) { (data, response, error) in // Success if let response = response { completion?(.success(response, data)) return } // Failure completion?(.failure(error ?? Error.unknown)) }.resume() } }
mit
0694002b557e0e2035016577c4b9bc16
27.348837
170
0.575608
5.100418
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSIndexSet.swift
1
25509
// 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 // /* Class for managing set of indexes. The set of valid indexes are 0 .. NSNotFound - 1; trying to use indexes outside this range is an error. NSIndexSet uses NSNotFound as a return value in cases where the queried index doesn't exist in the set; for instance, when you ask firstIndex and there are no indexes; or when you ask for indexGreaterThanIndex: on the last index, and so on. The following code snippets can be used to enumerate over the indexes in an NSIndexSet: // Forward var currentIndex = set.firstIndex while currentIndex != NSNotFound { ... currentIndex = set.indexGreaterThanIndex(currentIndex) } // Backward var currentIndex = set.lastIndex while currentIndex != NSNotFound { ... currentIndex = set.indexLessThanIndex(currentIndex) } To enumerate without doing a call per index, you can use the method getIndexes:maxCount:inIndexRange:. */ internal func __NSIndexSetRangeCount(_ indexSet: NSIndexSet) -> UInt { return UInt(indexSet._ranges.count) } internal func __NSIndexSetRangeAtIndex(_ indexSet: NSIndexSet, _ index: UInt, _ location : UnsafeMutablePointer<UInt>, _ length : UnsafeMutablePointer<UInt>) { // if Int(index) >= indexSet._ranges.count { // location.pointee = UInt(bitPattern: NSNotFound) // length.pointee = UInt(0) // return // } let range = indexSet._ranges[Int(index)] location.pointee = UInt(range.location) length.pointee = UInt(range.length) } internal func __NSIndexSetIndexOfRangeContainingIndex(_ indexSet: NSIndexSet, _ index: UInt) -> UInt { var idx = 0 while idx < indexSet._ranges.count { let range = indexSet._ranges[idx] if range.location <= Int(index) && Int(index) <= range.location + range.length { return UInt(idx) } idx += 1 } return UInt(bitPattern: NSNotFound) } public class NSIndexSet: NSObject, NSCopying, NSMutableCopying, NSSecureCoding { // all instance variables are private internal var _ranges = [NSRange]() internal var _count = 0 override public init() { _count = 0 _ranges = [] } public init(indexesIn range: NSRange) { _count = range.length _ranges = _count == 0 ? [] : [range] } public init(indexSet: IndexSet) { _ranges = indexSet.rangeView().map { NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound) } _count = indexSet.count } public override func copy() -> AnyObject { return copy(with: nil) } public func copy(with zone: NSZone? = nil) -> AnyObject { NSUnimplemented() } public override func mutableCopy() -> AnyObject { return mutableCopy(with: nil) } public func mutableCopy(with zone: NSZone? = nil) -> AnyObject { let set = NSMutableIndexSet() enumerateRanges([]) { set.add(in: $0.0) } return set } public static func supportsSecureCoding() -> Bool { return true } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encode(with aCoder: NSCoder) { NSUnimplemented() } public convenience init(index value: Int) { self.init(indexesIn: NSMakeRange(value, 1)) } public func isEqual(to indexSet: IndexSet) -> Bool { let otherRanges = indexSet.rangeView().map { NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound) } if _ranges.count != otherRanges.count { return false } for (r1, r2) in zip(_ranges, otherRanges) { if r1.length != r2.length || r1.location != r2.location { return false } } return true } public var count: Int { return _count } /* The following six methods will return NSNotFound if there is no index in the set satisfying the query. */ public var firstIndex: Int { return _ranges.first?.location ?? NSNotFound } public var lastIndex: Int { guard _ranges.count > 0 else { return NSNotFound } return NSMaxRange(_ranges.last!) - 1 } internal func _indexAndRangeAdjacentToOrContainingIndex(_ idx : Int) -> (Int, NSRange)? { let count = _ranges.count guard count > 0 else { return nil } var min = 0 var max = count - 1 while min < max { let rIdx = (min + max) / 2 let range = _ranges[rIdx] if range.location > idx { max = rIdx } else if NSMaxRange(range) - 1 < idx { min = rIdx + 1 } else { return (rIdx, range) } } return (min, _ranges[min]) } internal func _indexOfRangeContainingIndex (_ idx : Int) -> Int? { if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) { return NSLocationInRange(idx, range) ? rIdx : nil } else { return nil } } internal func _indexOfRangeBeforeOrContainingIndex(_ idx : Int) -> Int? { if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) { if range.location <= idx { return rIdx } else if rIdx > 0 { return rIdx - 1 } else { return nil } } else { return nil } } internal func _indexOfRangeAfterOrContainingIndex(_ idx : Int) -> Int? { if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) { if NSMaxRange(range) - 1 >= idx { return rIdx } else if rIdx + 1 < _ranges.count { return rIdx + 1 } else { return nil } } else { return nil } } internal func _indexClosestToIndex(_ idx: Int, equalAllowed : Bool, following: Bool) -> Int? { guard _count > 0 else { return nil } if following { var result = idx if !equalAllowed { guard idx < NSNotFound else { return nil } result += 1 } if let rangeIndex = _indexOfRangeAfterOrContainingIndex(result) { let range = _ranges[rangeIndex] return NSLocationInRange(result, range) ? result : range.location } } else { var result = idx if !equalAllowed { guard idx > 0 else { return nil } result -= 1 } if let rangeIndex = _indexOfRangeBeforeOrContainingIndex(result) { let range = _ranges[rangeIndex] return NSLocationInRange(result, range) ? result : (NSMaxRange(range) - 1) } } return nil } public func indexGreaterThanIndex(_ value: Int) -> Int { return _indexClosestToIndex(value, equalAllowed: false, following: true) ?? NSNotFound } public func indexLessThanIndex(_ value: Int) -> Int { return _indexClosestToIndex(value, equalAllowed: false, following: false) ?? NSNotFound } public func indexGreaterThanOrEqual(to value: Int) -> Int { return _indexClosestToIndex(value, equalAllowed: true, following: true) ?? NSNotFound } public func indexLessThanOrEqual(to value: Int) -> Int { return _indexClosestToIndex(value, equalAllowed: true, following: false) ?? NSNotFound } /* Fills up to bufferSize indexes in the specified range into the buffer and returns the number of indexes actually placed in the buffer; also modifies the optional range passed in by pointer to be "positioned" after the last index filled into the buffer.Example: if the index set contains the indexes 0, 2, 4, ..., 98, 100, for a buffer of size 10 and the range (20, 80) the buffer would contain 20, 22, ..., 38 and the range would be modified to (40, 60). */ public func getIndexes(_ indexBuffer: UnsafeMutablePointer<Int>, maxCount bufferSize: Int, inIndexRange range: NSRangePointer?) -> Int { let minIndex : Int let maxIndex : Int if let initialRange = range { minIndex = initialRange.pointee.location maxIndex = NSMaxRange(initialRange.pointee) - 1 } else { minIndex = firstIndex maxIndex = lastIndex } guard minIndex <= maxIndex else { return 0 } if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(minIndex) { var rangeIndex = initialRangeIndex let rangeCount = _ranges.count var counter = 0 var idx = minIndex var offset = 0 while rangeIndex < rangeCount && idx <= maxIndex && counter < bufferSize { let currentRange = _ranges[rangeIndex] if currentRange.location <= minIndex { idx = minIndex offset = minIndex - currentRange.location } else { idx = currentRange.location } while idx <= maxIndex && counter < bufferSize && offset < currentRange.length { indexBuffer.advanced(by: counter).pointee = idx counter += 1 idx += 1 offset += 1 } if offset >= currentRange.length { rangeIndex += 1 offset = 0 } } if counter > 0, let resultRange = range { let delta = indexBuffer.advanced(by: counter - 1).pointee - minIndex + 1 resultRange.pointee.location += delta resultRange.pointee.length -= delta } return counter } else { return 0 } } public func countOfIndexes(in range: NSRange) -> Int { guard _count > 0 && range.length > 0 else { return 0 } if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location) { var rangeIndex = initialRangeIndex let maxRangeIndex = NSMaxRange(range) - 1 var result = 0 let firstRange = _ranges[rangeIndex] if firstRange.location < range.location { if NSMaxRange(firstRange) - 1 >= maxRangeIndex { return range.length } result = NSMaxRange(firstRange) - range.location rangeIndex += 1 } for curRange in _ranges.suffix(from: rangeIndex) { if NSMaxRange(curRange) - 1 > maxRangeIndex { if curRange.location <= maxRangeIndex { result += maxRangeIndex + 1 - curRange.location } break } result += curRange.length } return result } else { return 0 } } public func contains(_ value: Int) -> Bool { return _indexOfRangeContainingIndex(value) != nil } public func contains(in range: NSRange) -> Bool { guard range.length > 0 else { return false } if let rIdx = self._indexOfRangeContainingIndex(range.location) { return NSMaxRange(_ranges[rIdx]) >= NSMaxRange(range) } else { return false } } public func contains(_ indexSet: IndexSet) -> Bool { var result = true enumerateRanges([]) { range, stop in if !self.contains(in: range) { result = false stop.pointee = true } } return result } public func intersects(in range: NSRange) -> Bool { guard range.length > 0 else { return false } if let rIdx = _indexOfRangeBeforeOrContainingIndex(range.location) { if NSMaxRange(_ranges[rIdx]) - 1 >= range.location { return true } } if let rIdx = _indexOfRangeAfterOrContainingIndex(range.location) { if NSMaxRange(range) - 1 >= _ranges[rIdx].location { return true } } return false } internal func _enumerateWithOptions<P, R>(_ opts : EnumerationOptions, range: NSRange, paramType: P.Type, returnType: R.Type, block: @noescape (P, UnsafeMutablePointer<ObjCBool>) -> R) -> Int? { guard !opts.contains(.concurrent) else { NSUnimplemented() } guard let startRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location), let endRangeIndex = _indexOfRangeBeforeOrContainingIndex(NSMaxRange(range) - 1) else { return nil } var result : Int? = nil let reverse = opts.contains(.reverse) let passRanges = paramType == NSRange.self let findIndex = returnType == Bool.self var stop = false let ranges = _ranges[startRangeIndex...endRangeIndex] let rangeSequence = (reverse ? AnySequence(ranges.reversed()) : AnySequence(ranges)) outer: for curRange in rangeSequence { let intersection = NSIntersectionRange(curRange, range) if passRanges { if intersection.length > 0 { let _ = block(intersection as! P, &stop) } if stop { break outer } } else if intersection.length > 0 { let maxIndex = NSMaxRange(intersection) - 1 let indexes = reverse ? stride(from: maxIndex, through: intersection.location, by: -1) : stride(from: intersection.location, through: maxIndex, by: 1) for idx in indexes { if findIndex { let found : Bool = block(idx as! P, &stop) as! Bool if found { result = idx stop = true } } else { let _ = block(idx as! P, &stop) } if stop { break outer } } } // else, continue } return result } public func enumerate(_ block: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerate([], using: block) } public func enumerate(_ opts: EnumerationOptions = [], using block: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Void) { let _ = _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: Int.self, returnType: Void.self, block: block) } public func enumerate(in range: NSRange, options opts: EnumerationOptions = [], using block: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Void) { let _ = _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self, block: block) } public func index(passingTest predicate: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { return index([], passingTest: predicate) } public func index(_ opts: EnumerationOptions = [], passingTest predicate: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { return _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound } public func index(in range: NSRange, options opts: EnumerationOptions = [], passingTest predicate: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { return _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound } public func indexes(passingTest predicate: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { return indexes(in: NSMakeRange(0, Int.max), options: [], passingTest: predicate) } public func indexes(_ opts: EnumerationOptions = [], passingTest predicate: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { return indexes(in: NSMakeRange(0, Int.max), options: opts, passingTest: predicate) } public func indexes(in range: NSRange, options opts: EnumerationOptions = [], passingTest predicate: @noescape (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { var result = IndexSet() let _ = _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self) { idx, stop in if predicate(idx, stop) { result.insert(idx) } } return result } /* The following three convenience methods allow you to enumerate the indexes in the receiver by ranges of contiguous indexes. The performance of these methods is not guaranteed to be any better than if they were implemented with enumerateIndexesInRange:options:usingBlock:. However, depending on the receiver's implementation, they may perform better than that. If the specified range for enumeration intersects a range of contiguous indexes in the receiver, then the block will be invoked with the intersection of those two ranges. */ public func enumerateRanges(_ block: @noescape (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerateRanges([], using: block) } public func enumerateRanges(_ opts: EnumerationOptions = [], using block: @noescape (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { let _ = _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: NSRange.self, returnType: Void.self, block: block) } public func enumerateRanges(in range: NSRange, options opts: EnumerationOptions = [], using block: @noescape (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { let _ = _enumerateWithOptions(opts, range: range, paramType: NSRange.self, returnType: Void.self, block: block) } } extension NSIndexSet: Sequence { public struct Iterator : IteratorProtocol { internal let _set: NSIndexSet internal var _first: Bool = true internal var _current: Int? internal init(_ set: NSIndexSet) { self._set = set self._current = nil } public mutating func next() -> Int? { if _first { _current = _set.firstIndex _first = false } else if let c = _current { _current = _set.indexGreaterThanIndex(c) } if _current == NSNotFound { _current = nil } return _current } } public func makeIterator() -> Iterator { return Iterator(self) } } public class NSMutableIndexSet : NSIndexSet { public func add(_ indexSet: IndexSet) { indexSet.rangeView().forEach { add(in: NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound)) } } public func remove(_ indexSet: IndexSet) { indexSet.rangeView().forEach { remove(in: NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound)) } } public func removeAllIndexes() { _ranges = [] _count = 0 } public func add(_ value: Int) { add(in: NSMakeRange(value, 1)) } public func remove(_ value: Int) { remove(in: NSMakeRange(value, 1)) } internal func _insertRange(_ range: NSRange, atIndex index: Int) { _ranges.insert(range, at: index) _count += range.length } internal func _replaceRangeAtIndex(_ index: Int, withRange range: NSRange?) { let oldRange = _ranges[index] if let range = range { _ranges[index] = range _count += range.length - oldRange.length } else { _ranges.remove(at: index) _count -= oldRange.length } } internal func _mergeOverlappingRangesStartingAtIndex(_ index: Int) { var rangeIndex = index while _ranges.count > 0 && rangeIndex < _ranges.count - 1 { let curRange = _ranges[rangeIndex] let nextRange = _ranges[rangeIndex + 1] let curEnd = NSMaxRange(curRange) let nextEnd = NSMaxRange(nextRange) if curEnd >= nextRange.location { // overlaps if curEnd < nextEnd { self._replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(nextEnd - curRange.location, curRange.length)) rangeIndex += 1 } self._replaceRangeAtIndex(rangeIndex + 1, withRange: nil) } else { break } } } public func add(in range: NSRange) { guard range.length > 0 else { return } let addEnd = NSMaxRange(range) let startRangeIndex = _indexOfRangeBeforeOrContainingIndex(range.location) ?? 0 var replacedRangeIndex : Int? var rangeIndex = startRangeIndex while rangeIndex < _ranges.count { let curRange = _ranges[rangeIndex] let curEnd = NSMaxRange(curRange) if addEnd < curRange.location { _insertRange(range, atIndex: rangeIndex) // Done. No need to merge return } else if range.location < curRange.location && addEnd >= curRange.location { if addEnd > curEnd { _replaceRangeAtIndex(rangeIndex, withRange: range) } else { _replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(range.location, curEnd - range.location)) } replacedRangeIndex = rangeIndex // Proceed to merging break } else if range.location >= curRange.location && addEnd < curEnd { // Nothing to add return } else if range.location >= curRange.location && range.location <= curEnd && addEnd > curEnd { _replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(curRange.location, addEnd - curRange.location)) replacedRangeIndex = rangeIndex // Proceed to merging break } rangeIndex += 1 } if let r = replacedRangeIndex { _mergeOverlappingRangesStartingAtIndex(r) } else { _insertRange(range, atIndex: _ranges.count) } } public func remove(in range: NSRange) { guard range.length > 0 else { return } guard let startRangeIndex = (range.location > 0) ? _indexOfRangeAfterOrContainingIndex(range.location) : 0 else { return } let removeEnd = NSMaxRange(range) var rangeIndex = startRangeIndex while rangeIndex < _ranges.count { let curRange = _ranges[rangeIndex] let curEnd = NSMaxRange(curRange) if removeEnd < curRange.location { // Nothing to remove return } else if range.location <= curRange.location && removeEnd >= curRange.location { if removeEnd >= curEnd { _replaceRangeAtIndex(rangeIndex, withRange: nil) // Don't increment rangeIndex continue } else { self._replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(removeEnd, curEnd - removeEnd)) return } } else if range.location > curRange.location && removeEnd < curEnd { let firstPiece = NSMakeRange(curRange.location, range.location - curRange.location) let secondPiece = NSMakeRange(removeEnd, curEnd - removeEnd) _replaceRangeAtIndex(rangeIndex, withRange: secondPiece) _insertRange(firstPiece, atIndex: rangeIndex) } else if range.location > curRange.location && range.location < curEnd && removeEnd >= curEnd { _replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(curRange.location, range.location - curRange.location)) } rangeIndex += 1 } } /* For a positive delta, shifts the indexes in [index, INT_MAX] to the right, thereby inserting an "empty space" [index, delta], for a negative delta, shifts the indexes in [index, INT_MAX] to the left, thereby deleting the indexes in the range [index - delta, delta]. */ public func shiftIndexesStarting(at index: Int, by delta: Int) { NSUnimplemented() } }
apache-2.0
310a7c39ce5fbe03742999f613bd8cb9
38.548837
461
0.571798
5.154375
false
false
false
false
bigscreen/mangindo-ios
Mangindo/Modules/Contents/ContentsModule.swift
1
691
// // ContentsModule.swift // Mangindo // // Created by Gallant Pratama on 27/11/18. // Copyright © 2018 Gallant Pratama. All rights reserved. // import UIKit class ContentsModule { private let segue: UIStoryboardSegue init(segue: UIStoryboardSegue) { self.segue = segue } func instantiate(pageTitle: String, mangaTitleId: String, chapter: Int) { let controller = segue.destination as! ContentsViewController let presenter = ContentsPresenter(view: controller, service: NetworkService.shared, mangaTitleId: mangaTitleId, chapter: chapter) controller.pageTitle = pageTitle controller.presenter = presenter } }
mit
a13f4f8ff108cd376f9cd67b299a903c
26.6
137
0.694203
4.367089
false
false
false
false
azizuysal/NetKit
NetKit/NetKit/WebRequest.swift
1
4325
// // WebRequest.swift // NetKit // // Created by Aziz Uysal on 2/12/16. // Copyright © 2016 Aziz Uysal. All rights reserved. // import Foundation public struct WebRequest { public struct Headers { public static let userAgent = "User-Agent" public static let contentType = "Content-Type" public static let contentLength = "Content-Length" public static let accept = "Accept" public static let cacheControl = "Cache-Control" public struct ContentType { public static let json = "application/json" public static let xml = "text/xml" public static let formEncoded = "application/x-www-form-urlencoded" } } public enum Method: String { case HEAD = "HEAD" case GET = "GET" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" } public enum ParameterEncoding { case percent, json public func encodeURL(_ url: URL, parameters: [String:Any]) -> URL? { if var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { components.appendPercentEncodedQuery(parameters.percentEncodedQueryString) return components.url } return nil } public func encodeBody(_ parameters: [String:Any]) -> Data? { switch self { case .percent: return parameters.percentEncodedQueryString.data(using: String.Encoding.utf8, allowLossyConversion: false) case .json: do { return try JSONSerialization.data(withJSONObject: parameters, options: []) } catch { return nil } } } } let method: Method private(set) var url: URL var body: Data? var cachePolicy = URLRequest.CachePolicy.useProtocolCachePolicy var urlParameters = [String:Any]() var bodyParameters = [String:Any]() var parameterEncoding = ParameterEncoding.percent { didSet { if parameterEncoding == .json { contentType = Headers.ContentType.json } } } var restPath = "" { didSet { url = url.appendingPathComponent(restPath) } } var headers = [String:String]() var contentType: String? { set { headers[Headers.contentType] = newValue } get { return headers[Headers.contentType] } } var urlRequest: URLRequest { let request = NSMutableURLRequest(url: url) request.httpMethod = method.rawValue request.cachePolicy = cachePolicy for (name, value) in headers { request.addValue(value, forHTTPHeaderField: name) } if urlParameters.count > 0 { if let url = request.url, let encodedURL = parameterEncoding.encodeURL(url, parameters: urlParameters) { request.url = encodedURL } } if bodyParameters.count > 0 { if let data = parameterEncoding.encodeBody(bodyParameters) { request.httpBody = data if request.value(forHTTPHeaderField: Headers.contentType) == nil { request.setValue(Headers.ContentType.formEncoded, forHTTPHeaderField: Headers.contentType) } } } if let body = body { request.httpBody = body } return request.copy() as! URLRequest } public init(method: Method, url: URL) { self.method = method self.url = url } } extension URLComponents { mutating func appendPercentEncodedQuery(_ query: String) { percentEncodedQuery = percentEncodedQuery == nil ? query : "\(percentEncodedQuery ?? "")&\(query)" } } extension Dictionary { var percentEncodedQueryString: String { var components = [String]() for (name, value) in self { if let percentEncodedPair = percentEncode((name, value)) { components.append(percentEncodedPair) } } return components.joined(separator: "&") } func percentEncode(_ element: Element) -> String? { let (name, value) = element if let encodedName = "\(name)".percentEncodeURLQueryCharacters, let encodedValue = "\(value)".percentEncodeURLQueryCharacters { return "\(encodedName)=\(encodedValue)" } return nil } } extension String { var percentEncodeURLQueryCharacters: String? { let allowedCharacterSet = CharacterSet(charactersIn: "\\!*'();:@&=+$,/?%#[] ").inverted return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet /*.urlQueryAllowed*/) } }
mit
d7e81ab69ad4e63eb9e7a790a5dd7f4b
26.717949
131
0.654024
4.6
false
false
false
false
ioscreator/ioscreator
IOSPlayMusicAVAudioPlayerTutorial/IOSPlayMusicAVAudioPlayerTutorial/ViewController.swift
1
1655
// // ViewController.swift // IOSPlayMusicAVAudioPlayerTutorial // // Created by Arthur Knopper on 27/11/2018. // Copyright © 2018 Arthur Knopper. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer = AVAudioPlayer() var isPlaying = false var timer:Timer! @IBOutlet weak var trackTitle: UILabel! @IBOutlet weak var playedTime: UILabel! @IBAction func playOrPauseMusic(_ sender: Any) { if isPlaying { audioPlayer.pause() isPlaying = false } else { audioPlayer.play() isPlaying = true timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true) } } @IBAction func stopMusic(_ sender: Any) { audioPlayer.stop() audioPlayer.currentTime = 0 isPlaying = false } override func viewDidLoad() { super.viewDidLoad() trackTitle.text = "Future Islands - Tin Man" let path = Bundle.main.path(forResource: "Future Islands - Tin Man", ofType: "mp3")! let url = URL(fileURLWithPath: path) do { audioPlayer = try AVAudioPlayer(contentsOf: url) } catch { // can't load file } } @objc func updateTime() { let currentTime = Int(audioPlayer.currentTime) let minutes = currentTime/60 let seconds = currentTime - minutes * 60 playedTime.text = String(format: "%02d:%02d", minutes,seconds) as String } }
mit
798b54e8b5efb998cdca23d24901a5e4
25.677419
136
0.594317
4.739255
false
false
false
false
slavapestov/swift
test/Constraints/diagnostics.swift
1
30676
// RUN: %target-parse-verify-swift protocol P { associatedtype SomeType } protocol P2 { func wonka() } extension Int : P { typealias SomeType = Int } extension Double : P { typealias SomeType = Double } func f0(x: Int, _ y: Float) { } func f1(_: (Int, Float) -> Int) { } func f2(_: (_: (Int) -> Int)) -> Int {} func f3(_: (_: (Int) -> Float) -> Int) {} func f4(x: Int) -> Int { } func f5<T : P2>(_ : T) { } func f6<T : P, U : P where T.SomeType == U.SomeType>(t: T, _ u: U) {} var i : Int var d : Double // Check the various forms of diagnostics the type checker can emit. // Tuple size mismatch. f1( f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}} ) // Tuple element unused. f0(i, i, i) // expected-error{{extra argument in call}} // Position mismatch f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}} // Tuple element not convertible. f0(i, d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}} ) // Function result not a subtype. f1( f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}} ) f3( f2 // expected-error {{cannot convert value of type '(((Int) -> Int)) -> Int' to expected argument type '((Int) -> Float) -> Int'}} ) f4(i, d) // expected-error {{extra argument in call}} // Missing member. i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}} // Generic member does not conform. extension Int { func wibble<T: P2>(x: T, _ y: T) -> T { return x } func wubble<T>(x: Int -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}} // Generic member args correct, but return type doesn't match. struct A : P2 { func wonka() {} } let a = A() for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'SequenceType'}} } // Generic as part of function/tuple types func f6<T:P2>(g: Void -> T) -> (c: Int, i: T) { return (c: 0, i: g()) } func f7() -> (c: Int, v: A) { let g: Void -> A = { return A() } return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}} } // <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals 1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}} [1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}} "awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}} // Does not conform to protocol. f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}} // Make sure we don't leave open existentials when diagnosing. // <rdar://problem/20598568> func pancakes(p: P2) { f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}} f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} } protocol Shoes { static func select(subject: Shoes) -> Self } // Here the opaque value has type (metatype_type (archetype_type ... )) func f(x: Shoes, asType t: Shoes.Type) { return t.select(x) // expected-error{{unexpected non-void return value in void function}} } infix operator **** { associativity left precedence 200 } func ****(_: Int, _: String) { } i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} infix operator ***~ { associativity left precedence 200 } func ***~(_: Int, _: String) { } i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} // <rdar://problem/20142523> // FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to // make sure that it doesn't crash. func rdar20142523() { map(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}} () return x }) } // <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, IntegerLiteralConvertible)' is not convertible to 'IntegerLiteralConvertible func rdar21080030() { var s = "Hello" if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'Distance'}} } // <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136'}} r21248136() // expected-error {{generic parameter 'T' could not be inferred}} let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}} // <rdar://problem/17080659> Error Message QOI - wrong return type in an overload func recArea(h: Int, w : Int) { return h * w // expected-error {{no '*' candidates produce the expected contextual result type '()'}} // expected-note @-1 {{overloads for '*' exist with these result types: UInt8, Int8, UInt16, Int16, UInt32, Int32, UInt64, Int64, UInt, Int, Float, Double}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(monthNumber : Int) { // expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}} // expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Memory>, Int), (UnsafePointer<Memory>, Int)}} let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber) } // <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?' func r17020197(x : Int?, y : Int) { if x! { } // expected-error {{type 'Int' does not conform to protocol 'BooleanType'}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{type 'Int' does not conform to protocol 'BooleanType'}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(text: String) { return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype class r20201968C { func blah() { r20201968C.blah() // expected-error {{use of instance member 'blah' on type 'r20201968C'; did you mean to use a value of type 'r20201968C' instead?}} } } // <rdar://problem/21459429> QoI: Poor compilation error calling assert func r21459429(a : Int) { assert(a != nil, "ASSERT COMPILATION ERROR") // expected-error {{value of type 'Int' can never be nil, comparison isn't allowed}} } // <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}} } // <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}} // <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf String().asdf // expected-error {{value of type 'String' has no member 'asdf'}} // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment protocol r21553065Protocol {} class r21553065Class<T : AnyObject> {} _ = r21553065Class<r21553065Protocol>() // expected-error {{type 'r21553065Protocol' does not conform to protocol 'AnyObject'}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{use of undeclared type 'Nail'}} func clip() { toenail.inspect { x in toenail.inspect { y in } } } } // <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic class r21447318 { var x = 42 func doThing() -> r21447318 { return self } } func test21447318(a : r21447318, b : () -> r21447318) { a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}} b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}} } // <rdar://problem/20409366> Diagnostics for init calls should print the class name class r20409366C { init(a : Int) {} init?(a : r20409366C) { let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}} } } // <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match func r18800223(i : Int) { // 20099385 _ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}} // 19648528 _ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}} var buttonTextColor: String? _ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}} } // <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back _ = { $0 } // expected-error {{unable to infer closure return type in current context}} _ = 4() // expected-error {{invalid use of '()' to call a value of non-function type 'Int'}} {{6-8=}} _ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}} // <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure. func rdar21784170() { let initial = (1.0 as Double, 2.0 as Double) (Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}} } // <rdar://problem/21829141> BOGUS: unexpected trailing closure func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } } func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } } let expectType1 = expect(Optional(3))(Optional<Int>.self) let expectType1Check: Int = expectType1 // <rdar://problem/19804707> Swift Enum Scoping Oddity func rdar19804707() { enum Op { case BinaryOperator((Double, Double) -> Double) } var knownOps : Op knownOps = Op.BinaryOperator({$1 - $0}) knownOps = Op.BinaryOperator(){$1 - $0} knownOps = Op.BinaryOperator{$1 - $0} knownOps = .BinaryOperator({$1 - $0}) // FIXME: rdar://19804707 - These two statements should be accepted by the type checker. knownOps = .BinaryOperator(){$1 - $0} // expected-error {{reference to member 'BinaryOperator' cannot be resolved without a contextual type}} knownOps = .BinaryOperator{$1 - $0} // expected-error {{reference to member 'BinaryOperator' cannot be resolved without a contextual type}} } // <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type func r20789423() { class C { func f(value: Int) { } } let p: C print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}} let _f = { (v: Int) in // expected-error {{unable to infer closure return type in current context}} print("a") return "hi" } } func f7(a: Int) -> (b: Int) -> Int { return { b in a+b } } f7(1)(b: 1) f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f7(1)(1.0) // expected-error {{missing argument label 'b:' in call}} f7(1)(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let f8 = f7(2) f8(b: 1) f8(10) // expected-error {{missing argument label 'b:' in call}} {{4-4=b: }} f8(1.0) // expected-error {{missing argument label 'b:' in call}} f8(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} class CurriedClass { func method1() {} func method2(a: Int) -> (b : Int) -> () { return { b in () } } func method3(a: Int, b : Int) {} } let c = CurriedClass() _ = c.method1 c.method1(1) // expected-error {{argument passed to call that takes no arguments}} _ = c.method2(1) _ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1)(b: 2) c.method2(1)(c: 2) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} {{14-15=b}} c.method2(1)(c: 2.0) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} c.method2(1)(b: 2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(b: 2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(b: 2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method1(c)() _ = CurriedClass.method1(c) CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}} CurriedClass.method1(2.0)(1) // expected-error {{use of instance member 'method1' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method2(c)(32)(b: 1) _ = CurriedClass.method2(c) _ = CurriedClass.method2(c)(32) _ = CurriedClass.method2(1,2) // expected-error {{use of instance member 'method2' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(1)(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} CurriedClass.method3(c)(32, b: 1) _ = CurriedClass.method3(c) _ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }} _ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}} _ = CurriedClass.method3(1, 2) // expected-error {{use of instance member 'method3' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}} CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}} extension CurriedClass { func f() { method3(1, b: 2) method3() // expected-error {{missing argument for parameter #1 in call}} method3(42) // expected-error {{missing argument for parameter 'b' in call}} method3(self) // expected-error {{missing argument for parameter 'b' in call}} } } extension CurriedClass { func m1(a : Int, b : Int) {} func m2(a : Int) {} } // <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method CurriedClass.m1(2, b: 42) // expected-error {{use of instance member 'm1' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} // <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method CurriedClass.m2(12) // expected-error {{use of instance member 'm2' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} // <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _") func ident<T>(t: T) -> T {} var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}} // <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block var afterMessageCount : Int? = nil func uintFunc() -> UInt {} func takeVoidVoidFn(a : () -> ()) {} takeVoidVoidFn { () -> Void in afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}} } // <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure func f19997471(x: String) {} func f19997471(x: Int) {} func someGeneric19997471<T>(x: T) { takeVoidVoidFn { f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}} // expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}} } } // <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information func f20371273() { let x: [Int] = [1, 2, 3, 4] let y: UInt = 4 x.filter { $0 == y } // expected-error {{binary operator '==' cannot be applied to operands of type 'Int' and 'UInt'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: (UInt, UInt), (Int, Int)}} } // <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } // FIXME: Should complain about not having a return type annotation in the closure. [0].map { _ in let r = (1,2).0; return r } // expected-error @-1 {{expression type '[_]' is ambiguous without more context}} // <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type func rdar21078316() { var foo : [String : String]? var bar : [(String, String)]? bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}} } // <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure var numbers = [1, 2, 3] zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}} // <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type' func foo20868864(callback: ([String]) -> ()) { } func rdar20868864(s: String) { var s = s foo20868864 { (strings: [String]) in s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}} } } // <rdar://problem/20491794> Error message does not tell me what the problem is enum Color { case Red case Unknown(description: String) static func rainbow() -> Color {} static func overload(a a : Int) -> Color {} static func overload(b b : Int) -> Color {} static func frob(a : Int, inout b : Int) -> Color {} } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }} let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }} let _: Int -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{46-46=description: }} let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }} let _: Color = .Unknown // expected-error {{contextual member 'Unknown' expects argument of type '(description: String)'}} let _: Color = .Unknown(42) // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}} let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} let _ : Color = .rainbow // expected-error {{contextual member 'rainbow' expects argument of type '()'}} let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .frob(1.0, &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} var someColor : Color = .red // expected-error {{type 'Color' has no member 'red'}} someColor = .red // expected-error {{type 'Color' has no member 'red'}} func testTypeSugar(a : Int) { typealias Stride = Int let x = Stride(a) x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Memory>), (Int, UnsafePointer<Memory>)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(y : Int) { let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}} //expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (UnsafeMutablePointer<Memory>, Int), (UnsafePointer<Memory>, Int)}} } // <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc protocol r22020088P {} func r22020088Foo<T>(t: T) {} func r22020088bar(p: r22020088P?) { r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}} } // <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type func f(arguments: [String]) -> [ArraySlice<String>] { return arguments.split(1, allowEmptySlices: true, isSeparator: { $0 == "--" }) } struct AOpts : OptionSetType { let rawValue : Int } class B { func function(x : Int8, a : AOpts) {} func f2(a : AOpts) {} static func f1(a : AOpts) {} } func test(a : B) { B.f1(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} a.function(42, a: nil) //expected-error {{nil is not compatible with expected argument type 'AOpts'}} a.function(42, nil) //expected-error {{missing argument label 'a:' in call}} a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} } // <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure typealias MyClosure = ([Int]) -> Bool func r21684487() { var closures = Array<MyClosure>() let testClosure = {(list: [Int]) -> Bool in return true} let closureIndex = closures.indexOf{$0 === testClosure} // expected-error {{cannot convert value of type 'MyClosure' (aka 'Array<Int> -> Bool') to expected argument type 'AnyObject?'}} } // <rdar://problem/18397777> QoI: special case comparisons with nil func r18397777(d : r21447318?) { let c = r21447318() if c != nil { // expected-error {{value of type 'r21447318' can never be nil, comparison isn't allowed}} } if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}} } if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{8-8= == nil)}} } if !Optional(c) { // expected-error {{optional type '_' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{18-18= == nil)}} } } // <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list func r22255907_1<T>(a : T, b : Int) {} func r22255907_2<T>(x : Int, a : T, b: Int) {} func reachabilityForInternetConnection() { var variable: Int = 42 r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}} } // <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}} _ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}} // <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init func r22263468(a : String?) { typealias MyTuple = (Int, String) _ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}} } // rdar://22470302 - Crash with parenthesized call result. class r22470302Class { func f() {} } func r22470302(c: r22470302Class) { print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}} } // <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile extension String { @available(*, unavailable, message="calling this is unwise") func unavail<T : SequenceType where T.Generator.Element == String> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}} (a : T) -> String {} } extension Array { func g() -> String { return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } func h() -> String { return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } } // <rdar://problem/22519983> QoI: Weird error when failing to infer archetype func safeAssign<T: RawRepresentable>(inout lhs: T) -> Bool {} // expected-note @-1 {{in call to function 'safeAssign'}} let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure func foo() -> [Int] { return Array <Int> (count: 1) { // expected-error {{cannot invoke initializer for type 'Array<Int>' with an argument list of type '(count: Int, () -> _)'}} // expected-note @-1 {{expected an argument list of type '(count: Int, repeatedValue: Element)'}} return 1 } } // <rdar://problem/17557899> - This shouldn't suggest calling with (). func someOtherFunction() {} func someFunction() -> () { // Producing an error suggesting that this return someOtherFunction // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic func r23560128() { var a : (Int,Int)? a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=!}} } // <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping struct ExampleStruct21890157 { var property = "property" } var example21890157: ExampleStruct21890157? example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=!}} struct UnaryOp {} _ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}} // expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(x : UnsafePointer<Int>) {} func segfault23433271(a : UnsafeMutablePointer<Void>) { f23433271(a[0]) // expected-error {{cannot convert value of type 'Void' (aka '()') to expected argument type 'UnsafePointer<Int>'}} } // <rdar://problem/22058555> crash in cs diags in withCString func r22058555() { var firstChar: UInt8 = 0 "abc".withCString { chars in firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} } } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets func r23641896() { var g = "Hello World" g.replaceRange(0...2, with: "ce") // expected-error {{String may not be indexed with 'Int', it has variable size elements}} // expected-note @-1 {{consider using an existing high level algorithm, str.startIndex.advancedBy(n), or a projection like str.utf8}} _ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}} } // <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 match.append(row, col) // expected-error {{extra argument in call}} }
apache-2.0
5f2e6ed21bd95e7daf613c17b86833f9
41.546463
193
0.670459
3.603007
false
false
false
false
insidegui/WWDC
PlayerUI/Controllers/PUIExternalPlaybackStatusViewController.swift
1
4236
// // PUIExternalPlaybackStatusViewController.swift // PlayerUI // // Created by Guilherme Rambo on 13/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa class PUIExternalPlaybackStatusViewController: NSViewController { private let blurFilter: CIFilter = { let f = CIFilter(name: "CIGaussianBlur")! f.setValue(100, forKey: kCIInputRadiusKey) return f }() private let saturationFilter: CIFilter = { let f = CIFilter(name: "CIColorControls")! f.setDefaults() f.setValue(2, forKey: kCIInputSaturationKey) return f }() private lazy var context = CIContext(options: [.useSoftwareRenderer: true]) var snapshot: CGImage? { didSet { snapshotLayer.contents = snapshot.flatMap { cgImage in let targetSize = snapshotLayer.bounds let transform = CGAffineTransform(scaleX: targetSize.width / CGFloat(cgImage.width), y: targetSize.height / CGFloat(cgImage.height)) let ciImage = CIImage(cgImage: cgImage).transformed(by: transform) let filters = [saturationFilter, blurFilter] guard let filteredImage = ciImage.filtered(with: filters) else { return nil } return context.createCGImage(filteredImage, from: ciImage.extent) } } } var providerIcon: NSImage? { didSet { iconImageView.image = providerIcon } } var providerName: String = "" { didSet { titleLabel.stringValue = providerName } } var providerDescription: String = "" { didSet { descriptionLabel.stringValue = providerDescription } } init() { super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var iconImageView: NSImageView = { let v = NSImageView() v.widthAnchor.constraint(equalToConstant: 74).isActive = true v.heightAnchor.constraint(equalToConstant: 74).isActive = true return v }() private lazy var titleLabel: NSTextField = { let f = NSTextField(labelWithString: "") f.font = .systemFont(ofSize: 20, weight: .medium) f.textColor = .externalPlaybackText f.alignment = .center return f }() private lazy var descriptionLabel: NSTextField = { let f = NSTextField(labelWithString: "") f.font = .systemFont(ofSize: 16) f.textColor = .timeLabel f.alignment = .center return f }() private lazy var stackView: NSStackView = { let v = NSStackView(views: [self.iconImageView, self.titleLabel, self.descriptionLabel]) v.translatesAutoresizingMaskIntoConstraints = false v.orientation = .vertical v.spacing = 6 return v }() private lazy var snapshotLayer: PUIBoringLayer = { let l = PUIBoringLayer() l.autoresizingMask = [.layerWidthSizable, .layerHeightSizable] l.backgroundColor = NSColor.black.cgColor return l }() override func loadView() { view = NSView() view.wantsLayer = true view.layer = PUIBoringLayer() view.layer?.masksToBounds = true view.layer?.backgroundColor = NSColor.black.cgColor snapshotLayer.frame = view.bounds view.layer?.addSublayer(snapshotLayer) view.addSubview(stackView) stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } } extension CIImage { func filtered(with ciFilters: [CIFilter]) -> CIImage? { var inputImage = self.clampedToExtent() var finalFilter: CIFilter? for filter in ciFilters { finalFilter = filter filter.setValue(inputImage, forKey: kCIInputImageKey) if let output = filter.outputImage { inputImage = output } } return finalFilter?.outputImage } }
bsd-2-clause
ef559b92b65b3a90cf28887796a060b9
26.861842
100
0.61464
5.041667
false
false
false
false
timfuqua/Bourgeoisie
Bourgeoisie/Bourgeoisie/Utility/CollectionUtility.swift
1
816
// // CollectionUtility.swift // Bourgeoisie // // Created by Tim Fuqua on 10/14/15. // Copyright © 2015 FuquaProductions. All rights reserved. // import Foundation // http://stackoverflow.com/a/24029847/4273137 extension CollectionType { /// Return a copy of `self` with its elements shuffled func shuffle() -> [Generator.Element] { var list = Array(self) list.shuffleInPlace() return list } } extension MutableCollectionType where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffleInPlace() { // empty and single-element collections don't shuffle if count < 2 { return } for i in 0..<count - 1 { let j = Int(arc4random_uniform(UInt32(count - i))) + i guard i != j else { continue } swap(&self[i], &self[j]) } } }
mit
f06c8c57747f1ecd053248a1791c614f
23.727273
60
0.650307
3.606195
false
false
false
false
nifty-swift/Nifty
Sources/rmap.swift
2
2663
/******************************************************************************* * rmap.swift * * This file provides functionality for remapping a number to a new range. * * Author: Philip Erickson * Creation Date: 1 May 2016 * Contributors: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2016 Philip Erickson ******************************************************************************/ /// Maps a number linearly from one range to another. /// /// - Parameters: /// - x: number to map /// - from: original range /// - to: target range /// - Returns: re-mapped number func rmap(_ x: Double, from: Range<Int>, to: Range<Int>) -> Double { let fromLow = Double(from.lowerBound) let fromHigh = Double(from.upperBound-1) let toLow = Double(to.lowerBound) let toHigh = Double(to.upperBound-1) return rmap(x, l: fromLow, h: fromHigh, tl: toLow, th: toHigh) } // TODO: should overloads get a comment header? // Check out how doc tool (e.g. jazzy) handles this func rmap(_ x: Int, from: Range<Int>, to: Range<Int>) -> Double { // FIXME: check whether this upperBound-1 makes sense (hold over from Swift 2.2) let fromLow = Double(from.lowerBound) let fromHigh = Double(from.upperBound-1) let toLow = Double(to.lowerBound) let toHigh = Double(to.upperBound-1) return rmap(Double(x), l: fromLow, h: fromHigh, tl: toLow, th: toHigh) } func rmap(_ x: Double, from: ClosedRange<Double>, to: ClosedRange<Double>) -> Double { let fromLow = from.lowerBound let fromHigh = from.upperBound let toLow = to.lowerBound let toHigh = to.upperBound return rmap(x, l: fromLow, h: fromHigh, tl: toLow, th: toHigh) } func rmap(_ x: Int, from: ClosedRange<Double>, to: ClosedRange<Double>) -> Double { let fromLow = from.lowerBound let fromHigh = from.upperBound let toLow = to.lowerBound let toHigh = to.upperBound return rmap(Double(x), l: fromLow, h: fromHigh, tl: toLow, th: toHigh) } private func rmap(_ x: Double, l: Double, h: Double, tl: Double, th: Double) -> Double { return (x-l) * (th-tl)/(h-l) + tl }
apache-2.0
4e8fd21ddac3573ab361d420bf319d27
31.47561
84
0.631243
3.815186
false
false
false
false
MakiZz/30DaysToLearnSwift3.0
project 25 - 基础动画/project 25 - 基础动画/OpacityViewController.swift
1
1734
// // OpacityViewController.swift // project 25 - 基础动画 // // Created by mk on 17/4/1. // Copyright © 2017年 maki. All rights reserved. // import UIKit class OpacityViewController: UIViewController { var view1 = UIView() var view2 = UIView() var view3 = UIView() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white view1.frame = CGRect.init(x: 30, y: 94, width: 100, height: 100) view2.frame = CGRect.init(x: 245, y: 94, width: 100, height: 100) view3.frame = CGRect.init(x: 87, y: 219, width: 200, height: 20) view1.backgroundColor = UIColor.black view2.backgroundColor = UIColor.black view3.backgroundColor = UIColor.black self.view.addSubview(view1) self.view.addSubview(view2) self.view.addSubview(view3) } override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 0.8, delay: 0.2, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: { self.view1.center.x = self.view.bounds.width - self.view1.center.x self.view1.center.y += 30 self.view2.center.x = self.view.bounds.width - self.view2.center.x self.view2.center.y += 30 }, completion: nil) UIView.animate(withDuration: 0.6, delay: 0.4, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: { self.view3.frame.size.height = 100 self.view3.center.y = self.view.bounds.height - self.view3.center.y }, completion: nil) } }
mit
805a773da97809a390978c4a4cf56980
32.784314
151
0.609402
3.795154
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00903-swift-scopeinfo-addtoscope.swift
11
627
// 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 struct S<T where A: AnyObject, b { } var f: Array<T, e: NSObject { struct c == nil self.B == { S(false)? } typealias e : String { self.b = b: a { } private let c { } class C) { protocol P { } protocol d where I) -> : a { } init(t: C {
apache-2.0
7e0b59a49c3aebc5233be36e270d656c
23.115385
78
0.685805
3.19898
false
false
false
false
skywalkerDavid/TipCalculator
Tips/SettingsViewController.swift
1
1477
// // SettingsViewController.swift // Tips // // Created by dawei_wang on 8/20/17. // Copyright © 2017 dawei_wang. All rights reserved. // import UIKit class SettingsViewController: UIViewController { let DEFAULT_PERCENTAGE_SETTING_KEY = "default_tip_percentage" @IBOutlet weak var defaultTipSegment: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let defaults = UserDefaults.standard let defaultPercentageIndex = defaults.integer(forKey: DEFAULT_PERCENTAGE_SETTING_KEY) defaultTipSegment.selectedSegmentIndex = defaultPercentageIndex } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func onTapDefaultTipPercentage(_ sender: Any) { let defaults = UserDefaults.standard defaults.set(defaultTipSegment.selectedSegmentIndex, forKey: DEFAULT_PERCENTAGE_SETTING_KEY) defaults.synchronize() } }
apache-2.0
fc52ec188f00e7bee6500c2f6002cfbd
29.75
106
0.691057
4.92
false
false
false
false
keighl/Pathology
Pathology/Path.swift
1
2175
// // Path.swift // Pathology // // Created by Kyle Truscott on 3/2/16. // Copyright © 2016 keighl. All rights reserved. // import Foundation import QuartzCore public struct Path { var elements: [Element] = [] public func toArray() -> [[String: AnyObject]] { return elements.map({el in return el.toDictionary() }) } public func toJSON(options: NSJSONWritingOptions) throws -> NSData { let data = try NSJSONSerialization.dataWithJSONObject(toArray(), options: options) return data } public func CGPath() -> QuartzCore.CGPath { let path = CGPathCreateMutable() for el in elements { let endPoint = el.endPoint() let ctrl1 = el.ctrlPoint1() let ctrl2 = el.ctrlPoint2() switch el.type { case .MoveToPoint: CGPathMoveToPoint(path, nil, endPoint.x, endPoint.y) case .AddLineToPoint: CGPathAddLineToPoint(path, nil, endPoint.x, endPoint.y) break case .AddQuadCurveToPoint: CGPathAddQuadCurveToPoint(path, nil, ctrl1.x, ctrl1.y, endPoint.x, endPoint.y) break case .AddCurveToPoint: CGPathAddCurveToPoint(path, nil, ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, endPoint.x, endPoint.y) break case .CloseSubpath: CGPathCloseSubpath(path) break case .Invalid: break } } return path } } extension Path { public init?(JSON: NSData) { do { let obj = try NSJSONSerialization.JSONObjectWithData(JSON, options: NSJSONReadingOptions(rawValue: 0)) if let arr = obj as? [[String: AnyObject]] { self.elements = arr.map({ el in return Element(dictionary: el) }) } } catch { return nil } } public init(data: [[String: AnyObject]]) { self.elements = data.map({ el in return Element(dictionary: el) }) } }
mit
e5d06f877e428b3f70bd0aab616f8902
27.618421
114
0.535419
4.726087
false
false
false
false
MobileFirstInc/MFCard
MFCard/Card /Helper Class/LBZSpinner.swift
1
13535
// // LBZSpinner.swift // LBZSpinner // // Created by LeBzul on 18/02/2016. // Copyright © 2016 LeBzul. All rights reserved. // import Foundation import UIKit @IBDesignable class LBZSpinner : UIView, UITableViewDelegate, UITableViewDataSource { fileprivate var firstDraw:Bool = true let heightTableviewCell:CGFloat = 45 var heightTableview:CGFloat = 200 //public variable static var INDEX_NOTHING = 0 //spinner @IBInspectable var textColor: UIColor = UIColor.gray { didSet{ updateUI() } } @IBInspectable var lineColor: UIColor = UIColor.gray { didSet{ updateUI() } } @IBInspectable var list:[String] = [String]() { didSet{ updateUI() } } @IBInspectable var text: String = "" { didSet{ updateUI() } } //Drop down list @IBInspectable var dDLMaxSize: CGFloat = 250 @IBInspectable var dDLColor: UIColor = UIColor.white @IBInspectable var dDLTextColor: UIColor = UIColor.gray @IBInspectable var dDLStroke: Bool = true @IBInspectable var dDLStrokeColor: UIColor = UIColor.gray @IBInspectable var dDLStrokeSize: CGFloat = 1 //Drop down list view back @IBInspectable var dDLblurEnable: Bool = true var delegate:LBZSpinnerDelegate! //actual seleted index fileprivate(set) internal var selectedIndex = INDEX_NOTHING open var labelValue: UILabel! fileprivate var blurEffectView:UIVisualEffectView! fileprivate var viewChooseDisable: UIView! fileprivate var tableviewChoose: UITableView! fileprivate var tableviewChooseShadow: UIView! override init(frame: CGRect) { super.init(frame: frame) self.initCustomView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initCustomView() } override func prepareForInterfaceBuilder() { backgroundColor = UIColor.clear // clear black background IB } fileprivate func initCustomView() { backgroundColor = UIColor.clear // clear black background NotificationCenter.default.addObserver(self, selector: #selector(LBZSpinner.orientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil) //Open spinner click let gesture = UITapGestureRecognizer(target: self, action: #selector(LBZSpinner.openSpinner(_:))) addGestureRecognizer(gesture) heightTableview = heightTableviewCell*CGFloat(list.count) } override func draw(_ rect: CGRect) { super.draw(rect) if firstDraw { //create spinner label labelValue = UILabel(frame: bounds) addSubview(labelValue) updateUI() firstDraw = false } drawCanvas(frame: rect) } func changeSelectedIndex(_ index:Int) { if list.count > index { selectedIndex = index text = list[selectedIndex] updateUI() if (delegate != nil) { delegate.spinnerChoose(self,index:selectedIndex, value: list[selectedIndex]) } } } fileprivate func updateUI() { if (labelValue != nil) { labelValue.text = text labelValue.textAlignment = .center labelValue.textColor = textColor } setNeedsDisplay() } //Config spinner style func decoratedSpinner(_ textColor:UIColor!,lineColor:UIColor!,text:String!) { if(textColor != nil) { self.textColor=textColor } if(lineColor != nil) { self.lineColor=lineColor } if(text != nil) { self.text=text } } //Config drop down list style func decoratedDropDownList(_ backgroundColor:UIColor!,textColor:UIColor!,withStroke:Bool!,strokeSize:CGFloat!,strokeColor:UIColor!) { if(backgroundColor != nil) { dDLColor=backgroundColor } if(textColor != nil) { dDLTextColor=textColor } if(withStroke != nil) { dDLStroke=withStroke } if(strokeSize != nil) { dDLStrokeSize=strokeSize } if(strokeColor != nil) { dDLStrokeColor=strokeColor } } //Update drop down list func updateList(_ list:[String]) { self.list = list; heightTableview = heightTableviewCell*CGFloat(list.count) if(tableviewChoose != nil) { tableviewChoose.reloadData() } } //Open spinner animation @objc func openSpinner(_ sender:UITapGestureRecognizer){ heightTableview = heightTableviewCell*CGFloat(list.count) let parentView = findLastUsableSuperview() let globalPoint = convert(bounds.origin, to:parentView) // position spinner in superview viewChooseDisable = UIView(frame: parentView.frame) // view back click if(dDLblurEnable) { // with blur effect let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark) blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.effect = nil blurEffectView.backgroundColor = UIColor.black.withAlphaComponent(0) blurEffectView.frame = viewChooseDisable.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] viewChooseDisable.addSubview(blurEffectView) } var expandBottomDirection = true if((globalPoint.y+heightTableview) < parentView.frame.height) { expandBottomDirection = true } else if((globalPoint.y-heightTableview) > 0) { expandBottomDirection = false } else { //find best direction let margeBot = parentView.frame.height - globalPoint.y let margeTop = parentView.frame.height - (parentView.frame.height - globalPoint.y) if( margeBot > margeTop ) { expandBottomDirection = true heightTableview = margeBot - 5 } else { expandBottomDirection = false heightTableview = margeTop - 5 } } if(heightTableview > dDLMaxSize) { heightTableview = dDLMaxSize } // expand bottom animation if (expandBottomDirection) { tableviewChoose = UITableView(frame: CGRect(x: globalPoint.x , y: globalPoint.y, width: frame.size.width, height: 0)) tableviewChooseShadow = UIView(frame: tableviewChoose.frame) UIView.animate(withDuration: 0.3, delay: 0.0, options: UIView.AnimationOptions.transitionFlipFromBottom, animations: { self.tableviewChoose.frame.size.height = self.heightTableview self.tableviewChooseShadow.frame.size.height = self.heightTableview if self.blurEffectView != nil { self.blurEffectView.backgroundColor = UIColor.black.withAlphaComponent(0.5) } }, completion: { finished in }) } // expand top animation else { tableviewChoose = UITableView(frame: CGRect(x: globalPoint.x , y: globalPoint.y, width: frame.size.width, height: self.frame.height)) tableviewChooseShadow = UIView(frame: tableviewChoose.frame) UIView.animate(withDuration: 0.3, delay: 0.0, options: UIView.AnimationOptions.transitionFlipFromBottom, animations: { self.tableviewChoose.frame.origin.y = globalPoint.y-self.heightTableview+self.frame.height self.tableviewChoose.frame.size.height = self.heightTableview self.tableviewChooseShadow.frame.origin.y = globalPoint.y-self.heightTableview+self.frame.height self.tableviewChooseShadow.frame.size.height = self.heightTableview if self.blurEffectView != nil { self.blurEffectView.backgroundColor = UIColor.black.withAlphaComponent(0.5) } }, completion: { finished in }) } // config tableview drop down list tableviewChoose.backgroundColor = dDLColor tableviewChoose.tableFooterView = UIView() //Eliminate Extra separators below UITableView tableviewChoose.delegate = self tableviewChoose.dataSource = self tableviewChoose.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") tableviewChoose.isUserInteractionEnabled = true tableviewChoose.showsHorizontalScrollIndicator = false tableviewChoose.showsVerticalScrollIndicator = false tableviewChoose.separatorStyle = UITableViewCell.SeparatorStyle.none tableviewChoose.layer.cornerRadius = 5 //Show stroke if(dDLStroke) { tableviewChoose.layer.borderColor = dDLStrokeColor.cgColor tableviewChoose.layer.borderWidth = dDLStrokeSize } // config shadow drop down list tableviewChooseShadow.backgroundColor = dDLColor tableviewChooseShadow.layer.shadowOpacity = 0.5; tableviewChooseShadow.layer.shadowOffset = CGSize(width: 3, height: 3); tableviewChooseShadow.layer.shadowRadius = 5; tableviewChooseShadow.layer.cornerRadius = 5 tableviewChooseShadow.layer.masksToBounds = false tableviewChooseShadow.clipsToBounds = false // add to superview parentView.addSubview(viewChooseDisable) parentView.addSubview(tableviewChooseShadow) parentView.addSubview(tableviewChoose) // close spinner click back let gesture = UITapGestureRecognizer(target: self, action: #selector(LBZSpinner.closeSpinner)) viewChooseDisable.addGestureRecognizer(gesture) } // close spinner animation @objc func closeSpinner() { if(tableviewChoose != nil) { UIView.animate(withDuration: 0.3, delay: 0.0, options: UIView.AnimationOptions.transitionFlipFromBottom, animations: { self.tableviewChoose.alpha = 0.0 self.tableviewChooseShadow.alpha = 0.0 self.viewChooseDisable.alpha = 0.0 }, completion: { finished in // delete dropdown list if self.tableviewChoose == nil{return} self.tableviewChoose.removeFromSuperview() self.viewChooseDisable.removeFromSuperview() self.tableviewChooseShadow.removeFromSuperview() self.tableviewChoose = nil self.tableviewChooseShadow = nil self.viewChooseDisable = nil }) } } // find usable superview fileprivate func findLastUsableSuperview() -> UIView { if let last = UIApplication.shared.keyWindow?.subviews.last as UIView?{ return last } return (window?.subviews[0])! } //draw background spinner fileprivate func drawCanvas(frame: CGRect = CGRect(x: 0, y: 0, width: 86, height: 11)) { let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: frame.maxX - 11, y: frame.maxY)) bezierPath.addLine(to: CGPoint(x: frame.maxX, y: frame.maxY)) bezierPath.addLine(to: CGPoint(x: frame.maxX, y: frame.maxY - 11)) bezierPath.addLine(to: CGPoint(x: frame.maxX - 11, y: frame.maxY)) bezierPath.close() bezierPath.lineCapStyle = .square; bezierPath.lineJoinStyle = .bevel; lineColor.setFill() bezierPath.fill() let rectanglePath = UIBezierPath(rect: CGRect(x: frame.minX, y: frame.minY + frame.height - 1, width: frame.width, height: 1)) lineColor.setFill() rectanglePath.fill() } @objc func orientationChanged() { /* if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) {} if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) {} */ if tableviewChoose != nil { closeSpinner() } } /** * TableView Delegate method **/ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { labelValue.text = list[indexPath.row] if (delegate != nil) { delegate.spinnerChoose(self,index: indexPath.row, value: list[indexPath.row]) } selectedIndex = indexPath.row closeSpinner() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return list.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for:indexPath) as UITableViewCell cell.contentView.backgroundColor = dDLColor cell.textLabel?.backgroundColor = UIColor.clear cell.detailTextLabel?.backgroundColor = UIColor.clear cell.textLabel?.text = list[indexPath.row] cell.textLabel?.textColor = dDLTextColor cell.textLabel?.textAlignment = .center cell.textLabel?.adjustsFontSizeToFitWidth = true return cell } } protocol LBZSpinnerDelegate{ func spinnerChoose(_ spinner:LBZSpinner, index:Int,value:String) }
mit
ec31221207af630c90d7e494635072a2
34.709763
166
0.631225
5.355758
false
false
false
false
zhengrenzhe/Liveline
Liveline/lib/motion.swift
1
2800
// // motion.swift // scene // // Created by zhengrenzhe on 16/5/15. // Copyright © 2016年 zhengrenzhe. All rights reserved. // import Foundation import CoreMotion class Motion: NSObject{ var UpdateInterval = 0.02 var Motion = CMMotionManager() var Altimeter = CMAltimeter() var Queue = NSOperationQueue() let Notify = NSNotificationCenter.defaultCenter() override init(){ super.init() Motion.accelerometerUpdateInterval = UpdateInterval Motion.gyroUpdateInterval = UpdateInterval Motion.magnetometerUpdateInterval = UpdateInterval Motion.showsDeviceMovementDisplay = true } func UpdateIntervalTime(time: Double){ self.UpdateInterval = time } func StartUpdate(){ if Motion.accelerometerAvailable{ Motion.startAccelerometerUpdatesToQueue(Queue, withHandler: OnAccelerometerUpdate) } if Motion.gyroAvailable{ Motion.startGyroUpdatesToQueue(Queue, withHandler: OnGyroUpdate) } if Motion.magnetometerAvailable{ Motion.startMagnetometerUpdatesToQueue(Queue, withHandler: OnMagnetometerUpdate) } if CMAltimeter.isRelativeAltitudeAvailable(){ Altimeter.startRelativeAltitudeUpdatesToQueue(Queue, withHandler: OnAltimeterUpdate) } if Motion.deviceMotionAvailable{ Motion.startDeviceMotionUpdatesToQueue(Queue, withHandler: OnDeviceMotionUpdate) } } func OnAccelerometerUpdate(AccelerometerData: CMAccelerometerData?, error: NSError?){ if let data = AccelerometerData{ Notify.postNotificationName("AccelerometerUpdate", object: [data.acceleration.x, data.acceleration.y, data.acceleration.z]) } } func OnGyroUpdate(GyroData: CMGyroData?, error: NSError?){ if let data = GyroData{ Notify.postNotificationName("GyroUpdate", object: [data.rotationRate.x, data.rotationRate.y, data.rotationRate.z]) } } func OnMagnetometerUpdate(MagnetometerData: CMMagnetometerData?, error: NSError?){ if let data = MagnetometerData{ Notify.postNotificationName("MagnetometerUpdate", object: [data.magneticField.x, data.magneticField.y, data.magneticField.z]) } } func OnAltimeterUpdate(AltimeterUpdateData: CMAltitudeData?, error: NSError?){ if let data = AltimeterUpdateData{ Notify.postNotificationName("AltimeterUpdate", object: [data.pressure]) } } func OnDeviceMotionUpdate(DeviceMotionData: CMDeviceMotion?, error: NSError?){ if let data = DeviceMotionData { Notify.postNotificationName("DeviceMotionUpdate", object: [data]) } } }
mit
5cb14de57bbb5d6999f719a862e2e9ad
31.905882
137
0.673579
5.17963
false
true
false
false
anthrgrnwrld/shootSpeed
Renda/GKScoreUtil.swift
1
759
// // GKScoreUtil.swift // Renda // // Created by Masaki Horimoto on 2015/08/17. // Copyright (c) 2015年 Masaki Horimoto. All rights reserved. // import UIKit import GameKit struct GKScoreUtil { static func reportScores(_ value:Int, leaderboardid:String){ print("\(#function) is called") let score:GKScore = GKScore(); score.value = Int64(value); score.leaderboardIdentifier = leaderboardid; let scoreArr:[GKScore] = [score]; GKScore.report(scoreArr, withCompletionHandler:{(error:Error?) -> Void in if( (error != nil)){ print("reportScore NG"); }else{ print("reportScore OK"); } }); } }
mit
83fb4b2bc52948bd1253dadf45335774
23.419355
81
0.558785
4.22905
false
false
false
false
austinzheng/swift
test/SILGen/opaque_ownership.swift
12
11290
// RUN: %target-swift-emit-silgen -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s // RUN: %target-swift-emit-silgen -target x86_64-apple-macosx10.9 -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck --check-prefix=CHECK-OSX %s public typealias AnyObject = Builtin.AnyObject precedencegroup AssignmentPrecedence {} precedencegroup CastingPrecedence {} precedencegroup ComparisonPrecedence {} public protocol _ObjectiveCBridgeable {} public protocol UnkeyedDecodingContainer { var isAtEnd: Builtin.Int1 { get } } public protocol Decoder { func unkeyedContainer() throws -> UnkeyedDecodingContainer } // Test open_existential_value ownership // --- // CHECK-LABEL: sil [ossa] @$ss11takeDecoder4fromBi1_s0B0_p_tKF : $@convention(thin) (@in_guaranteed Decoder) -> (Builtin.Int1, @error Error) { // CHECK: bb0(%0 : @guaranteed $Decoder): // CHECK: [[OPENED:%.*]] = open_existential_value %0 : $Decoder to $@opened("{{.*}}") Decoder // CHECK: [[WT:%.*]] = witness_method $@opened("{{.*}}") Decoder, #Decoder.unkeyedContainer!1 : <Self where Self : Decoder> (Self) -> () throws -> UnkeyedDecodingContainer, %3 : $@opened("{{.*}}") Decoder : $@convention(witness_method: Decoder) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Error) // CHECK: try_apply [[WT]]<@opened("{{.*}}") Decoder>([[OPENED]]) : $@convention(witness_method: Decoder) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Error), normal bb2, error bb1 // // CHECK:bb{{.*}}([[RET1:%.*]] : @owned $UnkeyedDecodingContainer): // CHECK: [[BORROW2:%.*]] = begin_borrow [[RET1]] : $UnkeyedDecodingContainer // CHECK: [[OPENED2:%.*]] = open_existential_value [[BORROW2]] : $UnkeyedDecodingContainer to $@opened("{{.*}}") UnkeyedDecodingContainer // CHECK: [[WT2:%.*]] = witness_method $@opened("{{.*}}") UnkeyedDecodingContainer, #UnkeyedDecodingContainer.isAtEnd!getter.1 : <Self where Self : UnkeyedDecodingContainer> (Self) -> () -> Builtin.Int1, [[OPENED2]] : $@opened("{{.*}}") UnkeyedDecodingContainer : $@convention(witness_method: UnkeyedDecodingContainer) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1 // CHECK: [[RET2:%.*]] = apply [[WT2]]<@opened("{{.*}}") UnkeyedDecodingContainer>([[OPENED2]]) : $@convention(witness_method: UnkeyedDecodingContainer) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1 // CHECK: end_borrow [[BORROW2]] : $UnkeyedDecodingContainer // CHECK: destroy_value [[RET1]] : $UnkeyedDecodingContainer // CHECK-NOT: destroy_value %0 : $Decoder // CHECK: return [[RET2]] : $Builtin.Int1 // CHECK-LABEL: } // end sil function '$ss11takeDecoder4fromBi1_s0B0_p_tKF' public func takeDecoder(from decoder: Decoder) throws -> Builtin.Int1 { let container = try decoder.unkeyedContainer() return container.isAtEnd } // Test unsafe_bitwise_cast nontrivial ownership. // --- // CHECK-LABEL: sil [ossa] @$ss13unsafeBitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG0:%.*]] : @guaranteed $T, [[ARG1:%.*]] : $@thick U.Type): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG0]] : $T // CHECK: [[RESULT:%.*]] = unchecked_bitwise_cast [[ARG_COPY]] : $T to $U // CHECK: [[RESULT_COPY:%.*]] = copy_value [[RESULT]] : $U // CHECK: destroy_value [[ARG_COPY]] : $T // CHECK: return [[RESULT_COPY]] : $U // CHECK-LABEL: } // end sil function '$ss13unsafeBitCast_2toq_x_q_mtr0_lF' public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { return Builtin.reinterpretCast(x) } // A lot of standard library support is necessary to support raw enums. // -------------------------------------------------------------------- infix operator == : ComparisonPrecedence infix operator ~= : ComparisonPrecedence public struct Bool { var _value: Builtin.Int1 public init() { let zero: Int64 = 0 self._value = Builtin.trunc_Int64_Int1(zero._value) } internal init(_ v: Builtin.Int1) { self._value = v } public init(_ value: Bool) { self = value } } extension Bool { public func _getBuiltinLogicValue() -> Builtin.Int1 { return _value } } public protocol Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func == (lhs: Self, rhs: Self) -> Bool } public func ~= <T : Equatable>(a: T, b: T) -> Bool { return a == b } public protocol RawRepresentable { associatedtype RawValue init?(rawValue: RawValue) var rawValue: RawValue { get } } public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool where T.RawValue : Equatable { return lhs.rawValue == rhs.rawValue } public typealias _MaxBuiltinIntegerType = Builtin.IntLiteral public protocol _ExpressibleByBuiltinIntegerLiteral { init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) } public protocol ExpressibleByIntegerLiteral { associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral init(integerLiteral value: IntegerLiteralType) } extension ExpressibleByIntegerLiteral where Self : _ExpressibleByBuiltinIntegerLiteral { @_transparent public init(integerLiteral value: Self) { self = value } } public protocol ExpressibleByStringLiteral {} public protocol ExpressibleByFloatLiteral {} public protocol ExpressibleByUnicodeScalarLiteral {} public protocol ExpressibleByExtendedGraphemeClusterLiteral {} public struct Int64 : ExpressibleByIntegerLiteral, _ExpressibleByBuiltinIntegerLiteral, Equatable { public var _value: Builtin.Int64 public init(_builtinIntegerLiteral x: _MaxBuiltinIntegerType) { _value = Builtin.s_to_s_checked_trunc_IntLiteral_Int64(x).0 } public typealias IntegerLiteralType = Int64 public init(integerLiteral value: Int64) { self = value } public static func ==(_ lhs: Int64, rhs: Int64) -> Bool { return Bool(Builtin.cmp_eq_Int64(lhs._value, rhs._value)) } } // Test ownership of multi-case Enum values in the context of to @in thunks. // --- // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW : $@convention(witness_method: Equatable) (@in_guaranteed FloatingPointSign, @in_guaranteed FloatingPointSign, @thick FloatingPointSign.Type) -> Bool { // CHECK: bb0(%0 : $FloatingPointSign, %1 : $FloatingPointSign, %2 : $@thick FloatingPointSign.Type): // CHECK: %3 = function_ref @$ss2eeoiySbx_xtSYRzSQ8RawValueRpzlF : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool // CHECK: %4 = apply %3<FloatingPointSign>(%0, %1) : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool // CHECK: return %4 : $Bool // CHECK-LABEL: } // end sil function '$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW' public enum FloatingPointSign: Int64 { /// The sign for a positive value. case plus /// The sign for a negative value. case minus } #if os(macOS) // Test open_existential_value used in a conversion context. // (the actual bridging call is dropped because we don't import Swift). // --- // CHECK-OSX-LABEL: sil [ossa] @$ss26_unsafeDowncastToAnyObject04fromD0yXlyp_tF : $@convention(thin) (@in_guaranteed Any) -> @owned AnyObject { // CHECK-OSX: bb0(%0 : @guaranteed $Any): // CHECK-OSX: [[COPY:%.*]] = copy_value %0 : $Any // CHECK-OSX: [[BORROW2:%.*]] = begin_borrow [[COPY]] : $Any // CHECK-OSX: [[VAL:%.*]] = open_existential_value [[BORROW2]] : $Any to $@opened // CHECK-OSX: [[COPY2:%.*]] = copy_value [[VAL]] : $@opened // CHECK-OSX: end_borrow [[BORROW2]] : $Any // CHECK-OSX: destroy_value [[COPY2]] : $@opened // CHECK-OSX: destroy_value [[COPY]] : $Any // CHECK-OSX-NOT: destroy_value %0 : $Any // CHECK-OSX: return undef : $AnyObject // CHECK-OSX-LABEL: } // end sil function '$ss26_unsafeDowncastToAnyObject04fromD0yXlyp_tF' public func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject { return any as AnyObject } #endif public protocol Error {} #if os(macOS) // Test open_existential_box_value in a conversion context. // --- // CHECK-OSX-LABEL: sil [ossa] @$ss3foo1eys5Error_pSg_tF : $@convention(thin) (@guaranteed Optional<Error>) -> () { // CHECK-OSX: [[BORROW:%.*]] = begin_borrow %{{.*}} : $Error // CHECK-OSX: [[VAL:%.*]] = open_existential_box_value [[BORROW]] : $Error to $@opened // CHECK-OSX: [[COPY:%.*]] = copy_value [[VAL]] : $@opened // CHECK-OSX: [[ANY:%.*]] = init_existential_value [[COPY]] : $@opened // CHECK-OSX: end_borrow [[BORROW]] : $Error // CHECK-OSX-LABEL: } // end sil function '$ss3foo1eys5Error_pSg_tF' public func foo(e: Error?) { if let u = e { let a: Any = u _ = a } } #endif public enum Optional<Wrapped> { case none case some(Wrapped) } public protocol IP {} public protocol Seq { associatedtype Iterator : IP func makeIterator() -> Iterator } extension Seq where Self.Iterator == Self { public func makeIterator() -> Self { return self } } public struct EnumIter<Base : IP> : IP, Seq { internal var _base: Base public typealias Iterator = EnumIter<Base> } // Test passing a +1 RValue to @in_guaranteed. // --- // CHECK-LABEL: sil [ossa] @$ss7EnumSeqV12makeIterators0A4IterVy0D0QzGyF : $@convention(method) <Base where Base : Seq> (@in_guaranteed EnumSeq<Base>) -> @out EnumIter<Base.Iterator> { // CHECK: bb0(%0 : @guaranteed $EnumSeq<Base>): // CHECK: [[MT:%.*]] = metatype $@thin EnumIter<Base.Iterator>.Type // CHECK: [[FIELD:%.*]] = struct_extract %0 : $EnumSeq<Base>, #EnumSeq._base // CHECK: [[COPY:%.*]] = copy_value [[FIELD]] : $Base // CHECK: [[WT:%.*]] = witness_method $Base, #Seq.makeIterator!1 : <Self where Self : Seq> (Self) -> () -> Self.Iterator : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator // CHECK: [[ITER:%.*]] = apply [[WT]]<Base>([[COPY]]) : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator // CHECK: destroy_value [[COPY]] : $Base // CHECK: [[FN:%.*]] = function_ref @$ss8EnumIterV5_baseAByxGx_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0> // CHECK: [[RET:%.*]] = apply [[FN]]<Base.Iterator>([[ITER]], [[MT]]) : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0> // CHECK: return [[RET]] : $EnumIter<Base.Iterator> // CHECK-LABEL: } // end sil function '$ss7EnumSeqV12makeIterators0A4IterVy0D0QzGyF' public struct EnumSeq<Base : Seq> : Seq { public typealias Iterator = EnumIter<Base.Iterator> internal var _base: Base public func makeIterator() -> Iterator { return EnumIter(_base: _base.makeIterator()) } }
apache-2.0
c095086a2ba25547d4dee590121890d8
42.774319
405
0.6736
3.561254
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/iOS/PictureOutput.swift
2
6026
import UIKit import OpenGLES public enum PictureFileFormat { case png case jpeg } public class PictureOutput: ImageConsumer { public var encodedImageAvailableCallback:((Data) -> ())? public var encodedImageFormat:PictureFileFormat = .png public var imageAvailableCallback:((UIImage) -> ())? public var onlyCaptureNextFrame:Bool = true public var keepImageAroundForSynchronousCapture:Bool = false var storedFramebuffer:Framebuffer? public let sources = SourceContainer() public let maximumInputs:UInt = 1 var url:URL! public init() { } deinit { } public func saveNextFrameToURL(_ url:URL, format:PictureFileFormat) { onlyCaptureNextFrame = true encodedImageFormat = format self.url = url // Create an intentional short-term retain cycle to prevent deallocation before next frame is captured encodedImageAvailableCallback = {imageData in do { try imageData.write(to: self.url, options:.atomic) } catch { // TODO: Handle this better print("WARNING: Couldn't save image with error:\(error)") } } } // TODO: Replace with texture caches func cgImageFromFramebuffer(_ framebuffer:Framebuffer) -> CGImage { let renderFramebuffer = sharedImageProcessingContext.framebufferCache.requestFramebufferWithProperties(orientation:framebuffer.orientation, size:framebuffer.size) renderFramebuffer.lock() renderFramebuffer.activateFramebufferForRendering() clearFramebufferWithColor(Color.red) renderQuadWithShader(sharedImageProcessingContext.passthroughShader, uniformSettings:ShaderUniformSettings(), vertexBufferObject:sharedImageProcessingContext.standardImageVBO, inputTextures:[framebuffer.texturePropertiesForOutputRotation(.noRotation)]) framebuffer.unlock() let imageByteSize = Int(framebuffer.size.width * framebuffer.size.height * 4) let data = UnsafeMutablePointer<UInt8>.allocate(capacity: imageByteSize) glReadPixels(0, 0, framebuffer.size.width, framebuffer.size.height, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), data) renderFramebuffer.unlock() guard let dataProvider = CGDataProvider(dataInfo:nil, data:data, size:imageByteSize, releaseData: dataProviderReleaseCallback) else {fatalError("Could not allocate a CGDataProvider")} let defaultRGBColorSpace = CGColorSpaceCreateDeviceRGB() return CGImage(width:Int(framebuffer.size.width), height:Int(framebuffer.size.height), bitsPerComponent:8, bitsPerPixel:32, bytesPerRow:4 * Int(framebuffer.size.width), space:defaultRGBColorSpace, bitmapInfo:CGBitmapInfo() /*| CGImageAlphaInfo.Last*/, provider:dataProvider, decode:nil, shouldInterpolate:false, intent:.defaultIntent)! } public func newFramebufferAvailable(_ framebuffer:Framebuffer, fromSourceIndex:UInt) { if keepImageAroundForSynchronousCapture { storedFramebuffer?.unlock() storedFramebuffer = framebuffer } if let imageCallback = imageAvailableCallback { let cgImageFromBytes = cgImageFromFramebuffer(framebuffer) // TODO: Let people specify orientations let image = UIImage(cgImage:cgImageFromBytes, scale:1.0, orientation:.up) imageCallback(image) if onlyCaptureNextFrame { imageAvailableCallback = nil } } if let imageCallback = encodedImageAvailableCallback { let cgImageFromBytes = cgImageFromFramebuffer(framebuffer) let image = UIImage(cgImage:cgImageFromBytes, scale:1.0, orientation:.up) let imageData:Data switch encodedImageFormat { case .png: imageData = UIImagePNGRepresentation(image)! // TODO: Better error handling here case .jpeg: imageData = UIImageJPEGRepresentation(image, 0.8)! // TODO: Be able to set image quality } imageCallback(imageData) if onlyCaptureNextFrame { encodedImageAvailableCallback = nil } } } public func synchronousImageCapture() -> UIImage { var outputImage:UIImage! sharedImageProcessingContext.runOperationSynchronously{ guard let currentFramebuffer = storedFramebuffer else { fatalError("Synchronous access requires keepImageAroundForSynchronousCapture to be set to true") } let cgImageFromBytes = cgImageFromFramebuffer(currentFramebuffer) outputImage = UIImage(cgImage:cgImageFromBytes, scale:1.0, orientation:.up) } return outputImage } } public extension ImageSource { public func saveNextFrameToURL(_ url:URL, format:PictureFileFormat) { let pictureOutput = PictureOutput() pictureOutput.saveNextFrameToURL(url, format:format) self --> pictureOutput } } public extension UIImage { public func filterWithOperation<T:ImageProcessingOperation>(_ operation:T) -> UIImage { return filterWithPipeline{input, output in input --> operation --> output } } public func filterWithPipeline(_ pipeline:(PictureInput, PictureOutput) -> ()) -> UIImage { let picture = PictureInput(image:self) var outputImage:UIImage? let pictureOutput = PictureOutput() pictureOutput.onlyCaptureNextFrame = true pictureOutput.imageAvailableCallback = {image in outputImage = image } pipeline(picture, pictureOutput) picture.processImage(synchronously:true) return outputImage! } } // Why are these flipped in the callback definition? func dataProviderReleaseCallback(_ context:UnsafeMutableRawPointer?, data:UnsafeRawPointer, size:Int) { data.deallocate(bytes:size, alignedTo:1) }
mit
11268e1cb7c2dda09c7dd8ee634a5e6f
42.042857
343
0.680883
5.518315
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/LeftBottomWidth.Individual.swift
1
1298
// // LeftBottomWidth.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct LeftBottomWidth { let left: LayoutElement.Horizontal let bottom: LayoutElement.Vertical let width: LayoutElement.Length } } // MARK: - Make Frame extension IndividualProperty.LeftBottomWidth { private func makeFrame(left: Float, bottom: Float, width: Float, height: Float) -> Rect { let x = left let y = bottom - height let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Height extension IndividualProperty.LeftBottomWidth: LayoutPropertyCanStoreHeightToEvaluateFrameType { public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let left = self.left.evaluated(from: parameters) let bottom = self.bottom.evaluated(from: parameters) let width = self.width.evaluated(from: parameters, withTheOtherAxis: .height(0)) let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width)) return self.makeFrame(left: left, bottom: bottom, width: width, height: height) } }
apache-2.0
36c02a5871c58537058d49fdb68b5c70
22.327273
116
0.723305
3.829851
false
false
false
false
brentdax/swift
test/SILGen/constrained_extensions.swift
2
12178
// RUN: %target-swift-emit-silgen -module-name constrained_extensions -enable-sil-ownership -primary-file %s | %FileCheck %s // RUN: %target-swift-emit-sil -module-name constrained_extensions -O -primary-file %s > /dev/null // RUN: %target-swift-emit-ir -module-name constrained_extensions -primary-file %s > /dev/null extension Array where Element == Int { // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE1xSaySiGyt_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int> public init(x: ()) { self.init() } // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE16instancePropertySivg : $@convention(method) (@guaranteed Array<Int>) -> Int // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE16instancePropertySivs : $@convention(method) (Int, @inout Array<Int>) -> () // CHECK-LABEL: sil [transparent] [serialized] @$sSa22constrained_extensionsSiRszlE16instancePropertySivM : $@yield_once @convention(method) (@inout Array<Int>) -> @yields @inout Int public var instanceProperty: Element { get { return self[0] } set { self[0] = newValue } } // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE14instanceMethodSiyF : $@convention(method) (@guaranteed Array<Int>) -> Int public func instanceMethod() -> Element { return instanceProperty } // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE14instanceMethod1eS2i_tF : $@convention(method) (Int, @guaranteed Array<Int>) -> Int public func instanceMethod(e: Element) -> Element { return e } // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE14staticPropertySivgZ : $@convention(method) (@thin Array<Int>.Type) -> Int public static var staticProperty: Element { return Array(x: ()).instanceProperty } // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE12staticMethodSiyFZ : $@convention(method) (@thin Array<Int>.Type) -> Int public static func staticMethod() -> Element { return staticProperty } // CHECK-LABEL: sil non_abi [serialized] @$sSa22constrained_extensionsSiRszlE12staticMethod1eS2iSg_tFZfA_ : $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE12staticMethod1eS2iSg_tFZ : $@convention(method) (Optional<Int>, @thin Array<Int>.Type) -> Int public static func staticMethod(e: Element? = nil) -> Element { return e! } // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlEySiyt_tcig : $@convention(method) (@guaranteed Array<Int>) -> Int public subscript(i: ()) -> Element { return self[0] } // CHECK-LABEL: sil @$sSa22constrained_extensionsSiRszlE21inoutAccessOfPropertyyyF : $@convention(method) (@inout Array<Int>) -> () public mutating func inoutAccessOfProperty() { func increment(x: inout Element) { x += 1 } increment(x: &instanceProperty) } } extension Dictionary where Key == Int { // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE1xSDySiq_Gyt_tcfC : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @owned Dictionary<Int, Value> { public init(x: ()) { self.init() } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE16instancePropertyq_vg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE16instancePropertyq_vs : $@convention(method) <Key, Value where Key == Int> (@in Value, @inout Dictionary<Int, Value>) -> () // CHECK-LABEL: sil [transparent] [serialized] @$sSD22constrained_extensionsSiRszrlE16instancePropertyq_vM : $@yield_once @convention(method) <Key, Value where Key == Int> (@inout Dictionary<Int, Value>) -> @yields @inout Value public var instanceProperty: Value { get { return self[0]! } set { self[0] = newValue } } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE14instanceMethodq_yF : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value public func instanceMethod() -> Value { return instanceProperty } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE14instanceMethod1vq_q__tF : $@convention(method) <Key, Value where Key == Int> (@in_guaranteed Value, @guaranteed Dictionary<Int, Value>) -> @out Value public func instanceMethod(v: Value) -> Value { return v } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE12staticMethodSiyFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int public static func staticMethod() -> Key { return staticProperty } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE14staticPropertySivgZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int public static var staticProperty: Key { return 0 } // CHECK-LABEL: sil non_abi [serialized] @$sSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZfA_ : $@convention(thin) <Key, Value where Key == Int> () -> Optional<Int> // CHECK-LABEL: sil non_abi [serialized] @$sSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZfA0_ : $@convention(thin) <Key, Value where Key == Int> () -> @out Optional<Value> // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZ : $@convention(method) <Key, Value where Key == Int> (Optional<Int>, @in_guaranteed Optional<Value>, @thin Dictionary<Int, Value>.Type) -> @out Value public static func staticMethod(k: Key? = nil, v: Value? = nil) -> Value { return v! } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE17callsStaticMethodq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value public static func callsStaticMethod() -> Value { return staticMethod() } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE16callsConstructorq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value public static func callsConstructor() -> Value { return Dictionary(x: ()).instanceMethod() } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlEyq_yt_tcig : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value public subscript(i: ()) -> Value { return self[0]! } // CHECK-LABEL: sil @$sSD22constrained_extensionsSiRszrlE21inoutAccessOfPropertyyyF : $@convention(method) <Key, Value where Key == Int> (@inout Dictionary<Int, Value>) -> () public mutating func inoutAccessOfProperty() { func increment(x: inout Value) { } increment(x: &instanceProperty) } } public class GenericClass<X, Y> {} extension GenericClass where Y == () { // CHECK-LABEL: sil @$s22constrained_extensions12GenericClassCAAytRs_rlE5valuexvg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X // CHECK-LABEL: sil @$s22constrained_extensions12GenericClassCAAytRs_rlE5valuexvs : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [transparent] [serialized] @$s22constrained_extensions12GenericClassCAAytRs_rlE5valuexvM : $@yield_once @convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @yields @inout X public var value: X { get { while true {} } set {} } // CHECK-LABEL: sil @$s22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil @$s22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvs : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [transparent] [serialized] @$s22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvM : $@yield_once @convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @yields @inout () public var empty: Y { get { return () } set {} } // CHECK-LABEL: sil @$s22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcig : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X // CHECK-LABEL: sil @$s22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [transparent] [serialized] @$s22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tciM : $@yield_once @convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @yields @inout X public subscript(_: Y) -> X { get { while true {} } set {} } // CHECK-LABEL: sil @$s22constrained_extensions12GenericClassCAAytRs_rlEyyxcig : $@convention(method) <X, Y where Y == ()> (@in_guaranteed X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil @$s22constrained_extensions12GenericClassCAAytRs_rlEyyxcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [transparent] [serialized] @$s22constrained_extensions12GenericClassCAAytRs_rlEyyxciM : $@yield_once @convention(method) <X, Y where Y == ()> (@in_guaranteed X, @guaranteed GenericClass<X, ()>) -> @yields @inout () public subscript(_: X) -> Y { get { while true {} } set {} } } protocol VeryConstrained {} struct AnythingGoes<T> { // CHECK-LABEL: sil hidden [transparent] @$s22constrained_extensions12AnythingGoesV13meaningOfLifexSgvpfi : $@convention(thin) <T> () -> @out Optional<T> var meaningOfLife: T? = nil } extension AnythingGoes where T : VeryConstrained { // CHECK-LABEL: sil hidden @$s22constrained_extensions12AnythingGoesVA2A15VeryConstrainedRzlE13fromExtensionACyxGyt_tcfC : $@convention(method) <T where T : VeryConstrained> (@thin AnythingGoes<T>.Type) -> @out AnythingGoes<T> { // CHECK: [[INIT:%.*]] = function_ref @$s22constrained_extensions12AnythingGoesV13meaningOfLifexSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK: [[RESULT:%.*]] = alloc_stack $Optional<T> // CHECK: apply [[INIT]]<T>([[RESULT]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK: return init(fromExtension: ()) {} } extension Array where Element == Int { struct Nested { // CHECK-LABEL: sil hidden [transparent] @$sSa22constrained_extensionsSiRszlE6NestedV1eSiSgvpfi : $@convention(thin) () -> Optional<Int> var e: Element? = nil // CHECK-LABEL: sil hidden @$sSa22constrained_extensionsSiRszlE6NestedV10hasDefault1eySiSg_tFfA_ : $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil hidden @$sSa22constrained_extensionsSiRszlE6NestedV10hasDefault1eySiSg_tF : $@convention(method) (Optional<Int>, @inout Array<Int>.Nested) -> () mutating func hasDefault(e: Element? = nil) { self.e = e } } } extension Array where Element == AnyObject { class NestedClass { // CHECK-LABEL: sil hidden @$sSa22constrained_extensionsyXlRszlE11NestedClassCfd : $@convention(method) (@guaranteed Array<AnyObject>.NestedClass) -> @owned Builtin.NativeObject // CHECK-LABEL: sil hidden @$sSa22constrained_extensionsyXlRszlE11NestedClassCfD : $@convention(method) (@owned Array<AnyObject>.NestedClass) -> () deinit { } // CHECK-LABEL: sil hidden @$sSa22constrained_extensionsyXlRszlE11NestedClassCACyyXl_GycfC : $@convention(method) (@thick Array<AnyObject>.NestedClass.Type) -> @owned Array<AnyObject>.NestedClass // CHECK-LABEL: sil hidden @$sSa22constrained_extensionsyXlRszlE11NestedClassCACyyXl_Gycfc : $@convention(method) (@owned Array<AnyObject>.NestedClass) -> @owned Array<AnyObject>.NestedClass } class DerivedClass : NestedClass { // CHECK-LABEL: sil hidden [transparent] @$sSa22constrained_extensionsyXlRszlE12DerivedClassC1eyXlSgvpfi : $@convention(thin) () -> @owned Optional<AnyObject> // CHECK-LABEL: sil hidden @$sSa22constrained_extensionsyXlRszlE12DerivedClassCfE : $@convention(method) (@guaranteed Array<AnyObject>.DerivedClass) -> () var e: Element? = nil } } func referenceNestedTypes() { _ = Array<AnyObject>.NestedClass() _ = Array<AnyObject>.DerivedClass() }
apache-2.0
48014a06f719877bb2ea40b3a5e72906
54.336364
241
0.706424
3.932171
false
false
false
false
kang77649119/DouYuDemo
DouYuDemo/DouYuDemo/Classes/Main/View/CollectionNormalCell.swift
1
1076
// // RecommendNormalCell.swift // DouYuDemo // // Created by 也许、 on 16/10/9. // Copyright © 2016年 K. All rights reserved. // import UIKit class CollectionNormalCell: UICollectionViewCell { @IBOutlet weak var onLineLabel: UILabel! @IBOutlet weak var nickNameLabel: UILabel! @IBOutlet weak var roomNameLabel: UILabel! @IBOutlet weak var iconImg: UIImageView! var anchor : Anchor? { didSet { var onlineCount = "" if anchor!.online > 10000 { onlineCount = String(format: "%d.%d万", anchor!.online / 10000, anchor!.online % 10000 / 1000) } else { onlineCount = "\(anchor!.online)" } self.onLineLabel.text = onlineCount self.iconImg.sd_setImage(with: URL(string: anchor!.vertical_src)) self.nickNameLabel.text = anchor!.nickname self.roomNameLabel.text = anchor!.room_name } } }
mit
524faaca6a996368a8b077ae08a6cefb
23.204545
109
0.53615
4.840909
false
false
false
false
ngageoint/fog-machine
Demo/FogViewshed/FogViewshed/Models/Viewshed/VanKreveld/VanKreveldStatusEntry.swift
1
604
import Foundation public class VanKreveldStatusEntry { var key: Double = 0.0 var value : VanKreveldCell var maxSlope :Double = 0.0 var slope : Double = 0.0 var left : VanKreveldStatusEntry! = nil var right: VanKreveldStatusEntry! = nil var parent: VanKreveldStatusEntry! = nil var flag: Bool init (key: Double, value: VanKreveldCell, slope: Double, parent: VanKreveldStatusEntry!) { self.key = key; self.value = value; self.maxSlope = slope; self.slope = slope; self.parent = parent; self.flag = false } }
mit
fff92d1c861ee4d5cf141ad3065835d8
26.5
94
0.629139
4.223776
false
false
false
false
sora0077/LoggingKit
LoggingKit/Logging.swift
1
10574
// // Logging.swift // LoggingKit // // Created by 林達也 on 2015/02/26. // Copyright (c) 2015年 林達也. All rights reserved. // import Foundation /** <#Description#> */ public func LOGGING_ERROR() { Logging.level = .Error } /** <#Description#> */ public func LOGGING_WARN() { Logging.level = .Warn } /** <#Description#> */ public func LOGGING_INFO() { Logging.level = .Info } /** <#Description#> */ public func LOGGING_DEBUG() { Logging.level = .Debug } /** <#Description#> */ public func LOGGING_VERBOSE() { Logging.level = .Verbose } public struct Logging { enum Level: Int, CustomStringConvertible { case Error = 1 case Warn case Info case Debug case Verbose var description: String { switch self { case .Error: return "ERROR" case .Warn: return "WARN" case .Info: return "INFO" case .Debug: return "DEBUG" case .Verbose: return "VERBOSE" } } } static var level = Level.Error /** <#Description#> :param: object <#object description#> :param: file <#file description#> :param: function <#function description#> :param: line <#line description#> */ public static func e<T>(@autoclosure object: () -> T!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { if let (p, t) = self.printer(.Error, object, file, function, line) { doPrint(p, t) } } /** <#Description#> :param: object <#object description#> :param: file <#file description#> :param: function <#function description#> :param: line <#line description#> */ public static func w<T>(@autoclosure object: () -> T!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { if let (p, t) = self.printer(.Warn, object, file, function, line) { doPrint(p, t) } } /** <#Description#> :param: object <#object description#> :param: file <#file description#> :param: function <#function description#> :param: line <#line description#> */ public static func i<T>(@autoclosure object: () -> T!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { if let (p, t) = self.printer(.Info, object, file, function, line) { doPrint(p, t) } } /** <#Description#> :param: object <#object description#> :param: file <#file description#> :param: function <#function description#> :param: line <#line description#> */ public static func d<T>(@autoclosure object: () -> T!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { if let (p, t) = self.printer(.Debug, object, file, function, line) { doPrint(p, t) } } /** <#Description#> :param: object <#object description#> :param: file <#file description#> :param: function <#function description#> :param: line <#line description#> */ public static func v<T>(@autoclosure object: () -> T!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { if let (p, t) = self.printer(.Verbose, object, file, function, line) { doPrint(p, t) } } static func printer<T>(level: Level, @autoclosure _ t: () -> T!, _ file: StaticString, _ function: StaticString, _ line: Int) -> (String, T!)? { if self.level.rawValue > level.rawValue - 1 { return ("[\(level)] \((file.stringValue as NSString).lastPathComponent):\(line) - \(function)", t()) } return nil } } //MARK: verbose extension Logging { public static func e<T1, T2>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.e((t1(), t2()), file, function, line) } public static func e<T1, T2, T3>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.e((t1(), t2(), t3()), file, function, line) } public static func e<T1, T2, T3, T4>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.e((t1(), t2(), t3(), t4()), file, function, line) } public static func e<T1, T2, T3, T4, T5>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, @autoclosure _ t5: () -> T5!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.e((t1(), t2(), t3(), t4(), t5()), file, function, line) } } //MARK: warn extension Logging { public static func w<T1, T2>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.w((t1(), t2()), file, function, line) } public static func w<T1, T2, T3>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.w((t1(), t2(), t3()), file, function, line) } public static func w<T1, T2, T3, T4>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.w((t1(), t2(), t3(), t4()), file, function, line) } public static func w<T1, T2, T3, T4, T5>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, @autoclosure _ t5: () -> T5!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.w((t1(), t2(), t3(), t4(), t5()), file, function, line) } } //MARK: info extension Logging { public static func i<T1, T2>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.i((t1(), t2()), file, function, line) } public static func i<T1, T2, T3>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.i((t1(), t2(), t3()), file, function, line) } public static func i<T1, T2, T3, T4>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.i((t1(), t2(), t3(), t4()), file, function, line) } public static func i<T1, T2, T3, T4, T5>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, @autoclosure _ t5: () -> T5!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.i((t1(), t2(), t3(), t4(), t5()), file, function, line) } } //MARK: debug extension Logging { public static func d<T1, T2>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.d((t1(), t2()), file, function, line) } public static func d<T1, T2, T3>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.d((t1(), t2(), t3()), file, function, line) } public static func d<T1, T2, T3, T4>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.d((t1(), t2(), t3(), t4()), file, function, line) } public static func d<T1, T2, T3, T4, T5>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, @autoclosure _ t5: () -> T5!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.d((t1(), t2(), t3(), t4(), t5()), file, function, line) } } //MARK: verbose extension Logging { public static func v<T1, T2>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.v((t1(), t2()), file, function, line) } public static func v<T1, T2, T3>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.v((t1(), t2(), t3()), file, function, line) } public static func v<T1, T2, T3, T4>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.v((t1(), t2(), t3(), t4()), file, function, line) } public static func v<T1, T2, T3, T4, T5>(@autoclosure t1: () -> T1!, @autoclosure _ t2: () -> T2!, @autoclosure _ t3: () -> T3!, @autoclosure _ t4: () -> T4!, @autoclosure _ t5: () -> T5!, _ file: StaticString = __FILE__, _ function: StaticString = __FUNCTION__, _ line: Int = __LINE__) { self.v((t1(), t2(), t3(), t4(), t5()), file, function, line) } } private func doPrint<T>(prefix: String, _ t: T!) { print(prefix, terminator: "") print(t) }
mit
0374f274625c3ae5cf5e253941ccab25
40.093385
292
0.52983
3.400966
false
false
false
false
jindulys/HackerRankSolutions
Sources/Strings.swift
1
13828
// // Strings.swift // HRSwift // // Created by yansong li on 2015-11-29. // Copyright © 2015 yansong li. All rights reserved. // import Foundation // https://www.hackerrank.com/challenges/pangrams public class Pangrams { public init() {} func solution() { checkPangramsWithSet(getLine()) } /** CheckPangramsWithSet - parameter s: string to check */ public func checkPangramsWithSet(s: String) { if s.containsAllEnglishCharacters() { print("pangram") } else { print("not pangram") } } func checkPangramsWithArray(s: String) -> Bool { var indexArray = [Bool](count: 26, repeatedValue: false) let a: Character = "a" for c in s.characters { let lowerCs = String(c).lowercaseString.characters let lowerC = lowerCs[lowerCs.startIndex] let index = lowerC.unicodeScalarCodePoint() - a.unicodeScalarCodePoint() switch index { case 0..<26: indexArray[index] = true default: continue } } let result = indexArray.reduce(true){result,current in result && current} if result { print("pangram") } else { print("not pangram") } // Return result for unit testing return result } } // https://www.hackerrank.com/challenges/funny-string public class FunnyString { public init() {} func solution() -> Void { let T = getInt() for _ in 0..<T { let input = getLine() //solve(input) // Use the better one solveAlternative(input) } } /** This method time out, I think it is because advancedBy take O(n) time and the for loop itself also takes O(n), so the total time is O(n^2) - parameter s: the string to be resolved */ public func solve(s: String) -> Void { var values = [Int]() var reversed = [Int]() let count = s.characters.count for (i, c) in s.characters.enumerate() { values.append(c.unicodeScalarCodePoint()) let reversedIndex = s.characters.startIndex.advancedBy(count - i.successor(), limit: s.characters.endIndex) reversed.append(s.characters[reversedIndex].unicodeScalarCodePoint()) } var isFunny = true for i in 1..<count { if abs(values[i] - values[i-1]) != abs(reversed[i] - reversed[i-1]) { isFunny = false break } } if isFunny { print("Funny") } else { print("Not Funny") } } /** This one is better, has O(n) running time - parameter s: the string to be resolved */ public func solveAlternative(s: String) -> Void { var values = [Int]() var reversed = [Int]() let count = s.characters.count for (_, c) in s.characters.enumerate() { values.append(c.unicodeScalarCodePoint()) } for (_, c) in s.characters.reverse().enumerate() { reversed.append(c.unicodeScalarCodePoint()) } var isFunny = true for i in 1..<count { if abs(values[i] - values[i-1]) != abs(reversed[i] - reversed[i-1]) { isFunny = false break } } if isFunny { print("Funny") } else { print("Not Funny") } } } public class AlternatingCharcters { public init() {} func solution() { let T = getInt() for _ in 0..<T { let currentLine = getLine() solve(currentLine) } } public func solve(input: String) -> Int { var previous = input.characters.first! var currentIndex = input.characters.startIndex.successor() var toDelete = 0 while currentIndex != input.characters.endIndex { let current = input.characters[currentIndex] if current == previous { toDelete += 1 } previous = current currentIndex = currentIndex.successor() } print("\(toDelete)") return toDelete } } public class GameofThrones { public init() {} func solution() { let input = getLine() solve(input) } public func solve(input: String) -> Bool { var charactersArray = Array(count: 26, repeatedValue: 0) for c in input.characters { let currentIndex = c.unicodeScalarCodePoint() - 97 charactersArray[currentIndex] = charactersArray[currentIndex] + 1 } let oddCount = charactersArray.filter { $0%2 == 1 }.count if oddCount > 1 { print("NO") return false } else { print("YES") return true } } } public class MakeItAnagram { public init() {} func solution() { let line1 = getLine() let line2 = getLine() solve(line1, line2: line2) } public func solve(line1: String, line2: String) -> Int { var line1Counts = Array(count: 26, repeatedValue: 0) var line2Counts = Array(count: 26, repeatedValue: 0) for c in line1.characters { let currentIndex = c.unicodeScalarCodePoint() - 97 line1Counts[currentIndex] = line1Counts[currentIndex] + 1 } for c in line2.characters { let currentIndex = c.unicodeScalarCodePoint() - 97 line2Counts[currentIndex] = line2Counts[currentIndex] + 1 } var sum = 0 for i in 0..<26 { sum += abs(line1Counts[i] - line2Counts[i]) } print(sum) return sum } } public class Anagram { public init() {} func solution() { let T = getInt() for _ in 0..<T { let input = getLine() solve(input) } } public func solve(input: String) -> Int { if input.characters.count % 2 != 0 { print("-1") return -1 } let count = input.characters.count // Use string index to operate on String let midIndex = input.startIndex.advancedBy(count/2) let a = input.substringToIndex(midIndex) let b = input.substringFromIndex(midIndex) var aCharacters = Array(count: 26, repeatedValue: 0) var bCharacters = Array(count: 26, repeatedValue: 0) for c in a.characters { let currentIndex = c.unicodeScalarCodePoint() - 97 aCharacters[currentIndex] += 1 } for c in b.characters { let currentIndex = c.unicodeScalarCodePoint() - 97 bCharacters[currentIndex] += 1 } var sum = 0 for i in 0..<26 { sum += abs(aCharacters[i] - bCharacters[i]) } print("\(sum/2)") return sum/2 } } // https://www.hackerrank.com/challenges/two-strings public class TwoStrings { public init() {} func solution() { let T = getInt() for _ in 0..<T { let s1 = getLine() let s2 = getLine() checkSubStringsExists(s1, t: s2) } } public func checkSubStringsExists(s: String, t: String) -> Bool { let sSet = s.convertToCharacterSet() let tSet = t.convertToCharacterSet() let intersections = sSet.intersect(tSet) let results = intersections.count > 0 if results { print("YES") } else { print("NO") } return results } } public class SherlockAndAnagrams { public init() {} func solution() { let T = getInt() for _ in 0..<T { let input = getLine() solve(input) } } public func solve(input: String) -> Int { // Generate all possible substrings, which requires O(n^2) time. let N = input.characters.count var subStringDict = [String: Int]() var currentIndex = input.characters.startIndex for i in SRange(end: N) { for l in SRange(start: 1, end: N-i+1) { let endIndex = currentIndex.advancedBy(l) let subString = input.substringWithRange(Range<String.CharacterView.Index>(start: currentIndex, end: endIndex)) //let sortedSubString = String(Array(subString.characters).sort()) // This solution might slightly improve performance let sortedSubString = String(Array(subString.utf16).sort()) if let currentSubStringCount = subStringDict[sortedSubString] { subStringDict[sortedSubString] = currentSubStringCount + 1 } else { subStringDict[sortedSubString] = 1 } } currentIndex = currentIndex.advancedBy(1) } var sum = 0 for value in subStringDict.values { sum += value * (value - 1) / 2 } print(sum) return sum } } // https://www.hackerrank.com/challenges/palindrome-index public class PalindromeIndex { public init() {} func solution() { let T = getInt() for _ in 0..<T { solve(getLine()) } } public func solve(s: String) { var start = s.startIndex var end = s.endIndex.predecessor() var i = 0 while start < end && s.characters[start] == s.characters[end] { start = start.successor() end = end.predecessor() i += 1 } var removeStart: String = s removeStart.removeAtIndex(start) if removeStart.isPalindrome() { print(i) return } var removeEnd: String = s removeEnd.removeAtIndex(end) if removeEnd.isPalindrome() { print(s.characters.count - 1 - i) return } print("-1") } } // https://www.hackerrank.com/challenges/sherlock-and-valid-string public class SherlockAndValidString { public init() {} var characterCounts = [Character: Int]() func solution() { let s = getLine() for c in s.characters { if let count = characterCounts[c] { characterCounts[c] = count + 1 } else { characterCounts[c] = 1 } } var countsOccurrence = [Int: Int]() for i in characterCounts.values { if let occurrence = countsOccurrence[i] { countsOccurrence[i] = occurrence + 1 } else { countsOccurrence[i] = 1 } } if countsOccurrence.keys.count > 2 { print("NO") } else if countsOccurrence.keys.count == 2 { let keys = [Int](countsOccurrence.keys) let bigKey = max(keys[0], keys[1]) let smallKey = min(keys[0], keys[1]) // case 1 we could always remove smallkey that only occur 1 and count is 1 // case 2 the difference of occurence is 1 and bigkey is only 1 element if (smallKey*countsOccurrence[smallKey]! == 1 || (abs(keys[0] - keys[1]) == 1 && countsOccurrence[bigKey]! == 1)) { print("YES") } else { print("NO") } } else { print("YES") } } } public class CommonChild { public init() {} func solution() { let a = getLine() let b = getLine() solve(a, second: b) } /** Solve this problem use dynamic programming. The basic idea is that we could take current character if current one and test one are equal, otherwise we could choose max from (1) take this character and dont take test one (2) take the test one and ignore current one dp[i][j] = dp[i-1][j-1] + 1 if first[i] == first[j] dp[i][j] = max(dp[i][j-1], dp[i-1][j]) if first[i] != first[j] - parameter first: input one - parameter second: input two - returns: the length of longest subString of both inputs */ public func solve(first: String, second: String) -> Int { let N = first.characters.count // Construct a N+1 by N+1 matrix so we could deal with 0 element. var dp = Array(count: N+1, repeatedValue: Array(count: N+1, repeatedValue: 0)) // Swift string do not support subscript so we should use index instead. var currentFirstIndex = first.characters.startIndex for i in 1..<N+1 { var currentSecondIndex = second.characters.startIndex for j in 1..<N+1 { if first.characters[currentFirstIndex] == second.characters[currentSecondIndex] { dp[i][j] = dp[i-1][j-1] + 1 } else { dp[i][j] = max(dp[i-1][j], dp[i][j-1]) } currentSecondIndex = currentSecondIndex.successor() } currentFirstIndex = currentFirstIndex.successor() } print(dp[N][N]) return dp[N][N] } }
mit
13f6c1a5c8674c4f81a4a12f41630d9a
26.820926
143
0.513994
4.552848
false
false
false
false
matsune/YMCalendar
YMCalendar/Utils/MonthDate.swift
1
1396
// // MonthDate.swift // YMCalendar // // Created by Yuma Matsune on 2018/03/20. // Copyright © 2018年 Yuma Matsune. All rights reserved. // import Foundation public struct MonthDate { public let year: Int public let month: Int public init(year: Int, month: Int) { guard year >= 0 && 1...12 ~= month else { fatalError("Invalid year or month") } self.year = year self.month = month } public func add(month: Int) -> MonthDate { let plusYear = month / 12 let plusMonth = month % 12 var y = self.year + plusYear var m = self.month + plusMonth if m > 12 { y += 1 m = m - 12 } else if m < 1 { y -= 1 m = 12 + m } return MonthDate(year: y, month: m) } public func monthDiff(with other: MonthDate) -> Int { let yDiff = other.year - year let mDiff = other.month - month return yDiff * 12 + mDiff } } extension MonthDate: Comparable { public static func ==(lhs: MonthDate, rhs: MonthDate) -> Bool { return lhs.hashValue == rhs.hashValue } public static func <(lhs: MonthDate, rhs: MonthDate) -> Bool { return lhs.hashValue < rhs.hashValue } } extension MonthDate: Hashable { public var hashValue: Int { return year * 12 + month } }
mit
4795a6adf54b6545738a138ccab9f3fb
22.610169
67
0.552046
3.957386
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift
6
1840
// // Scan.swift // RxSwift // // Created by Krunoslav Zaher on 6/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ScanSink<ElementType, Accumulate, O: ObserverType> : Sink<O>, ObserverType where O.E == Accumulate { typealias Parent = Scan<ElementType, Accumulate> typealias E = ElementType fileprivate let _parent: Parent fileprivate var _accumulate: Accumulate init(parent: Parent, observer: O) { _parent = parent _accumulate = parent._seed super.init(observer: observer) } func on(_ event: Event<ElementType>) { switch event { case .next(let element): do { _accumulate = try _parent._accumulator(_accumulate, element) forwardOn(.next(_accumulate)) } catch let error { forwardOn(.error(error)) dispose() } case .error(let error): forwardOn(.error(error)) dispose() case .completed: forwardOn(.completed) dispose() } } } class Scan<Element, Accumulate>: Producer<Accumulate> { typealias Accumulator = (Accumulate, Element) throws -> Accumulate fileprivate let _source: Observable<Element> fileprivate let _seed: Accumulate fileprivate let _accumulator: Accumulator init(source: Observable<Element>, seed: Accumulate, accumulator: @escaping Accumulator) { _source = source _seed = seed _accumulator = accumulator } override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Accumulate { let sink = ScanSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } }
mit
df563c76150d51289cb84ef3ce547f51
27.734375
106
0.59652
4.776623
false
false
false
false
pepibumur/SoundCloudSwift
SoundCloudSwift/Source/Core/Models/Comment.swift
2
1002
import Foundation import Genome /** * SoundCloud Comment */ public struct Comment: BasicMappable { // MARK: - Attributes /// Created at date public var createdAt: NSDate = NSDate() /// SoundCloud Identifier public var id: Int = -1 /// User identifier public var userId: Int = -1 /// Track identifier public var trackId: Int = -1 /// Timestamp public var timestamp: Int = -1 /// Body public var body: String = "" /// URI public var uri: String = "" // MARK: - Constructors public init() {} // MARK: - BasicMappable public mutating func sequence(map: Map) throws { try createdAt <~ map["created_at"].transformFromJson { date($0) } try id <~ map["id"] try userId <~ map["user_id"] try trackId <~ map["track_id"] try timestamp <~ map["timestamp"] try body <~ map["body"] try uri <~ map["uri"] } }
mit
8b467ff902fc0d983e853961c6532117
19.469388
73
0.535928
4.473214
false
false
false
false
jindulys/ChainPageCollectionView
Sources/CentralCardLayout.swift
1
6958
/** * Copyright (c) 2017 Yansong Li * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * 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 private let maxScaleOffset: CGFloat = 200 private let minScale: CGFloat = 0.9 private let minAlpha: CGFloat = 0.3 /// The layout that can place a card at the central of the screen. public class CentralCardLayout: UICollectionViewFlowLayout { public var scaled: Bool = false fileprivate var lastCollectionViewSize: CGSize = CGSize.zero public required init?(coder aDecoder: NSCoder) { fatalError() } public init(scaled: Bool) { self.scaled = scaled super.init() scrollDirection = .horizontal minimumLineSpacing = 25 } public override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with: context) guard let collectionView = collectionView else { return } if collectionView.bounds.size != lastCollectionViewSize { configureInset() lastCollectionViewSize = collectionView.bounds.size } } public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let attribute = super.layoutAttributesForItem(at: indexPath)?.copy() as? UICollectionViewLayoutAttributes else { return nil } if !scaled { return attribute } centerScaledAttribute(attribute: attribute) return attribute } public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil } if !scaled { return attributes } guard case let newAttributesArray as [UICollectionViewLayoutAttributes] = NSArray(array: attributes, copyItems: true) else { return nil } newAttributesArray.forEach { attribute in centerScaledAttribute(attribute: attribute) } return newAttributesArray } public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = collectionView else { return proposedContentOffset } let proposedRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.width, height: collectionView.bounds.height) guard let layoutAttributes = layoutAttributesForElements(in: proposedRect) else { return proposedContentOffset } var shouldBeChosenAttributes: UICollectionViewLayoutAttributes? var shouldBeChosenIndex: Int = -1 let proposedCenterX = proposedRect.midX for (i, attributes) in layoutAttributes.enumerated() { guard attributes .representedElementCategory == .cell else { continue } guard let currentChosenAttributes = shouldBeChosenAttributes else { shouldBeChosenAttributes = attributes shouldBeChosenIndex = i continue } if (fabs(attributes.frame.midX - proposedCenterX) < fabs(currentChosenAttributes.frame.midX - proposedCenterX)) { shouldBeChosenAttributes = attributes shouldBeChosenIndex = i } } // Adjust the case where a quick but small scroll occurs. if (fabs(collectionView.contentOffset.x - proposedContentOffset.x) < itemSize.width) { if velocity.x < -0.3 { shouldBeChosenIndex = shouldBeChosenIndex > 0 ? shouldBeChosenIndex - 1 : shouldBeChosenIndex } else if velocity.x > 0.3 { shouldBeChosenIndex = shouldBeChosenIndex < layoutAttributes.count - 1 ? shouldBeChosenIndex + 1 : shouldBeChosenIndex } shouldBeChosenAttributes = layoutAttributes[shouldBeChosenIndex] } guard let finalAttributes = shouldBeChosenAttributes else { return proposedContentOffset } return CGPoint(x: finalAttributes.frame.midX - collectionView.bounds.size.width / 2, y: proposedContentOffset.y) } } // MARK: helpers extension CentralCardLayout { fileprivate func centerScaledAttribute(attribute: UICollectionViewLayoutAttributes) { guard let collectionView = collectionView else { return } let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height) let visibleCenterX = visibleRect.midX let distanceFromCenter = visibleCenterX - attribute.center.x let distance = min(abs(distanceFromCenter), maxScaleOffset) let scale = distance * (minScale - 1) / maxScaleOffset + 1 attribute.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1) attribute.alpha = distance * (minAlpha - 1) / maxScaleOffset + 1 } fileprivate func configureInset() -> Void { guard let collectionView = collectionView else { return } let inset = collectionView.bounds.size.width / 2 - itemSize.width / 2 collectionView.contentInset = UIEdgeInsetsMake(0, inset, 0, inset) collectionView.contentOffset = CGPoint(x: -inset, y: 0) } }
mit
e4277a24430ffd178f5143dbbd8a6480
38.76
128
0.712561
5.291255
false
false
false
false
stardust139/ios-charts
Charts/Classes/Charts/BarLineChartViewBase.swift
1
63763
// // BarLineChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. public class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, UIGestureRecognizerDelegate { /// the maximum number of entried to which values will be drawn internal var _maxVisibleValueCount = 100 /// flag that indicates if auto scaling on the y axis is enabled private var _autoScaleMinMaxEnabled = false private var _autoScaleLastLowestVisibleXIndex: Int! private var _autoScaleLastHighestVisibleXIndex: Int! private var _pinchZoomEnabled = false private var _doubleTapToZoomEnabled = true private var _dragEnabled = true private var _scaleXEnabled = true private var _scaleYEnabled = true /// the color for the background of the chart-drawing area (everything behind the grid lines). public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0) public var borderColor = UIColor.blackColor() public var borderLineWidth: CGFloat = 1.0 /// flag indicating if the grid background should be drawn or not public var drawGridBackgroundEnabled = true /// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis. public var drawBordersEnabled = false /// Sets the minimum offset (padding) around the chart, defaults to 10 public var minOffset = CGFloat(10.0) /// the object representing the labels on the y-axis, this object is prepared /// in the pepareYLabels() method internal var _leftAxis: ChartYAxis! internal var _rightAxis: ChartYAxis! /// the object representing the labels on the x-axis internal var _xAxis: ChartXAxis! internal var _leftYAxisRenderer: ChartYAxisRenderer! internal var _rightYAxisRenderer: ChartYAxisRenderer! internal var _leftAxisTransformer: ChartTransformer! internal var _rightAxisTransformer: ChartTransformer! internal var _xAxisRenderer: ChartXAxisRenderer! internal var _tapGestureRecognizer: UITapGestureRecognizer! internal var _doubleTapGestureRecognizer: UITapGestureRecognizer! #if !os(tvOS) internal var _pinchGestureRecognizer: UIPinchGestureRecognizer! #endif internal var _panGestureRecognizer: UIPanGestureRecognizer! /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _leftAxis = ChartYAxis(position: .Left) _rightAxis = ChartYAxis(position: .Right) _xAxis = ChartXAxis() _leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer) _rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer) _xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer) _highlighter = ChartHighlighter(chart: self) _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")) _doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:")) _doubleTapGestureRecognizer.numberOfTapsRequired = 2 _panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:")) _panGestureRecognizer.delegate = self self.addGestureRecognizer(_tapGestureRecognizer) self.addGestureRecognizer(_doubleTapGestureRecognizer) self.addGestureRecognizer(_panGestureRecognizer) _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled _panGestureRecognizer.enabled = _dragEnabled #if !os(tvOS) _pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:")) _pinchGestureRecognizer.delegate = self self.addGestureRecognizer(_pinchGestureRecognizer) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } public override func drawRect(rect: CGRect) { super.drawRect(rect) if (_dataNotSet) { return } let optionalContext = UIGraphicsGetCurrentContext() guard let context = optionalContext else { return } calcModulus() if (_xAxisRenderer !== nil) { _xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } if (renderer !== nil) { renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } // execute all drawing commands drawGridBackground(context: context) if (_leftAxis.isEnabled) { _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) } if (_rightAxis.isEnabled) { _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) } _xAxisRenderer?.renderAxisLine(context: context) _leftYAxisRenderer?.renderAxisLine(context: context) _rightYAxisRenderer?.renderAxisLine(context: context) if (_autoScaleMinMaxEnabled) { let lowestVisibleXIndex = self.lowestVisibleXIndex, highestVisibleXIndex = self.highestVisibleXIndex if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex || _autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex) { calcMinMax() calculateOffsets() _autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex _autoScaleLastHighestVisibleXIndex = highestVisibleXIndex } } // make sure the graph values and grid cannot be drawn outside the content-rect CGContextSaveGState(context) CGContextClipToRect(context, _viewPortHandler.contentRect) if (_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } _xAxisRenderer?.renderGridLines(context: context) _leftYAxisRenderer?.renderGridLines(context: context) _rightYAxisRenderer?.renderGridLines(context: context) renderer?.drawData(context: context) if (!_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (!_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (!_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } // if highlighting is enabled if (valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHighlight) } // Removes clipping rectangle CGContextRestoreGState(context) renderer!.drawExtras(context: context) _xAxisRenderer.renderAxisLabels(context: context) _leftYAxisRenderer.renderAxisLabels(context: context) _rightYAxisRenderer.renderAxisLabels(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) // drawLegend() drawMarkers(context: context) drawDescription(context: context) } internal func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum) } internal func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted) _leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted) } public override func notifyDataSetChanged() { if (_dataNotSet) { return } calcMinMax() _leftAxis?._defaultValueFormatter = _defaultValueFormatter _rightAxis?._defaultValueFormatter = _defaultValueFormatter _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) _xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals) if (_legend !== nil) { _legendRenderer?.computeLegend(_data) } calculateOffsets() setNeedsDisplay() } internal override func calcMinMax() { if (_autoScaleMinMaxEnabled) { _data.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex) } var minLeft = _data.getYMin(.Left) var maxLeft = _data.getYMax(.Left) var minRight = _data.getYMin(.Right) var maxRight = _data.getYMax(.Right) let leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft)) let rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight)) // in case all values are equal if (leftRange == 0.0) { maxLeft = maxLeft + 1.0 if (!_leftAxis.isStartAtZeroEnabled) { minLeft = minLeft - 1.0 } } if (rightRange == 0.0) { maxRight = maxRight + 1.0 if (!_rightAxis.isStartAtZeroEnabled) { minRight = minRight - 1.0 } } let topSpaceLeft = leftRange * Double(_leftAxis.spaceTop) let topSpaceRight = rightRange * Double(_rightAxis.spaceTop) let bottomSpaceLeft = leftRange * Double(_leftAxis.spaceBottom) let bottomSpaceRight = rightRange * Double(_rightAxis.spaceBottom) _chartXMax = Double(_data.xVals.count - 1) _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) // Consider sticking one of the edges of the axis to zero (0.0) if _leftAxis.isStartAtZeroEnabled { if minLeft < 0.0 && maxLeft < 0.0 { // If the values are all negative, let's stay in the negative zone _leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _leftAxis.axisMaximum = 0.0 } else if minLeft >= 0.0 { // We have positive values only, stay in the positive zone _leftAxis.axisMinimum = 0.0 _leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)) } } else { // Use the values as they are _leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft) _leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft) } if _rightAxis.isStartAtZeroEnabled { if minRight < 0.0 && maxRight < 0.0 { // If the values are all negative, let's stay in the negative zone _rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)) _rightAxis.axisMaximum = 0.0 } else if minRight >= 0.0 { // We have positive values only, stay in the positive zone _rightAxis.axisMinimum = 0.0 _rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)) _rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)) } } else { _rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight) _rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight) } _leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum) _rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum) } internal override func calculateOffsets() { if (!_customViewPortEnabled) { var offsetLeft = CGFloat(0.0) var offsetRight = CGFloat(0.0) var offsetTop = CGFloat(0.0) var offsetBottom = CGFloat(0.0) // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = _legend.textHeightMax offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } else if (_legend.position == .AboveChartLeft || _legend.position == .AboveChartRight || _legend.position == .AboveChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = _legend.textHeightMax offsetTop += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } } // offsets for y-labels if (leftAxis.needsOffset) { offsetLeft += leftAxis.requiredSize().width } if (rightAxis.needsOffset) { offsetRight += rightAxis.requiredSize().width } if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled) { let xlabelheight = xAxis.labelHeight * 2.0 // offsets for x-labels if (xAxis.labelPosition == .Bottom) { offsetBottom += xlabelheight } else if (xAxis.labelPosition == .Top) { offsetTop += xlabelheight } else if (xAxis.labelPosition == .BothSided) { offsetBottom += xlabelheight offsetTop += xlabelheight } } offsetTop += self.extraTopOffset offsetRight += self.extraRightOffset offsetBottom += self.extraBottomOffset offsetLeft += self.extraLeftOffset _viewPortHandler.restrainViewPort( offsetLeft: max(self.minOffset, offsetLeft), offsetTop: max(self.minOffset, offsetTop), offsetRight: max(self.minOffset, offsetRight), offsetBottom: max(self.minOffset, offsetBottom)) } prepareOffsetMatrix() prepareValuePxMatrix() } /// calculates the modulus for x-labels and grid internal func calcModulus() { if (_xAxis === nil || !_xAxis.isEnabled) { return } if (!_xAxis.isAxisModulusCustom) { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a))) } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1 } } public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { let dataSetIndex = highlight.dataSetIndex var xPos = CGFloat(e.xIndex) var yPos = CGFloat(e.value) if (self.isKindOfClass(BarChartView)) { let bd = _data as! BarChartData let space = bd.groupSpace let setCount = _data.dataSetCount let i = e.xIndex if self is HorizontalBarChartView { // calculate the x-position, depending on datasetcount let y = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 yPos = y if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { xPos = CGFloat(highlight.range!.to) } else { xPos = CGFloat(e.value) } } } else { let x = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 xPos = x if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { yPos = CGFloat(highlight.range!.to) } else { yPos = CGFloat(e.value) } } } } // position of the marker depends on selected value index and value var pt = CGPoint(x: xPos, y: yPos * _animator.phaseY) getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt) return pt } /// draws the grid background internal func drawGridBackground(context context: CGContext) { if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextSaveGState(context) } if (drawGridBackgroundEnabled) { // draw the grid background CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor) CGContextFillRect(context, _viewPortHandler.contentRect) } if (drawBordersEnabled) { CGContextSetLineWidth(context, borderLineWidth) CGContextSetStrokeColorWithColor(context, borderColor.CGColor) CGContextStrokeRect(context, _viewPortHandler.contentRect) } if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextRestoreGState(context) } } // MARK: - Gestures private enum GestureScaleAxis { case Both case X case Y } private var _isDragging = false private var _isScaling = false private var _gestureScaleAxis = GestureScaleAxis.Both private var _closestDataSetToTouch: ChartDataSet! private var _panGestureReachedEdge: Bool = false private weak var _outerScrollView: UIScrollView? private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: CADisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return } if (recognizer.state == UIGestureRecognizerState.Ended) { if !self.isHighLightPerTapEnabled { return } let h = getHighlightByTouchPoint(recognizer.locationInView(self)) if (h === nil || h!.isEqual(self.lastHighlighted)) { self.highlightValue(highlight: nil, callDelegate: true) self.lastHighlighted = nil } else { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } @objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return } if (recognizer.state == UIGestureRecognizerState.Ended) { if (!_dataNotSet && _doubleTapToZoomEnabled) { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom) } self.zoom(isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y) } } } #if !os(tvOS) @objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration() if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)) { _isScaling = true if (_pinchZoomEnabled) { _gestureScaleAxis = .Both } else { let x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x) let y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y) if (x > y) { _gestureScaleAxis = .X } else { _gestureScaleAxis = .Y } } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isScaling) { _isScaling = false // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } else if (recognizer.state == UIGestureRecognizerState.Changed) { let isZoomingOut = (recognizer.scale < 1) var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY if (_isScaling) { canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .X); canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y); if canZoomMoreX || canZoomMoreY { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom) } let scaleX = canZoomMoreX ? recognizer.scale : 1.0 let scaleY = canZoomMoreY ? recognizer.scale : 1.0 var matrix = CGAffineTransformMakeTranslation(location.x, location.y) matrix = CGAffineTransformScale(matrix, scaleX, scaleY) matrix = CGAffineTransformTranslate(matrix, -location.x, -location.y) matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY) } } recognizer.scale = 1.0 } } } #endif @objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began && recognizer.numberOfTouches() > 0) { stopDeceleration() if !_dataNotSet && _dragEnabled && (!self.hasNoDragOffset || !self.isFullyZoomedOut || self.isHighlightPerDragEnabled) { _isDragging = true _closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self)) let translation = recognizer.translationInView(self) let didUserDrag = (self is HorizontalBarChartView) ? translation.y != 0.0 : translation.x != 0.0 // Check to see if user dragged at all and if so, can the chart be dragged by the given amount if (didUserDrag && !performPanChange(translation: translation)) { if (_outerScrollView !== nil) { // We can stop dragging right now, and let the scroll view take control _outerScrollView = nil _isDragging = false } } else { if (_outerScrollView !== nil) { // Prevent the parent scroll view from scrolling _outerScrollView?.scrollEnabled = false } } _lastPanPoint = recognizer.translationInView(self) } } else if (recognizer.state == UIGestureRecognizerState.Changed) { if (_isDragging) { let originalTranslation = recognizer.translationInView(self) let translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y) performPanChange(translation: translation) _lastPanPoint = originalTranslation } else if (isHighlightPerDragEnabled) { let h = getHighlightByTouchPoint(recognizer.locationInView(self)) let lastHighlighted = self.lastHighlighted if ((h === nil && lastHighlighted !== nil) || (h !== nil && lastHighlighted === nil) || (h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted))) { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isDragging) { if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled) { stopDeceleration() _decelerationLastTime = CACurrentMediaTime() _decelerationVelocity = recognizer.velocityInView(self) _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } _isDragging = false } if (_outerScrollView !== nil) { _outerScrollView?.scrollEnabled = true _outerScrollView = nil } } } private func performPanChange(var translation translation: CGPoint) -> Bool { if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { if (self is HorizontalBarChartView) { translation.x = -translation.x } else { translation.y = -translation.y } } let originalMatrix = _viewPortHandler.touchMatrix var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y) matrix = CGAffineTransformConcat(originalMatrix, matrix) matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y) } // Did we managed to actually drag or did we reach the edge? return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationVelocity.x *= self.dragDecelerationFrictionCoef _decelerationVelocity.y *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) let distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ) if (!performPanChange(translation: distance)) { // We reached the edge, stop _decelerationVelocity.x = 0.0 _decelerationVelocity.y = 0.0 } _decelerationLastTime = currentTime if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001) { stopDeceleration() // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if (!super.gestureRecognizerShouldBegin(gestureRecognizer)) { return false } if (gestureRecognizer == _panGestureRecognizer) { if _dataNotSet || !_dragEnabled || (self.hasNoDragOffset && self.isFullyZoomedOut && !self.isHighlightPerDragEnabled) { return false } } else { #if !os(tvOS) if (gestureRecognizer == _pinchGestureRecognizer) { if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled)) { return false } } #endif } return true } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { #if !os(tvOS) if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer))) { return true } #endif if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && ( gestureRecognizer == _panGestureRecognizer )) { var scrollView = self.superview while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView)) { scrollView = scrollView?.superview } var foundScrollView = scrollView as? UIScrollView if (foundScrollView !== nil && !foundScrollView!.scrollEnabled) { foundScrollView = nil } var scrollViewPanGestureRecognizer: UIGestureRecognizer! if (foundScrollView !== nil) { for scrollRecognizer in foundScrollView!.gestureRecognizers! { if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer)) { scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer break } } } if (otherGestureRecognizer === scrollViewPanGestureRecognizer) { _outerScrollView = foundScrollView return true } } return false } /// MARK: Viewport modifiers /// Zooms in by 1.4, into the charts center. center. public func zoomIn() { let matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms out by 0.7, from the charts center. center. public func zoomOut() { let matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter x: /// - parameter y: public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) { let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. public func fitScreen() { let matrix = _viewPortHandler.fitScreen() _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat) { _viewPortHandler.setMinimumScaleX(scaleX) _viewPortHandler.setMinimumScaleY(scaleY) } /// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMaximum(maxXRange: CGFloat) { let xScale = _deltaX / maxXRange _viewPortHandler.setMinimumScaleX(xScale) } /// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMinimum(minXRange: CGFloat) { let xScale = _deltaX / minXRange _viewPortHandler.setMaximumScaleX(xScale) } /// Limits the maximum and minimum value count that can be visible by pinching and zooming. /// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed /// at once without scrolling public func setVisibleXRange(minXRange minXRange: CGFloat, maxXRange: CGFloat) { let maxScale = _deltaX / minXRange let minScale = _deltaX / maxXRange _viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale) } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// - parameter yRange: /// - parameter axis: - the axis for which this limit should apply public func setVisibleYRangeMaximum(maxYRange: CGFloat, axis: ChartYAxis.AxisDependency) { let yScale = getDeltaY(axis) / maxYRange _viewPortHandler.setMinimumScaleY(yScale) } /// Moves the left side of the current viewport to the specified x-index. /// This also refreshes the chart by calling setNeedsDisplay(). public func moveViewToX(xIndex: Int) { if (_viewPortHandler.hasChartDimens) { var pt = CGPoint(x: CGFloat(xIndex), y: 0.0) getTransformer(.Left).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); }) } } /// Centers the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); }) } } /// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }) } } /// This will move the center of the current viewport to the specified x-index and y-value. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func centerViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }) } } /// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this. /// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`. public func setViewPortOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true if (NSThread.isMainThread()) { self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom) prepareOffsetMatrix() prepareValuePxMatrix() } else { dispatch_async(dispatch_get_main_queue(), { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom) }) } } /// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically. public func resetViewPortOffsets() { _customViewPortEnabled = false calculateOffsets() } // MARK: - Accessors /// - returns: the delta-y value (y-value range) of the specified axis. public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat { if (axis == .Left) { return CGFloat(leftAxis.axisRange) } else { return CGFloat(rightAxis.axisRange) } } /// - returns: the position (in pixels) the provided Entry has inside the chart view public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value)) getTransformer(axis).pointValueToPixel(&vals) return vals } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var dragEnabled: Bool { get { return _dragEnabled } set { if (_dragEnabled != newValue) { _dragEnabled = newValue } } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var isDragEnabled: Bool { return dragEnabled } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). public func setScaleEnabled(enabled: Bool) { if (_scaleXEnabled != enabled || _scaleYEnabled != enabled) { _scaleXEnabled = enabled _scaleYEnabled = enabled #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } public var scaleXEnabled: Bool { get { return _scaleXEnabled } set { if (_scaleXEnabled != newValue) { _scaleXEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var scaleYEnabled: Bool { get { return _scaleYEnabled } set { if (_scaleYEnabled != newValue) { _scaleYEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var isScaleXEnabled: Bool { return scaleXEnabled; } public var isScaleYEnabled: Bool { return scaleYEnabled; } /// flag that indicates if double tap zoom is enabled or not public var doubleTapToZoomEnabled: Bool { get { return _doubleTapToZoomEnabled } set { if (_doubleTapToZoomEnabled != newValue) { _doubleTapToZoomEnabled = newValue _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled } } } /// **default**: true /// - returns: true if zooming via double-tap is enabled false if not. public var isDoubleTapToZoomEnabled: Bool { return doubleTapToZoomEnabled } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled public var highlightPerDragEnabled = true /// If set to true, highlighting per dragging over a fully zoomed out chart is enabled /// You might want to disable this when using inside a `UIScrollView` /// /// **default**: true public var isHighlightPerDragEnabled: Bool { return highlightPerDragEnabled } /// **default**: true /// - returns: true if drawing the grid background is enabled, false if not. public var isDrawGridBackgroundEnabled: Bool { return drawGridBackgroundEnabled } /// **default**: false /// - returns: true if drawing the borders rectangle is enabled, false if not. public var isDrawBordersEnabled: Bool { return drawBordersEnabled } /// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart. public func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight? { if (_dataNotSet || _data === nil) { print("Can't select by touch. No data set.", terminator: "\n") return nil } return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y)) } /// - returns: the x and y values in the chart at the given touch point /// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// `getPixelsForValues(...)`. public func getValueByTouchPoint(var pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint { getTransformer(axis).pixelToValue(&pt) return pt } /// Transforms the given chart values into pixels. This is the opposite /// method to `getValueByTouchPoint(...)`. public func getPixelForValue(x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = CGPoint(x: CGFloat(x), y: CGFloat(y)) getTransformer(axis).pointValueToPixel(&pt) return pt } /// - returns: the y-value at the given touch position (must not necessarily be /// a value contained in one of the datasets) public func getYValueByTouchPoint(pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat { return getValueByTouchPoint(pt: pt, axis: axis).y } /// - returns: the Entry object displayed at the touched position of the chart public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data!.getEntryForHighlight(h!) } return nil } /// - returns: the DataSet object displayed at the touched position of the chart public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleBubbleChartDataSet! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data.getDataSetByIndex(h!.dataSetIndex) as! BarLineScatterCandleBubbleChartDataSet! } return nil } /// - returns: the current x-scale factor public var scaleX: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleX } /// - returns: the current y-scale factor public var scaleY: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleY } /// if the chart is fully zoomed out, return true public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; } /// - returns: the left y-axis object. In the horizontal bar-chart, this is the /// top axis. public var leftAxis: ChartYAxis { return _leftAxis } /// - returns: the right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. public var rightAxis: ChartYAxis { return _rightAxis; } /// - returns: the y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis { if (axis == .Left) { return _leftAxis } else { return _rightAxis } } /// - returns: the object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) public var xAxis: ChartXAxis { return _xAxis } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately public var pinchZoomEnabled: Bool { get { return _pinchZoomEnabled } set { if (_pinchZoomEnabled != newValue) { _pinchZoomEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } /// **default**: false /// - returns: true if pinch-zoom is enabled, false if not public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. public func setDragOffsetX(offset: CGFloat) { _viewPortHandler.setDragOffsetX(offset) } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. public func setDragOffsetY(offset: CGFloat) { _viewPortHandler.setDragOffsetY(offset) } /// - returns: true if both drag offsets (x and y) are zero or smaller. public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; } /// The X axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartXAxisRenderer /// - returns: The current set X axis renderer public var xAxisRenderer: ChartXAxisRenderer { get { return _xAxisRenderer } set { _xAxisRenderer = newValue } } /// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set left Y axis renderer public var leftYAxisRenderer: ChartYAxisRenderer { get { return _leftYAxisRenderer } set { _leftYAxisRenderer = newValue } } /// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set right Y axis renderer public var rightYAxisRenderer: ChartYAxisRenderer { get { return _rightYAxisRenderer } set { _rightYAxisRenderer = newValue } } public override var chartYMax: Double { return max(leftAxis.axisMaximum, rightAxis.axisMaximum) } public override var chartYMin: Double { return min(leftAxis.axisMinimum, rightAxis.axisMinimum) } /// - returns: true if either the left or the right or both axes are inverted. public var isAnyAxisInverted: Bool { return _leftAxis.isInverted || _rightAxis.isInverted } /// flag that indicates if auto scaling on the y axis is enabled. /// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes public var autoScaleMinMaxEnabled: Bool { get { return _autoScaleMinMaxEnabled; } set { _autoScaleMinMaxEnabled = newValue; } } /// **default**: false /// - returns: true if auto scaling on the y axis is enabled. public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; } /// Sets a minimum width to the specified y axis. public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.minWidth = width } else { _rightAxis.minWidth = width } } /// **default**: 0.0 /// - returns: the (custom) minimum width of the specified Y axis. public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.minWidth } else { return _rightAxis.minWidth } } /// Sets a maximum width to the specified y axis. /// Zero (0.0) means there's no maximum width public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.maxWidth = width } else { _rightAxis.maxWidth = width } } /// Zero (0.0) means there's no maximum width /// /// **default**: 0.0 (no maximum specified) /// - returns: the (custom) maximum width of the specified Y axis. public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.maxWidth } else { return _rightAxis.maxWidth } } /// - returns the width of the specified y axis. public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.requiredSize().width } else { return _rightAxis.requiredSize().width } } // MARK: - BarLineScatterCandleBubbleChartDataProvider /// - returns: the Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer { if (which == .Left) { return _leftAxisTransformer } else { return _rightAxisTransformer } } /// the number of maximum visible drawn values on the chart /// only active when `setDrawValues()` is enabled public var maxVisibleValueCount: Int { get { return _maxVisibleValueCount } set { _maxVisibleValueCount = newValue } } public func isInverted(axis: ChartYAxis.AxisDependency) -> Bool { return getAxis(axis).isInverted } /// - returns: the lowest x-index (value on the x-axis) that is still visible on he chart. public var lowestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0) } /// - returns: the highest x-index (value on the x-axis) that is still visible on the chart. public var highestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (_data != nil && Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x) } } /// Default formatter that calculates the position of the filled line. internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter { internal override init() { } internal func getFillLinePosition(dataSet dataSet: LineChartDataSet, dataProvider: LineChartDataProvider) -> CGFloat { var fillMin = CGFloat(0.0) if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0) { fillMin = 0.0 } else { if let data = dataProvider.data { if !dataProvider.getAxis(dataSet.axisDependency).isStartAtZeroEnabled { var max: Double, min: Double if (data.yMax > 0.0) { max = 0.0 } else { max = dataProvider.chartYMax } if (data.yMin < 0.0) { min = 0.0 } else { min = dataProvider.chartYMin } fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max) } else { fillMin = 0.0 } } } return fillMin } }
apache-2.0
20c1b136af480c7f07898bb79093e890
35.373645
238
0.575773
5.653249
false
false
false
false
peterxhu/ARGoal
ARGoal/Distance/DistanceSettingsViewController.swift
1
4993
// // DistanceSettingsViewController.swift // ARGoal // // Created by Peter Hu on 6/17/17. // Copyright © 2017 App Doctor Hu. All rights reserved. // import UIKit import SafariServices class DistanceSettingsViewController: UITableViewController, SFSafariViewControllerDelegate { // Shared settings with VirtualGoalSettingsViewController @IBOutlet weak var debugModeSwitch: UISwitch! @IBOutlet weak var ARPlanesSwitch: UISwitch! @IBOutlet weak var ARFeaturePointsSwitch: UISwitch! // Independent settings @IBOutlet weak var realTimeCalculationsSwitch: UISwitch! @IBOutlet weak var howToTableViewCell: UITableViewCell! @IBOutlet weak var moreInfoTableViewCell: UITableViewCell! @IBOutlet weak var resetTutorialTableViewCell: UITableViewCell! @IBOutlet weak var appVersionLabel: UILabel! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) populateSettings() } override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self appVersionLabel.text = UtilityMethods.appVersion() } @IBAction func didChangeSetting(_ sender: UISwitch) { let defaults = UserDefaults.standard switch sender { case debugModeSwitch: defaults.set(sender.isOn, for: .showDetailedMessages) case ARPlanesSwitch: defaults.set(sender.isOn, for: .showOverlayARPlanes) case ARFeaturePointsSwitch: defaults.set(sender.isOn, for: .showARFeaturePoints) case realTimeCalculationsSwitch: defaults.set(sender.isOn, for: .realTimeCalculations) default: break } } private func populateSettings() { let defaults = UserDefaults.standard debugModeSwitch.isOn = defaults.bool(for: .showDetailedMessages) ARPlanesSwitch.isOn = defaults.bool(for: .showOverlayARPlanes) ARFeaturePointsSwitch.isOn = defaults.bool(for: .showARFeaturePoints) realTimeCalculationsSwitch.isOn = defaults.bool(for: .realTimeCalculations) } /// MARK - Safari View Controller func loadHowToPage() { if let infoURL = URL(string: "https://github.com/peterxhu/ARGoal/wiki/ARGoal:-How-To-Guide") { let safariVC = SFSafariViewController(url: infoURL) self.present(safariVC, animated: true, completion: nil) safariVC.delegate = self } } func loadMoreInfoPage() { if let infoURL = URL(string: "https://github.com/peterxhu/ARGoal/blob/master/README.md") { let safariVC = SFSafariViewController(url: infoURL) self.present(safariVC, animated: true, completion: nil) safariVC.delegate = self } } func safariViewControllerDidFinish(_ controller: SFSafariViewController) { controller.dismiss(animated: true, completion: nil) } /// MARK - Table View Delegate override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) cell.selectionStyle = .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let selectedCell = tableView.cellForRow(at: indexPath) { switch selectedCell { case howToTableViewCell: loadHowToPage() case moreInfoTableViewCell: loadMoreInfoPage() case resetTutorialTableViewCell: let dismissAction = UIAlertAction(title: "OK", style: .cancel) showAlert(title: "Tutorial Reset", message: "Next time you load \"Goal Distance\", the tutorial will start", actions: [dismissAction]) UserDefaults.standard.set(false, for: .distanceMarkGoal1TutorialFulfilled) UserDefaults.standard.set(false, for: .distanceRealTime2TutorialFulfilled) UserDefaults.standard.set(false, for: .distanceMarkMe3TutorialFulfilled) UserDefaults.standard.set(false, for: .distanceSuggestion4TutorialFulfilled) UserDefaults.standard.set(false, for: .distanceTapScreen5TutorialFulfilled) UserDefaults.standard.set(false, for: .distanceEndOfTutorial6TutorialFulfilled) default: break } } } func showAlert(title: String, message: String, actions: [UIAlertAction]? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) if let actions = actions { for action in actions { alertController.addAction(action) } } else { alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) } self.present(alertController, animated: true, completion: nil) } }
apache-2.0
aea0f847da69e16eca220cd2e4152f67
38.619048
150
0.666066
5.002004
false
false
false
false
vbudhram/firefox-ios
Client/Frontend/ContentBlocker/ContentBlockerHelper.swift
1
15646
/* 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 WebKit import Shared import Deferred @available(iOS 11.0, *) class ContentBlockerHelper { static let PrefKeyEnabledState = "prefkey.trackingprotection.enabled" static let PrefKeyStrength = "prefkey.trackingprotection.strength" fileprivate let blocklistBasic = ["disconnect-advertising", "disconnect-analytics", "disconnect-social"] fileprivate let blocklistStrict = ["disconnect-content"] fileprivate let ruleStore: WKContentRuleListStore fileprivate weak var tab: Tab? fileprivate weak var profile: Profile? static fileprivate var blockImagesRule: WKContentRuleList? static fileprivate var whitelistedDomains = [String]() // Only set and used in UI test static weak var testInstance: ContentBlockerHelper? func whitelist(enable: Bool, forDomain domain: String, completion: (() -> Void)?) { if enable { ContentBlockerHelper.whitelistedDomains.append(domain) } else { ContentBlockerHelper.whitelistedDomains = ContentBlockerHelper.whitelistedDomains.filter { $0 != domain } } removeAllRulesInStore { self.compileListsNotInStore { NotificationCenter.default.post(name: .ContentBlockerUpdateNeeded, object: nil) completion?() } } guard let fileURL = whitelistFile else { return } let list = ContentBlockerHelper.whitelistedDomains.joined(separator: "\n") do { try list.write(to: fileURL, atomically: true, encoding: .utf8) } catch { Sentry.shared.send(message: "Failed to save whitelist file") } } enum TrackingProtectionPerTabEnabledState { case disabledInPrefs case enabledInPrefsAndNoPerTabOverride case forceEnabledPerTab case forceDisabledPerTab func isEnabledOverall() -> Bool { return self != .disabledInPrefs && self != .forceDisabledPerTab } } fileprivate var prefOverrideTrackingProtectionEnabled: Bool? var perTabEnabledState: TrackingProtectionPerTabEnabledState { if !trackingProtectionEnabledInSettings { return .disabledInPrefs } guard let enabled = prefOverrideTrackingProtectionEnabled else { return .enabledInPrefsAndNoPerTabOverride } return enabled ? .forceEnabledPerTab : .forceDisabledPerTab } // Raw values are stored to prefs, be careful changing them. enum EnabledState: String { case on case onInPrivateBrowsing case off var settingTitle: String { switch self { case .on: return Strings.TrackingProtectionOptionAlwaysOn case .onInPrivateBrowsing: return Strings.TrackingProtectionOptionOnInPrivateBrowsing case .off: return Strings.TrackingProtectionOptionAlwaysOff } } static func accessibilityId(for state: EnabledState) -> String { switch state { case .on: return "Settings.TrackingProtectionOption.OnLabel" case .onInPrivateBrowsing: return "Settings.TrackingProtectionOption.OnInPrivateBrowsingLabel" case .off: return "Settings.TrackingProtectionOption.OffLabel" } } static let allOptions: [EnabledState] = [.on, .onInPrivateBrowsing, .off] } // Raw values are stored to prefs, be careful changing them. enum BlockingStrength: String { case basic case strict var settingTitle: String { switch self { case .basic: return Strings.TrackingProtectionOptionBlockListTypeBasic case .strict: return Strings.TrackingProtectionOptionBlockListTypeStrict } } var subtitle: String { switch self { case .basic: return Strings.TrackingProtectionOptionBlockListTypeBasicDescription case .strict: return Strings.TrackingProtectionOptionBlockListTypeStrictDescription } } static func accessibilityId(for strength: BlockingStrength) -> String { switch strength { case .basic: return "Settings.TrackingProtectionOption.BlockListBasic" case .strict: return "Settings.TrackingProtectionOption.BlockListStrict" } } static let allOptions: [BlockingStrength] = [.basic, .strict] } static func prefsChanged() { NotificationCenter.default.post(name: .ContentBlockerUpdateNeeded, object: nil) } class func name() -> String { return "ContentBlockerHelper" } private static var heavyInitHasRunOnce = false private var whitelistFile: URL? { guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { Sentry.shared.send(message: "Failed to get doc dir for whitelist file.") return nil } return dir.appendingPathComponent("whitelist") } private func readWhitelistFile() -> String? { guard let fileURL = whitelistFile else { return nil } let text = try? String(contentsOf: fileURL, encoding: .utf8) return text } init(tab: Tab, profile: Profile) { self.ruleStore = WKContentRuleListStore.default() self.tab = tab self.profile = profile if AppConstants.IsRunningTest { ContentBlockerHelper.testInstance = self } if ContentBlockerHelper.heavyInitHasRunOnce { return } ContentBlockerHelper.heavyInitHasRunOnce = true // Read the whitelist at startup let text = readWhitelistFile() if let text = text, !text.isEmpty { ContentBlockerHelper.whitelistedDomains = text.components(separatedBy: .newlines) } removeOldListsByDateFromStore() { self.removeOldListsByNameFromStore() { self.compileListsNotInStore(completion: {}) } } let blockImages = "[{'trigger':{'url-filter':'.*','resource-type':['image']},'action':{'type':'block'}}]".replacingOccurrences(of: "'", with: "\"") ruleStore.compileContentRuleList(forIdentifier: "images", encodedContentRuleList: blockImages) { rule, error in assert(rule != nil && error == nil) ContentBlockerHelper.blockImagesRule = rule } } func setupForWebView() { NotificationCenter.default.addObserver(self, selector: #selector(updateTab), name: .ContentBlockerUpdateNeeded, object: nil) addActiveRulesToTab() } deinit { NotificationCenter.default.removeObserver(self) } @objc func updateTab() { addActiveRulesToTab() } func overridePrefsAndReloadTab(enableTrackingProtection: Bool) { prefOverrideTrackingProtectionEnabled = enableTrackingProtection updateTab() tab?.reload() } fileprivate var blockingStrengthPref: BlockingStrength { let pref = profile?.prefs.stringForKey(ContentBlockerHelper.PrefKeyStrength) ?? "" return BlockingStrength(rawValue: pref) ?? .basic } fileprivate var enabledStatePref: EnabledState { let pref = profile?.prefs.stringForKey(ContentBlockerHelper.PrefKeyEnabledState) ?? "" return EnabledState(rawValue: pref) ?? .onInPrivateBrowsing } fileprivate var trackingProtectionEnabledInSettings: Bool { switch enabledStatePref { case .off: return false case .on: return true case .onInPrivateBrowsing: return tab?.isPrivate ?? false } } fileprivate func addActiveRulesToTab() { removeTrackingProtectionFromTab() if !perTabEnabledState.isEnabledOverall() { return } let rules = blocklistBasic + (blockingStrengthPref == .strict ? blocklistStrict : []) for name in rules { ruleStore.lookUpContentRuleList(forIdentifier: name) { rule, error in guard let rule = rule else { let msg = "lookUpContentRuleList for \(name): \(error?.localizedDescription ?? "empty rules")" Sentry.shared.send(message: "Content blocker error", tag: .general, description: msg) return } self.addToTab(contentRuleList: rule) } } } func removeTrackingProtectionFromTab() { guard let tab = tab else { return } tab.webView?.configuration.userContentController.removeAllContentRuleLists() if let rule = ContentBlockerHelper.blockImagesRule, tab.noImageMode { addToTab(contentRuleList: rule) } } fileprivate func addToTab(contentRuleList: WKContentRuleList) { tab?.webView?.configuration.userContentController.add(contentRuleList) } func noImageMode(enabled: Bool) { guard let rule = ContentBlockerHelper.blockImagesRule else { return } if enabled { addToTab(contentRuleList: rule) } else { tab?.webView?.configuration.userContentController.remove(rule) } // Async required here to ensure remove() call is processed. DispatchQueue.main.async() { self.tab?.webView?.evaluateJavaScript("window.__firefox__.NoImageMode.setEnabled(\(enabled))", completionHandler: nil) } } } // MARK: Private initialization code // The rule store can compile JSON rule files into a private format which is cached on disk. // On app boot, we need to check if the ruleStore's data is out-of-date, or if the names of the rule files // no longer match. Finally, any JSON rule files that aren't in the ruleStore need to be compiled and stored in the // ruleStore. @available(iOS 11, *) extension ContentBlockerHelper { fileprivate func loadJsonFromBundle(forResource file: String, completion: @escaping (_ jsonString: String) -> Void) { DispatchQueue.global().async { guard let path = Bundle.main.path(forResource: file, ofType: "json"), let source = try? String(contentsOfFile: path, encoding: .utf8) else { return } DispatchQueue.main.async { completion(source) } } } fileprivate func lastModifiedSince1970(forFileAtPath path: String) -> Timestamp? { do { let url = URL(fileURLWithPath: path) let attr = try FileManager.default.attributesOfItem(atPath: url.path) guard let date = attr[FileAttributeKey.modificationDate] as? Date else { return nil } return UInt64(1000.0 * date.timeIntervalSince1970) } catch { return nil } } fileprivate func dateOfMostRecentBlockerFile() -> Timestamp { let blocklists = blocklistBasic + blocklistStrict return blocklists.reduce(Timestamp(0)) { result, filename in guard let path = Bundle.main.path(forResource: filename, ofType: "json") else { return result } let date = lastModifiedSince1970(forFileAtPath: path) ?? 0 return date > result ? date : result } } fileprivate func removeAllRulesInStore(completion: @escaping () -> Void) { ruleStore.getAvailableContentRuleListIdentifiers { available in guard let available = available else { completion() return } let deferreds: [Deferred<Void>] = available.map { filename in let result = Deferred<Void>() self.ruleStore.removeContentRuleList(forIdentifier: filename) { _ in result.fill() } return result } all(deferreds).uponQueue(.main) { _ in completion() } } } // If any blocker files are newer than the date saved in prefs, // remove all the content blockers and reload them. fileprivate func removeOldListsByDateFromStore(completion: @escaping () -> Void) { let fileDate = self.dateOfMostRecentBlockerFile() let prefsNewestDate = profile?.prefs.longForKey("blocker-file-date") ?? 0 if prefsNewestDate < 1 || fileDate <= prefsNewestDate { completion() return } profile?.prefs.setTimestamp(fileDate, forKey: "blocker-file-date") self.removeAllRulesInStore() { completion() } } fileprivate func removeOldListsByNameFromStore(completion: @escaping () -> Void) { var noMatchingIdentifierFoundForRule = false ruleStore.getAvailableContentRuleListIdentifiers { available in guard let available = available else { completion() return } let blocklists = self.blocklistBasic + self.blocklistStrict for contentRuleIdentifier in available { if !blocklists.contains(where: { $0 == contentRuleIdentifier }) { noMatchingIdentifierFoundForRule = true break } } let fileDate = self.dateOfMostRecentBlockerFile() let prefsNewestDate = self.profile?.prefs.timestampForKey("blocker-file-date") ?? 0 if prefsNewestDate > 0 && fileDate <= prefsNewestDate && !noMatchingIdentifierFoundForRule { completion() return } self.profile?.prefs.setTimestamp(fileDate, forKey: "blocker-file-date") self.removeAllRulesInStore { completion() } } } fileprivate func compileListsNotInStore(completion: @escaping () -> Void) { let blocklists = blocklistBasic + blocklistStrict let deferreds: [Deferred<Void>] = blocklists.map { filename in let result = Deferred<Void>() ruleStore.lookUpContentRuleList(forIdentifier: filename) { contentRuleList, error in if contentRuleList != nil { result.fill() return } self.loadJsonFromBundle(forResource: filename) { jsonString in var str = jsonString str.insert(contentsOf: self.whitelistJSON(), at: str.index(str.endIndex, offsetBy: -1) ) self.ruleStore.compileContentRuleList(forIdentifier: filename, encodedContentRuleList: str) { _, _ in result.fill() } } } return result } all(deferreds).uponQueue(.main) { _ in completion() } } func whitelistJSON() -> String { if ContentBlockerHelper.whitelistedDomains.isEmpty { return "" } // Note that * is added to the front of domains, so foo.com becomes *foo.com let list = "'*" + ContentBlockerHelper.whitelistedDomains.joined(separator: "','*") + "'" return ", {'action': { 'type': 'ignore-previous-rules' }, 'trigger': { 'url-filter': '.*', 'unless-domain': [\(list)] }".replacingOccurrences(of: "'", with: "\"") } }
mpl-2.0
b5e310ae794a5a4a9df30c6d541f45a2
35.98818
170
0.618177
5.356385
false
false
false
false
njdehoog/Spelt
Sources/Spelt/SiteRenderer.swift
1
1986
public struct SiteRenderer { public let site: Site public init(site: Site) { self.site = site } public func render() throws { try BuildDateRenderer(site: site).render() try CollectionRenderer(site: site).render() try PermalinkRenderer(site: site).render() try PaginationRenderer(site: site).render() try ExcerptRenderer(site: site).render() try TemplateRenderer(site: site, type: .inPlace).render() try convert() try TemplateRenderer(site: site, type: .usingTemplate).render() } private func convert() throws { let converters: [Converter] = [MarkdownConverter(), SassConverter(site: site)] for case let file as FileWithMetadata in site.files { let matchingConverters = converters.filter({ $0.matches(file.path.pathExtension) }) file.contents = try matchingConverters.reduce(file.contents) { contents, converter in return try converter.convert(contents) } if let outputPathExtension = matchingConverters.last?.outputPathExtension { file.destinationPath = file.destinationPath?.stringByReplacingPathExtension(withExtension: outputPathExtension) } } } } extension SiteRenderer { public struct RenderError: Error { public let filePath: String public let lineNumber: Int? public let underlyingError: Error init(filePath: String, lineNumber: Int? = nil, underlyingError: Error) { self.filePath = filePath self.lineNumber = lineNumber self.underlyingError = underlyingError } } } protocol Renderer { var site: Site { get } func render() throws } protocol Converter { var outputPathExtension: String { get } func matches(_ pathExtension: String) -> Bool func convert(_ content: String) throws -> String }
mit
ccf2ee71515b5a98397276ead3866802
31.032258
127
0.627895
4.977444
false
false
false
false
amandafer/ecommerce
ecommerce/View/ButtonView.swift
1
1631
// // ButtonsView.swift // ecommerce // // Created by Amanda Fernandes on 15/04/2017. // Copyright © 2017 Amanda Fernandes. All rights reserved. // import UIKit @IBDesignable class ButtonView: UIButton { var hasShadow: Bool = false @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.cgColor } } @IBInspectable var bgColor: UIColor? { didSet { backgroundColor = bgColor } } override func draw(_ rect: CGRect) { super.draw(rect) if hasShadow { let shadowLayer = UIView(frame: self.frame) shadowLayer.backgroundColor = UIColor.clear shadowLayer.layer.shadowColor = UIColor.darkGray.cgColor shadowLayer.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: self.cornerRadius).cgPath shadowLayer.layer.shadowOffset = CGSize(width: 1.0, height: 1.0) shadowLayer.layer.shadowOpacity = 0.5 shadowLayer.layer.shadowRadius = 0.3 shadowLayer.layer.masksToBounds = true shadowLayer.clipsToBounds = false self.superview?.addSubview(shadowLayer) self.superview?.bringSubview(toFront: self) } } }
mit
fd19eedd45cfa3d7c4c4b6601d588358
27.103448
116
0.59816
5.109718
false
false
false
false
crazypoo/PTools
Pods/SwifterSwift/Sources/SwifterSwift/SwiftStdlib/OptionalExtensions.swift
1
5810
// // OptionalExtensions.swift // SwifterSwift // // Created by Omar Albeik on 3/3/17. // Copyright © 2017 SwifterSwift // // MARK: - Methods public extension Optional { /// SwifterSwift: Get self of default value (if self is nil). /// /// let foo: String? = nil /// print(foo.unwrapped(or: "bar")) -> "bar" /// /// let bar: String? = "bar" /// print(bar.unwrapped(or: "foo")) -> "bar" /// /// - Parameter defaultValue: default value to return if self is nil. /// - Returns: self if not nil or default value if nil. func unwrapped(or defaultValue: Wrapped) -> Wrapped { // http://www.russbishop.net/improving-optionals return self ?? defaultValue } /// SwifterSwift: Gets the wrapped value of an optional. If the optional is `nil`, throw a custom error. /// /// let foo: String? = nil /// try print(foo.unwrapped(or: MyError.notFound)) -> error: MyError.notFound /// /// let bar: String? = "bar" /// try print(bar.unwrapped(or: MyError.notFound)) -> "bar" /// /// - Parameter error: The error to throw if the optional is `nil`. /// - Returns: The value wrapped by the optional. /// - Throws: The error passed in. func unwrapped(or error: Error) throws -> Wrapped { guard let wrapped = self else { throw error } return wrapped } /// SwifterSwift: Runs a block to Wrapped if not nil /// /// let foo: String? = nil /// foo.run { unwrappedFoo in /// // block will never run sice foo is nill /// print(unwrappedFoo) /// } /// /// let bar: String? = "bar" /// bar.run { unwrappedBar in /// // block will run sice bar is not nill /// print(unwrappedBar) -> "bar" /// } /// /// - Parameter block: a block to run if self is not nil. func run(_ block: (Wrapped) -> Void) { // http://www.russbishop.net/improving-optionals _ = map(block) } /// SwifterSwift: Assign an optional value to a variable only if the value is not nil. /// /// let someParameter: String? = nil /// let parameters = [String: Any]() // Some parameters to be attached to a GET request /// parameters[someKey] ??= someParameter // It won't be added to the parameters dict /// /// - Parameters: /// - lhs: Any? /// - rhs: Any? static func ??= (lhs: inout Optional, rhs: Optional) { guard let rhs = rhs else { return } lhs = rhs } /// SwifterSwift: Assign an optional value to a variable only if the variable is nil. /// /// var someText: String? = nil /// let newText = "Foo" /// let defaultText = "Bar" /// someText ?= newText // someText is now "Foo" because it was nil before /// someText ?= defaultText // someText doesn't change its value because it's not nil /// /// - Parameters: /// - lhs: Any? /// - rhs: Any? static func ?= (lhs: inout Optional, rhs: @autoclosure () -> Optional) { if lhs == nil { lhs = rhs() } } } // MARK: - Methods (Collection) public extension Optional where Wrapped: Collection { /// SwifterSwift: Check if optional is nil or empty collection. var isNilOrEmpty: Bool { guard let collection = self else { return true } return collection.isEmpty } /// SwifterSwift: Returns the collection only if it is not nill and not empty. var nonEmpty: Wrapped? { guard let collection = self else { return nil } guard !collection.isEmpty else { return nil } return collection } } // MARK: - Methods (RawRepresentable, RawValue: Equatable) public extension Optional where Wrapped: RawRepresentable, Wrapped.RawValue: Equatable { // swiftlint:disable missing_swifterswift_prefix /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @inlinable static func == (lhs: Optional, rhs: Wrapped.RawValue?) -> Bool { return lhs?.rawValue == rhs } /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @inlinable static func == (lhs: Wrapped.RawValue?, rhs: Optional) -> Bool { return lhs == rhs?.rawValue } /// Returns a Boolean value indicating whether two values are not equal. /// /// Inequality is the inverse of equality. For any values `a` and `b`, /// `a != b` implies that `a == b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @inlinable static func != (lhs: Optional, rhs: Wrapped.RawValue?) -> Bool { return lhs?.rawValue != rhs } /// Returns a Boolean value indicating whether two values are not equal. /// /// Inequality is the inverse of equality. For any values `a` and `b`, /// `a != b` implies that `a == b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @inlinable static func != (lhs: Wrapped.RawValue?, rhs: Optional) -> Bool { return lhs != rhs?.rawValue } // swiftlint:enable missing_swifterswift_prefix } // MARK: - Operators infix operator ??= : AssignmentPrecedence infix operator ?= : AssignmentPrecedence
mit
3f1bc3299b793c603319d899a5e734ef
32.578035
108
0.584438
4.053733
false
false
false
false
miracl/amcl
version3/swift/fp16.swift
2
12491
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // fp16.swift // // Created by Michael Scott on 07/07/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // /* Finite Field arithmetic Fp^16 functions */ /* FP16 elements are of the form a+ib, where i is sqrt(sqrt(sqrt(-1+sqrt(-1))) */ public struct FP16 { private var a:FP8 private var b:FP8 /* constructors */ init() { a=FP8() b=FP8() } init(_ c:Int) { a=FP8(c) b=FP8() } init(_ x:FP16) { a=FP8(x.a) b=FP8(x.b) } init(_ c:FP8,_ d:FP8) { a=FP8(c) b=FP8(d) } init(_ c:FP8) { a=FP8(c) b=FP8() } /* reduce all components of this mod Modulus */ mutating func reduce() { a.reduce() b.reduce() } /* normalise all components of this mod Modulus */ mutating func norm() { a.norm() b.norm() } /* test this==0 ? */ func iszilch() -> Bool { return a.iszilch() && b.iszilch() } mutating func cmove(_ g:FP16,_ d:Int) { a.cmove(g.a,d) b.cmove(g.b,d) } /* test this==1 ? */ func isunity() -> Bool { let one=FP8(1); return a.equals(one) && b.iszilch() } /* test is w real? That is in a+ib test b is zero */ func isreal() -> Bool { return b.iszilch(); } /* extract real part a */ func real() -> FP8 { return a; } func geta() -> FP8 { return a; } /* extract imaginary part b */ func getb() -> FP8 { return b; } mutating func set_fp8s(_ c: FP8,_ d: FP8) { a.copy(c) b.copy(d) } mutating func set_fp8(_ c: FP8) { a.copy(c) b.zero() } mutating func set_fp8h(_ c: FP8) { b.copy(c) a.zero() } /* test self=x? */ func equals(_ x:FP16) -> Bool { return a.equals(x.a) && b.equals(x.b) } /* copy self=x */ mutating func copy(_ x:FP16) { a.copy(x.a) b.copy(x.b) } /* set this=0 */ mutating func zero() { a.zero() b.zero() } /* set this=1 */ mutating func one() { a.one() b.zero() } /* set self=-self */ mutating func neg() { norm() var m=FP8(a) var t=FP8() m.add(b) m.neg() t.copy(m); t.add(b) b.copy(m) b.add(a) a.copy(t) norm() } /* self=conjugate(self) */ mutating func conj() { b.neg(); norm() } /* this=-conjugate(this) */ mutating func nconj() { a.neg(); norm() } /* self+=x */ mutating func adds(_ x: FP8) { a.add(x) } mutating func add(_ x:FP16) { a.add(x.a) b.add(x.b) } /* self-=x */ mutating func sub(_ x:FP16) { var m=FP16(x) m.neg() add(m) } /* self-=x */ mutating func rsub(_ x: FP16) { neg() add(x) } /* self*=s where s is FP8 */ mutating func pmul(_ s:FP8) { a.mul(s) b.mul(s) } /* self*=s where s is FP2 */ mutating func qmul(_ s:FP2) { a.qmul(s) b.qmul(s) } /* self*=c where c is int */ mutating func imul(_ c:Int) { a.imul(c) b.imul(c) } /* self*=self */ mutating func sqr() { var t1=FP8(a) var t2=FP8(b) var t3=FP8(a) t3.mul(b) t1.add(b) t2.times_i() t2.add(a) t1.norm(); t2.norm() a.copy(t1) a.mul(t2) t2.copy(t3) t2.times_i() t2.add(t3); t2.norm() t2.neg() a.add(t2) b.copy(t3) b.add(t3) norm() } /* self*=y */ mutating func mul(_ y:FP16) { var t1=FP8(a) var t2=FP8(b) var t3=FP8() var t4=FP8(b) t1.mul(y.a) t2.mul(y.b) t3.copy(y.b) t3.add(y.a) t4.add(a) t3.norm(); t4.norm() t4.mul(t3) t3.copy(t1) t3.neg() t4.add(t3) t4.norm() t3.copy(t2) t3.neg() b.copy(t4) b.add(t3) t2.times_i() a.copy(t2) a.add(t1) norm(); } /* convert this to hex string */ func toString() -> String { return ("["+a.toString()+","+b.toString()+"]") } func toRawString() -> String { return ("["+a.toRawString()+","+b.toRawString()+"]") } /* self=1/self */ mutating func inverse() { var t1=FP8(a) var t2=FP8(b) t1.sqr() t2.sqr() t2.times_i(); t2.norm() t1.sub(t2); t1.norm() t1.inverse() a.mul(t1) t1.neg(); t1.norm() b.mul(t1) } /* self*=i where i = sqrt(sqrt(-1+sqrt(-1))) */ mutating func times_i() { var s=FP8(b) let t=FP8(a) s.times_i() a.copy(s) b.copy(t) norm() } mutating func times_i2() { a.times_i() b.times_i() } mutating func times_i4() { a.times_i2() b.times_i2() } /* self=self^p using Frobenius */ mutating func frob(_ f:FP2) { var ff=FP2(f); ff.sqr(); ff.norm() a.frob(ff) b.frob(ff) b.qmul(f) b.times_i() } /* self=self^e */ func pow(_ e:BIG) -> FP16 { var w=FP16(self) w.norm() var z=BIG(e) var r=FP16(1) z.norm() while (true) { let bt=z.parity() z.fshr(1) if bt==1 {r.mul(w)} if z.iszilch() {break} w.sqr() } r.reduce() return r } /* XTR xtr_a function */ mutating func xtr_A(_ w:FP16,_ y:FP16,_ z:FP16) { var r=FP16(w) var t=FP16(w) r.sub(y); r.norm() r.pmul(a) t.add(y); t.norm() t.pmul(b) t.times_i() copy(r) add(t) add(z) norm() } /* XTR xtr_d function */ mutating func xtr_D() { var w=FP16(self) sqr(); w.conj() w.add(w); w.norm(); sub(w) reduce() } /* r=x^n using XTR method on traces of FP48s */ func xtr_pow(_ n:BIG) -> FP16 { var sf=FP16(self) sf.norm() var a=FP16(3) var b=FP16(sf) var c=FP16(b) c.xtr_D() var t=FP16() var r=FP16() let par=n.parity() var v=BIG(n); v.norm(); v.fshr(1) if par==0 {v.dec(1); v.norm()} let nb=v.nbits() var i=nb-1 while i>=0 { if (v.bit(UInt(i)) != 1) { t.copy(b) sf.conj() c.conj() b.xtr_A(a,sf,c) sf.conj() c.copy(t) c.xtr_D() a.xtr_D() } else { t.copy(a); t.conj() a.copy(b) a.xtr_D() b.xtr_A(c,sf,t) c.xtr_D() } i-=1 } if par==0 {r.copy(c)} else {r.copy(b)} r.reduce() return r } /* r=ck^a.cl^n using XTR double exponentiation method on traces of FP48s. See Stam thesis. */ func xtr_pow2(_ ck:FP16,_ ckml:FP16,_ ckm2l:FP16,_ a:BIG,_ b:BIG) -> FP16 { var e=BIG(a) var d=BIG(b) var w=BIG(0) e.norm(); d.norm() var cu=FP16(ck) // can probably be passed in w/o copying var cv=FP16(self) var cumv=FP16(ckml) var cum2v=FP16(ckm2l) var r=FP16() var t=FP16() var f2:Int=0 while d.parity()==0 && e.parity()==0 { d.fshr(1); e.fshr(1); f2 += 1; } while (BIG.comp(d,e) != 0) { if BIG.comp(d,e)>0 { w.copy(e); w.imul(4); w.norm() if BIG.comp(d,w)<=0 { w.copy(d); d.copy(e) e.rsub(w); e.norm() t.copy(cv) t.xtr_A(cu,cumv,cum2v) cum2v.copy(cumv) cum2v.conj() cumv.copy(cv) cv.copy(cu) cu.copy(t) } else if d.parity()==0 { d.fshr(1) r.copy(cum2v); r.conj() t.copy(cumv) t.xtr_A(cu,cv,r) cum2v.copy(cumv) cum2v.xtr_D() cumv.copy(t) cu.xtr_D() } else if e.parity()==1 { d.sub(e); d.norm() d.fshr(1) t.copy(cv) t.xtr_A(cu,cumv,cum2v) cu.xtr_D() cum2v.copy(cv) cum2v.xtr_D() cum2v.conj() cv.copy(t) } else { w.copy(d) d.copy(e); d.fshr(1) e.copy(w) t.copy(cumv) t.xtr_D() cumv.copy(cum2v); cumv.conj() cum2v.copy(t); cum2v.conj() t.copy(cv) t.xtr_D() cv.copy(cu) cu.copy(t) } } if BIG.comp(d,e)<0 { w.copy(d); w.imul(4); w.norm() if BIG.comp(e,w)<=0 { e.sub(d); e.norm() t.copy(cv) t.xtr_A(cu,cumv,cum2v) cum2v.copy(cumv) cumv.copy(cu) cu.copy(t) } else if e.parity()==0 { w.copy(d) d.copy(e); d.fshr(1) e.copy(w) t.copy(cumv) t.xtr_D() cumv.copy(cum2v); cumv.conj() cum2v.copy(t); cum2v.conj() t.copy(cv) t.xtr_D() cv.copy(cu) cu.copy(t) } else if d.parity()==1 { w.copy(e) e.copy(d) w.sub(d); w.norm() d.copy(w); d.fshr(1) t.copy(cv) t.xtr_A(cu,cumv,cum2v) cumv.conj() cum2v.copy(cu) cum2v.xtr_D() cum2v.conj() cu.copy(cv) cu.xtr_D() cv.copy(t) } else { d.fshr(1) r.copy(cum2v); r.conj() t.copy(cumv) t.xtr_A(cu,cv,r) cum2v.copy(cumv) cum2v.xtr_D() cumv.copy(t) cu.xtr_D() } } } r.copy(cv) r.xtr_A(cu,cumv,cum2v) for _ in 0 ..< f2 {r.xtr_D()} r=r.xtr_pow(d) return r } }
apache-2.0
8c3d120b6121dee0da842e177679578b
20.352137
97
0.381555
3.306247
false
false
false
false
DataBreweryIncubator/StructuredQuery
Sources/Relation/Expression.swift
1
6868
import Basic import Schema public protocol ExpressionConvertible { var toExpression: Expression { get } func label(as alias: String) -> Expression } extension ExpressionConvertible { public func label(as alias: String) -> Expression { return .alias(toExpression, alias) } } /// SQL Expression. /// /// Core data type that represents multiple types of a SQL expression nodes: /// literals, NULL, binary and unary operators, function calls, etc. public indirect enum Expression: Hashable, ExpressionConvertible { // Literals /// `NULL` literal case null /// Integer number literal case integer(Int) /// String or text literal case string(String) /// Boolean literal case bool(Bool) /// Binary operator case binary(String, Expression, Expression) /// Unary operator case unary(String, Expression) /// Function with multiple expressions as arguments case function(String, [Expression]) // Bind parameter case parameter(String) /// Expression with a name. Any expression can be given a name with /// `Expression.alias(as: name)`. /// /// - See: Expression.alias(as:) case alias(Expression, String) /// Reference to an attribute of any relation /// /// - See: AttributeReference case attribute(AttributeReference) /// Represents an errorneous expression – an expression that was not /// possible to determine. For example a column was missing. /// /// - See: ExpressionError /// case error(ExpressionError) // TODO: case, cast, extract /// Has value of `true` if the expression is an error, otherwise `false`. public var isError: Bool { switch self { case .error: return true default: return false } } /// List of all errors in the expression tree public var allErrors: [ExpressionError] { switch self { case let .error(error): return [error] default: return Array(children.map { $0.allErrors }.joined()) } } public var alias: String? { switch self { case let .alias(_, name): return name case let .attribute(ref): return ref.name default: return nil } } /// List of children from which the expression is composed. Does not go /// to underlying table expressions. public var children: [Expression] { switch self { case let .binary(_, lhs, rhs): return [lhs, rhs] case let .unary(_, expr): return [expr] case let .function(_, exprs): return exprs case let .alias(expr, _): return [expr] default: return [] } } /// Return all attribute references used in the expression tree /// /// All occurences are returned as they are observed during the children /// tree traversal. public var attributeReferences: [AttributeReference] { // TODO: Use this flatMap (does not compile) /* let refs: [AttributeReference] = children.flatMap { child in let out: [AttributeReference] switch child { case .attribute(let attr): out = [attr] default: out = child.attributeReferences } return out }*/ var refs = [AttributeReference]() children.forEach { child in switch child { case .attribute(let attr): refs.append(attr) default: refs += child.attributeReferences } } return refs } // TODO: Do we still need this? public var toExpression: Expression { return self } /// List of children from which the expression is composed. Does not go /// to underlying table expressions. public var hashValue: Int { switch self { case .null: return 0 case let .bool(value): return value.hashValue case let .integer(value): return value.hashValue case let .string(value): return value.hashValue case let .attribute(value): return value.hashValue case let .parameter(value): return value.hashValue case let .binary(op, lhs, rhs): return op.hashValue ^ lhs.hashValue ^ rhs.hashValue case let .unary(op, expr): return op.hashValue ^ expr.hashValue case let .function(f, exprs): return exprs.reduce(f.hashValue) { acc, elem in acc ^ elem.hashValue } case let .alias(expr, name): return expr.hashValue ^ name.hashValue case .error(_): return 0 } } } public func ==(left: Expression, right: Expression) -> Bool { switch (left, right) { case (.null, .null): return true case let(.integer(lval), .integer(rval)) where lval == rval: return true case let(.string(lval), .string(rval)) where lval == rval: return true case let(.bool(lval), .bool(rval)) where lval == rval: return true case let(.binary(lop, lv1, lv2), .binary(rop, rv1, rv2)) where lop == rop && lv1 == rv1 && lv2 == rv2: return true case let(.unary(lop, lv), .unary(rop, rv)) where lop == rop && lv == rv: return true case let(.alias(lval), .alias(rval)) where lval == rval: return true case let(.function(lname, largs), .function(rname, rargs)) where lname == rname && largs == rargs: return true case let(.parameter(lval), .parameter(rval)) where lval == rval: return true case let(.attribute(lval), .attribute(rval)) where lval == rval: return true case let(.error(lval), .error(rval)) where lval == rval: return true default: return false } } extension Expression: ExpressibleByStringLiteral { public init(stringLiteral value: String.StringLiteralType) { self = .string(value) } public init(extendedGraphemeClusterLiteral value: String.ExtendedGraphemeClusterLiteralType){ self = .string(value) } public init(unicodeScalarLiteral value: String.UnicodeScalarLiteralType) { self = .string(value) } } extension String: ExpressionConvertible { public var toExpression: Expression { return .string(self) } } extension Expression: ExpressibleByIntegerLiteral { public init(integerLiteral value: Int.IntegerLiteralType) { self = .integer(value) } } extension Int: ExpressionConvertible { public var toExpression: Expression { return .integer(self) } } extension Expression: ExpressibleByBooleanLiteral { public init(booleanLiteral value: Bool.BooleanLiteralType){ self = .bool(value) } } extension Bool: ExpressionConvertible { public var toExpression: Expression { return .bool(self) } } extension Expression: ExpressibleByNilLiteral { public init(nilLiteral: ()) { self = .null } }
mit
c72281722b1f1e0502b6b0adb31c286d
30.351598
80
0.625983
4.589572
false
false
false
false
DemocracyClass-HWs/VotingBooth-CastVote-iOS
VotingBooth/VotingBooth/CandidateVotingPage.swift
1
6445
// // CandidateVotingPage.swift // VotingBooth // // Created by Peyman Mortazavi on 11/13/15. // Copyright © 2015 Peyman. All rights reserved. // import UIKit import SDWebImage class CandidateVotingPage: PageViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { var nextButton = UIButton() override func viewWillAppear(animated: Bool) { // Next Button nextButton.setAttributedTitle(NSAttributedString(string: "Finish", attributes: [NSFontAttributeName:titleFont!.fontWithSize(35), NSForegroundColorAttributeName:UIColor.whiteColor()]), forState: .Normal) nextButton.layer.borderWidth = 1 nextButton.layer.borderColor = UIColor.whiteColor().CGColor nextButton.backgroundColor = UIColor(white: 200/255, alpha: 1) nextButton.enabled = false nextButton.addTarget(self, action: "finish_tapped", forControlEvents: .TouchUpInside) self.container.addSubview(nextButton) nextButton.snp_makeConstraints { (make) -> Void in make.left.right.bottom.equalTo(self.container) make.height.equalTo(60) } // Header let header1 = UILabel() header1.text = "Select a" header1.textColor = textColor header1.font = titleFont?.fontWithSize(55) self.container.addSubview(header1) header1.snp_makeConstraints { (make) -> Void in make.top.equalTo(self.container.snp_top).offset(50) make.left.right.equalTo(self.container).inset(125) make.height.equalTo(70) } let header2 = UILabel() header2.text = "Candidate" header2.textColor = textColor header2.font = largeTitleFont?.fontWithSize(60) self.container.addSubview(header2) header2.snp_makeConstraints { (make) -> Void in make.top.equalTo(header1.snp_bottom).offset(10) make.centerX.equalTo(self.container.snp_centerX).offset(50) make.height.equalTo(70) } // Collection view let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: 170, height: 190) flowLayout.sectionInset = UIEdgeInsets(top: 25, left: 100, bottom: 25, right: 100) flowLayout.minimumLineSpacing = 30 let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout) collectionView.registerClass(CandidateCollectionViewCell.self, forCellWithReuseIdentifier: "CandidateCell") collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor.clearColor() self.view.addSubview(collectionView) collectionView.snp_makeConstraints { (make) -> Void in make.top.equalTo(header2.snp_bottom).offset(20) make.bottom.equalTo(nextButton.snp_top).offset(-20) make.left.right.equalTo(self.container).inset(20) } } override func prefersStatusBarHidden() -> Bool { return true } func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) cell?.layer.removeAllAnimations() } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CandidateCollectionViewCell let animation = CABasicAnimation(keyPath: "shadowColor") animation.fromValue = cell?.layer.shadowColor if let candidate = data?.candidates[indexPath.row] { switch candidate.party { case .Democratic: animation.toValue = textColor.CGColor case .Republican: animation.toValue = UIColor.redColor().CGColor case _:return } } animation.duration = 0.5 animation.autoreverses = true animation.repeatCount = .infinity animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) cell?.layer.addAnimation(animation, forKey: "shadowColor") let shadowWidthAnimation = CABasicAnimation(keyPath: "shadowRadius") shadowWidthAnimation.fromValue = cell?.layer.shadowRadius shadowWidthAnimation.toValue = (cell?.layer.shadowRadius)! * 3 shadowWidthAnimation.duration = 0.5 shadowWidthAnimation.autoreverses = true shadowWidthAnimation.repeatCount = .infinity shadowWidthAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) cell?.layer.addAnimation(shadowWidthAnimation, forKey: "shadowRadius") selectedCandidate = data?.candidates[indexPath.row] nextButton.backgroundColor = textColor nextButton.enabled = true } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CandidateCell", forIndexPath: indexPath) if let candidateCell = cell as? CandidateCollectionViewCell, candidate = data?.candidates[indexPath.row] { let url = NSURL(string: candidate.imageUrl) candidateCell.imageViewer.sd_setImageWithURL(url) switch candidate.party { case .Democratic: candidateCell.frameView.backgroundColor = UIColor(red: 58/255, green: 82/255, blue: 124/255, alpha: 1) case .Republican: candidateCell.frameView.backgroundColor = UIColor(red: 177/255, green: 68/255, blue: 73/255, alpha: 1) case _: candidateCell.frameView.backgroundColor = UIColor.grayColor() } } return cell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data?.candidates.count ?? 0 } func finish_tapped() { if let device = photonDevice { device.callFunction("press", withArguments: nil, completion: { (statusCode, error) -> Void in }) } self.navigationController?.pushViewController(ThankYouPage(), animated: true) } }
gpl-2.0
fccff3f7b6cfcdd6476b8f8e0c44f2d6
42.547297
210
0.670857
5.2863
false
false
false
false
wikimedia/wikipedia-ios
WikipediaUITests/SnapshotHelper.swift
1
11305
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- import Foundation import XCTest var deviceLanguage = "" var locale = "" func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations) } func snapshot(_ name: String, waitForLoadingIndicator: Bool) { if waitForLoadingIndicator { Snapshot.snapshot(name) } else { Snapshot.snapshot(name, timeWaitingForIdle: 0) } } /// - Parameters: /// - name: The name of the snapshot /// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { Snapshot.snapshot(name, timeWaitingForIdle: timeout) } enum SnapshotError: Error, CustomDebugStringConvertible { case cannotDetectUser case cannotFindHomeDirectory case cannotFindSimulatorHomeDirectory case cannotAccessSimulatorHomeDirectory(String) case cannotRunOnPhysicalDevice var debugDescription: String { switch self { case .cannotDetectUser: return "Couldn't find Snapshot configuration files - can't detect current user " case .cannotFindHomeDirectory: return "Couldn't find Snapshot configuration files - can't detect `Users` dir" case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case .cannotAccessSimulatorHomeDirectory(let simulatorHostHome): return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?" case .cannotRunOnPhysicalDevice: return "Can't use Snapshot on a physical device." } } } @objcMembers open class Snapshot: NSObject { static var app: XCUIApplication? static var waitForAnimations = true static var cacheDirectory: URL? static var screenshotsDirectory: URL? { return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.app = app Snapshot.waitForAnimations = waitForAnimations do { let cacheDir = try pathPrefix() Snapshot.cacheDirectory = cacheDir setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { print(error) } } class func setLanguage(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { print("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { print("Couldn't detect/set locale...") } if locale.isEmpty && !deviceLanguage.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } if !locale.isEmpty { app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } } class func setLaunchArguments(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let range = NSRange(launchArguments.startIndex..<launchArguments.endIndex, in: launchArguments) let matches = regex.matches(in: launchArguments, options: [], range:range) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { print("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { if timeout > 0 { waitForLoadingIndicatorToDisappear(within: timeout) } print("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work if Snapshot.waitForAnimations { sleep(1) // Waiting for the animation to be finished (kind of) } #if os(OSX) guard let app = self.app else { print("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else guard let app = self.app else { print("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let window = app.windows.firstMatch let screenshot = window.screenshot() guard let simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") do { try screenshot.pngRepresentation.write(to: path) } catch let error { print("Problem writing screenshot: \(name) to \(path)") print(error) } #endif } class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { #if os(tvOS) return #endif guard let app = self.app else { print("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) } class func pathPrefix() throws -> URL? { let homeDir: URL // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) guard let user = ProcessInfo().environment["USER"] else { throw SnapshotError.cannotDetectUser } guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { throw SnapshotError.cannotFindHomeDirectory } homeDir = usersDir.appendingPathComponent(user) #else #if arch(i386) || arch(x86_64) guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } guard let homeDirUrl = URL(string: simulatorHostHome) else { throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome) } homeDir = URL(fileURLWithPath: homeDirUrl.path) #else throw SnapshotError.cannotRunOnPhysicalDevice #endif #endif return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") } } private extension XCUIElementAttributes { var isNetworkLoadingIndicator: Bool { if hasAllowedIdentifier { return false } let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize } var hasAllowedIdentifier: Bool { let allowedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] return allowedIdentifiers.contains(identifier) } func isStatusBar(_ deviceWidth: CGFloat) -> Bool { if elementType == .statusBar { return true } guard frame.origin == .zero else { return false } let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) let newStatusBarSize = CGSize(width: deviceWidth, height: 44) return [oldStatusBarSize, newStatusBarSize].contains(frame.size) } } private extension XCUIElementQuery { var networkLoadingIndicators: XCUIElementQuery { let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isNetworkLoadingIndicator } return self.containing(isNetworkLoadingIndicator) } var deviceStatusBars: XCUIElementQuery { guard let app = Snapshot.app else { fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") } let deviceWidth = app.windows.firstMatch.frame.width let isStatusBar = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isStatusBar(deviceWidth) } return self.containing(isStatusBar) } } private extension CGFloat { func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { return numberA...numberB ~= self } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.15]
mit
d2d344c2abf2724535265f0991e29dab
36.809365
158
0.635471
5.544385
false
false
false
false
gabrielafonsogoncalves/GoogleMapsRouteExample
GoogleMapsTestSwift/Classes/Services/Map/GBMapService.swift
1
1681
// // GBMapService.swift // GoogleMapsTestSwift // // Created by Gabriel Alejandro Afonso Goncalves on 8/3/15. // Copyright (c) 2015 Gabriel Alejandro Afonso Goncalves. All rights reserved. // import Foundation class GBMapService: GBAbstractService, GBConnectionDelegate { var connectionService: GBConnectionService? var delegate: GBMapServiceDelegate? init(delegate: GBMapServiceDelegate) { super.init() self.delegate = delegate self.connectionService = GBConnectionService() } //MARK: Public methods func routeFromOrigin(origin: CLLocationCoordinate2D, toDestination destination: CLLocationCoordinate2D, transportationMethod: String) { var url = "\(GBConstants.GoogleMaps.directionsBaseUrl)?origin=\(origin.latitude),\(origin.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false" if transportationMethod.isEmpty == false { url = "\(url)&mode=\(transportationMethod)" } self.connectionService?.GETRequestToUrl(url, delegate: self) } //MARK: GBConnectionDelegate func gotResponse(response: AnyObject?) { if let dictionary = response as? [String : AnyObject] { if let routeArray = dictionary[GBConstants.Parser.Routes] as? [AnyObject] { if let routeDictionary = routeArray.first as? [String: AnyObject] { let trip = self.builder.build(NSStringFromClass(GBTrip), fromDictionary: routeDictionary) as? GBTrip self.delegate?.routeIdFetched(trip?.polyline!.overviewPolyline) } } } } }
mit
acb3e3a8aadc5f3ea95b600900011413
35.543478
183
0.66627
4.802857
false
false
false
false
sunlijian/sinaBlog_repository
sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Module/Compose/View/EmotionKeyboard/IWEmotionTextView.swift
1
3001
// // IWEmotionTextView.swift // sinaBlog_sunlijian // // Created by sunlijian on 15/10/27. // Copyright © 2015年 myCompany. All rights reserved. // import UIKit class IWEmotionTextView: IWTextView { //计算型属性 var emotionText: String{ var statusText = String() //遍历 attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: []) { (dict, range, stop) -> Void in //如果发现是NSTextAttachment,就代表是表情 if let attachment = dict["NSAttachment"] { print(attachment) statusText += (attachment as! IWEmotionTextAttachment).emotion!.chs! }else{ //是文字 statusText += (self.attributedText.string as NSString).substringWithRange(range) } print(dict) print(range) } return statusText } func insertEmotion(emotion: IWEmotion){ //判断 emotion 的 type if emotion.type == 1 {//emoji表情 insertText((emotion.code! as NSString).emoji()) // textView.replaceRange(textView.selectedTextRange!, withText: (emotion.code! as NSString).emoji()) }else{//不是 emoji 表情 //处理表情 //初始化一个文字附件 let attachment = IWEmotionTextAttachment() //添加一个 emotion 属性 attachment.emotion = emotion attachment.image = UIImage(named: "\(emotion.prePath!)/\(emotion.png!)") attachment.bounds = CGRectMake(0, -4, font!.lineHeight, font!.lineHeight) //通过文字附件初始化一个NSAttributeString let attributeString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment)) //添加一个NSFontAttributeName 属性 attributeString.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1)) //取出textView 已经存在的 attributeText let original = NSMutableAttributedString(attributedString: attributedText) //获取当前选中的 range let range = selectedRange //添加处理过后的 表情 original.replaceCharactersInRange(selectedRange, withAttributedString: attributeString) //然后再把添加后的 original设置成textView 的attributeText attributedText = original //重新设置光标的位置 selectedRange = NSMakeRange(range.location + 1, 0) //添加一个通知 NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self, userInfo: nil) //执行代理 if let dele = delegate { dele.textViewDidChange!(self) } } } }
apache-2.0
c4010d3d6716116c4f8c4bcb59d18db4
34.818182
135
0.590645
5.386719
false
true
false
false
jalehman/YelpClone
YelpClone/SearchResultViewModel.swift
1
989
// // SearchResultViewModel.swift // YelpClone // // Created by Josh Lehman on 2/12/15. // Copyright (c) 2015 Josh Lehman. All rights reserved. // import Foundation class SearchResultViewModel: NSObject { // MARK: Properties let name: String let imageURL: NSURL? let address: String let rating: Float let reviewCount: Int let distance: Double let ratingImageURL: NSURL? let categories: [String] let result: SearchResult private let services: ViewModelServices init(services: ViewModelServices, result: SearchResult) { self.services = services self.name = result.name self.imageURL = result.imageURL self.address = result.address self.rating = result.rating self.reviewCount = result.reviewCount self.distance = result.distance self.ratingImageURL = result.ratingImageURL self.categories = result.categories self.result = result } }
gpl-2.0
e4f42877f942e81d406ede6b96604fbf
24.384615
61
0.662285
4.495455
false
false
false
false
mixalich7b/SwiftTBot
Sources/SwiftTBot/TBot+MessageHandler.swift
1
2557
// // TBot+MessageHandler.swift // SwiftTBot // // Created by Тупицин Константин on 27.04.16. // Copyright © 2016 mixalich7b. All rights reserved. // import Foundation public struct TextReply { private let replyClosure: (String) -> Void public func send(_ message: String) { replyClosure(message) } internal init(replyClosure: @escaping (String) -> Void) { self.replyClosure = replyClosure } } public extension TBot { // Async reply @discardableResult public func on(_ command: String, handler: @escaping (TBMessage, TextReply) -> Void) -> Self { self.setHandler({ (message) in let replier = TextReply(replyClosure: {[weak self] (replyString) in let request = TBSendMessageRequest(chatId: message.chat.id, text: replyString, replyMarkup: TBReplyMarkupNone()) self?.sendMessage(request) }) handler(message, replier) }, forCommand: command) return self } // Sync reply @discardableResult public func on(_ command: String, handler: @escaping (TBMessage) -> String) -> Self { self.setHandler({[weak self] (message) in let replyString = handler(message) let request = TBSendMessageRequest(chatId: message.chat.id, text: replyString, replyMarkup: TBReplyMarkupNone()) self?.sendMessage(request) }, forCommand: command) return self } // Regex based matching. Async reply @discardableResult public func on(_ regex: NSRegularExpression, handler: @escaping (TBMessage, NSRange, TextReply) -> Void) -> Self { self.setHandler({ (message, range) in let replier = TextReply(replyClosure: {[weak self] (replyString) in let request = TBSendMessageRequest(chatId: message.chat.id, text: replyString, replyMarkup: TBReplyMarkupNone()) self?.sendMessage(request) }) handler(message, range, replier) }, forRegexCommand: regex) return self } private func sendMessage(_ request: TBSendMessageRequest<TBMessage, TBReplyMarkupNone>) { do { try self.sendRequest(request, completion: { (response) in if !response.isOk { print("API error: \(response.error?.description ?? "unknown")") } }) } catch TBError.badRequest { print("Bad request") } catch { print("") } } }
gpl-3.0
6b7e00f198690256a97af35014d08e09
33.310811
128
0.602993
4.566547
false
false
false
false
sarvex/SwiftRecepies
CalendarsEvents/Constructing Date Objects/Constructing Date Objects/AppDelegate.swift
1
2674
// // AppDelegate.swift // Constructing Date Objects // // Created by Vandad Nahavandipoor on 6/23/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? enum GregorianEra: Int{ case BC = 0 case AD } func example1(){ let date = NSCalendar.currentCalendar().dateWithEra(GregorianEra.AD.rawValue, year: 2014, month: 12, day: 25, hour: 10, minute: 20, second: 30, nanosecond: 40) if date != nil{ println("The date is \(date)") } else { println("Could not construct the date") } } func example2(){ let now = NSDate() println(now) let newDate = NSCalendar.currentCalendar().dateByAddingUnit( .CalendarUnitHour, value: 10, toDate: now, options:.MatchNextTime) println(newDate) } func example3(){ let now = NSDate() let components = NSCalendar.currentCalendar().componentsInTimeZone( NSTimeZone.localTimeZone(), fromDate: now) dump(components) } func example4(){ var components = NSDateComponents() components.year = 2015 components.month = 3 components.day = 20 components.hour = 10 components.minute = 20 components.second = 30 let date = NSCalendar.currentCalendar().dateFromComponents(components) println(date) } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { example4() self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } }
isc
41f21d26da06acac50a921b76312a76f
24.466667
126
0.668661
4.412541
false
false
false
false
tattn/HackathonStarter
HackathonStarter/Utility/Extension/NSObject+.swift
1
1015
// // NSObject+className.swift // HackathonStarter // // Created by 田中 達也 on 2016/06/30. // Copyright © 2016年 tattn. All rights reserved. // import Foundation // for Debugging extension NSObjectProtocol where Self: NSObject { var description: String { let mirror = Mirror(reflecting: self) return mirror.children .map { element -> String in let key = element.label ?? "Unknown" let value = element.value return "\(key): \(value)" } .joined(separator: "\n") } var properties: [String: Any] { var properties: [String: Any] = [:] let mirror = Mirror(reflecting: self) mirror.children.forEach { if let key = $0.label { properties[key] = $0.value } } return properties } } import RxSwift import NSObject_Rx extension NSObject { var disposeBag: DisposeBag { return rx.disposeBag } }
mit
0c49d8de64eccbcf9e95314a1d784429
22.302326
52
0.557884
4.318966
false
false
false
false
changjianfeishui/iOS_Tutorials_Of_Swift
Beginning Text Kit/TextKitNotepad-Final/TextKitNotepad/TextKitNotepad/NotesListViewController.swift
1
2835
// // NotesListViewController.swift // TextKitNotepad // // Created by Scarecrow on 16/5/21. // Copyright © 2016年 XB. All rights reserved. // import UIKit class NotesListViewController: UITableViewController { lazy var notes:Array<Note> = { let appdelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate return appdelegate.notes }() override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.tableView.reloadData() } override func viewDidLoad() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(preferredContentSizeChanged(_:)), name: UIContentSizeCategoryDidChangeNotification, object: nil) } func preferredContentSizeChanged(notification:NSNotification) -> Void { self.tableView.reloadData() } //MARK: - TableView Delegate override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let label = UILabel() label.text = "test" label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) label.sizeToFit() return CGFloat(ceilf(Float(label.frame.size.height) * 1.7)) } //MARK: - TableView DataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.notes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let note = self.notes[indexPath.row].title let font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) let textColor = UIColor(colorLiteralRed: 0.175, green: 0.458, blue: 0.831, alpha: 1.0) let attrs = [NSForegroundColorAttributeName:textColor,NSFontAttributeName:font,NSTextEffectAttributeName:NSTextEffectLetterpressStyle] let attrString = NSAttributedString(string: note, attributes: attrs) cell.textLabel?.attributedText = attrString return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let editor = segue.destinationViewController as! NoteEditorViewController if segue.identifier == "CellSelected" { let path = tableView.indexPathForSelectedRow editor.note = self.notes[(path?.row)!] } if segue.identifier == "AddNewNote" { let note = Note.noteWithText("") self.notes.append(note) editor.note = note } } }
mit
9f13d0f32469f5d3de40999cd465cda1
35.779221
179
0.680085
5.343396
false
false
false
false
pusher/pusher-websocket-swift
Sources/ObjC/OCPusherHost.swift
2
382
import Foundation @objcMembers @objc public class OCPusherHost: NSObject { var type: Int var host: String? var cluster: String? override public init() { self.type = 2 } public init(host: String) { self.type = 0 self.host = host } public init(cluster: String) { self.type = 1 self.cluster = cluster } }
mit
85b8b13ec9724464036025acb8b928ee
16.363636
43
0.573298
3.897959
false
false
false
false
AndrewJByrne/GoodAsOldPhones-Swift
GoodAsOldPhones/ProductsTableViewController.swift
1
3293
// // ProductsTableViewController.swift // GoodAsOldPhones // // Created by Andrew Byrne on 3/4/16. // Copyright © 2016 Andrew Byrne. All rights reserved. // import UIKit class ProductsTableViewController: UITableViewController { var products: [Product]? override func viewDidLoad() { super.viewDidLoad() let product1 = Product() let product2 = Product() let product3 = Product() let product4 = Product() product1.name = "1907 Wall Set" product1.productImage = "phone-fullscreen1" product1.cellImage = "image-cell1" product1.price = 59.99 product2.name = "1921 Dial Phone" product2.productImage = "phone-fullscreen2" product2.cellImage = "image-cell2" product2.price = 39.99 product3.name = "1937 Desk Set" product3.productImage = "phone-fullscreen3" product3.cellImage = "image-cell3" product3.price = 8.75 product4.name = "1984 Motorola Portable" product4.productImage = "phone-fullscreen4" product4.cellImage = "image-cell4" product4.price = 127.44 // Set our array to have 4 values products = [product1, product2, product3, product4] let ordersInCart = Orders.readOrdersFromArchive() updateCartBadge(ordersInCart.count) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Optional binding using 'if let' construct if let p = products { return p.count } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell", forIndexPath: indexPath) let product = products?[indexPath.row] // Set product name if let p = product { cell.textLabel?.text = p.name if let i = p.cellImage { cell.imageView?.image = UIImage(named: i) } } return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowProduct" { let productVC = segue.destinationViewController as? ProductViewController // guard checks to make sure these values exist and if they do it sets them to the cell and indexPath variables => if you get past this guard, you can safely use these variablles. guard let cell = sender as? UITableViewCell, let indexPath = tableView.indexPathForCell(cell) else { return } // use the index path to get the product name productVC?.product = products?[indexPath.row] } } func updateCartBadge(count: Int) { let tabItem = self.tabBarController?.tabBar.items![2] if (count > 0) { tabItem?.badgeValue = "\(count)" } else { tabItem?.badgeValue = nil } } }
mit
9079defc33ae5e0bf812c502dc81e017
28.927273
191
0.576853
4.935532
false
false
false
false
OscarSwanros/swift
stdlib/public/core/CommandLine.swift
3
1990
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims /// Command-line arguments for the current process. public enum CommandLine { /// The backing static variable for argument count may come either from the /// entry point or it may need to be computed e.g. if we're in the REPL. @_versioned internal static var _argc: Int32 = Int32() /// The backing static variable for arguments may come either from the /// entry point or it may need to be computed e.g. if we're in the REPL. /// /// Care must be taken to ensure that `_swift_stdlib_getUnsafeArgvArgc` is /// not invoked more times than is necessary (at most once). @_versioned internal static var _unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> = _swift_stdlib_getUnsafeArgvArgc(&_argc) /// Access to the raw argc value from C. @_inlineable // FIXME(sil-serialize-all) public static var argc: Int32 { _ = CommandLine.unsafeArgv // Force evaluation of argv. return _argc } /// Access to the raw argv value from C. Accessing the argument vector /// through this pointer is unsafe. @_inlineable // FIXME(sil-serialize-all) public static var unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> { return _unsafeArgv } /// Access to the swift arguments, also use lazy initialization of static /// properties to safely initialize the swift arguments. public static var arguments: [String] = (0..<Int(argc)).map { String(cString: _unsafeArgv[$0]!) } }
apache-2.0
3f1e31583fbf46abc2652b8fa7f6918e
38.019608
80
0.657789
4.606481
false
false
false
false
meantheory/octopus
pipe.swift
1
1319
class Pipe<T:Parser, V> : Parser { typealias Target = V typealias R = T.Target let parser: T let fn : R -> V init(inner: T, fn: R -> V) { self.parser = inner self.fn = fn } func parse(stream: CharStream) -> Target? { if let value = parser.parse(stream) { return fn(value) } return nil } } func pipe<T:Parser, V>(inner: T, fn: T.Target -> V) -> Pipe<T,V> { return Pipe(inner:inner, fn:fn) } infix operator |> {associativity left precedence 130} func |> <T: Parser, V>(inner: T, fn: T.Target -> V) -> Pipe<T,V> { return pipe(inner, fn) } class Pipe2<T1:Parser, T2:Parser, V> : Parser { typealias Target = V typealias R1 = T1.Target typealias R2 = T2.Target let first: T1 let second: T2 let fn: (R1, R2) -> V init(first:T1, second:T2, fn: (R1, R2) -> V) { self.first = first self.second = second self.fn = fn } func parse(stream: CharStream) -> Target? { let old = stream.position if let a = first.parse(stream) { if let b = second.parse(stream) { return fn(a,b) } } stream.position = old return nil } } func pipe2<T1:Parser, T2:Parser, V> ( first : T1, second: T2, fn : (T1.Target, T2.Target) -> V ) -> Pipe2<T1,T2,V> { return Pipe2(first:first, second:second, fn:fn) }
apache-2.0
ef5a4503dabdf98d7d20cb6d00e6ac7f
19.609375
66
0.581501
2.830472
false
false
false
false
chrisbarrett/swift-mode
test/swift-files/indent/operators.swift
3
1091
// swift-mode:test:eval (setq-local swift-mode:basic-offset 4) // swift-mode:test:eval (setq-local swift-mode:parenthesized-expression-offset 2) // swift-mode:test:eval (setq-local swift-mode:multiline-statement-offset 2) // swift-mode:test:eval (setq-local swift-mode:switch-case-offset 0) // Simple case let x = 1 + 2 + 3 + 4 + 5 let x = 1 + 2 + 3 + 4 + 5 // User defined operator let x = 1 +++ 2 /=-+!*%<>&|^?~ 3 +++ 4 +++ 5 // Prefix operators and postfix operators let x = 1 +++foo() let x = 1+++ foo() // Comments precede over operators let x = 1 +// abc 2 +/* abc*/ 3 // Comments behave like whitespaces // https://github.com/apple/swift-evolution/blob/master/proposals/0037-clarify-comments-and-operators.md let x = 1 /*a*/+++foo() let x = 1 /*a*/+++ foo() let x = 1+++// foo() let x = 1+++/*a*/ foo() let x = 1 +++/*a*/ foo() // Operators with dot // This must be equal to let x = (a.++.) a let x = a.++. b // This must be equal to let x = (a++) . a let x = a++. a // Unicode operators let x = a × a // swift-mode:test:known-bug
gpl-3.0
a214fecdad533f606d556e1e9549d111
14.571429
104
0.592661
2.73183
false
true
false
false
Skorch/VueTabController
VueTabController/VueTabBarViewController.swift
1
3581
// // BurstTabBarViewController.swift // burstprototype // // Created by Drew Beaupre on 2015-09-14. // Copyright © 2015 Glass 10. All rights reserved. // import UIKit class VueTabBarViewController: UIViewController { @IBOutlet weak var contentView: UIView! @IBOutlet weak var activeIndicatorView: UIView! @IBOutlet weak var activeIndicatorLeadingContraint: NSLayoutConstraint! @IBOutlet var tabBarButtons: [UIButton]! var activeViewControllerIndex: Int? var viewControllers = [String:UIViewController]() var currentViewController: UIViewController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.viewControllers.count == 0{ tabBarButtons[0].sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { //TODO: notify view controller that it was re-selected. Provides the opportunity for that view controller to reset itself guard let index = activeViewControllerIndex, let button = sender as? UIButton else{ return true } return (tabBarButtons.indexOf(button) ?? -1) != index } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let identifier = segue.identifier else{ return assertionFailure("Custom Tab Bar segue must have an identifier.") } guard let senderValue = sender as? UIButton else{ return assertionFailure("Sender must be set and be a UIButton.") } if let tabSegue = segue as? VueTabBarSegue{ let destinationViewController = segue.destinationViewController if !viewControllers.keys.contains(identifier){ viewControllers[identifier] = destinationViewController } tabSegue.cachedViewController = viewControllers[identifier] if let index = self.tabBarButtons.indexOf(senderValue){ setActiveIndicatorViewToIndex(index, animated:true) } } } private func setActiveIndicatorViewToIndex(index: Int, animated: Bool){ for (buttonIndex, button) in self.tabBarButtons.enumerate(){ let color = (buttonIndex == index) ? self.view.tintColor : UIColor.grayColor() button.tintColor = color } activeViewControllerIndex = index let filteredItems = tabBarButtons[0...index] let newX = filteredItems.last?.frame.minX ?? 0.0 self.activeIndicatorLeadingContraint.constant = newX if animated { UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) } } }
mit
08806b6e0d4ad114aed155a5b9667a48
28.586777
131
0.593296
5.956739
false
false
false
false
leleks/TextFieldEffects
TextFieldEffects/TextFieldEffects/YokoTextField.swift
1
7180
// // YokoTextField.swift // TextFieldEffects // // Created by Raúl Riera on 30/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit @IBDesignable public class YokoTextField: TextFieldEffects { override public var placeholder: String? { didSet { updatePlaceholder() } } @IBInspectable public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } @IBInspectable public var foregroundColor: UIColor = UIColor.blackColor() { didSet { updateForeground() } } override public var bounds: CGRect { didSet { updateForeground() updatePlaceholder() } } private let foregroundView = UIView() private let foregroundLayer = CALayer() private let borderThickness: CGFloat = 3 private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) override func drawViewsForRect(rect: CGRect) { updateForeground() updatePlaceholder() addSubview(foregroundView) addSubview(placeholderLabel) layer.addSublayer(foregroundLayer) delegate = self } private func updateForeground() { foregroundView.frame = rectForForeground(frame) foregroundView.userInteractionEnabled = false foregroundView.layer.transform = rotationAndPerspectiveTransformForView(foregroundView) foregroundView.backgroundColor = foregroundColor foregroundLayer.borderWidth = borderThickness foregroundLayer.borderColor = colorWithBrightnessFactor(foregroundColor, factor: 0.8).CGColor foregroundLayer.frame = rectForBorder(foregroundView.frame, isFill: true) } private func updatePlaceholder() { placeholderLabel.font = placeholderFontFromFont(font) placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() || !text.isEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.7) return smallerFont } private func rectForForeground(bounds: CGRect) -> CGRect { let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y - borderThickness) return newRect } private func rectForBorder(bounds: CGRect, isFill: Bool) -> CGRect { var newRect = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: isFill ? borderThickness : 0) if !CATransform3DIsIdentity(foregroundView.layer.transform) { newRect.origin = CGPoint(x: 0, y: bounds.origin.y) } return newRect } private func layoutPlaceholderInTextRect() { let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } override func animateViewsForTextEntry() { UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.foregroundView.layer.transform = CATransform3DIdentity }, completion: nil) foregroundLayer.frame = rectForBorder(foregroundView.frame, isFill: false) } override func animateViewsForTextDisplay() { if text.isEmpty { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.foregroundLayer.frame = self.rectForBorder(self.foregroundView.frame, isFill: true) self.foregroundView.layer.transform = self.rotationAndPerspectiveTransformForView(self.foregroundView) }, completion: nil) } } // MARK: - private func setAnchorPoint(anchorPoint:CGPoint, forView view:UIView) { var newPoint:CGPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y) var oldPoint:CGPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y) newPoint = CGPointApplyAffineTransform(newPoint, view.transform) oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform) var position = view.layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y view.layer.position = position view.layer.anchorPoint = anchorPoint } private func colorWithBrightnessFactor(color: UIColor, factor: CGFloat) -> UIColor { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha) } else { return color; } } private func rotationAndPerspectiveTransformForView(view: UIView) -> CATransform3D { setAnchorPoint(CGPoint(x: 0.5, y: 1.0), forView:view) var rotationAndPerspectiveTransform = CATransform3DIdentity rotationAndPerspectiveTransform.m34 = 1.0/800 let radians = ((-90) / 180.0 * CGFloat(M_PI)) rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, radians, 1.0, 0.0, 0.0) return rotationAndPerspectiveTransform } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } }
mit
95e6f0d1b0d61baea27ed00abd328e54
36.586387
193
0.645772
5.124197
false
false
false
false
WebberLai/WLComics
Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift
2
19667
// // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. /// You can use the enum of option item with value to control some behaviors of Kingfisher. public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] extension Array where Element == KingfisherOptionsInfoItem { static let empty: KingfisherOptionsInfo = [] } /// Represents the available option items could be used in `KingfisherOptionsInfo`. public enum KingfisherOptionsInfoItem { /// Kingfisher will use the associated `ImageCache` object when handling related operations, /// including trying to retrieve the cached images and store the downloaded image to it. case targetCache(ImageCache) /// The `ImageCache` for storing and retrieving original images. If `originalCache` is /// contained in the options, it will be preferred for storing and retrieving original images. /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. /// /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is /// applied in the option, the original image will be stored to this `originalCache`. At the /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, /// Kingfisher will try to search the original image to check whether it is already there. If found, /// it will be used and applied with the given processor. It is an optimization for not downloading /// the same image for multiple times. case originalCache(ImageCache) /// Kingfisher will use the associated `ImageDownloader` object to download the requested images. case downloader(ImageDownloader) /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `.forceRefresh` as well. case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used. case downloadPriority(Float) /// If set, Kingfisher will ignore the cache and try to fire a download task for the resource. case forceRefresh /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory /// cache, then it will ignore the disk cache but download the image again from network. This is useful when /// you want to display a changeable image behind the same url at the same app session, while avoiding download /// it for multiple times. case fromMemoryCacheOrRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `.transition` option for more. case forceTransition /// If set, Kingfisher will only cache the value in memory but not in disk. case cacheMemoryOnly /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block. case waitForCache /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is /// not in cache, the image retrieving will fail with an error. case onlyFromCache /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen /// rendering to extract pixel information in background. This can speed up display, but will cost more time to /// prepare the image for using. case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, Kingfisher will use main queue for callbacks. @available(*, deprecated, message: "Use `.callbackQueue(CallbackQueue)` instead.") case callbackDispatchQueue(DispatchQueue?) /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks. /// /// - Note: /// This option does not affect the callbacks for UI related extension methods. You will always get the /// callbacks called from main queue. case callbackQueue(CallbackQueue) /// The associated value will be used as the scale factor when converting retrieved data to an image. /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0. case scaleFactor(CGFloat) /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory. /// /// This option is mainly used for back compatibility internally. You should not set it directly. Instead, /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once, /// which uses more memory but only decode image frames once. case preloadAllAnimationData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the image download request. You can modify the request for some /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. /// The original request will be sent without any modification by default. case requestModifier(ImageDownloadRequestModifier) /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. /// This is the posibility you can modify the image download request during redirect. You can modify the request for /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url /// mapping. /// The original redirection request will be sent without any modification by default. case redirectHandler(ImageDownloadRedirectHandler) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well. /// If not set, the `DefaultImageProcessor.default` will be used. case processor(ImageProcessor) /// Supplies a `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// If not set, the `DefaultCacheSerializer.default` will be used. case cacheSerializer(CacheSerializer) /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being /// fetched from a cache, the modifier will run after the `CacheSerializer`. /// /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`. case imageModifier(ImageModifier) /// Keep the existing image of image view while setting another image to it. /// By setting this option, the placeholder image parameter of image view extension method /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading /// If set, Kingfisher will only load the first frame from an animated image file as a single image. /// Loading an animated images may take too much memory. It will be useful when you want to display a /// static preview of the first frame from a animated image. /// /// This option will be ignored if the target image is not animated image data. case onlyLoadFirstFrame /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original /// images if necessary. /// /// The original image will be only cached to disk storage. case cacheOriginalImage /// If set and a downloading error occurred Kingfisher will set provided image (or empty) /// in place of requested one. It's useful when you don't want to show placeholder /// during loading time but wants to use some default image when requests will be failed. case onFailureImage(Image?) /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage /// aggressively. By default this is not contained in the options, that means if the requested image is already /// in disk cache, Kingfisher will not try to load it to memory. case alsoPrefetchToMemory /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already /// has an image set. /// /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance. case loadDiskFileSynchronously /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item. case memoryCacheExpiration(StorageExpiration) /// The expiration extending setting for memory cache. The item expiration time will be incremented by this value after access. /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending value: .cacheTime. /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options. case memoryCacheAccessExtendingExpiration(ExpirationExtending) /// The expiration setting for disk cache. By default, the underlying `DiskStorage.Backend` uses the /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item. case diskCacheExpiration(StorageExpiration) /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of /// blocking the UI, especially if the processor needs a lot of time to run). case processingQueue(CallbackQueue) /// Enable progressive image loading, Kingfisher will use the `ImageProgressive` of case progressiveJPEG(ImageProgressive) } // Improve performance by parsing the input `KingfisherOptionsInfo` (self) first. // So we can prevent the iterating over the options array again and again. /// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member /// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be /// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods. public struct KingfisherParsedOptionsInfo { public var targetCache: ImageCache? = nil public var originalCache: ImageCache? = nil public var downloader: ImageDownloader? = nil public var transition: ImageTransition = .none public var downloadPriority: Float = URLSessionTask.defaultPriority public var forceRefresh = false public var fromMemoryCacheOrRefresh = false public var forceTransition = false public var cacheMemoryOnly = false public var waitForCache = false public var onlyFromCache = false public var backgroundDecode = false public var preloadAllAnimationData = false public var callbackQueue: CallbackQueue = .mainCurrentOrAsync public var scaleFactor: CGFloat = 1.0 public var requestModifier: ImageDownloadRequestModifier? = nil public var redirectHandler: ImageDownloadRedirectHandler? = nil public var processor: ImageProcessor = DefaultImageProcessor.default public var imageModifier: ImageModifier? = nil public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default public var keepCurrentImageWhileLoading = false public var onlyLoadFirstFrame = false public var cacheOriginalImage = false public var onFailureImage: Optional<Image?> = .none public var alsoPrefetchToMemory = false public var loadDiskFileSynchronously = false public var memoryCacheExpiration: StorageExpiration? = nil public var memoryCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime public var diskCacheExpiration: StorageExpiration? = nil public var processingQueue: CallbackQueue? = nil public var progressiveJPEG: ImageProgressive? = nil var onDataReceived: [DataReceivingSideEffect]? = nil public init(_ info: KingfisherOptionsInfo?) { guard let info = info else { return } for option in info { switch option { case .targetCache(let value): targetCache = value case .originalCache(let value): originalCache = value case .downloader(let value): downloader = value case .transition(let value): transition = value case .downloadPriority(let value): downloadPriority = value case .forceRefresh: forceRefresh = true case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true case .forceTransition: forceTransition = true case .cacheMemoryOnly: cacheMemoryOnly = true case .waitForCache: waitForCache = true case .onlyFromCache: onlyFromCache = true case .backgroundDecode: backgroundDecode = true case .preloadAllAnimationData: preloadAllAnimationData = true case .callbackQueue(let value): callbackQueue = value case .scaleFactor(let value): scaleFactor = value case .requestModifier(let value): requestModifier = value case .redirectHandler(let value): redirectHandler = value case .processor(let value): processor = value case .imageModifier(let value): imageModifier = value case .cacheSerializer(let value): cacheSerializer = value case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true case .onlyLoadFirstFrame: onlyLoadFirstFrame = true case .cacheOriginalImage: cacheOriginalImage = true case .onFailureImage(let value): onFailureImage = .some(value) case .alsoPrefetchToMemory: alsoPrefetchToMemory = true case .loadDiskFileSynchronously: loadDiskFileSynchronously = true case .callbackDispatchQueue(let value): callbackQueue = value.map { .dispatch($0) } ?? .mainCurrentOrAsync case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration case .memoryCacheAccessExtendingExpiration(let expirationExtending): memoryCacheAccessExtendingExpiration = expirationExtending case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration case .processingQueue(let queue): processingQueue = queue case .progressiveJPEG(let value): progressiveJPEG = value } } if originalCache == nil { originalCache = targetCache } } } extension KingfisherParsedOptionsInfo { var imageCreatingOptions: ImageCreatingOptions { return ImageCreatingOptions( scale: scaleFactor, duration: 0.0, preloadAll: preloadAllAnimationData, onlyFirstFrame: onlyLoadFirstFrame) } } protocol DataReceivingSideEffect: AnyObject { var onShouldApply: () -> Bool { get set } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) } class ImageLoadingProgressSideEffect: DataReceivingSideEffect { var onShouldApply: () -> Bool = { return true } let block: DownloadProgressBlock init(_ block: @escaping DownloadProgressBlock) { self.block = block } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { guard onShouldApply() else { return } guard let expectedContentLength = task.task.response?.expectedContentLength, expectedContentLength != -1 else { return } let dataLength = Int64(task.mutableData.count) DispatchQueue.main.async { self.block(dataLength, expectedContentLength) } } }
mit
a3988d68aa9088b25cebc9bc376771ba
55.191429
139
0.727259
5.392651
false
false
false
false
BrisyIOS/zhangxuWeiBo
zhangxuWeiBo/zhangxuWeiBo/Account/ZXAccount.swift
1
2101
// // ZXAccount.swift // zhangxuWeiBo // // Created by zhangxu on 16/6/11. // Copyright © 2016年 zhangxu. All rights reserved. // import Foundation class ZXAccount: NSObject , NSCoding { var access_token : String?; var expires_in : NSNumber?; var expires_time : NSDate?; var remind_in : NSNumber?; var uid : NSNumber?; var name : String?; override init() { super.init(); } // 将字典转化为账户模型 func accountWithDic(dic : NSDictionary?) -> AnyObject { // 创建一个账户 let account = self; account.access_token = dic!["access_token"] as? String; account.uid = dic!["uid"] as? NSNumber; account.remind_in = dic!["remind_in"] as? NSNumber; account.expires_in = dic!["expires_in"] as? NSNumber; // 获得当前时间 let now = NSDate(); // 计算出过期时间 account.expires_time = now.dateByAddingTimeInterval(((account.expires_in)?.doubleValue)!); return account; } // 归档 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token"); aCoder.encodeObject(remind_in, forKey: "remind_in"); aCoder.encodeObject(expires_in, forKey: "expires_in"); aCoder.encodeObject(uid, forKey: "uid"); aCoder.encodeObject(name, forKey: "name"); aCoder.encodeObject(expires_time, forKey: "expires_time"); } // 解档 required init?(coder aDecoder: NSCoder) { self.access_token = aDecoder.decodeObjectForKey("access_token") as?String; print(access_token); self.remind_in = aDecoder.decodeObjectForKey("remind_in") as? NSNumber; self.expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber; self.uid = aDecoder.decodeObjectForKey("uid") as? NSNumber; self.name = aDecoder.decodeObjectForKey("name") as? String; self.expires_time = aDecoder.decodeObjectForKey("expires_time") as? NSDate; } }
apache-2.0
bb1add1d6b8a8c35a972fe82c6e783c6
28.449275
98
0.604331
4.215768
false
false
false
false
alskipp/Monoid
MonoidPlayTime.playground/Pages/Foldable.xcplaygroundpage/Contents.swift
1
3068
/*: **Note:** For **Monoid** to be imported into the Playground, ensure that the **Monoid-Mac** *scheme* is selected from the list of schemes. [**<- Previous page**](@previous) * * * ## Experimental Foldable protocol */ import Monoid //: We'll need `id` and `curry` functions func id<A>(_ a: A) -> A { return a } func curry<A,B,C>(_ f: @escaping (A,B) -> C) -> (A) -> (B) -> C { return { a in { b in f(a,b) } } } //: * * * protocol Foldable { associatedtype Element func foldMap<M: Monoid>(_ f: (Element) -> M) -> M } /*: All Foldables get many functions for free 🍻 */ extension Foldable { func foldr<B>(_ initial: B, combine: (Element) -> (B) -> B) -> B { return foldMap { Endo(combine($0)) }.value(initial) } func foldMap<M: Monoid>(_ f: (Element) -> M) -> M { let mappend = curry(M.combine) return foldr(M.mempty) { mappend(f($0)) } } func any(_ p: (Element) -> Bool) -> Bool { return foldMap { AnyOf(p($0)) }.value } func all(_ p: (Element) -> Bool) -> Bool { return foldMap { All(p($0)) }.value } var isEmpty: Bool { return foldr(true) { _ in { _ in false } } } var count: Int { return foldr(0) { _ in { c in c + 1 } } } } extension Foldable where Element: Monoid { func fold() -> Element { return foldMap(id) } } extension Foldable where Element: NumberType { var sum: Element { return foldMap(Sum.init).value } var product: Element { return foldMap(Product.init).value } } extension Foldable where Element: Equatable { func contains(_ x: Element) -> Bool { return any { $0 == x } } } extension Foldable where Element: Comparable { func minElement() -> Element? { return foldMap { Min.init($0) }.value } func maxElement() -> Element? { return foldMap { Max.init($0) }.value } } //: * * * enum List<Element> { case Nil indirect case Cons(Element, List<Element>) // Used to make `List` a `Monoid` func append(_ ys: List) -> List { switch self { case .Nil: return ys case let .Cons(head, tail): return .Cons(head, tail.append(ys)) } } } /*: Make List a `Monoid` */ extension List: Monoid { static var mempty: List { return .Nil } static func combine(_ a: List, _ b: List) -> List { return a.append(b) } } /*: Make List `Foldable` */ extension List: Foldable { func foldMap<M: Monoid>(_ f: (Element) -> M) -> M { switch self { case .Nil: return .mempty case let .Cons(head, tail): return .combine(f(head), tail.foldMap(f)) } } } /*: build some lists */ let listA = List.Cons(1,.Cons(2, .Nil)) let listB = List.Cons(5,.Cons(11,.Cons(3,.Nil))) let listC = listA <> listB // use Monoid method to append lists /*: As List implements both Monoid and Foldable we get lots of functions for free! */ listC.sum listB.product listB.contains(4) listA.isEmpty List<Int>.Nil.isEmpty listC.count listC.maxElement() listC.minElement() listB.any { $0 > 4 } listA.all { $0 > 1 } let listD = List.Cons("Hel",.Cons("lo",.Cons(" world",.Nil))) listD.fold() //: [Next](@next)
mit
dec7c2e49a252b0e36656fae6c7a274c
21.210145
139
0.601305
3.179461
false
false
false
false
Zig1375/SwiftClickHouse
Sources/SwiftClickHouse/Core/Connection.swift
1
10834
import Foundation import Socket public class Connection { static private let DBMS_VERSION_MAJOR : UInt64 = 1; static private let DBMS_VERSION_MINOR : UInt64 = 1; static private let REVISION : UInt64 = 54126; static public let DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES : UInt64 = 50264; static public let DBMS_MIN_REVISION_WITH_TOTAL_ROWS_IN_PROGRESS : UInt64 = 51554; static public let DBMS_MIN_REVISION_WITH_BLOCK_INFO : UInt64 = 51903; static public let DBMS_MIN_REVISION_WITH_CLIENT_INFO : UInt64 = 54032; static public let DBMS_MIN_REVISION_WITH_SERVER_TIMEZONE : UInt64 = 54058; static public let DBMS_MIN_REVISION_WITH_QUOTA_KEY_IN_CLIENT_INFO : UInt64 = 54060; private let socket : Socket; private var serverInfo : ServerInfo? = nil; private let compression : CompressionState; public convenience init(host : String = "localhost", port : Int, database : String = "default", user : String = "default", password : String = "", compression : CompressionState = .Disable) throws { try self.init(host: host, port: Int32(port), database : database); } public convenience init(host : String = "localhost", port : Int32 = 9000, database : String = "default", user : String = "default", password : String = "", compression : CompressionState = .Disable) throws { let config = ConnectionConfig(host : host, port : port, database : database, user : user, password: password, compression: compression); try self.init(config : config); } public init(config : ConnectionConfig) throws { let signature = try Socket.Signature(protocolFamily: .inet, socketType: .stream, proto: .tcp, hostname: config.host, port: config.port) self.socket = try Socket.create(connectedUsing: signature!) self.compression = config.compression; if (config.compression == CompressionState.Enable) { throw ClickHouseError.NotImplemented(message: "Compression not implemented"); } try sendHello(database : config.database, user : config.user, password : config.password); } public var isConnected : Bool { return self.socket.isConnected && self.serverInfo != nil; } private func sendHello(database : String, user : String, password : String) throws { let buffer = ByteBuffer(); buffer.add(ClientCodes.Hello); buffer.add("ClickHouse client"); buffer.add(Connection.DBMS_VERSION_MAJOR); buffer.add(Connection.DBMS_VERSION_MINOR); buffer.add(Connection.REVISION); buffer.add(database); buffer.add(user); buffer.add(password); try socket.write(from: buffer.toData()); guard let socketReader = try read(socket: socket) else { throw ClickHouseError.SocketError; } guard let code = socketReader.read() else { print("Unknown code"); throw ClickHouseError.Unknown; } guard let scode = ServerCodes(rawValue: code) else { print("Unknown code"); throw ClickHouseError.Unknown; } if (scode == ServerCodes.Exception) { try parseException(socketReader: socketReader); } if (scode == ServerCodes.Hello) { guard let name = socketReader.readString(), let version_major = socketReader.read(), let version_minor = socketReader.read(), let revision = socketReader.read() else { throw ClickHouseError.Unknown; } var timezone : String? = nil; if (revision >= Connection.DBMS_MIN_REVISION_WITH_SERVER_TIMEZONE) { if let tz = socketReader.readString() { timezone = tz; } } self.serverInfo = ServerInfo(name : name, version_major : version_major, version_minor : version_minor, revision : revision, timezone : timezone); return; } throw ClickHouseError.Unknown; } func parseException(socketReader : SocketReader) throws { let e = ClickHouseException(); var current = e; while(true) { if let code : UInt32 = socketReader.readInt() { current.code = code; } else { throw ClickHouseError.Unknown; } if let name = socketReader.readString() { current.name = name; } else { throw ClickHouseError.Unknown; } if let display_text = socketReader.readString() { current.display_text = display_text; } else { throw ClickHouseError.Unknown; } if let stack_trace = socketReader.readString() { current.stack_trace = stack_trace; } else { throw ClickHouseError.Unknown; } guard let has_nested = socketReader.readByte() else { throw ClickHouseError.Unknown; } if (has_nested == 1) { current.nested = ClickHouseException(); current = current.nested!; } else { break; } } print(e); throw ClickHouseError.Error(code: e.code, display_text: e.display_text, exception: e); } public func ping() throws -> Bool { if (!self.isConnected) { throw ClickHouseError.NotConnected; } let buffer = ByteBuffer(); buffer.add(ClientCodes.Ping); try socket.write(from: buffer.toData()); guard let socketReader = try read(socket: socket) else { throw ClickHouseError.SocketError; } guard let code = socketReader.read() else { print("Unknown code"); throw ClickHouseError.Unknown; } guard let scode = ServerCodes(rawValue: code) else { print("Unknown code"); throw ClickHouseError.Unknown; } if (scode == .Pong) { return true; } return false; } public func query(sql : String) throws -> ClickHouseResult? { try self.sendQuery(sql : sql); return try receivePacket(); } private func sendQuery(sql : String) throws { if (!self.isConnected) { throw ClickHouseError.NotConnected; } let buffer = ByteBuffer(); buffer.add(ClientCodes.Query); buffer.add(generateQueryId()); if (self.serverInfo!.revision >= Connection.DBMS_MIN_REVISION_WITH_CLIENT_INFO) { buffer.addFixed(UInt8(1)); // query_kind buffer.add(""); // initial_user buffer.add(""); // initial_query_id buffer.add("[::ffff:127.0.0.1]:0"); // initial_address buffer.addFixed(UInt8(1)); // iface_type buffer.add(""); // os_user buffer.add(""); // client_hostname buffer.add("ClickHouse client"); // client_name buffer.add(Connection.DBMS_VERSION_MAJOR); buffer.add(Connection.DBMS_VERSION_MINOR); buffer.add(Connection.REVISION); if (self.serverInfo!.revision >= Connection.DBMS_MIN_REVISION_WITH_QUOTA_KEY_IN_CLIENT_INFO) { buffer.add(""); // quota_key } } buffer.add(""); // ХЗ что это buffer.add(Stages.Complete.rawValue); buffer.add(self.compression.rawValue); buffer.add(sql); // Send empty block as marker of end of data try ClickHouseBlock().addToBuffer(buffer: buffer, revision: self.serverInfo!.revision); try socket.write(from: buffer.toData()); } public func insert(table : String, block : ClickHouseBlock) throws { try self.sendQuery(sql : "INSERT INTO \(table) VALUES"); let _ = try receivePacket(breakOnData : true); let buffer = ByteBuffer(); try block.addToBuffer(buffer: buffer, revision: self.serverInfo!.revision); try ClickHouseBlock().addToBuffer(buffer: buffer, revision: self.serverInfo!.revision); try socket.write(from: buffer.toData()); let _ = try receivePacket(); } func receivePacket(breakOnData : Bool = false) throws -> ClickHouseResult? { guard let socketReader = try read(socket: socket) else { return nil; } let block = Block(); let result = ClickHouseResult(block : block); while(true) { guard let code = socketReader.read() else { print("Unknown code"); throw ClickHouseError.Unknown; } guard let scode = ServerCodes(rawValue: code) else { print("Unknown code"); throw ClickHouseError.Unknown; } switch (scode) { case .Data: if (!(try receiveData(socketReader: socketReader, block : block))) { print("can't read data packet from input stream"); throw ClickHouseError.Unknown; } if (breakOnData) { return nil; } case .Progress : let _ = ClickHouseProgress(socketReader : socketReader, revision : self.serverInfo!.revision); case .Exception : try parseException(socketReader: socketReader); case .ProfileInfo : let _ = BlockProfile(socketReader: socketReader); case .EndOfStream : return result; default: return nil; } } } func receiveData(socketReader : SocketReader, block : Block) throws -> Bool { if (self.compression == CompressionState.Enable) { throw ClickHouseError.NotImplemented(message: "Compression not implemented"); } if (self.serverInfo!.revision >= Connection.DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES) { guard let _ = socketReader.readString() else { return false; } } return block.load(socketReader: socketReader, revision : self.serverInfo!.revision); } public func close() { if (self.socket.isConnected) { self.socket.close() } } private func generateQueryId() -> String { return "\(UUID().hashValue)"; } private func read(socket: Socket) throws -> SocketReader? { if let socketReader = SocketReader(socket: socket) { return socketReader; } return nil; } }
mit
cf46e6f641d96ee2e607bbb8322d9ae0
33.477707
211
0.570663
4.813695
false
false
false
false
instacrate/Subber-api
Sources/App/Stripe/HTTPClient.swift
2
5041
// // HTTPClient.swift // subber-api // // Created by Hakon Hanesand on 1/19/17. // // import Foundation import JSON import class HTTP.Serializer import class HTTP.Parser import HTTP import enum Vapor.Abort import Transport import class FormData.Serializer import class Multipart.Serializer import struct Multipart.Part import FormData func createToken(token: String) -> [HeaderKey: String] { let data = token.data(using: .utf8)!.base64EncodedString() return ["Authorization" : "Basic \(data)"] } public class HTTPClient { let baseURLString: String let client: Client<TCPClientStream, HTTP.Serializer<Request>, HTTP.Parser<Response>>.Type init(urlString: String) { baseURLString = urlString client = Client<TCPClientStream, HTTP.Serializer<Request>, HTTP.Parser<Response>>.self } func get<T: NodeConvertible>(_ resource: String, query: [String : CustomStringConvertible] = [:], token: String = Stripe.token) throws -> T { let response = try client.get(baseURLString + resource, headers: createToken(token: token), query: query) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) return try T.init(node: json.makeNode()) } func get<T: NodeConvertible>(_ resource: String, query: [String : CustomStringConvertible] = [:], token: String = Stripe.token) throws -> [T] { let response = try client.get(baseURLString + resource, headers: createToken(token: token), query: query) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) guard let objects = json.node["data"]?.nodeArray else { throw Abort.custom(status: .internalServerError, message: "Unexpected response formatting. \(json)") } return try objects.map { return try T.init(node: $0) } } func post<T: NodeConvertible>(_ resource: String, query: [String : CustomStringConvertible] = [:], token: String = Stripe.token) throws -> T { let response = try client.post(baseURLString + resource, headers: createToken(token: token), query: query) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) return try T.init(node: json.makeNode()) } func upload<T: NodeConvertible>(_ resource: String, query: [String: CustomStringConvertible] = [:], name: String, bytes: Bytes) throws -> T { guard let boundry = "\(UUID().uuidString)-boundary-\(UUID().uuidString)".data(using: .utf8) else { throw Abort.custom(status: .internalServerError, message: "Error generating mulitpart form data boundy for upload to Stripe.") } var data: Bytes = [] let multipartSerializer = Multipart.Serializer(boundary: [UInt8](boundry)) multipartSerializer.onSerialize = { bytes in data.append(contentsOf: bytes) } let formDataSerializer = FormData.Serializer(multipart: multipartSerializer) let fileField = Field(name: name, filename: nil, part: Multipart.Part.init(headers: [:], body: bytes)) try formDataSerializer.serialize(fileField) try formDataSerializer.multipart.finish() let contentType = try FormData.Serializer.generateContentType(boundary: boundry).string() let response = try client.post(baseURLString + resource, headers: [.contentType : contentType], body: Body.data(data)) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) return try T.init(node: json.makeNode()) } func delete(_ resource: String, query: [String : CustomStringConvertible] = [:], token: String = Stripe.token) throws -> JSON { let response = try client.delete(baseURLString + resource, headers: createToken(token: token), query: query) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) return json } private func checkForStripeError(in json: JSON, from resource: String) throws { if json.node["error"] != nil { throw Abort.custom(status: .internalServerError, message: "Error from Stripe:\(resource) >>> \(json.prettyString)") } } }
mit
fdbf6301ac93a0a7391891c97aa76d91
39.007937
147
0.641738
4.728893
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClientUnitTests/Spec/Partner Applications/PartnerApplicationsSearchRequestSpec.swift
1
1886
// // PartnerApplicationsSearchRequestSpec.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 Quick import Nimble @testable import CreatubblesAPIClient class PartnerApplicationsSearchRequestSpec: QuickSpec { let query = "example-app" override func spec() { describe("Partner Applications Search Request") { it("Should have proper endpoint") { let request = PartnerApplicationsSearchRequest(query: self.query) expect(request.endpoint) == "partner_applications" } it("Should have proper method") { let request = PartnerApplicationsSearchRequest(query: self.query) expect(request.method) == RequestMethod.get } } } }
mit
dc548cddc86b7610c66672a5e2ce36d7
40.911111
81
0.708378
4.738693
false
false
false
false
PartiallyFinite/SwiftDataStructures
Sources/Heap.swift
1
7777
// // Heap.swift // SwiftDataStructures // // The MIT License (MIT) // // Copyright (c) 2016 Greg Omelaenko // // 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. // /// Implements a binary heap in a given range in any compatible container. public struct _Heap<Container : MutableCollectionType where Container.Index : RandomAccessIndexType, Container.Index.Distance : IntegerArithmeticType> { typealias Element = Container.Generator.Element typealias Index = Container.Index public private(set) var range: Range<Index> public let before: (Element, Element) -> Bool /// `range.startIndex` public var startIndex: Index { return range.startIndex } /// `range.endIndex` public var endIndex: Index { return range.endIndex } /// `range.count` public var count: Index.Distance { return range.count } private init(inout container cont: Container, range: Range<Index>? = nil, comparator before: (Element, Element) -> Bool) { let range = range ?? cont.startIndex ..< cont.endIndex self.range = range self.before = before // fix the upper half of the heap (the lower half does not have children, so is already correctly ordered) for i in (range.startIndex ..< range.startIndex.advancedBy(range.count / 2)).reverse() { fix(&cont, index: i) } } /// Make a valid binary heap rooted at `i`. /// - Precondition: `i * 2 + 1` and `i * 2 + 2` are roots of valid binary heaps. /// - Postcondition: `i` is the root of a valid binary heap. /// - Complexity: O(log(`count`)) private mutating func fix(inout cont: Container, index i: Index) { precondition(range ~= i, "Heap range \(range) does not contain index \(i).") let l = i + startIndex.distanceTo(i) + 1 let r = l + 1 var mi: Index // if l exists and sorts before i if l < endIndex && before(cont[l], cont[i]) { mi = l } else { mi = i } // if r exists and sorts before the greatest of i and l (mi) if r < endIndex && before(cont[r], cont[mi]) { mi = r } // if something needs to change, swap and fix if mi != i { swap(&cont[i], &cont[mi]) fix(&cont, index: mi) } } private mutating func top(inout cont: Container) -> Element? { return range.count > 0 ? cont[startIndex] : nil } private mutating func pop(inout cont: Container) -> Element { precondition(range.count > 0, "Cannot pop from empty heap.") range.endIndex -= 1 if range.count > 0 { // swap the popped (first) element with the one that just went out of range swap(&cont[range.startIndex], &cont[range.endIndex]) // fix the heap from the top to correct the ordering fix(&cont, index: startIndex) } return cont[range.endIndex] } private mutating func update(inout cont: Container, value: Element? = nil, atIndex i: Index) { precondition(range ~= i, "Index \(i) outside of heap range \(range).") if let value = value { precondition(!before(cont[i], value), "New value must sort equal or before previous value.") cont[i] = value } func parent(i: Index) -> Index { // floor(i - 1) / 2 return startIndex.advancedBy((startIndex.distanceTo(i) - 1) / 2) } // repeatedly swap the new node upwards until it no longer sorts before its parent var i = i while i > startIndex && before(cont[i], cont[parent(i)]) { swap(&cont[parent(i)], &cont[i]) i = parent(i) } } private mutating func expand(inout cont: Container) { // expand the range to include the new element and run value update range.endIndex += 1 update(&cont, atIndex: endIndex - 1) } } extension MutableCollectionType where Index : RandomAccessIndexType, Index.Distance : IntegerArithmeticType { /// Construct a binary heap in `range`. /// - Postcondition: `self[range]` forms a valid binary heap. /// - Complexity: O(`range.count`) @warn_unused_result public mutating func _makeHeapIn(range: Range<Index>, comparator before: (Generator.Element, Generator.Element) -> Bool) -> _Heap<Self> { return _Heap(container: &self, range: range, comparator: before) } /// Return the top of `heap`, or `nil` if the heap is empty. /// - Complexity: O(1) @warn_unused_result public mutating func _heapTop(inout heap: _Heap<Self>) -> Generator.Element? { return heap.top(&self) } /// Remove and return the top of `heap`, leaving the popped element at position `heap.endIndex` (after this function returns). The count of `self` is unchanged. /// - Complexity: O(log `heap.count`). public mutating func _popHeap(inout heap: _Heap<Self>) -> Generator.Element { return heap.pop(&self) } /// Update the value of the element at index `i` in `heap` to `value` (if given), which compares *before or equal* to the previous value. /// - Precondition: `!heap.before(self[i], value)` /// - Complexity: O(log `heap.count`) public mutating func _heapUpdate(inout heap: _Heap<Self>, value: Generator.Element? = nil, atIndex i: Index) { heap.update(&self, value: value, atIndex: i) } /// Expand the tail of the heap to include one additional element. /// - Complexity: O(log `heap.count`) public mutating func _heapExpand(inout heap: _Heap<Self>) { heap.expand(&self) } /// Sort the elements in `range` in-place using `comparator`. /// - Parameter range: The range to sort. Defaults to `startIndex..<endIndex`. /// - Parameter ascending: Sort ascending instead of descending. Defaults to `true`. /// - Complexity: O(`range.count`) public mutating func heapsort(range: Range<Index>? = nil, comparator before: (Generator.Element, Generator.Element) -> Bool) { let range = range ?? startIndex..<endIndex var heap = _makeHeapIn(range, comparator: before) while heap.count > 0 { _popHeap(&heap) } } } extension MutableCollectionType where Index : RandomAccessIndexType, Index.Distance : IntegerArithmeticType, Generator.Element : Comparable { /// Sort the elements in `range` in-place. /// - Parameter range: The range to sort. Defaults to `startIndex..<endIndex`. /// - Parameter ascending: Sort ascending instead of descending. Defaults to `true`. /// - Complexity: O(`range.count`) public mutating func heapsort(range: Range<Index>? = nil, ascending: Bool = true) { heapsort(range, comparator: ascending ? (>) : (<)) } }
mit
15a09aa3b242e3f830c4aadba4abc65b
42.205556
164
0.644336
4.17221
false
false
false
false
nixzhu/WorkerBee
WorkerBee/FreeTimeJob.swift
1
1377
// // FreeTimeJob.swift // WorkerBee // // Created by NIX on 2016/11/18. // Copyright © 2016年 nixWork. All rights reserved. // import Foundation final public class FreeTimeJob { private static var set = NSMutableSet() private static var onceToken: Int = 0 private static var once: Void = { let runLoop = CFRunLoopGetMain() let observer: CFRunLoopObserver = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFRunLoopActivity.beforeWaiting.rawValue | CFRunLoopActivity.exit.rawValue, true, 0xFFFFFF) { (observer, activity) in guard set.count != 0 else { return } let currentSet = set set = NSMutableSet() currentSet.enumerateObjects({ (object, stop) in if let job = object as? FreeTimeJob { _ = job.target?.perform(job.selector) } }) } CFRunLoopAddObserver(runLoop, observer, CFRunLoopMode.commonModes) }() private class func setup() { _ = FreeTimeJob.once } private weak var target: NSObject? private let selector: Selector public init(target: NSObject, selector: Selector) { self.target = target self.selector = selector } public func commit() { FreeTimeJob.setup() FreeTimeJob.set.add(self) } }
mit
83088de450ed7a7f5b496565b8fb5d97
27.625
215
0.612082
4.855124
false
false
false
false
TheDarkCode/Example-Swift-Apps
Playgrounds/Optionals.playground/Contents.swift
1
1425
//: Playground - noun: a place where people can play import UIKit var lotteryWinnings: Int? // ? defines something as optional // ! explicit unwraps and forces a value print(lotteryWinnings) // First Way if lotteryWinnings != nil { print(lotteryWinnings!) } lotteryWinnings = 100 // Second Way if let winnings = lotteryWinnings { print(winnings) } // Any time a variable has a ? always use a if let class Car { var model: String? } var vehicle: Car? // Multi Line If Let if let v = vehicle { if let m = v.model { print(m) } } vehicle = Car() vehicle?.model = "Bronco" if let v = vehicle, let m = v.model { print(m) } var cars: [Car]? cars = [Car]() //if let carArr = cars { // if carArr.count > 0 { // // } //} if let carArr = cars where carArr.count > 0 { // only execute if not nil and more than 0 elements } else { cars?.append(Car()) print(cars?.count) } // Implicitly unwrapped optional class Person { var _age: Int! var age: Int { if _age == nil { _age = 21 } return _age } func setAge(newAge: Int) { self._age = newAge } } var jake = Person() //print(jake._age) print(jake.age) class Dog { var species: String init(someSpecies: String) { self.species = someSpecies } } var lab = Dog(someSpecies: "Black Lab") print(lab.species)
mit
2942fd738b64adf6c3dd2ffa64bd0cee
13.84375
55
0.588772
3.28341
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/InvTypeVariationsPresenter.swift
2
2391
// // InvTypeVariationsPresenter.swift // Neocom // // Created by Artem Shimanski on 9/28/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController import Expressible class InvTypeVariationsPresenter: TreePresenter { typealias View = InvTypeVariationsViewController typealias Interactor = InvTypeVariationsInteractor typealias Presentation = Tree.Item.FetchedResultsController<Tree.Item.NamedFetchedResultsSection<Tree.Item.FetchedResultsRow<SDEInvType>>> 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.TreeDefaultCell.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> { guard let input = view?.input else { return .init(.failure(NCError.invalidInput(type: type(of: self))))} let invType: SDEInvType switch input { case let .objectID(objectID): invType = try! Services.sde.viewContext.existingObject(with: objectID) } let what = invType.parentType ?? invType let controller = Services.sde.viewContext.managedObjectContext .from(SDEInvType.self) .filter(\SDEInvType.parentType == what || Self == what) .sort(by: \SDEInvType.metaGroup?.metaGroupID, ascending: true) .sort(by: \SDEInvType.metaLevel, ascending: true) .sort(by: \SDEInvType.typeName, ascending: true) .fetchedResultsController(sectionName: \SDEInvType.metaGroup?.metaGroupName, cacheName: nil) return .init(Presentation(controller, treeController: view?.treeController)) } func didSelect<T: TreeItem>(item: T) -> Void { guard let item = item as? Tree.Item.FetchedResultsRow<SDEInvType>, let view = view else {return} Router.SDE.invTypeInfo(.type(item.result)).perform(from: view) } }
lgpl-2.1
6468dce338be997aef67faba6654df61
33.142857
200
0.763598
4.185639
false
false
false
false
dimitris-c/Omicron
Sources/RxOmicron/RxAPIService+Defaults.swift
1
3167
// // RxAPIService.swift // Omicron // // Created by Dimitris C. on 24/06/2017. // Copyright © 2017 Decimal. All rights reserved. // import Foundation import Alamofire import RxSwift import SwiftyJSON #if !COCOAPODS import Omicron #endif // Subclass of APIService that returns Observable instances to use in RxSwift methods. public extension RxAPIService { func call<Model>(request: APIRequest, parse: APIResponse<Model>) -> Observable<Model> { return Observable.create({ [request, parse] (observer) -> Disposable in let apiRequest = self.call(request: request, parse: parse, { (success, result, response) in if let value = result.value, success { observer.on(.next(value)) observer.on(.completed) } else if let error = result.error { observer.on(.error(error)) } }) return Disposables.create { apiRequest.cancel() } }) } func callJSON(request: APIRequest) -> Observable<JSON> { return Observable.create({ (observer) -> Disposable in let apiRequest = self.callJSON(request: request, { (success, result, response) in if let value = result.value, success { observer.on(.next(value)) observer.on(.completed) } else if let error = result.error { observer.on(.error(error)) } }) return Disposables.create { apiRequest.cancel() } }) } func callString(request: APIRequest) -> Observable<String> { return Observable.create({ (observer) -> Disposable in let apiRequest = self.callString(request: request, { (success, result, response) in if success { if let value = result.value { observer.on(.next(value)) observer.on(.completed) } else { observer.on(.error(APIError.parseError())) } } else if let error = result.error { observer.on(.error(error)) } }) return Disposables.create { apiRequest.cancel() } }) } func callData(request: APIRequest) -> Observable<Data> { return Observable.create({ (observer) -> Disposable in let apiRequest = self.callData(request: request, { (success, result, response) in if success { if let value = result.value { observer.on(.next(value)) observer.on(.completed) } else { observer.on(.error(APIError.parseError())) } } else if let error = result.error { observer.on(.error(error)) } }) return Disposables.create { apiRequest.cancel() } }) } }
mit
8896bd471674cd182767946c59b8b96d
33.413043
103
0.501895
5.147967
false
false
false
false
cplaverty/KeitaiWaniKani
AlliCrab/ViewControllers/SubjectDetailViewController.swift
1
16782
// // SubjectDetailViewController.swift // AlliCrab // // Copyright © 2019 Chris Laverty. All rights reserved. // import os import UIKit import WaniKaniKit private let enFont = UIFont.preferredFont(forTextStyle: .body) private let jpFont = UIFont(name: "Hiragino Sans W3", size: enFont.pointSize) ?? enFont class SubjectDetailViewController: UIViewController { // MARK: - Properties private let relativeDateFormatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.allowedUnits = [.month, .day, .hour, .minute] formatter.formattingContext = .standalone formatter.includesApproximationPhrase = true formatter.maximumUnitCount = 1 formatter.unitsStyle = .full return formatter }() private let absoluteDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .none return formatter }() var repositoryReader: ResourceRepositoryReader! var subjectID: Int? private var subject: Subject? private var studyMaterials: StudyMaterials? private var assignment: Assignment? private var reviewStatistics: ReviewStatistics? // MARK: - Outlets @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var headerView: UIView! @IBOutlet weak var characterView: SubjectCharacterView! @IBOutlet weak var levelLabel: UILabel! @IBOutlet weak var primaryMeaningLabel: UILabel! @IBOutlet weak var alternativeMeaningsLabel: UILabel! @IBOutlet weak var userSynonymsLabel: UILabel! @IBOutlet weak var partOfSpeechLabel: UILabel! @IBOutlet weak var radicalCombinationContainerViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var onyomiTitleLabel: UILabel! @IBOutlet weak var onyomiLabel: UILabel! @IBOutlet weak var kunyomiTitleLabel: UILabel! @IBOutlet weak var kunyomiLabel: UILabel! @IBOutlet weak var nanoriTitleLabel: UILabel! @IBOutlet weak var nanoriLabel: UILabel! @IBOutlet weak var vocabularyReadingLabel: UILabel! @IBOutlet weak var contextSentencesStackView: UIStackView! @IBOutlet weak var meaningMnemonicTitleLabel: UILabel! @IBOutlet weak var meaningMnemonicLabel: UILabel! @IBOutlet weak var meaningHintView: UIView! @IBOutlet weak var meaningHintLabel: UILabel! @IBOutlet weak var meaningNoteLabel: UILabel! @IBOutlet weak var readingMnemonicTitleLabel: UILabel! @IBOutlet weak var readingMnemonicLabel: UILabel! @IBOutlet weak var readingHintView: UIView! @IBOutlet weak var readingHintLabel: UILabel! @IBOutlet weak var readingNoteLabel: UILabel! @IBOutlet weak var relatedSubjectsLabel: UILabel! @IBOutlet weak var relatedSubjectsView: UIView! @IBOutlet weak var relatedSubjectsContainerViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var foundInVocabularyView: UIView! @IBOutlet weak var foundInVocabularyContainerViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var srsStageImageView: UIImageView! @IBOutlet weak var srsStageNameLabel: UILabel! @IBOutlet weak var combinedAnsweredCorrectProgressBarView: ProgressBarView! @IBOutlet weak var meaningAnsweredCorrectProgressBarView: ProgressBarView! @IBOutlet weak var readingAnsweredCorrectProgressBarView: ProgressBarView! @IBOutlet weak var nextReviewTitleLabel: UILabel! @IBOutlet weak var nextReviewLabel: UILabel! @IBOutlet weak var unlockedDateLabel: UILabel! @IBOutlet var visibleViewsForRadical: [UIView]! @IBOutlet var visibleViewsForKanji: [UIView]! @IBOutlet var visibleViewsForVocabulary: [UIView]! @IBOutlet var reviewStatisticsViews: [UIView]! // MARK: - Actions @IBAction func openInSafariButtonTapped(_ sender: UIBarButtonItem) { guard let subject = subject else { return } self.presentSafariViewController(url: subject.documentURL) } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() try! updateSubjectDetail() } override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) { super.preferredContentSizeDidChange(forChildContentContainer: container) let newHeight = container.preferredContentSize.height if container === children[0] { os_log("Changing height constraint for radicals to %.1f", type: .debug, newHeight) radicalCombinationContainerViewHeightConstraint.constant = newHeight } else if container === children[1] { os_log("Changing height constraint for related subjects to %.1f", type: .debug, newHeight) relatedSubjectsContainerViewHeightConstraint.constant = newHeight } else if container === children[2] { os_log("Changing height constraint for vocabulary to %.1f", type: .debug, newHeight) foundInVocabularyContainerViewHeightConstraint.constant = newHeight } else { os_log("Content size change for unknown container %@: %@", type: .debug, ObjectIdentifier(container).debugDescription, container.preferredContentSize.debugDescription) } } // MARK: - Update UI private func updateSubjectDetail() throws { guard let repositoryReader = repositoryReader, let subjectID = subjectID else { fatalError("SubjectDetailViewController: repositoryReader or subjectID nil") } os_log("Fetching subject detail for %d", type: .info, subjectID) let (subject, studyMaterials, assignment, reviewStatistics) = try repositoryReader.subjectDetail(id: subjectID) self.subject = subject self.studyMaterials = studyMaterials self.assignment = assignment self.reviewStatistics = reviewStatistics characterView.setSubject(subject, id: subjectID) headerView.backgroundColor = subject.subjectType.backgroundColor levelLabel.text = String(subject.level) switch subject { case let r as Radical: navigationItem.title = r.slug removeSubviews(from: stackView, ifNotIn: visibleViewsForRadical) partOfSpeechLabel.removeFromSuperview() meaningMnemonicTitleLabel.text = "Name Mnemonic" setText(markup: r.meaningMnemonic, to: meaningMnemonicLabel) try setRelatedSubjects(ids: r.amalgamationSubjectIDs, title: "Found In Kanji") meaningAnsweredCorrectProgressBarView.title = "Name Answered Correct" case let k as Kanji: navigationItem.title = k.characters removeSubviews(from: stackView, ifNotIn: visibleViewsForKanji) partOfSpeechLabel.removeFromSuperview() setRadicalCombination(ids: k.componentSubjectIDs) updateKanjiReading(kanji: k, type: .onyomi, titleLabel: onyomiTitleLabel, label: onyomiLabel) updateKanjiReading(kanji: k, type: .kunyomi, titleLabel: kunyomiTitleLabel, label: kunyomiLabel) updateKanjiReading(kanji: k, type: .nanori, titleLabel: nanoriTitleLabel, label: nanoriLabel) meaningMnemonicTitleLabel.text = "Meaning Mnemonic" setText(markup: k.meaningMnemonic, to: meaningMnemonicLabel) if let meaningHint = k.meaningHint { setText(markup: meaningHint, to: meaningHintLabel) } else { meaningHintView.removeFromSuperview() } readingMnemonicTitleLabel.text = "Reading Mnemonic" setText(markup: k.readingMnemonic, to: readingMnemonicLabel) if let readingHint = k.readingHint { setText(markup: readingHint, to: readingHintLabel) } else { readingHintView.removeFromSuperview() } try setRelatedSubjects(ids: k.visuallySimilarSubjectIDs, title: "Visually Similar Kanji") try setFoundVocabulary(ids: k.amalgamationSubjectIDs) case let v as Vocabulary: navigationItem.title = v.characters removeSubviews(from: stackView, ifNotIn: visibleViewsForVocabulary) setText(items: v.normalisedPartsOfSpeech, title: "Part of Speech", to: partOfSpeechLabel) vocabularyReadingLabel.text = v.allReadings vocabularyReadingLabel.font = jpFont setContextSentences(v.contextSentences) meaningMnemonicTitleLabel.text = "Meaning Explanation" setText(markup: v.meaningMnemonic, to: meaningMnemonicLabel) readingMnemonicTitleLabel.text = "Reading Explanation" setText(markup: v.readingMnemonic, to: readingMnemonicLabel) try setRelatedSubjects(ids: v.componentSubjectIDs, title: "Utilised Kanji") default: fatalError("Unknown subject type") } setMeanings(from: subject) setStudyMaterials(studyMaterials) setSubjectProgression(assignment: assignment, reviewStatistics: reviewStatistics) } private func setRadicalCombination(ids: [Int]) { setSubjectIDs(ids, toChildAtIndex: 0, autoSize: true) } private func setRelatedSubjects(ids: [Int], title: String) throws { let uniqueSubjectIDs = ids.filterDuplicates() guard !uniqueSubjectIDs.isEmpty else { relatedSubjectsView.removeFromSuperview() return } relatedSubjectsLabel.text = title setSubjectIDs(uniqueSubjectIDs, toChildAtIndex: 1, autoSize: false) } private func setFoundVocabulary(ids: [Int]) throws { let uniqueSubjectIDs = ids.filterDuplicates() guard !uniqueSubjectIDs.isEmpty else { foundInVocabularyView.removeFromSuperview() return } setSubjectIDs(uniqueSubjectIDs, toChildAtIndex: 2, autoSize: false) } private func setSubjectIDs(_ ids: [Int], toChildAtIndex index: Int, autoSize: Bool) { let subjectSummaryViewController = children[index] as! SubjectSummaryCollectionViewController subjectSummaryViewController.repositoryReader = repositoryReader subjectSummaryViewController.subjectIDs = ids if autoSize { let flowLayout = subjectSummaryViewController.collectionView.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize } } private func setContextSentences(_ sentences: [Vocabulary.ContextSentence]) { for sentence in sentences { let contextSentenceView = ContextSentenceView(frame: .zero) contextSentenceView.japaneseSentenceLabel.font = jpFont contextSentenceView.japanese = sentence.japanese contextSentenceView.english = sentence.english contextSentencesStackView.addArrangedSubview(contextSentenceView) } } private func updateKanjiReading(kanji: Kanji, type: ReadingType, titleLabel: UILabel, label: UILabel) { let textColour = kanji.isPrimary(type: type) ? .black : UIColor.darkGray.withAlphaComponent(0.75) titleLabel.textColor = textColour label.textColor = textColour if let readings = kanji.readings(type: type), readings != "None" { label.text = readings label.font = jpFont } else { label.text = "None" label.font = enFont } } private func setText(items: [String], title: String, to label: UILabel) { guard !items.isEmpty else { label.removeFromSuperview() return } let boldFont = UIFont(descriptor: label.font.fontDescriptor.withSymbolicTraits(.traitBold)!, size: label.font.pointSize) let text = NSMutableAttributedString(string: title, attributes: [.font: boldFont]) text.append(NSAttributedString(string: " " + items.joined(separator: ", "))) label.attributedText = text } private func setText(markup str: String, to label: UILabel) { label.attributedText = NSAttributedString(wkMarkup: str, jpFont: jpFont, attributes: [.font: label.font!]) } private func setText(note str: String?, to label: UILabel) { if let str = str, !str.isEmpty { label.text = str } else { label.attributedText = NSAttributedString(string: "None", attributes: [.foregroundColor: UIColor.darkGray.withAlphaComponent(0.75)]) } } private func setMeanings(from subject: Subject) { primaryMeaningLabel.text = subject.primaryMeaning let alternativeMeanings = subject.meanings.lazy.filter({ !$0.isPrimary }).map({ $0.meaning }).joined(separator: ", ") if alternativeMeanings.isEmpty { alternativeMeaningsLabel.removeFromSuperview() } else { alternativeMeaningsLabel.text = alternativeMeanings } } private func setStudyMaterials(_ studyMaterials: StudyMaterials?) { setText(note: studyMaterials?.meaningNote, to: meaningNoteLabel) setText(note: studyMaterials?.readingNote, to: readingNoteLabel) if let studyMaterials = studyMaterials { setText(items: studyMaterials.meaningSynonyms, title: "User Synonyms", to: userSynonymsLabel) } else { userSynonymsLabel.removeFromSuperview() } } private func setSubjectProgression(assignment: Assignment?, reviewStatistics: ReviewStatistics?) { guard let assignment = assignment, let srsStage = SRSStage(numericLevel: assignment.srsStage), srsStage != .initiate else { reviewStatisticsViews.forEach { view in view.removeFromSuperview() } return } srsStageNameLabel.text = srsStage.rawValue srsStageImageView.image = UIImage(named: srsStage.rawValue)!.withRenderingMode(.alwaysOriginal) setReviewStatistics(reviewStatistics) if let burnedAt = assignment.burnedAt { nextReviewTitleLabel.text = "Retired Date" nextReviewLabel.text = absoluteDateFormatter.string(from: burnedAt) } else { nextReviewTitleLabel.text = "Next Review" switch NextReviewTime(date: assignment.availableAt) { case .none: nextReviewLabel.text = "-" case .now: nextReviewLabel.text = "Available Now" case let .date(date): nextReviewLabel.text = relativeDateFormatter.string(from: date.timeIntervalSinceNow) } } if let unlockedAt = assignment.unlockedAt { unlockedDateLabel.text = absoluteDateFormatter.string(from: unlockedAt) } } private func setReviewStatistics(_ reviewStatistics: ReviewStatistics?) { guard let reviewStatistics = reviewStatistics else { meaningAnsweredCorrectProgressBarView.progress = 1.0 meaningAnsweredCorrectProgressBarView.totalCount = 0 combinedAnsweredCorrectProgressBarView.progress = 1.0 combinedAnsweredCorrectProgressBarView.totalCount = 0 readingAnsweredCorrectProgressBarView.progress = 1.0 readingAnsweredCorrectProgressBarView.totalCount = 0 return } meaningAnsweredCorrectProgressBarView.progress = Float(reviewStatistics.meaningPercentageCorrect) / 100.0 meaningAnsweredCorrectProgressBarView.totalCount = reviewStatistics.meaningTotal combinedAnsweredCorrectProgressBarView.progress = Float(reviewStatistics.percentageCorrect) / 100.0 combinedAnsweredCorrectProgressBarView.totalCount = reviewStatistics.total readingAnsweredCorrectProgressBarView.progress = Float(reviewStatistics.readingPercentageCorrect) / 100.0 readingAnsweredCorrectProgressBarView.totalCount = reviewStatistics.readingTotal } private func removeSubviews(from stackView: UIStackView, ifNotIn visibleViews: [UIView]) { stackView.arrangedSubviews.forEach { view in if !visibleViews.contains(view) { view.removeFromSuperview() } } } }
mit
850b0e5117fe6b3b72a1499f65b7c086
41.808673
179
0.670341
5.621776
false
false
false
false
SMACKHigh/PubNubSimpleHistory
Pod/Classes/PubNub.swift
1
6168
// // PubNubHistory.swift // Pods // // Created by Terry on 3/24/16. // // import Foundation import PubNub let PubNubSimpleHistoryQueue = dispatch_queue_create("com.smackhigh.pubnub", DISPATCH_QUEUE_SERIAL) public extension PubNub { /** Download messages from **now** to earlier in time, until limit is reached or end of channel history is reached. - parameter inChannel: required channel name to download message from - parameter limit: required maximum number of messages to download - parameter newerThan: optional oldest timetoken at which to stop download - parameter pageSize: optional how many messages to download per request, maximum is 100 - parameter completion: required result handler, if any errors occurred PNErrorStatus will be set */ public func downloadLatestMessages(inChannel: String, limit: Int, pageSize: Int? = 100, completion: ([[String:AnyObject]], PNErrorStatus?) -> Void) { downloadMessages(inChannel, limit: limit, newerThan: nil, olderThan: nil, pageSize: pageSize, completion: completion) } /** Download messages from **now** to earlier in time, until limit is reached, reached a certain point in time, or end of channel history is reached. - parameter inChannel: required channel name to download message from - parameter limit: optional maximum number of messages to download - parameter newerThan: optional oldest timetoken at which to stop download - parameter pageSize: optional how many messages to download per request, maximum is 100 - parameter completion: required result handler, if any errors occurred PNErrorStatus will be set */ public func downloadLatestMessagesNewerThan(inChannel: String, limit: Int?, newerThan: NSNumber? = nil, pageSize: Int? = 100, completion: ([[String:AnyObject]], PNErrorStatus?) -> Void) { downloadMessages(inChannel, limit: limit ?? Int.max, newerThan: newerThan, olderThan: nil, pageSize: pageSize, completion: completion) } /** Download messages from a given timetoken to earlier in time, until the limit is reached or end of channel history is reached - parameter inChannel: required channel name to download message from - parameter limit: required maximum number of messages to download - parameter olderThan: required timetoken older than which message download will begin - parameter pageSize: optional how many messages to download per request, maximum is 100 - parameter completion: required result handler, if any errors occurred PNErrorStatus will be set */ public func downloadMessagesOlderThan(inChannel: String, limit: Int, olderThan: NSNumber, pageSize: Int? = 100, completion: ([[String:AnyObject]], PNErrorStatus?) -> Void) { downloadMessages(inChannel, limit: limit, newerThan: nil, olderThan: olderThan, pageSize: pageSize, completion: completion) } func downloadMessages(inChannel: String, limit: Int, newerThan: NSNumber? = nil, olderThan: NSNumber? = nil, pageSize: Int? = 100, completion: ([[String:AnyObject]], PNErrorStatus?) -> Void) { let PUBNUB_LIMIT = (pageSize ?? 0) > 100 || (pageSize ?? 0) < 0 ? 100 : (pageSize ?? 100) // Result var results: [[[String:AnyObject]]] = [] var total: Int = 0 func finish(status: PNErrorStatus?) { self.queue { // clean up messages older than given timestamp or beyond the limit var flattened = Array(results.flatten()) // if cutoff date is specified, filter results if let newerThan = newerThan { flattened = flattened.filter { dict in if let tk = dict["timetoken"] as? NSNumber { // only return results newer than the cut off time return tk.longLongValue >= newerThan.longLongValue } return false } } // since messages are ordered from oldest to newest, we take x elements from the end of the array. if flattened.count > limit { flattened = Array(flattened[(flattened.count - limit)..<flattened.count]) } dispatch_async(dispatch_get_main_queue()) { completion(flattened, status) } } } func downloadMessages(olderThan: NSNumber) { // Load messages from newest to oldest self.historyForChannel(inChannel, start: olderThan, end: nil, limit: UInt(PUBNUB_LIMIT), reverse: false, includeTimeToken: true) { (result, status) -> Void in if status != nil { finish(status) return } guard let messages = result?.data.messages as? [[String:AnyObject]] else { finish(status) return } guard let oldest = result?.data.start else { finish(status) return } results.insert(messages, atIndex: 0) total += messages.count if messages.count < PUBNUB_LIMIT || total >= limit || oldest.longLongValue <= newerThan?.longLongValue { // We are done finish(status) } else { // Download older messages from the oldest message in this batch downloadMessages(oldest) } } } downloadMessages(olderThan ?? PubNub.currentTimetoken()) } public static func currentTimetoken() -> NSNumber { return convertNSDate(NSDate()) } public static func convertNSDate(date: NSDate) -> NSNumber { // Rely on PubNub's precision correction mechanism to convert it properly. return date.timeIntervalSince1970 } func queue(block: dispatch_block_t) { dispatch_async(PubNubSimpleHistoryQueue, block) } }
mit
77e2edbe64363fa16fbdb2c8b6807e08
42.43662
196
0.619001
5.200675
false
false
false
false
qxuewei/XWSwiftWB
XWSwiftWB/XWSwiftWB/Classes/Main/MainTabBar.swift
1
5543
// // MainTabBar.swift // XWSwiftWB // // Created by 邱学伟 on 16/10/25. // Copyright © 2016年 邱学伟. All rights reserved. // import UIKit class MainTabBar: UITabBarController { //MARK: - 成员属性 let composeBtn : UIButton = UIButton(imageName: "tabbar_compose_icon_add", BGIamgeName: "tabbar_compose_button") override func viewDidLoad() { super.viewDidLoad() // self.view.backgroundColor = UIColor.red setupComposeBtn() } } //MARK: - 设置UI界面 extension MainTabBar{ func setupComposeBtn(){ tabBar.addSubview(composeBtn) composeBtn.center = CGPoint(x: tabBar.center.x, y: tabBar.bounds.size.height * 0.5) composeBtn.addTarget(self, action: #selector(MainTabBar.composeClick), for: .touchUpInside) } } //MARK: - 监听方法 extension MainTabBar{ func composeClick() { // XWLog("点击发布!") guard UserAccountViewModel.shareInstance.isLogin == true else { let AC : UIAlertController = UIAlertController(title: nil, message: "您尚未登录,请登陆后重试", preferredStyle: .alert) let OKAction : UIAlertAction = UIAlertAction(title: "OK", style: .default, handler: nil) // if (OKAction.value(forKey: "_titleTextColor") != nil) { // OKAction.setValue(UIColor.red, forKey: "_titleTextColor") // } AC.addAction(OKAction) present(AC, animated: true, completion: nil) return } present(UINavigationController(rootViewController: ComposeVC()), animated: true, completion: nil) } } //MARK: - 纯代码方式创建Tabbar extension MainTabBar{ private func codeCreatTabBar(){ //通过JSON文件创建自控制器 //获取JSON文件路径 guard let JSONPath = Bundle.main.path(forResource: "MainVCSettings.json", ofType: nil) else{ XWLog("没获取到本地JSON文件") return } guard let JSONData = NSData(contentsOfFile: JSONPath) else{ XWLog("没有转成nsdata") return } guard let anyObject = try? JSONSerialization.jsonObject(with: JSONData as Data, options: .mutableLeaves) else{ return } guard let JSONArr = anyObject as? [[String : AnyObject]] else{ return } XWLog(JSONArr) for dict in JSONArr { XWLog(dict) guard let imageName = dict["imageName"] as? String else{ continue } guard let title = dict["title"] as? String else { continue } guard let vcName = dict["vcName"] as? String else{ continue } addChildViewController(childVCName: vcName, title: title, imageName: imageName) } } //MARK: - 私有方法 private func addChildViewsWithVC(){ //添加控制器 addChildViewController(childVC: HomeTableVC(), title: "首页", imageName: "tabbar_home") addChildViewController(childVC: MessageTableVC(), title: "消息", imageName: "tabbar_message_center") addChildViewController(childVC: DiscoverTableVC(), title: "发现", imageName: "tabbar_discover") addChildViewController(childVC: ProfileTableVC(), title: "我", imageName: "tabbar_profile") } private func addChildViewsWithVCName(){ //添加控制器 addChildViewController(childVCName: "HomeTableVC", title: "首页", imageName: "tabbar_home") addChildViewController(childVCName: "MessageTableVC", title: "消息", imageName: "tabbar_message_center") addChildViewController(childVCName: "DiscoverTableVC", title: "发现", imageName: "tabbar_discover") addChildViewController(childVCName: "ProfileTableVC", title: "我", imageName: "tabbar_profile") } //添加子控制器 private func addChildViewController(childVC : UIViewController, title : String, imageName : String){ childVC.title = title childVC.tabBarItem.image = UIImage(named: imageName) childVC.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") let childNav = UINavigationController(rootViewController: childVC) addChildViewController(childNav) } //传入控制器名称添加自控制器 private func addChildViewController(childVCName : String, title : String, imageName : String) { //1.拿到命名空间 guard let spaceName = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else { XWLog("没有取到命名空间") return } //2.根据传入的字符串名称和命名空间获取对应的class guard let childVCClass = NSClassFromString(spaceName + "." + childVCName) else { XWLog("没有获取到字符串对应的class") return } //3.将对应的AnyClass转成相应控制器类型 guard let childVCType = childVCClass as? UIViewController.Type else{ XWLog("没有获取到对应控制器类型") return } //4.创建对应的控制器对象 let childVC = childVCType.init() childVC.title = title childVC.tabBarItem.image = UIImage(named: imageName) childVC.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") let childNav = UINavigationController(rootViewController: childVC) addChildViewController(childNav) } }
apache-2.0
bc7da7e59b222e5c5537ebf2308e2bdf
37.432836
119
0.63165
4.65642
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Camera/Model/CameraRenderer.swift
1
8276
// // CameraRenderer.swift // HXPHPicker // // Created by Slience on 2022/2/15. // import UIKit import AVKit class CameraRenderer { var isPrepared = false private var ciContext: CIContext? private var outputColorSpace: CGColorSpace? private var outputPixelBufferPool: CVPixelBufferPool? private(set) var outputFormatDescription: CMFormatDescription? private(set) var inputFormatDescription: CMFormatDescription? private let filters: [CameraFilter] var filterIndex: Int { willSet { currentFilter.reset() } didSet { if filterIndex > filters.count - 1 { filterIndex = 0 }else if filterIndex < 0 { filterIndex = filters.count - 1 } if isPrepared { currentFilter.prepare(imageSize) } } } var currentFilter: CameraFilter { filters[filterIndex] } var currentFilterName: String { currentFilter.filterName } init(_ filters: [CameraFilter], _ index: Int) { self.filters = filters filterIndex = index } var imageSize: CGSize = .zero func prepare( with formatDescription: CMFormatDescription, outputRetainedBufferCountHint: Int, imageSize: CGSize ) { reset() if filterIndex == 0 { return } ( outputPixelBufferPool, outputColorSpace, outputFormatDescription ) = allocateOutputBufferPool( with: formatDescription, outputRetainedBufferCountHint: outputRetainedBufferCountHint ) if outputPixelBufferPool == nil { return } inputFormatDescription = formatDescription ciContext = CIContext() self.imageSize = imageSize currentFilter.prepare(imageSize) isPrepared = true } func reset() { ciContext = nil outputColorSpace = nil outputPixelBufferPool = nil outputFormatDescription = nil inputFormatDescription = nil currentFilter.reset() isPrepared = false } func render(pixelBuffer: CVPixelBuffer) -> CVPixelBuffer? { if filterIndex == 0 || !isPrepared { return nil } guard let outputPixelBufferPool = outputPixelBufferPool, let ciContext = ciContext else { return nil } if let filteredImage = currentFilter.render(pixelBuffer) { var pbuf: CVPixelBuffer? CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, outputPixelBufferPool, &pbuf) guard let outputPixelBuffer = pbuf else { print("Allocation failure") return nil } ciContext.render( filteredImage, to: outputPixelBuffer, bounds: filteredImage.extent, colorSpace: outputColorSpace ) return outputPixelBuffer } return currentFilter.render(pixelBuffer, outputPixelBufferPool, ciContext) } func allocateOutputBufferPool( with inputFormatDescription: CMFormatDescription, outputRetainedBufferCountHint: Int ) ->( outputBufferPool: CVPixelBufferPool?, outputColorSpace: CGColorSpace?, outputFormatDescription: CMFormatDescription? ) { let inputMediaSubType = CMFormatDescriptionGetMediaSubType(inputFormatDescription) if inputMediaSubType != kCVPixelFormatType_32BGRA { return (nil, nil, nil) } let inputDimensions = CMVideoFormatDescriptionGetDimensions(inputFormatDescription) var pixelBufferAttributes: [String: Any] = [ kCVPixelBufferPixelFormatTypeKey as String: UInt(inputMediaSubType), kCVPixelBufferWidthKey as String: Int(inputDimensions.width), kCVPixelBufferHeightKey as String: Int(inputDimensions.height), kCVPixelBufferIOSurfacePropertiesKey as String: [:] ] // Get pixel buffer attributes and color space from the input format description. var cgColorSpace = CGColorSpaceCreateDeviceRGB() if let inputFormatDescriptionExtension = CMFormatDescriptionGetExtensions( inputFormatDescription ) as Dictionary? { let colorPrimaries = inputFormatDescriptionExtension[kCVImageBufferColorPrimariesKey] if let colorPrimaries = colorPrimaries { var colorSpaceProperties: [String: AnyObject] = [ kCVImageBufferColorPrimariesKey as String: colorPrimaries ] if let yCbCrMatrix = inputFormatDescriptionExtension[kCVImageBufferYCbCrMatrixKey] { colorSpaceProperties[kCVImageBufferYCbCrMatrixKey as String] = yCbCrMatrix } if let transferFunction = inputFormatDescriptionExtension[kCVImageBufferTransferFunctionKey] { colorSpaceProperties[kCVImageBufferTransferFunctionKey as String] = transferFunction } pixelBufferAttributes[kCVBufferPropagatedAttachmentsKey as String] = colorSpaceProperties } if let cvColorspace = inputFormatDescriptionExtension[kCVImageBufferCGColorSpaceKey] { cgColorSpace = cvColorspace as! CGColorSpace } else if (colorPrimaries as? String) == (kCVImageBufferColorPrimaries_P3_D65 as String) { cgColorSpace = CGColorSpace(name: CGColorSpace.displayP3)! } } // Create a pixel buffer pool with the same pixel attributes as the input format description. let poolAttributes = [kCVPixelBufferPoolMinimumBufferCountKey as String: outputRetainedBufferCountHint] var cvPixelBufferPool: CVPixelBufferPool? CVPixelBufferPoolCreate( kCFAllocatorDefault, poolAttributes as NSDictionary?, pixelBufferAttributes as NSDictionary?, &cvPixelBufferPool ) guard let pixelBufferPool = cvPixelBufferPool else { return (nil, nil, nil) } preallocateBuffers(pool: pixelBufferPool, allocationThreshold: outputRetainedBufferCountHint) // Get the output format description. var pixelBuffer: CVPixelBuffer? var outputFormatDescription: CMFormatDescription? let auxAttributes = [ kCVPixelBufferPoolAllocationThresholdKey as String: outputRetainedBufferCountHint ] as NSDictionary CVPixelBufferPoolCreatePixelBufferWithAuxAttributes( kCFAllocatorDefault, pixelBufferPool, auxAttributes, &pixelBuffer ) if let pixelBuffer = pixelBuffer { CMVideoFormatDescriptionCreateForImageBuffer( allocator: kCFAllocatorDefault, imageBuffer: pixelBuffer, formatDescriptionOut: &outputFormatDescription ) } pixelBuffer = nil return (pixelBufferPool, cgColorSpace, outputFormatDescription) } /// - Tag: AllocateRenderBuffers private func preallocateBuffers(pool: CVPixelBufferPool, allocationThreshold: Int) { var pixelBuffers = [CVPixelBuffer]() var error: CVReturn = kCVReturnSuccess let auxAttributes = [kCVPixelBufferPoolAllocationThresholdKey as String: allocationThreshold] as NSDictionary var pixelBuffer: CVPixelBuffer? while error == kCVReturnSuccess { error = CVPixelBufferPoolCreatePixelBufferWithAuxAttributes( kCFAllocatorDefault, pool, auxAttributes, &pixelBuffer ) if let pixelBuffer = pixelBuffer { pixelBuffers.append(pixelBuffer) } pixelBuffer = nil } pixelBuffers.removeAll() } deinit { currentFilter.reset() } } class OriginalFilter: CameraFilter { var filterName: String { "原片".localized } }
mit
a84ac151884570bea8b0cfd5e9826c65
35.280702
117
0.624879
6.596491
false
false
false
false
parkboo/ios-charts
Charts/Classes/Charts/BarChartView.swift
2
5810
// // BarChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics /// Chart that draws bars. public class BarChartView: BarLineChartViewBase, BarChartDataProvider { /// flag that enables or disables the highlighting arrow private var _drawHighlightArrowEnabled = false /// if set to true, all values are drawn above their bars, instead of below their top private var _drawValueAboveBarEnabled = true /// if set to true, a grey area is darawn behind each bar that indicates the maximum value private var _drawBarShadowEnabled = false internal override func initialize() { super.initialize() renderer = BarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler) _xAxisRenderer = ChartXAxisRendererBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self) _highlighter = BarChartHighlighter(chart: self) _chartXMin = -0.5 } internal override func calcMinMax() { super.calcMinMax() if (_data === nil) { return } let barData = _data as! BarChartData // increase deltax by 1 because the bars have a width of 1 _deltaX += 0.5 // extend xDelta to make space for multiple datasets (if ther are one) _deltaX *= CGFloat(_data.dataSetCount) let groupSpace = barData.groupSpace _deltaX += CGFloat(barData.xValCount) * groupSpace _chartXMax = Double(_deltaX) - _chartXMin } /// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart. public override func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight? { if (_dataNotSet || _data === nil) { print("Can't select by touch. No data set.", terminator: "\n") return nil } return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y)) } /// - returns: the bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data. public func getBarBounds(e: BarChartDataEntry) -> CGRect { let set = _data.getDataSetForEntry(e) as! BarChartDataSet! if (set === nil) { return CGRectNull } let barspace = set.barSpace let y = CGFloat(e.value) let x = CGFloat(e.xIndex) let barWidth: CGFloat = 0.5 let spaceHalf = barspace / 2.0 let left = x - barWidth + spaceHalf let right = x + barWidth - spaceHalf let top = y >= 0.0 ? y : 0.0 let bottom = y <= 0.0 ? y : 0.0 var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top) getTransformer(set.axisDependency).rectValueToPixel(&bounds) return bounds } public override var lowestVisibleXIndex: Int { let step = CGFloat(_data.dataSetCount) let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom) getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt) return Int((pt.x <= CGFloat(chartXMin)) ? 0.0 : (pt.x / div) + 1.0) } public override var highestVisibleXIndex: Int { let step = CGFloat(_data.dataSetCount) let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace var pt = CGPoint(x: _viewPortHandler.contentRight, y: _viewPortHandler.contentBottom) getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt) return Int((pt.x >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.x / div)) } // MARK: Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return _drawHighlightArrowEnabled; } set { _drawHighlightArrowEnabled = newValue setNeedsDisplay() } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return _drawValueAboveBarEnabled; } set { _drawValueAboveBarEnabled = newValue setNeedsDisplay() } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return _drawBarShadowEnabled; } set { _drawBarShadowEnabled = newValue setNeedsDisplay() } } // MARK: - BarChartDataProbider public var barData: BarChartData? { return _data as? BarChartData } /// - returns: true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled } /// - returns: true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled } /// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled } }
apache-2.0
ee3d15b4e38e40a6ebf6196d153c2a77
32.589595
149
0.618589
5.008621
false
false
false
false
annatovstyga/REA-Schedule
Raspisaniye/kConstant.swift
1
1520
// // kConstant.swift // SideMenuSwiftDemo // // Created by Kiran Patel on 1/2/16.Mod by Ivan Gulakov. // Copyright © 2016 SOTSYS175. All rights reserved. // import Foundation import UIKit let sideMenuVC = KSideMenuVC() let appDelegate = UIApplication.shared.delegate as! AppDelegate class kConstant { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) func SetIntialMainViewController(_ aStoryBoardID: String)->(KSideMenuVC){ let sideMenuObj = mainStoryboard.instantiateViewController(withIdentifier: "leftMenu") let mainVcObj = mainStoryboard.instantiateViewController(withIdentifier: aStoryBoardID) let navigationController : UINavigationController = UINavigationController(rootViewController: mainVcObj) navigationController.isNavigationBarHidden = true sideMenuVC.view.frame = UIScreen.main.bounds sideMenuVC.RGsetMainViewController(navigationController) sideMenuVC.RGsetMenuViewController(sideMenuObj) return sideMenuVC } func SetMainViewController(_ aStoryBoardID: String)->(KSideMenuVC){ let mainVcObj = mainStoryboard.instantiateViewController(withIdentifier: aStoryBoardID) let navigationController : UINavigationController = UINavigationController(rootViewController: mainVcObj) navigationController.isNavigationBarHidden = true sideMenuVC.view.frame = UIScreen.main.bounds sideMenuVC.RGsetMainViewController(navigationController) return sideMenuVC } }
mit
81279bd8ceb18403dc4ea9be7667068f
41.194444
113
0.761685
5.367491
false
false
false
false
GlebRadchenko/AmazingBubbles
AmazingBubbles/Sources /Constants/Constants.swift
1
601
// // Constants.swift // AmazingBubbles // // Created by GlebRadchenko on 3/31/17. // Copyright © 2017 Gleb Rachenko. All rights reserved. // import Foundation public struct BubbleConstants { public static var initialGravityStrength: CGFloat = 6 public static var pushGravityStrength: CGFloat = 4 public static var panGravityStrength: CGFloat = 20 public static var minimalSizeForItem: CGSize = CGSize(width: 40, height: 40) public static var maximumSizeForItem: CGSize = CGSize(width: 100, height: 100) public static var growAnimationDuration: Double = 0.2 }
mit
6ad1d96213dfe118d25716e21361f0ca
29
82
0.728333
4.166667
false
false
false
false