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
optimizely/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/TweakPersistency.swift
1
6943
// // TweakPersistency.swift // SwiftTweaks // // Created by Bryan Clark on 11/16/15. // Copyright © 2015 Khan Academy. All rights reserved. // import UIKit /// Identifies tweaks in TweakPersistency internal protocol TweakIdentifiable { var persistenceIdentifier: String { get } } /// Caches Tweak values internal typealias TweakCache = [String: TweakableType] /// Persists state for tweaks in a TweakCache internal final class TweakPersistency { private let diskPersistency: TweakDiskPersistency private var tweakCache: TweakCache = [:] init(identifier: String) { self.diskPersistency = TweakDiskPersistency(identifier: identifier) self.tweakCache = self.diskPersistency.loadFromDisk() } internal func currentValueForTweak<T>(_ tweak: Tweak<T>) -> T? { return persistedValueForTweakIdentifiable(AnyTweak(tweak: tweak)) as? T } internal func currentValueForTweak<T>(_ tweak: Tweak<T>) -> T? where T: SignedNumeric & Comparable { if let currentValue = persistedValueForTweakIdentifiable(AnyTweak(tweak: tweak)) as? T { // If the tweak can be clipped, then we'll need to clip it - because // the tweak might've been persisted without a min / max, but then you changed the tweak definition. // example: you tweaked it to 11, then set a max of 10 - the persisted value is still 11! return clip(currentValue, tweak.minimumValue, tweak.maximumValue) } return nil } internal func persistedValueForTweakIdentifiable(_ tweakID: TweakIdentifiable) -> TweakableType? { return tweakCache[tweakID.persistenceIdentifier] } internal func setValue(_ value: TweakableType?, forTweakIdentifiable tweakID: TweakIdentifiable) { tweakCache[tweakID.persistenceIdentifier] = value self.diskPersistency.saveToDisk(tweakCache) } internal func clearAllData() { tweakCache = [:] self.diskPersistency.saveToDisk(tweakCache) } } /// Persists a TweakCache on disk using NSCoding private final class TweakDiskPersistency { private let fileURL: URL private static func fileURLForIdentifier(_ identifier: String) -> URL { return try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("MPSwiftTweaks") .appendingPathComponent("\(identifier)") .appendingPathExtension("db") } private let queue = DispatchQueue(label: "org.khanacademy.swift_tweaks.disk_persistency", qos: .utility, attributes: []) init(identifier: String) { self.fileURL = TweakDiskPersistency.fileURLForIdentifier(identifier) self.ensureDirectoryExists() } /// Creates a directory (if needed) for our persisted TweakCache on disk private func ensureDirectoryExists() { (self.queue).async { try! FileManager.default.createDirectory(at: self.fileURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil) } } func loadFromDisk() -> TweakCache { var result: TweakCache! self.queue.sync { NSKeyedUnarchiver.setClass(Data.self, forClassName: "Data") result = (try? Foundation.Data(contentsOf: self.fileURL)) .flatMap(NSKeyedUnarchiver.unarchiveObject(with:)) .flatMap { $0 as? Data } .map { $0.cache } ?? [:] } return result } func saveToDisk(_ data: TweakCache) { self.queue.async { let data = Data(cache: data) NSKeyedArchiver.setClassName("Data", for: type(of: data)) let nsData = NSKeyedArchiver.archivedData(withRootObject: data) try? nsData.write(to: self.fileURL, options: [.atomic]) } } /// Implements NSCoding for TweakCache. /// TweakCache a flat dictionary: [String: TweakableType]. /// However, because re-hydrating TweakableType from its underlying NSNumber gets Bool & Int mixed up, /// we have to persist a different structure on disk: [TweakViewDataType: [String: AnyObject]] /// This ensures that if something was saved as a Bool, it's read back as a Bool. @objc(TweakDiskPersistencyData) private final class Data: NSObject, NSCoding { let cache: TweakCache init(cache: TweakCache) { self.cache = cache } @objc convenience init?(coder aDecoder: NSCoder) { var cache: TweakCache = [:] // Read through each TweakViewDataType... for dataType in TweakViewDataType.allTypes { // If a sub-dictionary exists for that type, if let dataTypeDictionary = aDecoder.decodeObject(forKey: dataType.nsCodingKey) as? Dictionary<String, AnyObject> { // Read through each entry and populate the cache for (key, value) in dataTypeDictionary { if let value = Data.tweakableTypeWithAnyObject(value, withType: dataType) { cache[key] = value } } } } self.init(cache: cache) } @objc fileprivate func encode(with aCoder: NSCoder) { // Our "dictionary of dictionaries" that is persisted on disk var diskPersistedDictionary: [TweakViewDataType : [String: AnyObject]] = [:] // For each thing in our TweakCache, for (key, value) in cache { let dataType = type(of: value).tweakViewDataType // ... create the "sub-dictionary" if it doesn't already exist for a particular TweakViewDataType if diskPersistedDictionary[dataType] == nil { diskPersistedDictionary[dataType] = [:] } // ... and set the cached value inside the sub-dictionary. diskPersistedDictionary[dataType]![key] = value.nsCoding } // Now we persist the "dictionary of dictionaries" on disk! for (key, value) in diskPersistedDictionary { aCoder.encode(value, forKey: key.nsCodingKey) } } // Reads from the cache, casting to the appropriate TweakViewDataType private static func tweakableTypeWithAnyObject(_ anyObject: AnyObject, withType type: TweakViewDataType) -> TweakableType? { switch type { case .integer: return anyObject as? Int case .boolean: return anyObject as? Bool case .cgFloat: return anyObject as? CGFloat case .double: return anyObject as? Double case .string: return anyObject as? String } } } } private extension TweakViewDataType { /// Identifies our TweakViewDataType when in NSCoding. See implementation of TweakDiskPersistency.Data var nsCodingKey: String { switch self { case .boolean: return "boolean" case .integer: return "integer" case .cgFloat: return "cgfloat" case .double: return "double" case .string: return "string" } } } private extension TweakableType { /// Gets the underlying value from a Tweakable Type var nsCoding: AnyObject { switch type(of: self).tweakViewDataType { case .boolean: return self as AnyObject case .integer: return self as AnyObject case .cgFloat: return self as AnyObject case .double: return self as AnyObject case .string: return self as AnyObject } } }
apache-2.0
02aef64aed4e17e83f7d674b22768966
33.029412
126
0.701527
4.207273
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/IAPHelper.swift
1
5383
// // IAPHelper.swift // TeacherTools // // Created by Parker Rushton on 12/2/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import StoreKit public typealias ProductIdentifier = String public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> () open class IAPHelper: NSObject { fileprivate let productIdentifiers: Set<ProductIdentifier> fileprivate var purchasedProductIdentifiers = Set<ProductIdentifier>() fileprivate var productsRequest: SKProductsRequest? fileprivate var productsRequestCompletionHandler: ProductsRequestCompletionHandler? var core = App.core public init(productIds: Set<ProductIdentifier>) { productIdentifiers = productIds for productIdentifier in productIds { if let user = core.state.currentUser, user.purchases.map( { $0.productId }).contains(productIdentifier) { purchasedProductIdentifiers.insert(productIdentifier) print("Previously purchased: \(productIdentifier)") } else { print("Not purchased: \(productIdentifier)") } } super.init() SKPaymentQueue.default().add(self) } } // MARK: - StoreKit API extension IAPHelper { public func requestProducts(completionHandler: @escaping ProductsRequestCompletionHandler) { productsRequest?.cancel() productsRequestCompletionHandler = completionHandler productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers) productsRequest?.delegate = self productsRequest?.start() } public func buyProduct(_ product: SKProduct) { print("Buying \(product.productIdentifier)...") let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool { return purchasedProductIdentifiers.contains(productIdentifier) } public class func canMakePayments() -> Bool { return SKPaymentQueue.canMakePayments() } public func restorePurchases() { SKPaymentQueue.default().restoreCompletedTransactions() } } // MARK: - SKProductsRequestDelegate extension IAPHelper: SKProductsRequestDelegate { public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let products = response.products productsRequestCompletionHandler?(true, products) clearRequestAndHandler() for p in products { print("Found product: \(p.productIdentifier) \(p.localizedTitle) \(p.price.floatValue)") } } public func request(_ request: SKRequest, didFailWithError error: Error) { AnalyticsHelper.logEvent(.productRequestFailure) productsRequestCompletionHandler?(false, nil) clearRequestAndHandler() } private func clearRequestAndHandler() { productsRequest = nil productsRequestCompletionHandler = nil } } // MARK: - SKPaymentTransactionObserver extension IAPHelper: SKPaymentTransactionObserver { public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .purchased: complete(transaction: transaction) case .restored: restore(transaction: transaction) case .failed: fail(transaction: transaction) case .deferred, .purchasing: break } } } public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { print("Finished restoring completed transactions\(queue)") } public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { AnalyticsHelper.logEvent(.productRestoreFailiure) print("Restore **FAILED**\n\(queue)\n\(error)") } private func complete(transaction: SKPaymentTransaction) { deliverPurchaseNotification(for: transaction.payment.productIdentifier) SKPaymentQueue.default().finishTransaction(transaction) } private func restore(transaction: SKPaymentTransaction) { AnalyticsHelper.logEvent(.proRestored) let productIdentifier = transaction.original?.payment.productIdentifier ?? transaction.payment.productIdentifier deliverPurchaseNotification(for: productIdentifier) SKPaymentQueue.default().finishTransaction(transaction) } private func fail(transaction: SKPaymentTransaction) { AnalyticsHelper.logEvent(.productPurchaseFailure) if let transactionError = transaction.error as NSError? { if transactionError.code != SKError.paymentCancelled.rawValue { print("Transaction Error: \(String(describing: transaction.error?.localizedDescription))") } } SKPaymentQueue.default().finishTransaction(transaction) } private func deliverPurchaseNotification(for identifier: String) { purchasedProductIdentifiers.insert(identifier) core.fire(command: MarkUserPro()) } }
mit
0981950e809c2e16be6013abb839f52d
34.176471
120
0.683389
5.933848
false
false
false
false
harlanhaskins/SwiftSAT
Sources/SAT/main.swift
1
1210
// // main.swift // SAT // // Created by Harlan Haskins on 9/21/17. // Copyright © 2017 Harlan Haskins. All rights reserved. // import Dispatch import Foundation extension FileHandle: TextOutputStream { public func write(_ string: String) { write(string.data(using: .utf8)!) } } var stderr = FileHandle.standardError func usage() -> Never { print("usage: SAT <DIMACS file>", to: &stderr) exit(-1) } func time<T>(_ f: () throws -> T) rethrows -> (UInt64, T) { let start = DispatchTime.now() let v = try f() let end = DispatchTime.now() let milliseconds = (end.uptimeNanoseconds - start.uptimeNanoseconds) / NSEC_PER_MSEC return (milliseconds, v) } func main() throws { guard CommandLine.arguments.count > 1 else { usage() } let reader = DIMACSReader() let (parseTime, formula) = try time { try reader.read(filename: CommandLine.arguments[1]) } let (solveTime, isSat) = time { formula.isSatisfiable() } print("Parse time: \(parseTime)ms") print("Solving time: \(solveTime)ms") print(isSat ? "SATISFIABLE" : "UNSATISFIABLE") } do { try main() } catch { print("error: \(error)", to: &stderr) }
mit
c9e4ce8c1d406bcd76dd39e1aa4dc4b9
20.981818
88
0.628619
3.424929
false
false
false
false
sstanic/Shopfred
Shopfred/Shopfred/Data/ShoppingStore.swift
1
28951
// // ShoppingStore.swift // Shopfred // // Created by Sascha Stanic on 01.11.17. // Copyright © 2017 Sascha Stanic. All rights reserved. // import Foundation import CoreData /** The ShoppingStore is the connecting class to the data layer and to the external database for shopping space specific functionality. - attention: An instance is created by the **DataStore** class, do not create an instance by yourself. - important: The class should be accessed only by the public attribute *userStore* of the **DataStore** shared instance. Please check the **DataStore** for more information. # Initializer - dataStore: The **DataStore* instance */ class ShoppingStore { // MARK: - Public Attributes var localData: LocalData! var shoppingSpace: ShoppingSpace! { get { return self.localData.current } set { self.localData.current = newValue } } var CurrentContext: ShoppingContext? { get { return self.currentContext } set { self.currentContext = newValue if let context = self.currentContext { UserDefaults.standard.set(context.name, forKey: Constants.CurrentContext) self.userStore.setUserPreference(lastContextId: context.id ?? "") } } } var CurrentShoppingList: ShoppingList? { get { return self.currentShoppingList } set { self.currentShoppingList = newValue if let shoppingList = self.currentShoppingList { UserDefaults.standard.set(shoppingList.name, forKey: Constants.CurrentShoppingList) } } } // MARK: - Private Attributes private var dataStore: DataStore! private var userStore: UserStore! private var currentShoppingList: ShoppingList? private var currentContext: ShoppingContext? // MARK: - Initializer init(dataStore: DataStore) { self.dataStore = dataStore } func setUserStore(store: UserStore) { self.userStore = store } // MARK: - Public Functions / Shoppingspace-User-Management func initializeShoppingSpaceAfterLogout() { print("initialize shopping space after logout") if self.shoppingSpace != nil { // Move to archive self.moveCurrentShoppingSpaceToArchive() // try to get the archived shoppingspace without a registered user if self.shoppingSpace == nil { self.shoppingSpace = self.getShoppingSpaceFromArchive(withUserId: Constants.UserNotSet) } // if finally no shoppingspace is found, create a new one if self.shoppingSpace == nil { self.createNewShoppingSpace(initialContextName: Constants.InitialContextName, user: nil) } } } func InitializeShoppingSpace(forUser user: User, completion: @escaping (_ success: Bool, _ error: Error?) -> Void) { print("initialize shopping space for current user <\(String(describing: user))>") guard let archive = self.localData.archive else { fatalError("Archive in local data not set.") } // Check is user is member in current (local) shoppingSpace (not new) if self.shoppingSpaceHasUser(withId: user.id!) { print("found user <\(user.firstName! + " " + user.lastName!)> in local shoppingSpace. Cool.") } else { // Move to archive self.moveCurrentShoppingSpaceToArchive() } // Check for shopping space in local archive if self.shoppingSpace == nil { let usersShoppingSpace = self.getShoppingSpaceFromArchive(withUserId: user.id!) if usersShoppingSpace != nil { // Check for shoppingSpace in archive. If found: Move to local archive.removeFromShoppingSpaces(usersShoppingSpace!) self.localData.current = usersShoppingSpace } } // Check for shopping space in external database if self.shoppingSpace == nil { // Get shoppingSpace ids from DB (Open: if more than one, show selection list) self.getShoppingSpaceIdsFromDb(forUser: user) { shoppingSpaceIds, error in print("found shopping space ids: \(shoppingSpaceIds)") if shoppingSpaceIds.count == 0 { // No shoppingSpace in DB available, create new one (empty, no sample data) self.createNewShoppingSpace(initialContextName: Constants.InitialContextName, user: user) self.addShoppingSpaceToDbUser(for: user, with: self.shoppingSpace) // sync newly created shoppingSpace with db self.syncShoppingSpaceWithDb() self.dataStore.saveContextWithoutSync() { success, error in if success { // we just created the shopping space and synced it to the external database, no need to sync it immediately (db -> local) completion(true, nil) } else { completion(false, error) } } } else { if let dbConnector = self.dataStore.dbConnector { dbConnector.getShoppingSpace(withId: shoppingSpaceIds.first!.key) { space, error in if error != nil { print("failed to get shopping space from db. Error: <\(String(describing: error))>") completion(false, error) } else { self.shoppingSpace = space self.dataStore.saveContextWithoutSync() { success, error in if success { // we just got the shopping space from the external database, no need to sync it immediately (db -> local) completion(true, nil) } else { completion(false, error) } } } } } else { // this cannot happen, dbConnector was already accessed print("lost dbConnector - should not happen") } } } } else { // Shopping space available, negotiate sync with external database self.dataStore.saveContextWithoutSync() { success, error in if success { self.dataStore.negotiateSyncWithExternalDb() completion(true, nil) } else { completion(false, error) } } } } func createNewShoppingSpace(initialContextName: String, user: User?) { print("create new shopping space") if let _ = self.localData.current { fatalError("Current shopping space must not be set if a new one is created!") } let shoppingSpace = ShoppingSpace(name: Constants.InitialShoppingSpaceName, context: self.dataStore.stack.context) if let user = user { shoppingSpace.addToUsers(user) } else { let standardUser = User(firstName: Constants.StandardUserFirstname, lastName: Constants.StandardUserLastname, context: self.dataStore.stack.context) standardUser.email = Constants.StandardUserEmail standardUser.id = Constants.UserNotSet shoppingSpace.addToUsers(standardUser) } let initialContext = ShoppingContext(name: initialContextName, context: self.dataStore.stack.context) shoppingSpace.addToShoppingContexts(initialContext) shoppingSpace.addToCategories(self.createCategories()) shoppingSpace.addToUnits(self.createUnits()) self.localData.current = shoppingSpace } func addShoppingSpaceToDbUser(for user: User, with shoppingSpace: ShoppingSpace) { print("add shopping space to db-user") guard let dbConnector = self.dataStore.dbConnector else { fatalError("Cannot add shopping space to db user without a db connection, dbConnector not set.") } dbConnector.addShoppingSpaceToDbUser(for: user, with: shoppingSpace) { success, error in if success { user.addToShoppingSpaces(shoppingSpace) } else { print("could not add shopping space <\(shoppingSpace.name!)> to user <\(user.firstName! + " " + user.lastName!)>") } } } func addNewUserToShoppingspace(user: User) { print("add new user to shopping space") guard let shoppingSpace = self.shoppingSpace else { fatalError("Cannnot add new user to shopping space, shopping space is not set.") } if let users = shoppingSpace.users { let u = users.allObjects.first as! User if u.id == Constants.UserNotSet { self.dataStore.stack.context.delete(u) } } shoppingSpace.addToUsers(user) self.dataStore.saveContext() { success, error in // completion parameters not used self.addShoppingSpaceToDbUser(for: user, with: shoppingSpace) } } func getShoppingSpaceFromArchive(withUserId userid: String) -> ShoppingSpace? { print("get shopping space from archive") if let spaces = self.localData.archive!.shoppingSpaces { for space in spaces.allObjects as! [ShoppingSpace] { if let users = space.users { for user in users.allObjects as! [User] { if user.id! == userid { print("....found shopping space with id \(String(describing: space.id))") return space } } } } } print("....no shopping space found in archive.") return nil } func moveCurrentShoppingSpaceToArchive() { print("move current shopping space to archive") self.localData.archive!.addToShoppingSpaces(self.shoppingSpace) self.localData.current = nil } func isShoppingSpaceNew(space: ShoppingSpace) -> Bool { print("check: is shopping space new?") if let users = space.users { let allUsers = users.allObjects as! [User] let currentUser = allUsers.first(where: { $0.id == Constants.UserNotSet }) return currentUser != nil && allUsers.count == 1 } return false } func shoppingSpaceHasUser(withId id: String) -> Bool { print("check if user with id: <\(id)> is registered in current shopping space") guard self.shoppingSpace?.users != nil else { print("....no, user is not registered.") return false } let allUsers = self.shoppingSpace.users!.allObjects as! [User] let currentUser = allUsers.first(where: { $0.id == id }) return currentUser != nil } func getShoppingSpaceIdsFromDb(forUser user: User, completion: @escaping (_ spaces: [String : Bool], _ error: Error?) -> Void) { print("get shopping space ids from db for user <\(user)>") guard let dbConnector = self.dataStore.dbConnector else { fatalError("cannot get shopping space ids, dbConnector is not set.") } dbConnector.getAllShoppingSpaces(forUser: user, completion: completion) } // MARK: - Public Functions / Sync Shoppingspace with Database func syncShoppingSpaceWithDb() { print("sync shopping space with db.") guard let dbConnector = self.dataStore.dbConnector else { print("Cannot sync to external db, dbConnector not set. Skipping sync.") return } // check if user is logged in let loggedIn = UserDefaults.standard.bool(forKey: Constants.IsLoggedIn) // sync shopping space only if a user is registered let allUsers = self.shoppingSpace.users!.allObjects as! [User] let standardUserRegistered = allUsers.count == 1 && allUsers.first(where: { $0.email == Constants.StandardUserEmail }) != nil if loggedIn { if !standardUserRegistered { if let shoppingSpaceId = self.shoppingSpace.id { dbConnector.syncToExternalDb(withId: shoppingSpaceId) if let currentUser = self.userStore.CurrentUser { self.userStore.updateDbUser(user: currentUser) } } else { print("current shopping space id is not available. Sync is not executed.") } } else { print("standard user is still registered in shopping space, skipping sync to external DB.") } } else { print("user is not logged in, skipping sync to external DB.") } } // MARK: - Public Functions / Initialize Shoppingspace on First Use func initializeShoppingContextOnFirstUse() { print("initialize shopping context for first use") // ==== called by AppDelegate on first use of app ==== // data self.localData = LocalData(context: self.dataStore.stack.context) self.localData.archive = DataArchive(context: self.dataStore.stack.context) // shopping context let initialContext = ShoppingContext(name: Constants.InitialContextName, context: self.dataStore.stack.context) let vacationContext = ShoppingContext(name: "On Vacation", context: self.dataStore.stack.context) // local user let user = User(firstName: Constants.StandardUserFirstname, lastName: Constants.StandardUserLastname, context: self.dataStore.stack.context) user.email = Constants.StandardUserEmail user.id = Constants.UserNotSet // user preferences let userPreferences = UserPreferences(showGroups: Constants.InitialUserPreferenceShoppingListShowGroups, showDone: Constants.InitialUserPreferenceShoppingListShowDone, sortAscending: Constants.InitialUserPreferenceShoppingListSortAscending, lastShoppingContext: Constants.InitialUserPreferenceShoppingContextIdLastSelected, context: self.dataStore.stack.context) user.userPreferences = userPreferences // shopping space let shoppingSpace = ShoppingSpace(name: Constants.InitialShoppingSpaceName, context: self.dataStore.stack.context) shoppingSpace.addToUsers(user) shoppingSpace.addToShoppingContexts(initialContext) shoppingSpace.addToShoppingContexts(vacationContext) // add to local data self.localData.current = shoppingSpace // shopping list let shoppingList = ShoppingList(name: "Sample List", context: self.dataStore.stack.context) initialContext.addToShoppingLists(shoppingList) let shoppingList2 = ShoppingList(name: "Second Sample List", context: self.dataStore.stack.context) initialContext.addToShoppingLists(shoppingList2) let shoppingList3 = ShoppingList(name: "Third List", context: self.dataStore.stack.context) vacationContext.addToShoppingLists(shoppingList3) // categories let noCategory = Category(name: "No Category", context: self.dataStore.stack.context) //standard Category for a new item let grocery = Category(name: "Grocery", context: self.dataStore.stack.context) let homeImprovement = Category(name: "Home Improvement", context: self.dataStore.stack.context) let kidsCategory = Category(name: "Kids", context: self.dataStore.stack.context) let gadgets = Category(name: "Gadgets", context: self.dataStore.stack.context) let itStuff = Category(name: "IT stuff", context: self.dataStore.stack.context) let setOfCategories = NSSet(array: [noCategory, grocery, homeImprovement, kidsCategory, gadgets, itStuff]) // units let unitItems = Unit(name: "Item", shortcut: "", context: self.dataStore.stack.context) let unitBottles = Unit(name: "Bottle", shortcut: "btl", context: self.dataStore.stack.context) let unitBags = Unit(name: "Bag", shortcut: "bag", context: self.dataStore.stack.context) let unitLiter = Unit(name: "Liter", shortcut: "ltr", context: self.dataStore.stack.context) let setOfUnits = NSSet(array: [unitItems, unitBottles, unitBags, unitLiter]) shoppingSpace.addToCategories(setOfCategories) shoppingSpace.addToUnits(setOfUnits) // == Sample List == // items let banana = Item(name: "Banana", amount: 8, category: grocery, unit: unitItems, context: self.dataStore.stack.context) let apple = Item(name: "Apple", amount: 6, category: grocery, unit: unitItems, context: self.dataStore.stack.context) let gripper = Item(name: "Gripper", amount: 1, category: homeImprovement, unit: unitItems, context: self.dataStore.stack.context) let redApple = Item(name: "Red Apple", amount: 2, category: grocery, unit: unitBags, context: self.dataStore.stack.context) let iPadCase = Item(name: "iPad Protection Case", amount: 1, category: itStuff, unit: unitItems, context: self.dataStore.stack.context) let wine = Item(name: "Red Wine", amount: 2, category: noCategory, unit: unitBottles, context: self.dataStore.stack.context) let beer = Item(name: "Beer", amount: 40, category: noCategory, unit: unitLiter, context: self.dataStore.stack.context) apple.done = true shoppingList.addToItems(banana) shoppingList.addToItems(apple) shoppingList.addToItems(gripper) shoppingList.addToItems(redApple) shoppingList.addToItems(iPadCase) shoppingList.addToItems(wine) shoppingList.addToItems(beer) // master items let bananaMaster = MasterItem(name: "Banana", context: self.dataStore.stack.context) bananaMaster.item = banana let appleMaster = MasterItem(name: "Apple", context: self.dataStore.stack.context) appleMaster.item = apple let gripperMaster = MasterItem(name: "Gripper", context: self.dataStore.stack.context) gripperMaster.item = gripper let redAppleMaster = MasterItem(name: "Red Apple", context: self.dataStore.stack.context) redAppleMaster.item = redApple let iPadCaseMaster = MasterItem(name: "iPad Protection Case", context: self.dataStore.stack.context) iPadCaseMaster.item = iPadCase let wineMaster = MasterItem(name: "Red Wine", context: self.dataStore.stack.context) wineMaster.item = wine let beerMaster = MasterItem(name: "Beer", context: self.dataStore.stack.context) beerMaster.item = beer // == Second Sample List == // items let bear = Item(name: "Teddy Bear", amount: 1, category: kidsCategory, unit: unitItems, context: self.dataStore.stack.context) shoppingList2.addToItems(bear) // master items let bearMaster = MasterItem(name: "Teddy Bear", context: self.dataStore.stack.context) bearMaster.item = bear let setOfMasterItems = NSSet(array: [bananaMaster, appleMaster, gripperMaster, redAppleMaster, iPadCaseMaster, wineMaster, beerMaster, bearMaster]) shoppingSpace.addToMasterItems(setOfMasterItems) self.dataStore.saveContext() { (success, error) in // completion parameters not used } } // MARK: - Public Functions / Add & Create Entities func addItem(name: String) -> Item { print ("add item") var masterItem = self.getMasterItem(withName: name) // every item has a master item: Create master item first if (masterItem == nil) { masterItem = MasterItem(name: name, context: self.dataStore.stack.context) } return self.addItem(item: masterItem!) } func addShoppingList(name: String, shoppingContext: ShoppingContext) -> ShoppingList { print ("add shopping list <\(name)> in shopping context <\(shoppingContext)>") let newShoppingList = ShoppingList(name: name, shoppingContext: shoppingContext, context: self.dataStore.stack.context) return newShoppingList } func addContext(name: String) -> ShoppingContext { print ("add shopping context <\(name)>") let newContext = ShoppingContext(name: name, context: self.dataStore.stack.context) self.shoppingSpace.addToShoppingContexts(newContext) return newContext } func addCategory(name: String) -> Category { print ("add category <\(name)>") let newCategory = Category(name: name, context: self.dataStore.stack.context) self.shoppingSpace.addToCategories(newCategory) return newCategory } func getCategory(withName name: String) -> Category? { print ("get category <\(name)>") if let categories = self.shoppingSpace.categories { let categoryObjects = categories.allObjects as! [Category] return categoryObjects.first(where: { $0.name == name }) } else { return nil } } func getUnit(withName name: String) -> Unit? { print ("get unit <\(name)>") if let units = self.shoppingSpace.units { let unitObjects = units.allObjects as! [Unit] return unitObjects.first(where: { $0.name == name }) } else { return nil } } func addUnit(name: String, shortcut: String) -> Unit { print ("add unit <\(name)>") let newUnit = Unit(name: name, shortcut: shortcut, context: self.dataStore.stack.context) self.shoppingSpace.addToUnits(newUnit) return newUnit } // MARK: - Private Functions / Add & Create Items private func createNewItem(name: String, list: ShoppingList?) -> Item { print ("create new item <\(name)> in shopping list <\(String(describing: list))>") let newItem = Item(name: name, amount: 1, context: self.dataStore.stack.context) newItem.shoppingList = self.currentShoppingList //no link (nil) is set, in case no shoppinglist is selected return newItem } private func addItem(item: MasterItem) -> Item { print ("add item base on master item <\(item)>") // list is set if (self.currentShoppingList != nil) { // check if item already in list let itemInList = self.getItem(name: item.name!, list: self.currentShoppingList!) // item found if (itemInList != nil) { return itemInList! } else { // create new item let newItem = self.createNewItem(name: item.name!, list: self.currentShoppingList) newItem.category = self.getCategoryNone() newItem.unit = self.getUnitNone() return newItem } } // no list (will be selected tand linked later by user) else { let newItem = self.createNewItem(name: item.name!, list: nil) newItem.category = self.getCategoryNone() newItem.unit = self.getUnitNone() return newItem } } private func getMasterItem(withName name: String) -> MasterItem? { print ("get master item <\(name)>") if let masterItems = self.shoppingSpace.masterItems { let masterItemObjects = masterItems.allObjects as! [MasterItem] return masterItemObjects.first(where: { $0.name == name }) } else { return nil } } private func getItem(name: String, list: ShoppingList) -> Item? { print ("get item <\(name)> in shopping list <\(list)>") if let items = list.items { let allitemsInShoppingList = items.allObjects as! [Item] return allitemsInShoppingList.first(where: { $0.name == name }) } else { return nil } } // MARK: - Private Functions / Get Initial Categorie & Unit private func getCategoryNone() -> Category? { return self.getCategory(withName: "No Category") } private func getUnitNone() -> Unit? { return self.getUnit(withName: "Item") } // MARK: - Private Functions / Create Standard Categories & Units private func createCategories() -> NSSet { print ("create standard categories") let noCategory = Category(name: "No Category", context: self.dataStore.stack.context) //standard Category for a new item let grocery = Category(name: "Grocery", context: self.dataStore.stack.context) let homeImprovement = Category(name: "Home Improvement", context: self.dataStore.stack.context) let kidsCategory = Category(name: "Kids", context: self.dataStore.stack.context) let gadgets = Category(name: "Gadgets", context: self.dataStore.stack.context) let itStuff = Category(name: "IT stuff", context: self.dataStore.stack.context) return NSSet(array: [noCategory, grocery, homeImprovement, kidsCategory, gadgets, itStuff]) } private func createUnits() -> NSSet { print ("create standard units") let unitItems = Unit(name: "Item", shortcut: "", context: self.dataStore.stack.context) let unitBottles = Unit(name: "Bottle", shortcut: "btl", context: self.dataStore.stack.context) let unitBags = Unit(name: "Bag", shortcut: "bag", context: self.dataStore.stack.context) let unitLiter = Unit(name: "Liter", shortcut: "ltr", context: self.dataStore.stack.context) return NSSet(array: [unitItems, unitBottles, unitBags, unitLiter]) } }
mit
44be637462b1bffa039a2dd12c180135
37.142292
370
0.561105
5.211521
false
false
false
false
tardieu/swift
benchmark/single-source/ObjectAllocation.swift
10
2580
//===--- ObjectAllocation.swift -------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // This test checks the performance of allocations. import TestsUtils final class XX { var xx: Int init(_ x: Int) { xx = x } } final class TreeNode { let left: XX let right: XX init(_ l: XX, _ r: XX) { left = l right = r } } final class LinkedNode { var next: LinkedNode? var xx: Int init(_ x: Int, _ n: LinkedNode?) { xx = x next = n } } @inline(never) func getInt(_ x: XX) -> Int { return x.xx } @inline(never) func testSingleObject() -> Int { var s = 0 for i in 0..<1000 { let x = XX(i) s += getInt(x) } return s } @inline(never) func addInts(_ t: TreeNode) -> Int { return t.left.xx + t.right.xx } @inline(never) func testTree() -> Int { var s = 0 for i in 0..<300 { let t = TreeNode(XX(i), XX(i + 1)) s += addInts(t) } return s } @inline(never) func addAllInts(_ n: LinkedNode) -> Int { var s = 0 var iter: LinkedNode? = n while let iter2 = iter { s += iter2.xx iter = iter2.next } return s } @inline(never) func testList() -> Int { var s = 0 for i in 0..<250 { let l = LinkedNode(i, LinkedNode(27, LinkedNode(42, nil))) s += addAllInts(l) } return s } @inline(never) func identity(_ x: Int) -> Int { return x } @inline(never) func testArray() -> Int { var s = 0 for _ in 0..<1000 { for i in [0, 1, 2] { s += identity(i) } } return s } @inline(never) public func run_ObjectAllocation(_ N: Int) { var SingleObjectResult = 0 var TreeResult = 0 var ListResult = 0 var ArrayResult = 0 for _ in 0..<N { SingleObjectResult = testSingleObject() TreeResult = testTree() ListResult = testList() ArrayResult = testArray() } CheckResults(SingleObjectResult == 499500, "Incorrect results in testSingleObject") CheckResults(TreeResult == 90000, "Incorrect results in testTree") CheckResults(ListResult == 48375, "Incorrect results in testList") CheckResults(ArrayResult == 3000, "Incorrect results in testArray") }
apache-2.0
283186a09a81f077c44c001c75fcf40f
18.111111
80
0.57907
3.534247
false
true
false
false
lotpb/iosSQLswift
mySQLswift/Blog.swift
1
35220
// // Blog.swift // mySQLswift // // Created by Peter Balsamo on 12/8/15. // Copyright © 2015 Peter Balsamo. All rights reserved. // import UIKit //import Firebase import Parse import Social class Blog: UIViewController, UITableViewDelegate, UITableViewDataSource { let searchScope = ["subject", "date", "rating", "postby"] @IBOutlet weak var tableView: UITableView? var _feedItems : NSMutableArray = NSMutableArray() var _feedheadItems : NSMutableArray = NSMutableArray() var filteredString : NSMutableArray = NSMutableArray() /* var messages = [Message]() var messagesDictionary = [String: Message]() var users = [User]() var usersDictionary = [String: User]() */ var buttonView: UIView? var likeButton: UIButton? var refreshControl: UIRefreshControl! let searchController = UISearchController(searchResultsController: nil) var isReplyClicked = true var posttoIndex: NSString? var userIndex: NSString? var titleLabel = String() override func viewDidLoad() { super.viewDidLoad() let titleLabel = UILabel(frame: CGRectMake(0, 0, 100, view.frame.height)) titleLabel.text = "myBlog" titleLabel.textColor = UIColor.whiteColor() titleLabel.font = Font.navlabel titleLabel.textAlignment = NSTextAlignment.Center navigationItem.titleView = titleLabel self.tableView!.delegate = self self.tableView!.dataSource = self self.tableView!.estimatedRowHeight = 110 self.tableView!.rowHeight = UITableViewAutomaticDimension self.tableView!.backgroundColor = UIColor(white:0.90, alpha:1.0) // get rid of black bar underneath navbar UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: .Default) let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action:#selector(Blog.newButton)) let searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action:#selector(Blog.searchButton)) let buttons:NSArray = [addButton,searchButton] self.navigationItem.rightBarButtonItems = buttons as? [UIBarButtonItem] /* if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } */ /* FIRAuth.auth()?.signInWithEmail("[email protected]", password: "united", completion: { (user, error) in if error != nil { print(error) return } self.observeMessages() //self.observeUser() //self.checkIfUserIsLoggedIn() }) */ parseData() self.refreshControl = UIRefreshControl() self.refreshControl.backgroundColor = Color.Blog.navColor self.refreshControl.tintColor = UIColor.whiteColor() let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh", attributes: attributes) //self.refreshControl.attributedTitle = NSAttributedString(string: "Last updated on \(NSDate())", attributes: attributes) self.refreshControl.addTarget(self, action: #selector(Blog.refreshData), forControlEvents: UIControlEvents.ValueChanged) self.tableView!.addSubview(refreshControl) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad { self.navigationController?.navigationBar.barTintColor = UIColor.blackColor() } else { self.navigationController?.navigationBar.barTintColor = Color.Blog.navColor } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) refreshData(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - refresh func refreshData(sender:AnyObject) { parseData() self.refreshControl?.endRefreshing() } // MARK: - Table View func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.active { return filteredString.count } else { return _feedItems.count ?? 0 //return messages.count } } func handleCancel() { dismissViewControllerAnimated(true, completion: nil) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomTableCell! /* cell.selectionStyle = UITableViewCellSelectionStyle.None if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad { cell.blogtitleLabel!.font = Font.Blog.celltitle cell.blogsubtitleLabel!.font = Font.Blog.cellsubtitle cell.blogmsgDateLabel.font = Font.Blog.celldate cell.numLabel.font = Font.Blog.cellLabel cell.commentLabel.font = Font.Blog.cellLabel } else { cell.blogtitleLabel!.font = Font.Blog.celltitle cell.blogsubtitleLabel!.font = Font.Blog.cellsubtitle cell.blogmsgDateLabel.font = Font.Blog.celldate cell.numLabel.font = Font.Blog.cellLabel cell.commentLabel.font = Font.Blog.cellLabel } if cell == nil { cell = CustomTableCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") } let message = messages[indexPath.row] //let user = users[0] /* if let profileImageUrl = user.profileImageUrl { cell.blogImageView?.loadImageUsingCacheWithUrlString(profileImageUrl) } */ cell.blogImageView?.layer.cornerRadius = (cell.blogImageView?.frame.size.width)! / 2 cell.blogImageView?.layer.borderColor = UIColor.lightGrayColor().CGColor cell.blogImageView?.layer.borderWidth = 0.5 cell.blogImageView?.layer.masksToBounds = true cell.blogImageView?.userInteractionEnabled = true cell.blogImageView?.contentMode = .ScaleAspectFill cell.blogImageView?.tag = indexPath.row let tap = UITapGestureRecognizer(target: self, action:#selector(Blog.imgLoadSegue)) cell.blogImageView.addGestureRecognizer(tap) cell.blogtitleLabel.text = message.PostBy cell.blogsubtitleLabel!.text = message.Subject let dateStr = message.MsgDate let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let date:NSDate = dateFormatter.dateFromString(dateStr!)as NSDate! dateFormatter.dateFormat = "MMM-dd" cell.blogmsgDateLabel.text = dateFormatter.stringFromDate(date)as String! var Liked:Int? = message.Liked as? Int if Liked == nil { Liked = 0 } cell.numLabel?.text = "\(Liked!)" var CommentCount:Int? = message.CommentCount as? Int if CommentCount == nil { CommentCount = 0 } cell.commentLabel?.text = "\(CommentCount!)" cell.replyButton.tintColor = UIColor.lightGrayColor() let replyimage : UIImage? = UIImage(named:"Commentfilled.png")!.imageWithRenderingMode(.AlwaysTemplate) cell.replyButton .setImage(replyimage, forState: .Normal) cell.replyButton .addTarget(self, action: #selector(Blog.replyButton), forControlEvents: UIControlEvents.TouchUpInside) cell.likeButton.tintColor = UIColor.lightGrayColor() let likeimage : UIImage? = UIImage(named:"Thumb Up.png")!.imageWithRenderingMode(.AlwaysTemplate) cell.likeButton .setImage(likeimage, forState: .Normal) cell.likeButton .addTarget(self, action: #selector(Blog.likeButton), forControlEvents: UIControlEvents.TouchUpInside) cell.flagButton.tintColor = UIColor.lightGrayColor() let reportimage : UIImage? = UIImage(named:"Flag.png")!.imageWithRenderingMode(.AlwaysTemplate) cell.flagButton .setImage(reportimage, forState: .Normal) cell.flagButton .addTarget(self, action: #selector(Blog.flagButton), forControlEvents: UIControlEvents.TouchUpInside) cell.actionBtn.tintColor = UIColor.lightGrayColor() let actionimage : UIImage? = UIImage(named:"nav_more_icon.png")!.imageWithRenderingMode(.AlwaysTemplate) cell.actionBtn .setImage(actionimage, forState: .Normal) cell.actionBtn .addTarget(self, action: #selector(Blog.showShare), forControlEvents: UIControlEvents.TouchUpInside) if !(cell.numLabel.text! == "0") { cell.numLabel.textColor = Color.Blog.buttonColor } else { cell.numLabel.text! = "" } if !(cell.commentLabel.text! == "0") { cell.commentLabel.textColor = UIColor.lightGrayColor() } else { cell.commentLabel.text! = "" } if (cell.commentLabel.text! == "") { cell.replyButton.tintColor = UIColor.lightGrayColor() } else { cell.replyButton.tintColor = Color.Blog.buttonColor } */ cell.selectionStyle = UITableViewCellSelectionStyle.None if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad { cell.blogtitleLabel!.font = Font.Blog.celltitle cell.blogsubtitleLabel!.font = Font.Blog.cellsubtitle cell.blogmsgDateLabel.font = Font.Blog.celldate cell.numLabel.font = Font.Blog.cellLabel cell.commentLabel.font = Font.Blog.cellLabel } else { cell.blogtitleLabel!.font = Font.Blog.celltitle cell.blogsubtitleLabel!.font = Font.Blog.cellsubtitle cell.blogmsgDateLabel.font = Font.Blog.celldate cell.numLabel.font = Font.Blog.cellLabel cell.commentLabel.font = Font.Blog.cellLabel } let query:PFQuery = PFUser.query()! query.whereKey("username", equalTo:self._feedItems[indexPath.row] .valueForKey("PostBy") as! String) query.cachePolicy = PFCachePolicy.CacheThenNetwork query.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in if error == nil { if let imageFile = object!.objectForKey("imageFile") as? PFFile { imageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in cell.blogImageView?.image = UIImage(data: imageData!) } } } } cell.blogImageView?.layer.cornerRadius = (cell.blogImageView?.frame.size.width)! / 2 cell.blogImageView?.layer.borderColor = UIColor.lightGrayColor().CGColor cell.blogImageView?.layer.borderWidth = 0.5 cell.blogImageView?.layer.masksToBounds = true cell.blogImageView?.userInteractionEnabled = true cell.blogImageView?.contentMode = .ScaleAspectFill cell.blogImageView?.tag = indexPath.row let tap = UITapGestureRecognizer(target: self, action:#selector(Blog.imgLoadSegue)) cell.blogImageView.addGestureRecognizer(tap) let dateStr = _feedItems[indexPath.row] .valueForKey("MsgDate") as? String let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let date:NSDate = dateFormatter.dateFromString(dateStr!)as NSDate! dateFormatter.dateFormat = "MMM-dd" if searchController.active { cell.blogtitleLabel?.text = filteredString[indexPath.row] .valueForKey("PostBy") as? String cell.blogsubtitleLabel?.text = filteredString[indexPath.row] .valueForKey("Subject") as? String cell.blogmsgDateLabel?.text = filteredString[indexPath.row] .valueForKey("MsgDate") as? String cell.numLabel?.text = filteredString[indexPath.row] .valueForKey("Liked") as? String cell.commentLabel?.text = filteredString[indexPath.row] .valueForKey("CommentCount") as? String } else { cell.blogtitleLabel?.text = _feedItems[indexPath.row] .valueForKey("PostBy") as? String cell.blogsubtitleLabel?.text = _feedItems[indexPath.row] .valueForKey("Subject") as? String cell.blogmsgDateLabel?.text = dateFormatter.stringFromDate(date)as String! var Liked:Int? = _feedItems[indexPath.row] .valueForKey("Liked")as? Int if Liked == nil { Liked = 0 } cell.numLabel?.text = "\(Liked!)" var CommentCount:Int? = _feedItems[indexPath.row] .valueForKey("CommentCount")as? Int if CommentCount == nil { CommentCount = 0 } cell.commentLabel?.text = "\(CommentCount!)" } cell.replyButton.tintColor = UIColor.lightGrayColor() let replyimage : UIImage? = UIImage(named:"Commentfilled.png")!.imageWithRenderingMode(.AlwaysTemplate) cell.replyButton .setImage(replyimage, forState: .Normal) cell.replyButton .addTarget(self, action: #selector(Blog.replyButton), forControlEvents: UIControlEvents.TouchUpInside) cell.likeButton.tintColor = UIColor.lightGrayColor() let likeimage : UIImage? = UIImage(named:"Thumb Up.png")!.imageWithRenderingMode(.AlwaysTemplate) cell.likeButton .setImage(likeimage, forState: .Normal) cell.likeButton .addTarget(self, action: #selector(Blog.likeButton), forControlEvents: UIControlEvents.TouchUpInside) cell.flagButton.tintColor = UIColor.lightGrayColor() let reportimage : UIImage? = UIImage(named:"Flag.png")!.imageWithRenderingMode(.AlwaysTemplate) cell.flagButton .setImage(reportimage, forState: .Normal) cell.flagButton .addTarget(self, action: #selector(Blog.flagButton), forControlEvents: UIControlEvents.TouchUpInside) cell.actionBtn.tintColor = UIColor.lightGrayColor() let actionimage : UIImage? = UIImage(named:"nav_more_icon.png")!.imageWithRenderingMode(.AlwaysTemplate) cell.actionBtn .setImage(actionimage, forState: .Normal) cell.actionBtn .addTarget(self, action: #selector(Blog.showShare), forControlEvents: UIControlEvents.TouchUpInside) if !(cell.numLabel.text! == "0") { cell.numLabel.textColor = Color.Blog.buttonColor } else { cell.numLabel.text! = "" } if !(cell.commentLabel.text! == "0") { cell.commentLabel.textColor = UIColor.lightGrayColor() } else { cell.commentLabel.text! = "" } if (cell.commentLabel.text! == "") { cell.replyButton.tintColor = UIColor.lightGrayColor() } else { cell.replyButton.tintColor = Color.Blog.buttonColor } return cell } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone { return 90.0 } else { return 0.0 } } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let vw = UIView() vw.backgroundColor = Color.Blog.navColor //tableView.tableHeaderView = vw let myLabel1:UILabel = UILabel(frame: CGRectMake(10, 15, 50, 50)) myLabel1.numberOfLines = 0 myLabel1.backgroundColor = UIColor.whiteColor() myLabel1.textColor = UIColor.blackColor() myLabel1.textAlignment = NSTextAlignment.Center myLabel1.layer.masksToBounds = true myLabel1.text = String(format: "%@%d", "Blog\n", _feedItems.count) myLabel1.font = Font.headtitle myLabel1.layer.cornerRadius = 25.0 myLabel1.layer.borderColor = Color.Blog.borderbtnColor myLabel1.layer.borderWidth = 1 myLabel1.userInteractionEnabled = true vw.addSubview(myLabel1) let separatorLineView1 = UIView(frame: CGRectMake(10, 75, 50, 2.5)) separatorLineView1.backgroundColor = UIColor.whiteColor() vw.addSubview(separatorLineView1) let myLabel2:UILabel = UILabel(frame: CGRectMake(80, 15, 50, 50)) myLabel2.numberOfLines = 0 myLabel2.backgroundColor = UIColor.whiteColor() myLabel2.textColor = UIColor.blackColor() myLabel2.textAlignment = NSTextAlignment.Center myLabel2.layer.masksToBounds = true myLabel2.text = String(format: "%@%d", "Likes\n", _feedheadItems.count) myLabel2.font = Font.headtitle myLabel2.layer.cornerRadius = 25.0 myLabel2.layer.borderColor = Color.Blog.borderbtnColor myLabel2.layer.borderWidth = 1 myLabel2.userInteractionEnabled = true vw.addSubview(myLabel2) let separatorLineView2 = UIView(frame: CGRectMake(80, 75, 50, 2.5)) separatorLineView2.backgroundColor = UIColor.whiteColor() vw.addSubview(separatorLineView2) let myLabel3:UILabel = UILabel(frame: CGRectMake(150, 15, 50, 50)) myLabel3.numberOfLines = 0 myLabel3.backgroundColor = UIColor.whiteColor() myLabel3.textColor = UIColor.blackColor() myLabel3.textAlignment = NSTextAlignment.Center myLabel3.layer.masksToBounds = true myLabel3.text = String(format: "%@%d", "Events\n", 3) myLabel3.font = Font.headtitle myLabel3.layer.cornerRadius = 25.0 myLabel3.layer.borderColor = Color.Blog.borderbtnColor myLabel3.layer.borderWidth = 1 myLabel3.userInteractionEnabled = true vw.addSubview(myLabel3) let separatorLineView3 = UIView(frame: CGRectMake(150, 75, 50, 2.5)) separatorLineView3.backgroundColor = UIColor.whiteColor() vw.addSubview(separatorLineView3) return vw } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let query = PFQuery(className:"Blog") query.whereKey("objectId", equalTo:(self._feedItems.objectAtIndex(indexPath.row) .valueForKey("objectId") as? String)!) let alertController = UIAlertController(title: "Delete", message: "Confirm Delete", preferredStyle: .Alert) let destroyAction = UIAlertAction(title: "Delete!", style: .Destructive) { (action) in query.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error: NSError?) -> Void in if error == nil { for object in objects! { object.deleteInBackground() self.refreshData(self) } } }) } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in self.refreshData(self) } alertController.addAction(cancelAction) alertController.addAction(destroyAction) self.presentViewController(alertController, animated: true) { } _feedItems.removeObjectAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } // MARK: - Button func newButton(sender: AnyObject) { isReplyClicked = false self.performSegueWithIdentifier("blognewSegue", sender: self) } func likeButton(sender:UIButton) { likeButton?.selected = true sender.tintColor = UIColor.redColor() let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView) let indexPath = self.tableView!.indexPathForRowAtPoint(hitPoint) let query = PFQuery(className:"Blog") query.whereKey("objectId", equalTo:(_feedItems.objectAtIndex((indexPath?.row)!) .valueForKey("objectId") as? String)!) query.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in if error == nil { object!.incrementKey("Liked") object!.saveInBackground() } } } func replyButton(sender:UIButton) { isReplyClicked = true let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView) let indexPath = self.tableView!.indexPathForRowAtPoint(hitPoint) posttoIndex = _feedItems.objectAtIndex((indexPath?.row)!) .valueForKey("PostBy") as? String userIndex = _feedItems.objectAtIndex((indexPath?.row)!) .valueForKey("objectId") as? String self.performSegueWithIdentifier("blognewSegue", sender: self) } func flagButton(sender:UIButton) { } // MARK: - Firebase //----------------------------------------- /* func observeUser() { let ref = FIRDatabase.database().reference().child("Users") ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in //print(snapshot.value) if let dictionary = snapshot.value as? [String: AnyObject] { let user = User() user.setValuesForKeysWithDictionary(dictionary) self.users.append(user) print(self.users) //this will crash because of background thread, so lets call this on dispatch_async main thread dispatch_async(dispatch_get_main_queue(), { self.tableView!.reloadData() }) } }, withCancelBlock: nil) } func observeMessages() { let ref = FIRDatabase.database().reference().child("Blog") ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in //print(snapshot.value) if let dictionary = snapshot.value as? [String: AnyObject] { let message = Message() message.setValuesForKeysWithDictionary(dictionary) self.messages.append(message) if let toId = message.objectId { self.messagesDictionary[toId] = message self.messages = Array(self.messagesDictionary.values) self.messages.sortInPlace({ (message1, message2) -> Bool in return message1.MsgDate > message2.MsgDate }) } //this will crash because of background thread, so lets call this on dispatch_async main thread dispatch_async(dispatch_get_main_queue(), { self.tableView!.reloadData() }) } }, withCancelBlock: nil) } func checkIfUserIsLoggedIn() { if FIRAuth.auth()?.currentUser?.uid == nil { print("Crap") //performSelector(#selector(handleLogout), withObject: nil, afterDelay: 0) } else { fetchUserAndSetupNavBarTitle() } } func fetchUserAndSetupNavBarTitle() { guard let uid = FIRAuth.auth()?.currentUser?.uid else { //for some reason uid = nil return } FIRDatabase.database().reference().child("users").child(uid).observeSingleEventOfType(.Value, withBlock: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { // self.navigationItem.title = dictionary["name"] as? String let user = User() user.setValuesForKeysWithDictionary(dictionary) //self.setupNavBarWithUser(user) } }, withCancelBlock: nil) } */ //----------------------------------------- // MARK: - Search func searchButton(sender: AnyObject) { //UIApplication.sharedApplication().statusBarHidden = true searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.searchBar.showsBookmarkButton = false searchController.searchBar.showsCancelButton = true searchController.searchBar.placeholder = "Search here..." searchController.searchBar.sizeToFit() searchController.searchBar.searchBarStyle = UISearchBarStyle.Prominent definesPresentationContext = true searchController.dimsBackgroundDuringPresentation = true searchController.hidesNavigationBarDuringPresentation = true searchController.searchBar.scopeButtonTitles = searchScope searchController.searchBar.barTintColor = Color.Blog.navColor tableView!.tableFooterView = UIView(frame: .zero) self.presentViewController(searchController, animated: true, completion: nil) } func filterContentForSearchText(searchText: String, scope: String = "All") { } // MARK: - Parse func parseData() { let query = PFQuery(className:"Blog") query.limit = 1000 query.whereKey("ReplyId", equalTo:NSNull()) query.cachePolicy = PFCachePolicy.CacheThenNetwork query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in if error == nil { let temp: NSArray = objects! as NSArray self._feedItems = temp.mutableCopy() as! NSMutableArray self.tableView!.reloadData() } else { print("Error") } } let query1 = PFQuery(className:"Blog") query1.limit = 1000 query1.whereKey("Rating", equalTo:"5") query1.cachePolicy = PFCachePolicy.CacheThenNetwork query1.orderByDescending("createdAt") query1.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in if error == nil { let temp: NSArray = objects! as NSArray self._feedheadItems = temp.mutableCopy() as! NSMutableArray self.tableView!.reloadData() } else { print("Error") } } } // MARK: - AlertController func showShare(sender:UIButton) { let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView) let indexPath = self.tableView!.indexPathForRowAtPoint(hitPoint) let socialText = self._feedItems[indexPath!.row] .valueForKey("Subject") as? String let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let tweetAction = UIAlertAction(title: "Share on Twitter", style: UIAlertActionStyle.Default) { (action) -> Void in if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) { let twitterComposeVC = SLComposeViewController(forServiceType: SLServiceTypeTwitter) if socialText!.characters.count <= 140 { twitterComposeVC.setInitialText(socialText) } else { let index = socialText!.startIndex.advancedBy(140) let subText = socialText!.substringToIndex(index) twitterComposeVC.setInitialText("\(subText)") } self.presentViewController(twitterComposeVC, animated: true, completion: nil) } else { self.showAlertMessage("You are not logged in to your Twitter account.") } } let facebookPostAction = UIAlertAction(title: "Share on Facebook", style: UIAlertActionStyle.Default) { (action) -> Void in if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) { let facebookComposeVC = SLComposeViewController(forServiceType: SLServiceTypeFacebook) //facebookComposeVC.setInitialText(socialText) //facebookComposeVC.addImage(detailImageView.image!) facebookComposeVC.addURL(NSURL(string: "http://lotpb.github.io/UnitedWebPage/index.html")) self.presentViewController(facebookComposeVC, animated: true, completion: nil) } else { self.showAlertMessage("You are not connected to your Facebook account.") } } let moreAction = UIAlertAction(title: "More", style: UIAlertActionStyle.Default) { (action) -> Void in let activityViewController = UIActivityViewController(activityItems: [socialText!], applicationActivities: nil) //activityViewController.excludedActivityTypes = [UIActivityTypeMail] self.presentViewController(activityViewController, animated: true, completion: nil) } let follow = UIAlertAction(title: "Follow", style: .Default) { (alert: UIAlertAction!) -> Void in NSLog("You pressed button one") } let block = UIAlertAction(title: "Block this Message", style: .Default) { (alert: UIAlertAction!) -> Void in NSLog("You pressed button two") } let report = UIAlertAction(title: "Report this User", style: .Destructive) { (alert: UIAlertAction!) -> Void in NSLog("You pressed button one") } let dismissAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel) { (action) -> Void in } actionSheet.addAction(follow) actionSheet.addAction(block) actionSheet.addAction(report) actionSheet.addAction(tweetAction) actionSheet.addAction(facebookPostAction) actionSheet.addAction(moreAction) actionSheet.addAction(dismissAction) self.presentViewController(actionSheet, animated: true, completion: nil) } func showAlertMessage(message: String!) { let alertController = UIAlertController(title: "EasyShare", message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } // MARK: - imgLoadSegue func imgLoadSegue(sender:UITapGestureRecognizer) { titleLabel = (_feedItems.objectAtIndex((sender.view!.tag)) .valueForKey("PostBy") as? String)! self.performSegueWithIdentifier("bloguserSegue", sender: self) } // MARK: - Segues func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("blogeditSegue", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "blogeditSegue" { let VC = segue.destinationViewController as? BlogEditController let myIndexPath = self.tableView!.indexPathForSelectedRow!.row VC!.objectId = _feedItems[myIndexPath] .valueForKey("objectId") as? String VC!.msgNo = _feedItems[myIndexPath] .valueForKey("MsgNo") as? String VC!.postby = _feedItems[myIndexPath] .valueForKey("PostBy") as? String VC!.subject = _feedItems[myIndexPath] .valueForKey("Subject") as? String VC!.msgDate = _feedItems[myIndexPath] .valueForKey("MsgDate") as? String VC!.rating = _feedItems[myIndexPath] .valueForKey("Rating") as? String VC!.liked = _feedItems[myIndexPath] .valueForKey("Liked") as? Int VC!.replyId = _feedItems[myIndexPath] .valueForKey("ReplyId") as? String } if segue.identifier == "blognewSegue" { let VC = segue.destinationViewController as? BlogNewController if isReplyClicked == true { VC!.formStatus = "Reply" VC!.textcontentsubject = String(format:"@%@", posttoIndex!) VC!.textcontentpostby = PFUser.currentUser()!.valueForKey("username") as! String VC!.replyId = String(format:"%@", userIndex!) } else { VC!.formStatus = "New" VC!.textcontentpostby = PFUser.currentUser()!.username } } if segue.identifier == "bloguserSegue" { let controller = segue.destinationViewController as? LeadUserController controller!.formController = "Blog" controller!.postBy = titleLabel } } } // MARK: - UISearchBar Delegate extension Blog: UISearchBarDelegate { func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope]) } } extension Blog: UISearchResultsUpdating { func updateSearchResultsForSearchController(searchController: UISearchController) { let searchBar = searchController.searchBar let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex] filterContentForSearchText(searchController.searchBar.text!, scope: scope) } }
gpl-2.0
dbbb19916907bb9bb3417b73b458dca8
42.69603
148
0.620432
5.256567
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/SimpleBuy/CashIdentityVerificationRouter.swift
1
871
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import PlatformUIKit import RxRelay import RxSwift import UIComponentsKit final class CashIdentityVerificationRouter { private weak var topMostViewControllerProvider: TopMostViewControllerProviding! private let kycRouter: KYCRouterAPI init( topMostViewControllerProvider: TopMostViewControllerProviding = resolve(), kycRouter: KYCRouterAPI = resolve() ) { self.kycRouter = kycRouter self.topMostViewControllerProvider = topMostViewControllerProvider } func dismiss(startKYC: Bool = false) { let kycRouter = kycRouter topMostViewControllerProvider.topMostViewController?.dismiss(animated: true, completion: { guard startKYC else { return } kycRouter.start(parentFlow: .cash) }) } }
lgpl-3.0
7cac0e67192cd930ca8b227b390de900
29
98
0.724138
5.878378
false
false
false
false
toshiapp/toshi-ios-client
Toshi/Views/CellSectionData/TableViewData.swift
1
6419
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation public final class TableSectionData { var tag: Int = 0 var headerTitle = "" var footerTitle = "" var cellsData: [TableCellData] init(cellsData: [TableCellData] = [], headerTitle: String = "", footerTitle: String = "") { self.cellsData = cellsData self.headerTitle = headerTitle self.footerTitle = footerTitle } } public struct TableCellDataComponents: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } static let title = TableCellDataComponents(rawValue: 1 << 0) static let subtitle = TableCellDataComponents(rawValue: 1 << 1) static let details = TableCellDataComponents(rawValue: 1 << 2) static let leftImage = TableCellDataComponents(rawValue: 1 << 3) static let switchControl = TableCellDataComponents(rawValue: 1 << 4) static let doubleImage = TableCellDataComponents(rawValue: 1 << 5) static let doubleAction = TableCellDataComponents(rawValue: 1 << 6) static let badge = TableCellDataComponents(rawValue: 1 << 7) static let checkbox = TableCellDataComponents(rawValue: 1 << 8) static let topDetails = TableCellDataComponents(rawValue: 1 << 9) static let description = TableCellDataComponents(rawValue: 1 << 10) static let titleSubtitle: TableCellDataComponents = [.title, .subtitle] static let titleLeftImage: TableCellDataComponents = [.title, .leftImage] static let titleSubtitleLeftImage: TableCellDataComponents = [.titleSubtitle, .leftImage] static let titleSubtitleLeftImageCheckbox: TableCellDataComponents = [.titleSubtitleLeftImage, .checkbox] static let titleSubtitleDetailsLeftImage: TableCellDataComponents = [.titleSubtitle, .details, .leftImage] static let titleSwitchControl: TableCellDataComponents = [.title, .switchControl] static let titleDetailsLeftImage: TableCellDataComponents = [.title, .details, .leftImage] static let titleSubtitleSwitchControl: TableCellDataComponents = [.titleSwitchControl, .subtitle] static let titleSubtitleSwitchControlLeftImage: TableCellDataComponents = [.titleLeftImage, .subtitle, .switchControl] static let titleSubtitleDoubleImage: TableCellDataComponents = [.titleSubtitle, .doubleImage] static let titleSubtitleDoubleImageImage: TableCellDataComponents = [.titleSubtitle, .doubleImage] static let leftImageTitleSubtitleDoubleAction: TableCellDataComponents = [.titleSubtitleLeftImage, .doubleAction] static let titleSubtitleDetailsLeftImageBadge: TableCellDataComponents = [.titleSubtitleDetailsLeftImage, .badge] static let titleSubtitleLeftImageTopDetails: TableCellDataComponents = [.titleSubtitleLeftImage, .topDetails] static let titleLeftImageDescription: TableCellDataComponents = [.titleLeftImage, .description] static let titleSubtitleLeftImageDescription: TableCellDataComponents = [.titleSubtitleLeftImage, .description] } public final class TableCellData { var tag: Int? var title: String? var subtitle: String? var description: String? var leftImage: UIImage? var leftImagePath: String? var details: String? var switchState: Bool? var doubleImage: (firstImage: UIImage, secondImage: UIImage)? var doubleActionImages: (firstImage: UIImage, secondImage: UIImage)? var badgeText: String? var topDetails: String? var showCheckmark: Bool var isPlaceholder = false private(set) var components: TableCellDataComponents = [] init(title: String? = nil, isPlaceholder: Bool = false, subtitle: String? = nil, leftImage: UIImage? = nil, leftImagePath: String? = nil, details: String? = nil, topDetails: String? = nil, showCheckmark: Bool = false, switchState: Bool? = nil, doubleImage: (firstImage: UIImage, secondImage: UIImage)? = nil, doubleActionImages: (firstImage: UIImage, secondImage: UIImage)? = nil, badgeText: String? = nil, description: String? = nil) { self.title = title self.subtitle = subtitle self.leftImage = leftImage self.leftImagePath = leftImagePath self.details = details self.topDetails = topDetails self.showCheckmark = showCheckmark self.switchState = switchState self.isPlaceholder = isPlaceholder self.doubleImage = doubleImage self.doubleActionImages = doubleActionImages self.badgeText = badgeText self.description = description setupComponents() } //swiftlint:disable cyclomatic_complexity - This is basically the entire point of having this configure things. private func setupComponents() { if title != nil { components.insert(.title) } if subtitle != nil { components.insert(.subtitle) } if leftImage != nil || leftImagePath != nil { components.insert(.leftImage) } if details != nil { components.insert(.details) } if topDetails != nil { components.insert(.topDetails) } if switchState != nil { components.insert(.switchControl) } if doubleImage != nil { components.insert(.doubleImage) } if doubleActionImages != nil { components.insert(.doubleAction) } if badgeText != nil { components.insert(.badge) } if showCheckmark { components.insert(.checkbox) } if description != nil { components.insert(.description) } } // swiftlint:enable cyclomatic_complexity }
gpl-3.0
cb748eaa438f5ff19f123c2e259a890c
36.319767
122
0.69045
4.80824
false
false
false
false
dvl/imagefy-ios
imagefy/Classes/Extensions/Consts.swift
1
541
// // Consts.swift // imagefy // // Created by Alan Magalhães Lira on 21/05/16. // Copyright © 2016 Alan M. Lira. All rights reserved. // import Foundation let myAppDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let kPrimaryColor = UIColor(rgba: "#2196F3") let kDarkPrimaryColor = UIColor(rgba: "#1976D2") let kLightPrimaryColor = UIColor(rgba: "##BBDEFB") let kAccentColor = UIColor(rgba: "#FF5252") let kSecondaryTextColor = UIColor(rgba: "#727272") let kDividerColor = UIColor(rgba: "#B6B6B6")
mit
9a1142565b1fb946ca4af0326bb4c7cf
29
91
0.736549
3.306748
false
false
false
false
shaps80/Peek
Pod/Classes/Model/UIView+Filter.swift
1
2189
// // UIView+Ignore.swift // Peek // // Created by Shaps Benkau on 26/03/2018. // import UIKit extension UIView { /** Determines if Peek should ignore this view when parsing it into a model - parameter peek: The Peek instance - returns: Returns true if Peek should ignore this view, false otherwise */ internal override func isVisibleInOverlay(options: PeekOptions) -> Bool { let isContainer = isMember(of: UIView.self) && subviews.count > 0 if isContainer && options.ignoresContainerViews { return false } let isInvisible = isHidden || alpha == 0 || frame.equalTo(CGRect.zero) if isInvisible { return false } let isTableViewOrCell = isMember(of: UITableViewCell.self) || isMember(of: UITableView.self) if isTableViewOrCell { return false } let isCollectionView = isMember(of: UICollectionView.self) if isCollectionView { return false } let isFullScreen = frame.equalTo(window?.bounds ?? UIScreen.main.bounds) if isFullScreen { return false } if String(describing: classForCoder).hasPrefix("_UIModern") { return true } let blacklist = [ "UIPickerTableView", "UIPickerColumnView", "UITableViewCellContentView" ] let className = String(describing: classForCoder) if className.hasPrefix("_") || blacklist.contains(className) { return false } let invalidContainerClassNames = [ "UINavigationButton" ] var superview = self.superview while superview != nil { if superview?.isComponent == true { return false } // also need to check private internal classes for className in invalidContainerClassNames { if let klass = NSClassFromString(className) { if superview?.isMember(of: klass) ?? false { return false } } } superview = superview?.superview } return true } }
mit
c7c8e2f0bbf39d1595bd98339d67c5a0
31.671642
100
0.578803
5.339024
false
false
false
false
danielsaidi/iExtra
iExtra/UI/Extensions/UIView/UIView+Distance.swift
1
867
// // UIView+Distance.swift // Appamini // // Created by Daniel Saidi on 2016-03-14. // Copyright © 2018 Daniel Saidi. All rights reserved. // import UIKit public extension UIView { func closestView(in views: [UIView]) -> UIView? { var distance = CGFloat(Int.max) var closest: UIView? for view in views { let viewDistance = self.distance(to: view) if viewDistance < distance && view != self { distance = viewDistance closest = view } } return closest } func distance(to view: UIView) -> CGFloat { guard let viewCenter = superview?.convert(view.center, from: view.superview) else { return -1 } let dx = center.x - viewCenter.x let dy = center.y - viewCenter.y return sqrt(dx * dx + dy * dy) } }
mit
3f46dd0762eff5f63dd8b0df00cae8ec
26.0625
103
0.568129
4.104265
false
false
false
false
sky15179/swift-learn
data-Base-exercises/Pods/Dollar/Sources/Dollar.swift
2
61746
// // ___ ___ __ ___ ________ _________ // _|\ \__|\ \ |\ \|\ \|\ _____\\___ ___\ // |\ ____\ \ \ \ \ \ \ \ \ \__/\|___ \ \_| // \ \ \___|\ \ \ __\ \ \ \ \ \ __\ \ \ \ // \ \_____ \ \ \|\__\_\ \ \ \ \ \_| \ \ \ // \|____|\ \ \____________\ \__\ \__\ \ \__\ // ____\_\ \|____________|\|__|\|__| \|__| // |\___ __\ // \|___|\__\_| // \|__| // // Dollar.swift // $ - A functional tool-belt for Swift Language // // Created by Ankur Patel on 6/3/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // #if os(Linux) import Glibc #endif import Foundation fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } open class $ { /// ___ ___ _______ ___ ________ _______ ________ /// |\ \|\ \|\ ___ \ |\ \ |\ __ \|\ ___ \ |\ __ \ /// \ \ \\\ \ \ __/|\ \ \ \ \ \|\ \ \ __/|\ \ \|\ \ /// \ \ __ \ \ \_|/_\ \ \ \ \ ____\ \ \_|/_\ \ _ _\ /// \ \ \ \ \ \ \_|\ \ \ \____\ \ \___|\ \ \_|\ \ \ \\ \| /// \ \__\ \__\ \_______\ \_______\ \__\ \ \_______\ \__\\ _\ /// \|__|\|__|\|_______|\|_______|\|__| \|_______|\|__|\|__| /// /// Creates a function that executes passed function only after being called n times. /// /// - parameter num: Number of times after which to call function. /// - parameter function: Function to be called that takes params. /// - returns: Function that can be called n times after which the callback function is called. open class func after<T, E>(_ num: Int, function: @escaping (T...) -> E) -> ((T...) -> E?) { var counter = num return { (params: T...) -> E? in typealias Function = ([T]) -> E counter -= 1 if counter <= 0 { let f = unsafeBitCast(function, to: Function.self) return f(params) } return .none } } /// Creates a function that executes passed function only after being called n times. /// /// - parameter num: Number of times after which to call function. /// - parameter function: Function to be called that does not take any params. /// - returns: Function that can be called n times after which the callback function is called. open class func after<T>(_ num: Int, function: @escaping () -> T) -> (() -> T?) { let f = self.after(num) { (params: Any?...) -> T in return function() } return { f() } } /// Creates an array of elements from the specified indexes, or keys, of the collection. /// Indexes may be specified as individual arguments or as arrays of indexes. /// /// - parameter array: The array to source from /// - parameter indexes: Get elements from these indexes /// - returns: New array with elements from the indexes specified. open class func at<T>(_ array: [T], indexes: Int...) -> [T] { return self.at(array, indexes: indexes) } /// Creates an array of elements from the specified indexes, or keys, of the collection. /// Indexes may be specified as individual arguments or as arrays of indexes. /// /// - parameter array: The array to source from /// - parameter indexes: Get elements from these indexes /// - returns: New array with elements from the indexes specified. open class func at<T>(_ array: [T], indexes: [Int]) -> [T] { var result: [T] = [] for index in indexes { result.append(array[index]) } return result } /// Creates a function that, when called, invokes func with the binding of arguments provided. /// /// - parameter function: Function to be bound. /// - parameter parameters: Parameters to be passed into the function when being invoked. /// - returns: A new function that when called will invoked the passed function with the parameters specified. open class func bind<T, E>(_ function: @escaping (T...) -> E, _ parameters: T...) -> (() -> E) { return { () -> E in typealias Function = ([T]) -> E let f = unsafeBitCast(function, to: Function.self) return f(parameters) } } /// Creates an array of elements split into groups the length of size. /// If array can’t be split evenly, the final chunk will be the remaining elements. /// /// - parameter array: to chunk /// - parameter size: size of each chunk /// - returns: array elements chunked open class func chunk<T>(_ array: [T], size: Int = 1) -> [[T]] { var result = [[T]]() var chunk = -1 for (index, elem) in array.enumerated() { if index % size == 0 { result.append([T]()) chunk += 1 } result[chunk].append(elem) } return result } /// Creates an array with all nil values removed. /// /// - parameter array: Array to be compacted. /// - returns: A new array that doesnt have any nil values. open class func compact<T>(_ array: [T?]) -> [T] { var result: [T] = [] for elem in array { if let val = elem { result.append(val) } } return result } /// Compose two or more functions passing result of the first function /// into the next function until all the functions have been evaluated /// /// - parameter functions: - list of functions /// - returns: A function that can be called with variadic parameters of values open class func compose<T>(_ functions: ((T...) -> [T])...) -> ((T...) -> [T]) { typealias Function = ([T]) -> [T] return { var result = $0 for fun in functions { let f = unsafeBitCast(fun, to: Function.self) result = f(result) } return result } } /// Compose two or more functions passing result of the first function /// into the next function until all the functions have been evaluated /// /// - parameter functions: - list of functions /// - returns: A function that can be called with array of values open class func compose<T>(_ functions: (([T]) -> [T])...) -> (([T]) -> [T]) { return { var result = $0 for fun in functions { result = fun(result) } return result } } /// Checks if a given value is present in the array. /// /// - parameter array: The array to check against. /// - parameter value: The value to check. /// - returns: Whether value is in the array. open class func contains<T: Equatable>(_ array: [T], value: T) -> Bool { return array.contains(value) } /// Create a copy of an array /// /// - parameter array: The array to copy /// - returns: New copy of array open class func copy<T>(_ array: [T]) -> [T] { var newArr: [T] = [] for elem in array { newArr.append(elem) } return newArr } /// Cycles through the array indefinetly passing each element into the callback function /// /// - parameter array: to cycle through /// - parameter callback: function to call with the element open class func cycle<T, U>(_ array: [T], callback: (T) -> U) { while true { for elem in array { _ = callback(elem) } } } /// Cycles through the array n times passing each element into the callback function /// /// - parameter array: to cycle through /// - parameter times: Number of times to cycle through the array /// - parameter callback: function to call with the element open class func cycle<T, U>(_ array: [T], _ times: Int, callback: (T) -> U) { for _ in 0..<times { for elem in array { _ = callback(elem) } } } /// Delays the execution of a function by the specified DispatchTimeInterval /// /// - parameter by: interval to delay the execution of the function by /// - parameter queue: Queue to run the function on. Defaults to main queue /// - parameter function: function to execute open class func delay(by interval: DispatchTimeInterval, queue: DispatchQueue = .main, _ function: @escaping () -> Void) { queue.asyncAfter(deadline: .now() + interval, execute: function) } /// Debounce a function such that the function is only invoked once no matter how many times /// it is called within the delayBy interval /// /// - parameter delayBy: interval to delay the execution of the function by /// - parameter queue: Queue to run the function on. Defaults to main queue /// - parameter function: function to execute /// - returns: Function that is debounced and will only invoke once within the delayBy interval open class func debounce(delayBy: DispatchTimeInterval, queue: DispatchQueue = .main, _ function: @escaping (() -> Void)) -> () -> Void { var currentWorkItem: DispatchWorkItem? return { currentWorkItem?.cancel() currentWorkItem = DispatchWorkItem { function() } queue.asyncAfter(deadline: .now() + delayBy, execute: currentWorkItem!) } } /// Creates an array excluding all values of the provided arrays in order /// /// - parameter arrays: The arrays to difference between. /// - returns: The difference between the first array and all the remaining arrays from the arrays params. open class func differenceInOrder<T: Equatable>(_ arrays: [[T]]) -> [T] { return $.reduce(self.rest(arrays), initial: self.first(arrays)!) { (result, arr) -> [T] in return result.filter() { !arr.contains($0) } } } /// Creates an array excluding all values of the provided arrays with or without order /// Without order difference is much faster and at times 100% than difference with order /// /// - parameter arrays: The arrays to difference between. /// - parameter inOrder: Optional Paramter which is true by default /// - returns: The difference between the first array and all the remaining arrays from the arrays params. open class func difference<T: Hashable>(_ arrays: [T]..., inOrder: Bool = true) -> [T] { if inOrder { return self.differenceInOrder(arrays) } else { var result: [T] = [] var map: [T: Int] = [T: Int]() let firstArr: [T] = self.first(arrays)! let restArr: [[T]] = self.rest(arrays) as [[T]] for elem in firstArr { if let val = map[elem] { map[elem] = val + 1 } else { map[elem] = 1 } } for arr in restArr { for elem in arr { map.removeValue(forKey: elem) } } for (key, count) in map { for _ in 0..<count { result.append(key) } } return result } } /// Call the callback passing each element in the array /// /// - parameter array: The array to iterate over /// - parameter callback: function that gets called with each item in the array /// - returns: The array passed @discardableResult open class func each<T>(_ array: [T], callback: (T) -> ()) -> [T] { for elem in array { callback(elem) } return array } /// Call the callback passing index of the element and each element in the array /// /// - parameter array: The array to iterate over /// - parameter callback: function that gets called with each item in the array with its index /// - returns: The array passed @discardableResult open class func each<T>(_ array: [T], callback: (Int, T) -> ()) -> [T] { for (index, elem): (Int, T) in array.enumerated() { callback(index, elem) } return array } /// Call the callback on all elements that meet the when condition /// /// - parameter array: The array to check. /// - parameter when: Condition to check before performing callback /// - parameter callback: Check whether element value is true or false. /// - returns: The array passed @discardableResult open class func each<T>(_ array: [T], when: (T) -> Bool, callback: (T) -> ()) -> [T] { for elem in array where when(elem) { callback(elem) } return array } /// Checks if two optionals containing Equatable types are equal. /// /// - parameter value: The first optional to check. /// - parameter other: The second optional to check. /// - returns: true if the optionals contain two equal values, or both are nil; false otherwise. open class func equal<T: Equatable>(_ value: T?, _ other: T?) -> Bool { switch (value, other) { case (.none, .none): return true case (.none, .some(_)): return false case (.some(_), .none): return false case (.some(let unwrappedValue), .some(let otherUnwrappedValue)): return unwrappedValue == otherUnwrappedValue } } /// Checks if the given callback returns true value for all items in the array. /// /// - parameter array: The array to check. /// - parameter callback: Check whether element value is true or false. /// - returns: true if the given callback returns true value for all items in the array; false otherwise. open class func every<T>(_ array: [T], callback: (T) -> Bool) -> Bool { for elem in array { if !callback(elem) { return false } } return true } /// Returns Factorial of integer /// /// - parameter num: number whose factorial needs to be calculated /// - returns: factorial open class func factorial(_ num: Int) -> Int { guard num > 0 else { return 1 } return num * $.factorial(num - 1) } /// Get element from an array at the given index which can be negative /// to find elements from the end of the array /// /// - parameter array: The array to fetch from /// - parameter index: Can be positive or negative to find from end of the array /// - parameter orElse: Default value to use if index is out of bounds /// - returns: Element fetched from the array or the default value passed in orElse open class func fetch<T>(_ array: [T], _ index: Int, orElse: T? = .none) -> T! { if index < 0 && -index < array.count { return array[array.count + index] } else if index < array.count { return array[index] } else { return orElse } } /// Fills elements of array with value from start up to, but not including, end. /// /// - parameter array: to fill /// - parameter withElem: the element to replace /// - parameter startIndex: start index /// - parameter endIndex: end index /// - returns: array elements chunked open class func fill<T>(_ array: inout [T], withElem elem: T, startIndex: Int = 0, endIndex: Int? = .none) -> [T] { let endIndex = endIndex ?? array.count for (index, _) in array.enumerated() { if index > endIndex { break } if index >= startIndex && index <= endIndex { array[index] = elem } } return array } /// Iterates over elements of an array and returning the first element /// that the callback returns true for. /// /// - parameter array: The array to search for the element in. /// - parameter callback: The callback function to tell whether element is found. /// - returns: Optional containing either found element or nil. open class func find<T>(_ array: [T], callback: (T) -> Bool) -> T? { for elem in array { let result = callback(elem) if result { return elem } } return .none } /// This method is like find except that it returns the index of the first element /// that passes the callback check. /// /// - parameter array: The array to search for the element in. /// - parameter callback: Function used to figure out whether element is the same. /// - returns: First element's index from the array found using the callback. open class func findIndex<T>(_ array: [T], callback: (T) -> Bool) -> Int? { for (index, elem): (Int, T) in array.enumerated() { if callback(elem) { return index } } return .none } /// This method is like findIndex except that it iterates over elements of the array /// from right to left. /// /// - parameter array: The array to search for the element in. /// - parameter callback: Function used to figure out whether element is the same. /// - returns: Last element's index from the array found using the callback. open class func findLastIndex<T>(_ array: [T], callback: (T) -> Bool) -> Int? { let count = array.count for (index, _) in array.enumerated() { let reverseIndex = count - (index + 1) let elem: T = array[reverseIndex] if callback(elem) { return reverseIndex } } return .none } /// Gets the first element in the array. /// /// - parameter array: The array to wrap. /// - returns: First element from the array. open class func first<T>(_ array: [T]) -> T? { if array.isEmpty { return .none } else { return array[0] } } /// Splits a collection into sets, grouped by the result of running each value through a callback. /// /// - parameter array: The array to group /// - parameter callback: Function whose response will be used as a key in the new string /// - returns: grouped collection open class func groupBy<T, U: Hashable>(_ array: [T], callback: (T) -> U) -> [U: [T]] { var grouped = [U: [T]]() for element in array { let key = callback(element) if var arr = grouped[key] { arr.append(element) grouped[key] = arr } else { grouped[key] = [element] } } return grouped } /// Gets the second element in the array. /// /// - parameter array: The array to wrap. /// - returns: Second element from the array. open class func second<T>(_ array: [T]) -> T? { if array.count < 2 { return .none } else { return array[1] } } /// Gets the third element in the array. /// /// - parameter array: The array to wrap. /// - returns: Third element from the array. open class func third<T>(_ array: [T]) -> T? { if array.count < 3 { return .none } else { return array[2] } } /// Flattens a nested array of any depth. /// /// - parameter array: The array to flatten. /// - returns: Flattened array. open class func flatten<T>(_ array: [T]) -> [T] { var resultArr: [T] = [] for elem: T in array { if let val = elem as? [T] { resultArr += self.flatten(val) } else { resultArr.append(elem) } } return resultArr } /// Maps a function that converts elements to a list and then concatenates them. /// /// - parameter array: The array to map. /// - parameter function: callback function that should return flattened values /// - returns: The array with the transformed values concatenated together. open class func flatMap<T, U>(_ array: [T], function: (T) -> ([U])) -> [U] { return array.map(function).reduce([], +) } /// Maps a function that converts a type to an Optional over an Optional, and then returns a single-level Optional. /// /// - parameter value: The array to map. /// - parameter function: callback function that should return mapped values /// - returns: The array with the transformed values concatenated together. open class func flatMap<T, U>(_ value: T?, function: (T) -> (U?)) -> U? { if let unwrapped = value.map(function) { return unwrapped } else { return .none } } /// Returns size of the array /// /// - parameter array: The array to size. /// - returns: size of the array open class func size<T>(_ array: [T]) -> Int { return array.count } /// Randomly shuffles the elements of an array. /// /// - parameter array: The array to shuffle. /// - returns: Shuffled array open class func shuffle<T>(_ array: [T]) -> [T] { var newArr = self.copy(array) // Implementation of Fisher-Yates shuffle // http://en.wikipedia.org/wiki/Fisher-Yates_Shuffle for index in 0..<array.count { let randIndex = self.random(index) if index != randIndex { Swift.swap(&newArr[index], &newArr[randIndex]) } } return newArr } /// This method returns a dictionary of values in an array mapping to the /// total number of occurrences in the array. /// /// - parameter array: The array to source from. /// - returns: Dictionary that contains the key generated from the element passed in the function. open class func frequencies<T>(_ array: [T]) -> [T: Int] { return self.frequencies(array) { $0 } } /// This method returns a dictionary of values in an array mapping to the /// total number of occurrences in the array. If passed a function it returns /// a frequency table of the results of the given function on the arrays elements. /// /// - parameter array: The array to source from. /// - parameter function: The function to get value of the key for each element to group by. /// - returns: Dictionary that contains the key generated from the element passed in the function. open class func frequencies<T, U: Equatable>(_ array: [T], function: (T) -> U) -> [U: Int] { var result = [U: Int]() for elem in array { let key = function(elem) if let freq = result[key] { result[key] = freq + 1 } else { result[key] = 1 } } return result } /// GCD function return greatest common denominator /// /// - parameter first: number /// - parameter second: number /// - returns: Greatest common denominator open class func gcd(_ first: Int, _ second: Int) -> Int { var first = first var second = second while second != 0 { (first, second) = (second, first % second) } return Swift.abs(first) } /// LCM function return least common multiple /// /// - parameter first: number /// - parameter second: number /// - returns: Least common multiple open class func lcm(_ first: Int, _ second: Int) -> Int { return (first / $.gcd(first, second)) * second } /// The identity function. Returns the argument it is given. /// /// - parameter arg: Value to return /// - returns: Argument that was passed open class func id<T>(_ arg: T) -> T { return arg } /// Gets the index at which the first occurrence of value is found. /// /// - parameter array: The array to source from. /// - parameter value: Value whose index needs to be found. /// - returns: Index of the element otherwise returns nil if not found. open class func indexOf<T: Equatable>(_ array: [T], value: T) -> Int? { return self.findIndex(array) { $0 == value } } /// Gets all but the last element or last n elements of an array. /// /// - parameter array: The array to source from. /// - parameter numElements: The number of elements to ignore in the end. /// - returns: Array of initial values. open class func initial<T>(_ array: [T], numElements: Int = 1) -> [T] { var result: [T] = [] if array.count > numElements && numElements >= 0 { for index in 0..<(array.count - numElements) { result.append(array[index]) } } return result } /// Creates an array of unique values present in all provided arrays. /// /// - parameter arrays: The arrays to perform an intersection on. /// - returns: Intersection of all arrays passed. open class func intersection<T: Hashable>(_ arrays: [T]...) -> [T] { var map: [T: Int] = [T: Int]() for arr in arrays { for elem in arr { if let val: Int = map[elem] { map[elem] = val + 1 } else { map[elem] = 1 } } } var result: [T] = [] let count = arrays.count for (key, value) in map { if value == count { result.append(key) } } return result } /// Returns true if i is in range /// /// - parameter index: to check if it is in range /// - parameter isIn: to check in /// - returns: true if it is in range otherwise false open class func it<T: Comparable>(_ index: T, isIn range: Range<T>) -> Bool { return index >= range.lowerBound && index < range.upperBound } /// Joins the elements in the array to create a concatenated element of the same type. /// /// - parameter array: The array to join the elements of. /// - parameter separator: The separator to join the elements with. /// - returns: Joined element from the array of elements. open class func join(_ array: [String], separator: String) -> String { return array.joined(separator: separator) } /// Creates an array of keys given a dictionary. /// /// - parameter dictionary: The dictionary to source from. /// - returns: Array of keys from dictionary. open class func keys<T, U>(_ dictionary: [T: U]) -> [T] { var result: [T] = [] for key in dictionary.keys { result.append(key) } return result } /// Gets the last element from the array. /// /// - parameter array: The array to source from. /// - returns: Last element from the array. open class func last<T>(_ array: [T]) -> T? { if array.isEmpty { return .none } else { return array[array.count - 1] } } /// Gets the index at which the last occurrence of value is found. /// /// - parameter array: The array to source from. /// - parameter value: The value whose last index needs to be found. /// - returns: Last index of element if found otherwise returns nil. open class func lastIndexOf<T: Equatable>(_ array: [T], value: T) -> Int? { return self.findLastIndex(array) { $0 == value } } /// Maps each element to new value based on the map function passed /// /// - parameter collection: The collection to source from /// - parameter transform: The mapping function /// - returns: Array of elements mapped using the map function open class func map<T: Collection, E>(_ collection: T, transform: (T.Iterator.Element) -> E) -> [E] { return collection.map(transform) } /// Maps each element to new value based on the map function passed /// /// - parameter sequence: The sequence to source from /// - parameter transform: The mapping function /// - returns: Array of elements mapped using the map function open class func map<T: Sequence, E>(_ sequence: T, transform: (T.Iterator.Element) -> E) -> [E] { return sequence.map(transform) } /// Retrieves the maximum value in an array. /// /// - parameter array: The array to source from. /// - returns: Maximum element in array. open class func max<T: Comparable>(_ array: [T]) -> T? { if var maxVal = array.first { for elem in array { if maxVal < elem { maxVal = elem } } return maxVal } return .none } /// Get memoized function to improve performance /// /// - parameter function: The function to memoize. /// - returns: Memoized function open class func memoize<T: Hashable, U>(_ function: @escaping (((T) -> U), T) -> U) -> ((T) -> U) { var cache = [T: U]() var funcRef: ((T) -> U)! funcRef = { (param: T) -> U in if let cacheVal = cache[param] { return cacheVal } else { cache[param] = function(funcRef, param) return cache[param]! } } return funcRef } /// Merge dictionaries together, later dictionaries overiding earlier values of keys. /// /// - parameter dictionaries: The dictionaries to source from. /// - returns: Merged dictionary with all of its keys and values. open class func merge<T, U>(_ dictionaries: [T: U]...) -> [T: U] { var result = [T: U]() for dict in dictionaries { for (key, value) in dict { result[key] = value } } return result } /// Merge arrays together in the supplied order. /// /// - parameter arrays: The arrays to source from. /// - returns: Array with all values merged, including duplicates. open class func merge<T>(_ arrays: [T]...) -> [T] { var result = [T]() for arr in arrays { result += arr } return result } /// Retrieves the minimum value in an array. /// /// - parameter array: The array to source from. /// - returns: Minimum value from array. open class func min<T: Comparable>(_ array: [T]) -> T? { if var minVal = array.first { for elem in array { if minVal > elem { minVal = elem } } return minVal } return .none } /// A no-operation function. /// /// - returns: nil. open class func noop() -> () { } /// Gets the number of seconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC). /// /// - returns: number of seconds as double open class func now() -> TimeInterval { return Date().timeIntervalSince1970 } /// Creates a shallow clone of a dictionary excluding the specified keys. /// /// - parameter dictionary: The dictionary to source from. /// - parameter keys: The keys to omit from returning dictionary. /// - returns: Dictionary with the keys specified omitted. open class func omit<T, U>(_ dictionary: [T: U], keys: T...) -> [T: U] { var result: [T: U] = [T: U]() for (key, value) in dictionary { if !self.contains(keys, value: key) { result[key] = value } } return result } /// Get a wrapper function that executes the passed function only once /// /// - parameter function: That takes variadic arguments and return nil or some value /// - returns: Wrapper function that executes the passed function only once /// Consecutive calls will return the value returned when calling the function first time open class func once<T, U>(_ function: @escaping (T...) -> U) -> (T...) -> U { var result: U? let onceFunc = { (params: T...) -> U in typealias Function = ([T]) -> U if let returnVal = result { return returnVal } else { let f = unsafeBitCast(function, to: Function.self) result = f(params) return result! } } return onceFunc } /// Get a wrapper function that executes the passed function only once /// /// - parameter function: That takes variadic arguments and return nil or some value /// - returns: Wrapper function that executes the passed function only once /// Consecutive calls will return the value returned when calling the function first time open class func once<U>(_ function: @escaping () -> U) -> () -> U { var result: U? let onceFunc = { () -> U in if let returnVal = result { return returnVal } else { result = function() return result! } } return onceFunc } /// Creates a function that, when called, invokes func with any additional partial arguments prepended to those provided to the new function. /// /// - parameter function: to invoke /// - parameter parameters: to pass the function when invoked /// - returns: Function with partial arguments prepended open class func partial<T, E> (_ function: @escaping (T...) -> E, _ parameters: T...) -> ((T...) -> E) { return { (params: T...) -> E in typealias Function = ([T]) -> E let f = unsafeBitCast(function, to: Function.self) return f(parameters + params) } } /// Produces an array of arrays, each containing n elements, each offset by step. /// If the final partition is not n elements long it is dropped. /// /// - parameter array: The array to partition. /// - parameter n: The number of elements in each partition. /// - parameter step: The number of elements to progress between each partition. Set to n if not supplied. /// - returns: Array partitioned into n element arrays, starting step elements apart. open class func partition<T>(_ array: [T], n num: Int, step: Int? = .none) -> [[T]] { var num = num var step = step var result = [[T]]() if step == .none { step = num } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if num < 1 { num = 0 } // Allow 0 if user wants [[],[],[]] for some reason. if num > array.count { return [[]] } for i in self.range(from: 0, through: array.count - num, incrementBy: step!) { result.append(Array(array[i..<(i + num)] as ArraySlice<T>)) } return result } /// Produces an array of arrays, each containing n elements, each offset by step. /// /// - parameter array: The array to partition. /// - parameter n: The number of elements in each partition. /// - parameter step: The number of elements to progress between each partition. Set to n if not supplied. /// - parameter pad: An array of elements to pad the last partition if it is not long enough to /// contain n elements. If there are not enough pad elements /// the last partition may less than n elements long. /// - returns: Array partitioned into n element arrays, starting step elements apart. open class func partition<T>(_ array: [T], n num: Int, step: Int? = .none, pad: [T]?) -> [[T]] { var array = array var num = num var step = step var result: [[T]] = [] var need = 0 if step == .none { step = num } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if num < 1 { num = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in self.range(from: 0, to: array.count, incrementBy: step!) { var end = i + num if end > array.count { end = array.count } result.append(Array(array[i..<end] as ArraySlice<T>)) if end != i + num { need = i + num - end; break } } if need != 0 { if let padding = pad { let end = padding.count > need ? need : padding.count result[result.count - 1] += Array(padding[0..<end] as ArraySlice<T>) } } return result } /// Produces an array of arrays, each containing n elements, each offset by step. /// /// - parameter array: The array to partition. /// - parameter n: The number of elements in each partition. /// - parameter step: The number of elements to progress between each partition. Set to n if not supplied. /// - returns: Array partitioned into n element arrays, starting step elements apart. open class func partitionAll<T>(_ array: [T], n num: Int, step: Int? = .none) -> [[T]] { var num = num var step = step var result = [[T]]() if step == .none { step = num } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if num < 1 { num = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in self.range(from: 0, to: array.count, incrementBy: step!) { var end = i + num if end > array.count { end = array.count } result.append(Array(array[i..<end] as ArraySlice<T>)) } return result } /// Applies function to each element in array, splitting it each time function returns a new value. /// /// - parameter array: The array to partition. /// - parameter function: Function which takes an element and produces an equatable result. /// - returns: Array partitioned in order, splitting via results of function. open class func partitionBy<T, U: Equatable>(_ array: [T], function: (T) -> U) -> [[T]] { var result = [[T]]() var lastValue: U? = .none for item in array { let value = function(item) if let lastValue = lastValue, value == lastValue { result[result.count-1].append(item) } else { result.append([item]) lastValue = value } } return result } /// Creates a shallow clone of a dictionary composed of the specified keys. /// /// - parameter dictionary: The dictionary to source from. /// - parameter keys: The keys to pick values from. /// - returns: Dictionary with the key and values picked from the keys specified. open class func pick<T, U>(_ dictionary: [T: U], keys: T...) -> [T: U] { var result: [T: U] = [T: U]() for key in keys { result[key] = dictionary[key] } return result } /// Retrieves the value of a specified property from all elements in the array. /// /// - parameter array: The array to source from. /// - parameter value: The property on object to pull out value from. /// - returns: Array of values from array of objects with property of value. open class func pluck<T, E>(_ array: [[T: E]], value: T) -> [E] { var result: [E] = [] for obj in array { if let val = obj[value] { result.append(val) } } return result } /// Removes all provided values from the given array. /// /// - parameter array: The array to source from. /// - parameter values: values to remove from the array /// - returns: Array with values pulled out. open class func pull<T: Equatable>(_ array: [T], values: T...) -> [T] { return self.pull(array, values: values) } /// Removes all provided values from the given array. /// /// - parameter array: The array to source from. /// - parameter values: The values to remove. /// - returns: Array with values pulled out. open class func pull<T: Equatable>(_ array: [T], values: [T]) -> [T] { return array.filter { !self.contains(values, value: $0) } } /// Removes all provided values from the given array at the given indices /// /// - parameter array: The array to source from. /// - parameter indices: The indices to remove from. /// - returns: Array with values pulled out. open class func pullAt<T: Equatable>(_ array: [T], indices: Int...) -> [T] { var elemToRemove = [T]() for index in indices { elemToRemove.append(array[index]) } return $.pull(array, values: elemToRemove) } /// Returns permutation of array /// /// - parameter character: Characters to source the permutation /// - returns: Array of permutation of the characters specified open class func permutation<T>(_ elements: [T]) -> [String] where T : CustomStringConvertible { guard elements.count > 1 else { return $.map(elements) { $0.description } } let strings = self.permutation($.initial(elements)) if let char = $.last(elements) { return $.reduce(strings, initial: []) { (result, str) -> [String] in let splitStr = $.map(str.description.characters) { $0.description } return result + $.map(0...splitStr.count) { (index) -> String in var copy = $.copy(splitStr) copy.insert(char.description, at: (splitStr.count - index)) return $.join(copy, separator: "") } }.sorted() } return [] } /// Returns random number from 0 upto but not including upperBound /// /// - parameter upperBound: upper bound when generating random number /// - returns: Random number open class func random(_ upperBound: Int) -> Int { #if os(Linux) let time = UInt32(NSDate().timeIntervalSinceReferenceDate) srand(time) let randomNumber = Glibc.random() % upperBound #else let randomNumber = Int(arc4random_uniform(UInt32(upperBound))) #endif return randomNumber } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// - parameter endVal: End value of range. /// - returns: Array of elements based on the sequence starting from 0 to endVal and incremented by 1. open class func range<T: Strideable>(_ endVal: T) -> [T] where T : ExpressibleByIntegerLiteral { return self.range(from: 0, to: endVal) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// - parameter from: Start value of range /// - parameter to: End value of range /// - returns: Array of elements based on the sequence that is incremented by 1 open class func range<T: Strideable>(from startVal: T, to endVal: T) -> [T] where T.Stride : ExpressibleByIntegerLiteral { return self.range(from: startVal, to: endVal, incrementBy: 1) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// - parameter from: Start value of range. /// - parameter to: End value of range. /// - parameter incrementBy: Increment sequence by. /// - returns: Array of elements based on the sequence. open class func range<T: Strideable>(from startVal: T, to endVal: T, incrementBy: T.Stride) -> [T] { let range = stride(from: startVal, to: endVal, by: incrementBy) return self.sequence(range) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// - parameter from: Start value of range /// - parameter through: End value of range /// - returns: Array of elements based on the sequence that is incremented by 1 open class func range<T: Strideable>(from startVal: T, through endVal: T) -> [T] where T.Stride : ExpressibleByIntegerLiteral { return self.range(from: startVal, to: endVal + 1, incrementBy: 1) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// - parameter from: Start value of range. /// - parameter through: End value of range. /// - parameter incrementBy: Increment sequence by. /// - returns: Array of elements based on the sequence. open class func range<T: Strideable>(from startVal: T, through endVal: T, incrementBy: T.Stride) -> [T] { return self.range(from: startVal, to: endVal + 1, incrementBy: incrementBy) } /// Reduce function that will resolve to one value after performing combine function on all elements /// /// - parameter array: The array to source from. /// - parameter initial: Initial value to seed the reduce function with /// - parameter combine: Function that will combine the passed value with element in the array /// - returns: The result of reducing all of the elements in the array into one value open class func reduce<U, T>(_ array: [T], initial: U, combine: (U, T) -> U) -> U { return array.reduce(initial, combine) } /// Creates an array of an arbitrary sequence. Especially useful with builtin ranges. /// /// - parameter seq: The sequence to generate from. /// - returns: Array of elements generated from the sequence. open class func sequence<S: Sequence>(_ seq: S) -> [S.Iterator.Element] { return Array<S.Iterator.Element>(seq) } /// Removes all elements from an array that the callback returns true. /// /// - parameter array: The array to wrap. /// - parameter callback: Remove elements for which callback returns true. /// - returns: Array with elements filtered out. open class func remove<T>(_ array: [T], callback: (T) -> Bool) -> [T] { return array.filter { !callback($0) } } /// Removes an element from an array. /// /// - parameter array: The array to source from. /// - parameter value: Element that is to be removed /// - returns: Array with element removed. open class func remove<T: Equatable>(_ array: [T], value: T) -> [T] { return self.remove(array, callback: {$0 == value}) } /// The opposite of initial this method gets all but the first element or first n elements of an array. /// /// - parameter array: The array to source from. /// - parameter numElements: The number of elements to exclude from the beginning. /// - returns: The rest of the elements. open class func rest<T>(_ array: [T], numElements: Int = 1) -> [T] { var result: [T] = [] if numElements < array.count && numElements >= 0 { for index in numElements..<array.count { result.append(array[index]) } } return result } /// Returns a sample from the array. /// /// - parameter array: The array to sample from. /// - returns: Random element from array. open class func sample<T>(_ array: [T]) -> T { return array[self.random(array.count)] } /// Slices the array based on the start and end position. If an end position is not specified it will slice till the end of the array. /// /// - parameter array: The array to slice. /// - parameter start: Start index. /// - parameter end: End index. /// - returns: First element from the array. open class func slice<T>(_ array: [T], start: Int, end: Int = 0) -> [T] { var uend = end if uend == 0 { uend = array.count } if end > array.count || start > array.count || uend < start { return [] } else { return Array(array[start..<uend]) } } /// Gives the smallest index at which a value should be inserted into a given the array is sorted. /// /// - parameter array: The array to source from. /// - parameter value: Find sorted index of this value. /// - returns: Index of where the elemnt should be inserted. open class func sortedIndex<T: Comparable>(_ array: [T], value: T) -> Int { for (index, elem) in array.enumerated() { if elem > value { return index } } return array.count } /// Invokes interceptor with the object and then returns object. /// /// - parameter object: Object to tap into. /// - parameter function: Callback function to invoke. /// - returns: Returns the object back. open class func tap<T>(_ object: T, function: (T) -> ()) -> T { function(object) return object } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// - parameter num: Number of times to call function. /// - parameter function: The function to be called every time. /// - returns: Values returned from callback function. open class func times<T>(_ num: Int, function: () -> T) -> [T] { return self.times(num) { (index: Int) -> T in return function() } } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// - parameter num: Number of times to call function /// - parameter function: The function to be called every time open class func times(_ num: Int, function: (Void) -> Void) { _ = self.times(num) { (index: Int) -> () in function() } } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// - parameter num: Number of times to call function. /// - parameter function: The function to be called every time that takes index. /// - returns: Values returned from callback function. open class func times<T>(_ num: Int, function: (Int) -> T) -> [T] { var result: [T] = [] for index in (0..<num) { result.append(function(index)) } return result } /// Transposes matrix if able. If unable; parameter matrix is returned. /// /// - parameter matrix: Generic matrix containing any type. /// - returns: A transposed version of input matrix. open class func transpose<T>(_ matrix: [[T]]) -> [[T]] { guard matrix.filter({ return $0.count == matrix[0].count }).count == matrix.count else { return matrix } var returnMatrix: [[T?]] = Array(repeating: Array(repeating: nil, count: matrix.count), count: matrix.first!.count) for (rowNumber, row) in matrix.enumerated() { for (index, item) in row.enumerated() { returnMatrix[index][rowNumber] = item } } return returnMatrix.flatMap { $0.flatMap { $0 } } } /// Creates an array of unique values, in order, of the provided arrays. /// /// - parameter arrays: The arrays to perform union on. /// - returns: Resulting array after union. open class func union<T: Hashable>(_ arrays: [T]...) -> [T] { var result: [T] = [] for arr in arrays { result += arr } return self.uniq(result) } /// Creates a duplicate-value-free version of an array. /// /// - parameter array: The array to source from. /// - returns: An array with unique values. open class func uniq<T: Hashable>(_ array: [T]) -> [T] { var result: [T] = [] var map: [T: Bool] = [T: Bool]() for elem in array { if map[elem] == .none { result.append(elem) } map[elem] = true } return result } /// Create a duplicate-value-free version of an array based on the condition. /// Uses the last value generated by the condition function /// /// - parameter array: The array to source from. /// - parameter condition: Called per iteration /// - returns: An array with unique values. open class func uniq<T: Hashable, U: Hashable>(_ array: [T], by condition: (T) -> U) -> [T] { var result: [T] = [] var map: [U: Bool] = [U: Bool]() for elem in array { let val = condition(elem) if map[val] == .none { result.append(elem) } map[val] = true } return result } /// Creates an array of values of a given dictionary. /// /// - parameter dictionary: The dictionary to source from. /// - returns: An array of values from the dictionary. open class func values<T, U>(_ dictionary: [T: U]) -> [U] { var result: [U] = [] for value in dictionary.values { result.append(value) } return result } /// Creates an array excluding all provided values. /// /// - parameter array: The array to source from. /// - parameter values: Values to exclude. /// - returns: Array excluding provided values. open class func without<T: Equatable>(_ array: [T], values: T...) -> [T] { return self.pull(array, values: values) } /// Creates an array that is the symmetric difference of the provided arrays. /// /// - parameter arrays: The arrays to perform xor on in order. /// - returns: Resulting array after performing xor. open class func xor<T: Hashable>(_ arrays: [T]...) -> [T] { var map: [T: Bool] = [T: Bool]() for arr in arrays { for elem in arr { map[elem] = !(map[elem] ?? false) } } var result: [T] = [] for (key, value) in map { if value { result.append(key) } } return result } /// Creates an array of grouped elements, the first of which contains the first elements /// of the given arrays. /// /// - parameter arrays: The arrays to be grouped. /// - returns: An array of grouped elements. open class func zip<T>(_ arrays: [T]...) -> [[T]] { var result: [[T]] = [] for _ in self.first(arrays)! as [T] { result.append([] as [T]) } for (_, array) in arrays.enumerated() { for (elemIndex, elem): (Int, T) in array.enumerated() { result[elemIndex].append(elem) } } return result } /// Creates an object composed from arrays of keys and values. /// /// - parameter keys: The array of keys. /// - parameter values: The array of values. /// - returns: Dictionary based on the keys and values passed in order. open class func zipObject<T, E>(_ keys: [T], values: [E]) -> [T: E] { var result = [T: E]() for (index, key) in keys.enumerated() { result[key] = values[index] } return result } /// Returns the collection wrapped in the chain object /// /// - parameter collection: of elements /// - returns: Chain object open class func chain<T>(_ collection: [T]) -> Chain<T> { return Chain(collection) } } // ________ ___ ___ ________ ___ ________ // |\ ____\|\ \|\ \|\ __ \|\ \|\ ___ \ // \ \ \___|\ \ \\\ \ \ \|\ \ \ \ \ \\ \ \ // \ \ \ \ \ __ \ \ __ \ \ \ \ \\ \ \ // \ \ \____\ \ \ \ \ \ \ \ \ \ \ \ \\ \ \ // \ \_______\ \__\ \__\ \__\ \__\ \__\ \__\\ \__\ // \|_______|\|__|\|__|\|__|\|__|\|__|\|__| \|__| // open class Chain<C> { fileprivate var result: Wrapper<[C]> fileprivate var funcQueue: [(Wrapper<[C]>) -> Wrapper<[C]>] = [] open var value: [C] { get { var result: Wrapper<[C]> = self.result for function in self.funcQueue { result = function(result) } return result.value } } /// Initializer of the wrapper object for chaining. /// /// - parameter collection: The array to wrap. public init(_ collection: [C]) { self.result = Wrapper(collection) } /// Get the first object in the wrapper object. /// /// - returns: First element from the array. open func first() -> C? { return $.first(self.value) } /// Get the second object in the wrapper object. /// /// - returns: Second element from the array. open func second() -> C? { return $.second(self.value) } /// Get the third object in the wrapper object. /// /// - returns: Third element from the array. open func third() -> C? { return $.third(self.value) } /// Flattens nested array. /// /// - returns: The wrapper object. open func flatten() -> Chain { return self.queue { return Wrapper($.flatten($0.value)) } } /// Keeps all the elements except last one. /// /// - returns: The wrapper object. open func initial() -> Chain { return self.initial(1) } /// Keeps all the elements except last n elements. /// /// - parameter numElements: Number of items to remove from the end of the array. /// - returns: The wrapper object. open func initial(_ numElements: Int) -> Chain { return self.queue { return Wrapper($.initial($0.value, numElements: numElements)) } } /// Maps elements to new elements. /// /// - parameter function: Function to map. /// - returns: The wrapper object. open func map(_ function: @escaping (C) -> C) -> Chain { return self.queue { var result: [C] = [] for elem: C in $0.value { result.append(function(elem)) } return Wrapper(result) } } /// Get the first object in the wrapper object. /// /// - parameter function: The array to wrap. /// - returns: The wrapper object. open func map(_ function: @escaping (Int, C) -> C) -> Chain { return self.queue { var result: [C] = [] for (index, elem) in $0.value.enumerated() { result.append(function(index, elem)) } return Wrapper(result) } } /// Get the first object in the wrapper object. /// /// - parameter function: The array to wrap. /// - returns: The wrapper object. open func each(_ function: @escaping (C) -> ()) -> Chain { return self.queue { for elem in $0.value { function(elem) } return $0 } } /// Get the first object in the wrapper object. /// /// - parameter function: The array to wrap. /// - returns: The wrapper object. open func each(_ function: @escaping (Int, C) -> ()) -> Chain { return self.queue { for (index, elem) in $0.value.enumerated() { function(index, elem) } return $0 } } /// Filter elements based on the function passed. /// /// - parameter function: Function to tell whether to keep an element or remove. /// - returns: The wrapper object. open func filter(_ function: @escaping (C) -> Bool) -> Chain { return self.queue { return Wrapper(($0.value).filter(function)) } } /// Returns if all elements in array are true based on the passed function. /// /// - parameter function: Function to tell whether element value is true or false. /// - returns: Whether all elements are true according to func function. open func all(_ function: (C) -> Bool) -> Bool { return $.every(self.value, callback: function) } /// Returns if any element in array is true based on the passed function. /// /// - parameter function: Function to tell whether element value is true or false. /// - returns: Whether any one element is true according to func function in the array. open func any(_ function: (C) -> Bool) -> Bool { let resultArr = self.value for elem in resultArr { if function(elem) { return true } } return false } /// Returns size of the array /// /// - returns: The wrapper object. open func size() -> Int { return self.value.count } /// Slice the array into smaller size based on start and end value. /// /// - parameter start: Start index to start slicing from. /// - parameter end: End index to stop slicing to and not including element at that index. /// - returns: The wrapper object. open func slice(_ start: Int, end: Int = 0) -> Chain { return self.queue { return Wrapper($.slice($0.value, start: start, end: end)) } } fileprivate func queue(_ function: @escaping (Wrapper<[C]>) -> Wrapper<[C]>) -> Chain { funcQueue.append(function) return self } } private struct Wrapper<V> { let value: V init(_ value: V) { self.value = value } }
apache-2.0
dcd6bc8080e272145c60a165fd0c7e5f
36.810165
145
0.559844
4.298823
false
false
false
false
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/Pods/SwiftyUtils/Sources/Extensions/ReusableFormatters.swift
2
1027
// // Created by Tom Baranes on 24/04/16. // Copyright © 2016 Tom Baranes. All rights reserved. // import Foundation public struct SUDateFormatter { public static let shared = DateFormatter() private init() {} } public struct SUNumberFormatter { public static let shared = NumberFormatter() private init() {} } public struct SUByteCountFormatter { public static let shared = ByteCountFormatter() private init() {} } public struct SUDateComponentsFormatter { public static let shared = DateComponentsFormatter() private init() {} } public struct SUDateIntervalFormatter { public static let shared = DateIntervalFormatter() private init() {} } public struct SUEnergyFormatter { public static let shared = EnergyFormatter() private init() {} } public struct SUMassFormatter { public static let shared = MassFormatter() private init() {} } public struct SULengthFormatter { public static let shared = LengthFormatter() private init() {} }
mit
972a861b77db79bb3806982d043303c4
15.548387
56
0.69883
4.56
false
false
false
false
witekbobrowski/Stanford-CS193p-Winter-2017
Asteroids/Asteroids/AsteroidsViewController.swift
1
3937
// // AsteroidsViewController.swift // Asteroids // // Created by Witek on 18/09/2017. // Copyright © 2017 Witek Bobrowski. All rights reserved. // import UIKit class AsteroidsViewController: UIViewController { // MARK: Constants private struct Constants { static let initialAsteroidCount = 20 static let shipBoundaryName = "Ship" static let shipSizeToMinBoundsEdgeRatio: CGFloat = 1/5 static let asteroidFieldMagnitude: CGFloat = 10 // as a multiple of view.bounds.size static let burnAcceleration: CGFloat = 0.07 // points/s/s struct Shield { static let duration: TimeInterval = 1.0 // how long shield stays up static let activationCost: Double = 15 // per activation } } private var asteroidField: AsteroidFieldView! private var shipView: SpaceshipView! private lazy var animator: UIDynamicAnimator = UIDynamicAnimator(referenceView: self.asteroidField) private var asteroidBehavior = AsteroidBehavior() override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) initializeIfNeeded() animator.addBehavior(asteroidBehavior) asteroidBehavior.pushAllAsteroids() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) animator.removeBehavior(asteroidBehavior) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() asteroidField?.center = view.bounds.mid repositionShip() } @IBAction func burn(_ sender: UILongPressGestureRecognizer) { switch sender.state { case .began, .changed: shipView.direction = (sender.location(in: view) - shipView.center).angle burn() case .ended: endBurn() default: break } } private func burn() { shipView.enginesAreFiring = true asteroidBehavior.acceleration.angle = shipView.direction - .pi asteroidBehavior.acceleration.magnitude = Constants.burnAcceleration } private func endBurn() { shipView.enginesAreFiring = false asteroidBehavior.acceleration.magnitude = 0 } private func initializeIfNeeded() { if asteroidField == nil { asteroidField = AsteroidFieldView(frame: CGRect(center: view.bounds.mid, size: view.bounds.size * Constants.asteroidFieldMagnitude)) view.addSubview(asteroidField) let shipSize = view.bounds.size.minEdge * Constants.shipSizeToMinBoundsEdgeRatio shipView = SpaceshipView(frame: CGRect(squareCenteredAt: asteroidField.center , size: shipSize)) view.addSubview(shipView) repositionShip() asteroidField.asteroidBehavior = asteroidBehavior asteroidField.addAsteroids(count: Constants.initialAsteroidCount, exclusionZone: shipView.convert(shipView.bounds, to: asteroidField)) } } private func repositionShip() { if asteroidField != nil { shipView.center = asteroidField.center asteroidBehavior.setBoundary(shipView.shieldBoundary(in: asteroidField) , named: Constants.shipBoundaryName) { [weak self] in if let ship = self?.shipView { guard !ship.shieldIsActive else { return } ship.shieldIsActive = true ship.shieldLevel -= Constants.Shield.activationCost Timer.scheduledTimer(withTimeInterval: Constants.Shield.duration, repeats: false) { timer in ship.shieldIsActive = false if ship.shieldLevel == 0 { ship.shieldLevel = 100 } } } } } } }
mit
88eba94773c2a82cba31d8b43fa39d83
35.785047
146
0.623984
4.753623
false
false
false
false
apple/swift
benchmark/single-source/DictTest4.swift
10
3079
//===--- DictTest4.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 TestsUtils // This benchmark mostly measures lookups in dictionaries with complex keys, // exercising the default hash compression function. public let benchmarks = [ BenchmarkInfo( name: "Dictionary4", runFunction: run_Dictionary4, tags: [.validation, .api, .Dictionary]), BenchmarkInfo( name: "Dictionary4OfObjects", runFunction: run_Dictionary4OfObjects, tags: [.validation, .api, .Dictionary]), ] struct LargeKey: Hashable { let i: Int let j: Int let k: Double let l: UInt32 let m: Bool let n: Bool let o: Bool let p: Bool let q: Bool init(_ value: Int) { self.i = value self.j = 2 * value self.k = Double(value) / 7 self.l = UInt32(truncatingIfNeeded: value) self.m = value & 1 == 0 self.n = value & 2 == 0 self.o = value & 4 == 0 self.p = value & 8 == 0 self.q = value & 16 == 0 } } @inline(never) public func run_Dictionary4(_ n: Int) { let size1 = 100 let reps = 20 let ref_result = "1 99 \(reps) \(reps * 99)" var hash1 = [LargeKey: Int]() var hash2 = [LargeKey: Int]() var res = "" for _ in 1...n { // Test insertions hash1 = [:] for i in 0..<size1 { hash1[LargeKey(i)] = i } hash2 = hash1 // Test lookups & value replacement for _ in 1..<reps { for (k, v) in hash1 { hash2[k] = hash2[k]! + v } } res = "\(hash1[LargeKey(1)]!) \(hash1[LargeKey(99)]!)" + " \(hash2[LargeKey(1)]!) \(hash2[LargeKey(99)]!)" if res != ref_result { break } } check(res == ref_result) } class Box<T : Hashable> : Hashable { var value: T init(_ v: T) { value = v } func hash(into hasher: inout Hasher) { hasher.combine(value) } static func ==(lhs: Box, rhs: Box) -> Bool { return lhs.value == rhs.value } } @inline(never) public func run_Dictionary4OfObjects(_ n: Int) { let size1 = 100 let reps = 20 let ref_result = "1 99 \(reps) \(reps * 99)" var hash1 = [Box<LargeKey>: Int]() var hash2 = [Box<LargeKey>: Int]() var res = "" for _ in 1...n { // Test insertions hash1 = [:] for i in 0..<size1 { hash1[Box(LargeKey(i))] = i } hash2 = hash1 // Test lookups & value replacement for _ in 1..<reps { for (k, v) in hash1 { hash2[k] = hash2[k]! + v } } res = "\(hash1[Box(LargeKey(1))]!) \(hash1[Box(LargeKey(99))]!)" + " \(hash2[Box(LargeKey(1))]!) \(hash2[Box(LargeKey(99))]!)" if res != ref_result { break } } check(res == ref_result) }
apache-2.0
94ebb4f67a764fb366e05692fad7b4e7
21.807407
80
0.5557
3.409745
false
false
false
false
vector-im/vector-ios
Riot/Modules/ContextMenu/Services/UnownedRoomContextActionService.swift
1
3867
// // Copyright 2022 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// `RoomContextActionService` implements all the possible actions for a room not owned by the user (e.g. `MXPublicRoom`, `MXSpaceChildInfo`) class UnownedRoomContextActionService: NSObject, RoomContextActionServiceProtocol { // MARK: - RoomContextActionServiceProtocol internal let roomId: String internal let session: MXSession internal weak var delegate: RoomContextActionServiceDelegate? // MARK: - Properties private let canonicalAlias: String? // MARK: - Setup init(roomId: String, canonicalAlias: String?, session: MXSession, delegate: RoomContextActionServiceDelegate?) { self.roomId = roomId self.canonicalAlias = canonicalAlias self.session = session self.delegate = delegate } // MARK: - Public func joinRoom() { self.delegate?.roomContextActionService(self, updateActivityIndicator: true) if let canonicalAlias = canonicalAlias { self.session.matrixRestClient.resolveRoomAlias(canonicalAlias) { [weak self] (response) in guard let self = self else { return } switch response { case .success(let resolution): self.joinRoom(withId: resolution.roomId, via: resolution.servers) case .failure(let error): MXLog.warning("[UnownedRoomContextActionService] joinRoom: failed to resolve room alias due to error \(error).") self.joinRoom(withId: self.roomId, via: nil) } } } else { MXLog.warning("[UnownedRoomContextActionService] joinRoom: no canonical alias provided.") joinRoom(withId: self.roomId, via: nil) } } // MARK: - Private private func joinRoom(withId roomId: String, via viaServers: [String]?) { self.session.joinRoom(roomId, viaServers: viaServers, withSignUrl: nil) { [weak self] response in guard let self = self else { return } switch response { case .success: self.delegate?.roomContextActionService(self, updateActivityIndicator: false) self.delegate?.roomContextActionServiceDidJoinRoom(self) case .failure(let error): self.delegate?.roomContextActionService(self, updateActivityIndicator: false) self.delegate?.roomContextActionService(self, presentAlert: self.roomJoinFailedAlert(with: error)) } } } private func roomJoinFailedAlert(with error: Error) -> UIAlertController { var message = (error as NSError).userInfo[NSLocalizedDescriptionKey] as? String if message == "No known servers" { // minging kludge until https://matrix.org/jira/browse/SYN-678 is fixed // 'Error when trying to join an empty room should be more explicit' message = VectorL10n.roomErrorJoinFailedEmptyRoom } let alertController = UIAlertController(title: VectorL10n.roomErrorJoinFailedTitle, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: VectorL10n.ok, style: .default, handler: nil)) return alertController } }
apache-2.0
4c7005986c8143a6182b057bc636d6db
41.966667
141
0.665115
4.779975
false
false
false
false
chinlam91/edx-app-ios
Source/NSNotificationCenter+SafeSwift.swift
3
1624
// // NSNotificationCenter+SafeSwift.swift // edX // // Created by Akiva Leffert on 5/15/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit private class NotificationListener : NSObject, Removable { var action : ((NSNotification, Removable) -> Void)? var removeAction : (NotificationListener -> Void)? @objc func notificationFired(notification : NSNotification) { self.action?(notification, self) } func remove() { NSNotificationCenter.defaultCenter().removeObserver(self) self.removeAction?(self) self.action = nil } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } extension NSNotificationCenter { func oex_addObserver<A : NSObject>(observer : A, name : String, action : (NSNotification, A, Removable) -> Void) -> Removable { let listener = NotificationListener() listener.action = {[weak observer] (notification, removable) in if let observer = observer { action(notification, observer, removable) } } let removable = observer.oex_performActionOnDealloc { listener.remove() } self.addObserver(listener, selector: "notificationFired:", name: name, object: nil) return BlockRemovable { removable.remove() } } } public func addNotificationObserver<A : NSObject>(observer : A, name : String, action : (NSNotification, A, Removable) -> Void) -> Removable { return NSNotificationCenter.defaultCenter().oex_addObserver(observer, name: name, action: action) }
apache-2.0
3d6b055cd644ea0794a257ea8879bc87
30.843137
142
0.652709
4.762463
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/AttributedString/Conversion.swift
1
17712
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 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 // //===----------------------------------------------------------------------===// @_spi(Reflection) import Swift @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) public protocol ObjectiveCConvertibleAttributedStringKey : AttributedStringKey { associatedtype ObjectiveCValue : NSObject static func objectiveCValue(for value: Value) throws -> ObjectiveCValue static func value(for object: ObjectiveCValue) throws -> Value } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) public extension ObjectiveCConvertibleAttributedStringKey where Value : RawRepresentable, Value.RawValue == Int, ObjectiveCValue == NSNumber { static func objectiveCValue(for value: Value) throws -> ObjectiveCValue { return NSNumber(value: value.rawValue) } static func value(for object: ObjectiveCValue) throws -> Value { if let val = Value(rawValue: object.intValue) { return val } throw CocoaError(.coderInvalidValue) } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) public extension ObjectiveCConvertibleAttributedStringKey where Value : RawRepresentable, Value.RawValue == String, ObjectiveCValue == NSString { static func objectiveCValue(for value: Value) throws -> ObjectiveCValue { return value.rawValue as NSString } static func value(for object: ObjectiveCValue) throws -> Value { if let val = Value(rawValue: object as String) { return val } throw CocoaError(.coderInvalidValue) } } internal struct _AttributeConversionOptions : OptionSet { let rawValue: Int // If an attribute's value(for: ObjectieCValue) or objectiveCValue(for: Value) function throws, ignore the error and drop the attribute static let dropThrowingAttributes = Self(rawValue: 1 << 0) } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) public extension AttributeContainer { init(_ dictionary: [NSAttributedString.Key : Any]) { var attributeKeyTypes = _loadDefaultAttributes() // Passing .dropThrowingAttributes causes attributes that throw during conversion to be dropped, so it is safe to do try! here try! self.init(dictionary, including: AttributeScopes.FoundationAttributes.self, attributeKeyTypes: &attributeKeyTypes, options: .dropThrowingAttributes) } init<S: AttributeScope>(_ dictionary: [NSAttributedString.Key : Any], including scope: KeyPath<AttributeScopes, S.Type>) throws { try self.init(dictionary, including: S.self) } init<S: AttributeScope>(_ dictionary: [NSAttributedString.Key : Any], including scope: S.Type) throws { var attributeKeyTypes = [String : Any.Type]() try self.init(dictionary, including: scope, attributeKeyTypes: &attributeKeyTypes) } fileprivate init<S: AttributeScope>(_ dictionary: [NSAttributedString.Key : Any], including scope: S.Type, attributeKeyTypes: inout [String : Any.Type], options: _AttributeConversionOptions = []) throws { contents = [:] for (key, value) in dictionary { if let type = attributeKeyTypes[key.rawValue] ?? S.attributeKeyType(matching: key.rawValue) { attributeKeyTypes[key.rawValue] = type var swiftVal: AnyHashable? func project<T>(_: T.Type) throws { if let val = try ConvertFromObjCIfObjCAttribute(T.self, value: value as AnyObject).attemptAction() { // Value is converted via the function defined by `ObjectiveCConvertibleAttributedStringKey` swiftVal = val } else if let val = try ConvertFromObjCIfAttribute(T.self, value: value as AnyObject).attemptAction() { // Attribute is only `AttributedStringKey`, so converted by casting to Value type // This implicitly bridges or unboxes the value swiftVal = val } // else: the type was not an attribute (should never happen) } do { try _openExistential(type, do: project) } catch let conversionError { if !options.contains(.dropThrowingAttributes) { throw conversionError } } if let swiftVal = swiftVal { contents[key.rawValue] = swiftVal } } // else, attribute is not in provided scope, so drop it } } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) public extension Dictionary where Key == NSAttributedString.Key, Value == Any { init(_ container: AttributeContainer) { var attributeKeyTypes = _loadDefaultAttributes() // Passing .dropThrowingAttributes causes attributes that throw during conversion to be dropped, so it is safe to do try! here try! self.init(container, including: AttributeScopes.FoundationAttributes.self, attributeKeyTypes: &attributeKeyTypes, options: .dropThrowingAttributes) } init<S: AttributeScope>(_ container: AttributeContainer, including scope: KeyPath<AttributeScopes, S.Type>) throws { try self.init(container, including: S.self) } init<S: AttributeScope>(_ container: AttributeContainer, including scope: S.Type) throws { var attributeKeyTypes = [String : Any.Type]() try self.init(container, including: scope, attributeKeyTypes: &attributeKeyTypes) } // These includingOnly SPI initializers were provided originally when conversion boxed attributes outside of the given scope as an AnyObject // After rdar://80201634, these SPI initializers have the same behavior as the API initializers @_spi(AttributedString) init<S: AttributeScope>(_ container: AttributeContainer, includingOnly scope: KeyPath<AttributeScopes, S.Type>) throws { try self.init(container, including: S.self) } @_spi(AttributedString) init<S: AttributeScope>(_ container: AttributeContainer, includingOnly scope: S.Type) throws { try self.init(container, including: S.self) } fileprivate init<S: AttributeScope>(_ container: AttributeContainer, including scope: S.Type, attributeKeyTypes: inout [String : Any.Type], options: _AttributeConversionOptions = []) throws { self.init() for (key, value) in container.contents { if let type = attributeKeyTypes[key] ?? S.attributeKeyType(matching: key) { attributeKeyTypes[key] = type var objcVal: AnyObject? func project<T>(_: T.Type) throws { if let val = try ConvertToObjCIfObjCAttribute(T.self, value: value).attemptAction() { objcVal = val } else { // Attribute is not `ObjectiveCConvertibleAttributedStringKey`, so cast it to AnyObject to implicitly bridge it or box it objcVal = value as AnyObject } } do { try _openExistential(type, do: project) } catch let conversionError { if !options.contains(.dropThrowingAttributes) { throw conversionError } } if let val = objcVal { self[NSAttributedString.Key(rawValue: key)] = val } } } } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) public extension NSAttributedString { convenience init(_ attrStr: AttributedString) { // Passing .dropThrowingAttributes causes attributes that throw during conversion to be dropped, so it is safe to do try! here try! self.init(attrStr, scope: AttributeScopes.FoundationAttributes.self, otherAttributeTypes: _loadDefaultAttributes(), options: .dropThrowingAttributes) } convenience init<S: AttributeScope>(_ attrStr: AttributedString, including scope: KeyPath<AttributeScopes, S.Type>) throws { try self.init(attrStr, scope: S.self) } convenience init<S: AttributeScope>(_ attrStr: AttributedString, including scope: S.Type) throws { try self.init(attrStr, scope: scope) } @_spi(AttributedString) convenience init<S: AttributeScope>(_ attrStr: AttributedString, includingOnly scope: KeyPath<AttributeScopes, S.Type>) throws { try self.init(attrStr, scope: S.self) } @_spi(AttributedString) convenience init<S: AttributeScope>(_ attrStr: AttributedString, includingOnly scope: S.Type) throws { try self.init(attrStr, scope: scope) } internal convenience init<S: AttributeScope>(_ attrStr: AttributedString, scope: S.Type, otherAttributeTypes: [String : Any.Type] = [:], options: _AttributeConversionOptions = []) throws { let result = NSMutableAttributedString(string: attrStr._guts.string) var attributeKeyTypes: [String : Any.Type] = otherAttributeTypes // Iterate through each run of the source var nsStartIndex = 0 var stringStart = attrStr._guts.string.startIndex for run in attrStr._guts.runs { let stringEnd = attrStr._guts.string.utf8.index(stringStart, offsetBy: run.length) let utf16Length = attrStr._guts.string.utf16.distance(from: stringStart, to: stringEnd) let range = NSRange(location: nsStartIndex, length: utf16Length) let attributes = try Dictionary(AttributeContainer(run.attributes.contents), including: scope, attributeKeyTypes: &attributeKeyTypes, options: options) result.setAttributes(attributes, range: range) nsStartIndex += utf16Length stringStart = stringEnd } self.init(attributedString: result) } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) public extension AttributedString { init(_ nsStr: NSAttributedString) { // Passing .dropThrowingAttributes causes attributes that throw during conversion to be dropped, so it is safe to do try! here try! self.init(nsStr, scope: AttributeScopes.FoundationAttributes.self, otherAttributeTypes: _loadDefaultAttributes(), options: .dropThrowingAttributes) } init<S: AttributeScope>(_ nsStr: NSAttributedString, including scope: KeyPath<AttributeScopes, S.Type>) throws { try self.init(nsStr, scope: S.self) } init<S: AttributeScope>(_ nsStr: NSAttributedString, including scope: S.Type) throws { try self.init(nsStr, scope: S.self) } private init<S: AttributeScope>(_ nsStr: NSAttributedString, scope: S.Type, otherAttributeTypes: [String : Any.Type] = [:], options: _AttributeConversionOptions = []) throws { let string = nsStr.string var runs: [_InternalRun] = [] var attributeKeyTypes: [String : Any.Type] = otherAttributeTypes var conversionError: Error? var stringStart = string.startIndex nsStr.enumerateAttributes(in: NSMakeRange(0, nsStr.length), options: []) { (nsAttrs, range, stop) in let container: AttributeContainer do { container = try AttributeContainer(nsAttrs, including: scope, attributeKeyTypes: &attributeKeyTypes, options: options) } catch { conversionError = error stop.pointee = true return } let stringEnd = string.utf16.index(stringStart, offsetBy: range.length) let runLength = string.utf8.distance(from: stringStart, to: stringEnd) let attrStorage = _AttributeStorage(container.contents) if let previous = runs.last, previous.attributes == attrStorage { runs[runs.endIndex - 1].length += runLength } else { runs.append(_InternalRun(length: runLength, attributes: attrStorage)) } stringStart = stringEnd } if let error = conversionError { throw error } self = AttributedString(Guts(string: string, runs: runs)) } } fileprivate var _loadedScopeCache = [String : [String : Any.Type]]() fileprivate var _loadedScopeCacheLock = Lock() @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) internal func _loadDefaultAttributes() -> [String : Any.Type] { #if os(macOS) #if !targetEnvironment(macCatalyst) // AppKit scope on macOS let macOSSymbol = ("$s10Foundation15AttributeScopesO6AppKitE0dE10AttributesVN", "/usr/lib/swift/libswiftAppKit.dylib") #else // UIKit scope on macOS let macOSSymbol = ("$s10Foundation15AttributeScopesO5UIKitE0D10AttributesVN", "/System/iOSSupport/usr/lib/swift/libswiftUIKit.dylib") #endif let loadedScopes = [ macOSSymbol, // UIKit scope on non-macOS ("$s10Foundation15AttributeScopesO5UIKitE0D10AttributesVN", "/usr/lib/swift/libswiftUIKit.dylib"), // SwiftUI scope ("$s10Foundation15AttributeScopesO7SwiftUIE0D12UIAttributesVN", "/System/Library/Frameworks/SwiftUI.framework/SwiftUI"), // Accessibility scope ("$s10Foundation15AttributeScopesO13AccessibilityE0D10AttributesVN", "/System/Library/Frameworks/Accessibility.framework/Accessibility") ].compactMap { _loadScopeAttributes(forSymbol: $0.0, from: $0.1) } return loadedScopes.reduce([:]) { result, item in result.merging(item) { current, new in new } } #else return [:] #endif // os(macOS) } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) fileprivate func _loadScopeAttributes(forSymbol symbol: String, from path: String) -> [String : Any.Type]? { #if os(macOS) _loadedScopeCacheLock.lock() defer { _loadedScopeCacheLock.unlock() } if let cachedResult = _loadedScopeCache[symbol] { return cachedResult } guard let handle = dlopen(path, RTLD_NOLOAD) else { return nil } guard let symbolPointer = dlsym(handle, symbol) else { return nil } let scopeType = unsafeBitCast(symbolPointer, to: Any.Type.self) let attributeTypes = _loadAttributeTypes(from: scopeType) _loadedScopeCache[symbol] = attributeTypes return attributeTypes #else return nil #endif // os(macOS) } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) fileprivate func _loadAttributeTypes(from scope: Any.Type) -> [String : Any.Type] { var result = [String : Any.Type]() _forEachField(of: scope, options: [.ignoreUnknown]) { pointer, offset, type, kind -> Bool in func project<K>(_: K.Type) { if let key = GetNameIfAttribute(K.self).attemptAction() { result[key] = type } else if let subResults = GetAllAttributeTypesIfAttributeScope(K.self).attemptAction() { result.merge(subResults, uniquingKeysWith: { current, new in new }) } } _openExistential(type, do: project) return true } return result } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) extension String.Index { public init?<S: StringProtocol>(_ sourcePosition: AttributedString.Index, within target: S) { self.init(sourcePosition.characterIndex, within: target) } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) extension AttributedString.Index { public init?<S: AttributedStringProtocol>(_ sourcePosition: String.Index, within target: S) { guard let strIndex = String.Index(sourcePosition, within: target.__guts.string) else { return nil } self.init(characterIndex: strIndex) } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) extension NSRange { public init<R: RangeExpression, S: AttributedStringProtocol>(_ region: R, in target: S) where R.Bound == AttributedString.Index { let str = target.__guts.string let r = region.relative(to: target.characters)._stringRange.relative(to: str) self.init(str._toUTF16Offsets(r)) } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) extension Range where Bound == AttributedString.Index { public init?<S: AttributedStringProtocol>(_ range: NSRange, in attrStr: S) { if let r = Range<String.Index>(range, in: attrStr.__guts.string) { self = r._attributedStringRange } else { return nil } } public init?<R: RangeExpression, S: AttributedStringProtocol>(_ region: R, in attrStr: S) where R.Bound == String.Index { let range = region.relative(to: attrStr.__guts.string) if let lwr = Bound(range.lowerBound, within: attrStr), let upr = Bound(range.upperBound, within: attrStr) { self = lwr ..< upr } else { return nil } } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) extension Range where Bound == String.Index { public init?<R: RangeExpression, S: StringProtocol>(_ region: R, in string: S) where R.Bound == AttributedString.Index { let range = region.relative(to: AttributedString(string).characters) if let lwr = Bound(range.lowerBound, within: string), let upr = Bound(range.upperBound, within: string) { self = lwr ..< upr } else { return nil } } }
apache-2.0
23b60c8db559bcb6d4530a372cc53832
45.245431
208
0.648769
4.562597
false
false
false
false
abring/sample_ios
Abring/ABRVersion.swift
1
5818
// // ABVersion.swift // Pouya // // Created by Hosein Abbaspour on 4/28/1396 AP. // Copyright © 1396 AP AsemanLTD. All rights reserved. // import Foundation /** Make an instance of this class from version in string format. All the main operations like == != etc are supported. */ public struct ABRVersion : Equatable { /// Version in string format. public var versionString : String /// Major part of version. for example 2 in 2.3.4 public var major : Int? /// Middle part of version. for example 3 in 2.3.4 public var mid : Int? /// Minor part of version. for example 4 in 2.3.4 public var minor : Int? //MARK: init methods /// Set your version in string as parameter like `1.1.2` public init(_ version : String) { self.versionString = version let versionComponents = versionString.components(separatedBy: ".") major = Int(versionComponents.first ?? "0") if versionComponents.count > 1 { mid = Int(versionComponents[1]) } if versionComponents.count > 2 { minor = Int(versionComponents[2]) } } //MARK: other methods /** The main method for checking if there is new version of your app available. ## Usage You must have a variable named 'update' in your app data in your [Abring](http://abring.ir) Panel. Set update variable like this: { ```` "ios" : { "current" : "1.3" , "force" : "1.2" , "link" : "http://downloadUrl.com" } } ```` In above example current is the latest version of your app that is live now. Force is the minimum version that user can run your app. Link is the url for downloading your app, for example you can use appstore link. */ public static func checkForUpdate() { ABRApp.get { (success, _ , app) in if success { var vc : ABRNewVersionViewController! if Bundle.main.path(forResource: "ABRNewVersion", ofType: "nib") != nil { print("found xib main bundle") vc = ABRNewVersionViewController(nibName: "ABRNewVersion", bundle: Bundle.main) } else { vc = ABRNewVersionViewController(nibName: "ABRNewVersion", bundle: Bundle.init(for: ABRNewVersionViewController.self)) } vc.modalPresentationStyle = .overCurrentContext vc.app = app let bundleVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String if let current = app?.currentVersion { if current > ABRVersion(bundleVersion) { if ABRVersion(bundleVersion) < (app?.minimumVersion)! { // force update vc.isForce = true ABRUtils.topViewController?.present(vc, animated: true, completion: nil) } else { if let ver = app?.currentVersion?.versionString { let savedVer = UserDefaults.standard.bool(forKey: ver) if !savedVer { // normal update print("Abring : Update available") ABRUtils.topViewController?.present(vc, animated: true, completion: nil) } else { print("Abring : Update View Controller has been shown before") } } } } else { print("Abring : Your app is up to date") } } else { print("Abring : Define update variable in your appdata in Abring Panel") } } else { print("Abring : Couldn't check for update") } } } //MARK: Operators public static func ==(lhs: ABRVersion, rhs: ABRVersion) -> Bool { if lhs.minor == nil || rhs.minor == nil { return (lhs.major == rhs.major) && (lhs.mid == rhs.mid) } else { return (lhs.major == rhs.major) && (lhs.mid == rhs.mid) && (lhs.minor == rhs.minor) } } public static func >(lhs: ABRVersion, rhs: ABRVersion) -> Bool { return lhs.major ?? 0 > rhs.major ?? 0 || lhs.major == rhs.major && lhs.mid ?? 0 > rhs.mid ?? 0 || lhs.major == rhs.major && lhs.mid == rhs.mid && lhs.minor ?? 0 > rhs.minor ?? 0 } public static func <(lhs: ABRVersion, rhs: ABRVersion) -> Bool { return lhs.major ?? 0 < rhs.major ?? 0 || lhs.major == rhs.major && lhs.mid ?? 0 < rhs.mid ?? 0 || lhs.major == rhs.major && lhs.mid == rhs.mid && lhs.minor ?? 0 < rhs.minor ?? 0 } public static func >=(lhs: ABRVersion, rhs: ABRVersion) -> Bool { return (lhs.major ?? 0 > rhs.major ?? 0 || lhs.major == rhs.major && lhs.mid ?? 0 > rhs.mid ?? 0 || lhs.major == rhs.major && lhs.mid == rhs.mid && lhs.minor ?? 0 > rhs.minor ?? 0) || ((lhs.major == rhs.major) && (lhs.mid == rhs.mid) && (lhs.minor == rhs.minor)) } public static func <=(lhs: ABRVersion, rhs: ABRVersion) -> Bool { return (lhs.major ?? 0 < rhs.major ?? 0 || lhs.major == rhs.major && lhs.mid ?? 0 < rhs.mid ?? 0 || lhs.major == rhs.major && lhs.mid == rhs.mid && lhs.minor ?? 0 < rhs.minor ?? 0) || ((lhs.major == rhs.major) && (lhs.mid == rhs.mid) && (lhs.minor == rhs.minor)) } }
mit
bef6cca3304cc1b2cf8c3bf43e621af1
37.523179
138
0.511088
4.350785
false
false
false
false
roambotics/swift
stdlib/public/core/SmallString.swift
2
14448
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // The code units in _SmallString are always stored in memory in the same order // that they would be stored in an array. This means that on big-endian // platforms the order of the bytes in storage is reversed compared to // _StringObject whereas on little-endian platforms the order is the same. // // Memory layout: // // |0 1 2 3 4 5 6 7 8 9 A B C D E F| ← hexadecimal offset in bytes // | _storage.0 | _storage.1 | ← raw bits // | code units | | ← encoded layout // ↑ ↑ // first (leftmost) code unit discriminator (incl. count) // // On Android AArch64, there is one less byte available because the discriminator // is stored in the penultimate code unit instead, to match where it's stored // for large strings. @frozen @usableFromInline internal struct _SmallString { @usableFromInline internal typealias RawBitPattern = (UInt64, UInt64) // Small strings are values; store them raw @usableFromInline internal var _storage: RawBitPattern @inlinable @inline(__always) internal var rawBits: RawBitPattern { return _storage } @inlinable internal var leadingRawBits: UInt64 { @inline(__always) get { return _storage.0 } @inline(__always) set { _storage.0 = newValue } } @inlinable internal var trailingRawBits: UInt64 { @inline(__always) get { return _storage.1 } @inline(__always) set { _storage.1 = newValue } } @inlinable @inline(__always) internal init(rawUnchecked bits: RawBitPattern) { self._storage = bits } @inlinable @inline(__always) internal init(raw bits: RawBitPattern) { self.init(rawUnchecked: bits) _invariantCheck() } @inlinable @inline(__always) internal init(_ object: _StringObject) { _internalInvariant(object.isSmall) // On big-endian platforms the byte order is the reverse of _StringObject. let leading = object.rawBits.0.littleEndian let trailing = object.rawBits.1.littleEndian self.init(raw: (leading, trailing)) } @inlinable @inline(__always) internal init() { self.init(_StringObject(empty:())) } } extension _SmallString { @inlinable @inline(__always) internal static var capacity: Int { #if arch(i386) || arch(arm) || arch(arm64_32) || arch(wasm32) return 10 #elseif os(Android) && arch(arm64) return 14 #else return 15 #endif } // Get an integer equivalent to the _StringObject.discriminatedObjectRawBits // computed property. @inlinable @inline(__always) internal var rawDiscriminatedObject: UInt64 { // Reverse the bytes on big-endian systems. return _storage.1.littleEndian } @inlinable @inline(__always) internal var capacity: Int { return _SmallString.capacity } @inlinable @inline(__always) internal var count: Int { return _StringObject.getSmallCount(fromRaw: rawDiscriminatedObject) } @inlinable @inline(__always) internal var unusedCapacity: Int { return capacity &- count } @inlinable @inline(__always) internal var isASCII: Bool { return _StringObject.getSmallIsASCII(fromRaw: rawDiscriminatedObject) } // Give raw, nul-terminated code units. This is only for limited internal // usage: it always clears the discriminator and count (in case it's full) @inlinable @inline(__always) internal var zeroTerminatedRawCodeUnits: RawBitPattern { #if os(Android) && arch(arm64) let smallStringCodeUnitMask = ~UInt64(0xFFFF).bigEndian // zero last two bytes #else let smallStringCodeUnitMask = ~UInt64(0xFF).bigEndian // zero last byte #endif return (self._storage.0, self._storage.1 & smallStringCodeUnitMask) } internal func computeIsASCII() -> Bool { let asciiMask: UInt64 = 0x8080_8080_8080_8080 let raw = zeroTerminatedRawCodeUnits return (raw.0 | raw.1) & asciiMask == 0 } } // Internal invariants extension _SmallString { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { _internalInvariant(count <= _SmallString.capacity) _internalInvariant(isASCII == computeIsASCII()) // No bits should be set between the last code unit and the discriminator var copy = self withUnsafeBytes(of: &copy._storage) { _internalInvariant( $0[count..<_SmallString.capacity].allSatisfy { $0 == 0 }) } } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { #if INTERNAL_CHECKS_ENABLED print(""" smallUTF8: count: \(self.count), codeUnits: \( self.map { String($0, radix: 16) }.joined() ) """) #endif // INTERNAL_CHECKS_ENABLED } } // Provide a RAC interface extension _SmallString: RandomAccessCollection, MutableCollection { @usableFromInline internal typealias Index = Int @usableFromInline internal typealias Element = UInt8 @usableFromInline internal typealias SubSequence = _SmallString @inlinable @inline(__always) internal var startIndex: Int { return 0 } @inlinable @inline(__always) internal var endIndex: Int { return count } @inlinable internal subscript(_ idx: Int) -> UInt8 { @inline(__always) get { _internalInvariant(idx >= 0 && idx <= 15) if idx < 8 { return leadingRawBits._uncheckedGetByte(at: idx) } else { return trailingRawBits._uncheckedGetByte(at: idx &- 8) } } @inline(__always) set { _internalInvariant(idx >= 0 && idx <= 15) if idx < 8 { leadingRawBits._uncheckedSetByte(at: idx, to: newValue) } else { trailingRawBits._uncheckedSetByte(at: idx &- 8, to: newValue) } } } @inlinable @inline(__always) internal subscript(_ bounds: Range<Index>) -> SubSequence { get { // TODO(String performance): In-vector-register operation return self.withUTF8 { utf8 in let rebased = UnsafeBufferPointer(rebasing: utf8[bounds]) return _SmallString(rebased)._unsafelyUnwrappedUnchecked } } // This setter is required for _SmallString to be a valid MutableCollection. // Since _SmallString is internal and this setter unused, we cheat. @_alwaysEmitIntoClient set { fatalError() } @_alwaysEmitIntoClient _modify { fatalError() } } } extension _SmallString { @inlinable @inline(__always) internal func withUTF8<Result>( _ f: (UnsafeBufferPointer<UInt8>) throws -> Result ) rethrows -> Result { let count = self.count var raw = self.zeroTerminatedRawCodeUnits return try Swift._withUnprotectedUnsafeBytes(of: &raw) { let rawPtr = $0.baseAddress._unsafelyUnwrappedUnchecked // Rebind the underlying (UInt64, UInt64) tuple to UInt8 for the // duration of the closure. Accessing self after this rebind is undefined. let ptr = rawPtr.bindMemory(to: UInt8.self, capacity: count) defer { // Restore the memory type of self._storage _ = rawPtr.bindMemory(to: RawBitPattern.self, capacity: 1) } return try f(UnsafeBufferPointer(_uncheckedStart: ptr, count: count)) } } // Overwrite stored code units, including uninitialized. `f` should return the // new count. This will re-establish the invariant after `f` that all bits // between the last code unit and the discriminator are unset. @inline(__always) fileprivate mutating func withMutableCapacity( _ f: (UnsafeMutableRawBufferPointer) throws -> Int ) rethrows { let len = try withUnsafeMutableBytes(of: &_storage, f) if len <= 0 { _debugPrecondition(len == 0) self = _SmallString() return } _SmallString.zeroTrailingBytes(of: &_storage, from: len) self = _SmallString(leading: _storage.0, trailing: _storage.1, count: len) } @inlinable @_alwaysEmitIntoClient internal static func zeroTrailingBytes( of storage: inout RawBitPattern, from index: Int ) { _internalInvariant(index > 0) _internalInvariant(index <= _SmallString.capacity) //FIXME: Verify this on big-endian architecture let mask0 = (UInt64(bitPattern: ~0) &>> (8 &* ( 8 &- Swift.min(index, 8)))) let mask1 = (UInt64(bitPattern: ~0) &>> (8 &* (16 &- Swift.max(index, 8)))) storage.0 &= (index <= 0) ? 0 : mask0.littleEndian storage.1 &= (index <= 8) ? 0 : mask1.littleEndian } } // Creation extension _SmallString { @inlinable @inline(__always) internal init(leading: UInt64, trailing: UInt64, count: Int) { _internalInvariant(count <= _SmallString.capacity) let isASCII = (leading | trailing) & 0x8080_8080_8080_8080 == 0 let discriminator = _StringObject.Nibbles .small(withCount: count, isASCII: isASCII) .littleEndian // reversed byte order on big-endian platforms _internalInvariant(trailing & discriminator == 0) self.init(raw: (leading, trailing | discriminator)) _internalInvariant(self.count == count) } // Direct from UTF-8 @inlinable @inline(__always) internal init?(_ input: UnsafeBufferPointer<UInt8>) { if input.isEmpty { self.init() return } let count = input.count guard count <= _SmallString.capacity else { return nil } // TODO(SIMD): The below can be replaced with just be a masked unaligned // vector load let ptr = input.baseAddress._unsafelyUnwrappedUnchecked let leading = _bytesToUInt64(ptr, Swift.min(input.count, 8)) let trailing = count > 8 ? _bytesToUInt64(ptr + 8, count &- 8) : 0 self.init(leading: leading, trailing: trailing, count: count) } @inline(__always) internal init( initializingUTF8With initializer: ( _ buffer: UnsafeMutableBufferPointer<UInt8> ) throws -> Int ) rethrows { self.init() try self.withMutableCapacity { let capacity = $0.count let rawPtr = $0.baseAddress._unsafelyUnwrappedUnchecked // Rebind the underlying (UInt64, UInt64) tuple to UInt8 for the // duration of the closure. Accessing self after this rebind is undefined. let ptr = rawPtr.bindMemory(to: UInt8.self, capacity: capacity) defer { // Restore the memory type of self._storage _ = rawPtr.bindMemory(to: RawBitPattern.self, capacity: 1) } return try initializer( UnsafeMutableBufferPointer<UInt8>(start: ptr, count: capacity)) } self._invariantCheck() } @usableFromInline // @testable internal init?(_ base: _SmallString, appending other: _SmallString) { let totalCount = base.count + other.count guard totalCount <= _SmallString.capacity else { return nil } // TODO(SIMD): The below can be replaced with just be a couple vector ops var result = base var writeIdx = base.count for readIdx in 0..<other.count { result[writeIdx] = other[readIdx] writeIdx &+= 1 } _internalInvariant(writeIdx == totalCount) let (leading, trailing) = result.zeroTerminatedRawCodeUnits self.init(leading: leading, trailing: trailing, count: totalCount) } } #if _runtime(_ObjC) && !(arch(i386) || arch(arm) || arch(arm64_32)) // Cocoa interop extension _SmallString { // Resiliently create from a tagged cocoa string // @_effects(readonly) // @opaque @usableFromInline // testable internal init?(taggedCocoa cocoa: AnyObject) { self.init() var success = true self.withMutableCapacity { /* For regular NSTaggedPointerStrings we will always succeed here, but tagged NSLocalizedStrings may not fit in a SmallString */ if let len = _bridgeTagged(cocoa, intoUTF8: $0) { return len } success = false return 0 } if !success { return nil } self._invariantCheck() } @_effects(readonly) // @opaque internal init?(taggedASCIICocoa cocoa: AnyObject) { self.init() var success = true self.withMutableCapacity { /* For regular NSTaggedPointerStrings we will always succeed here, but tagged NSLocalizedStrings may not fit in a SmallString */ if let len = _bridgeTaggedASCII(cocoa, intoUTF8: $0) { return len } success = false return 0 } if !success { return nil } self._invariantCheck() } } #endif extension UInt64 { // Fetches the `i`th byte in memory order. On little-endian systems the byte // at i=0 is the least significant byte (LSB) while on big-endian systems the // byte at i=7 is the LSB. @inlinable @inline(__always) internal func _uncheckedGetByte(at i: Int) -> UInt8 { _internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride) #if _endian(big) let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8 #else let shift = UInt64(truncatingIfNeeded: i) &* 8 #endif return UInt8(truncatingIfNeeded: (self &>> shift)) } // Sets the `i`th byte in memory order. On little-endian systems the byte // at i=0 is the least significant byte (LSB) while on big-endian systems the // byte at i=7 is the LSB. @inlinable @inline(__always) internal mutating func _uncheckedSetByte(at i: Int, to value: UInt8) { _internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride) #if _endian(big) let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8 #else let shift = UInt64(truncatingIfNeeded: i) &* 8 #endif let valueMask: UInt64 = 0xFF &<< shift self = (self & ~valueMask) | (UInt64(truncatingIfNeeded: value) &<< shift) } } @inlinable @inline(__always) internal func _bytesToUInt64( _ input: UnsafePointer<UInt8>, _ c: Int ) -> UInt64 { // FIXME: This should be unified with _loadPartialUnalignedUInt64LE. // Unfortunately that causes regressions in literal concatenation tests. (Some // owned to guaranteed specializations don't get inlined.) var r: UInt64 = 0 var shift: Int = 0 for idx in 0..<c { r = r | (UInt64(input[idx]) &<< shift) shift = shift &+ 8 } // Convert from little-endian to host byte order. return r.littleEndian }
apache-2.0
d8e5606911dc4f849744cabb534a49ba
31.372197
82
0.665535
4.135778
false
false
false
false
roambotics/swift
lib/ASTGen/Sources/ASTGen/Decls.swift
1
4918
import CASTBridging import SwiftParser import SwiftSyntax extension ASTGenVisitor { public func visit(_ node: TypealiasDeclSyntax) -> ASTNode { let aliasLoc = self.base.advanced(by: node.typealiasKeyword.position.utf8Offset).raw let equalLoc = self.base.advanced(by: node.initializer.equal.position.utf8Offset).raw var nameText = node.identifier.text let name = nameText.withUTF8 { buf in return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) } let nameLoc = self.base.advanced(by: node.identifier.position.utf8Offset).raw let genericParams = node.genericParameterClause.map { self.visit($0).rawValue } let out = TypeAliasDecl_create( self.ctx, self.declContext, aliasLoc, equalLoc, name, nameLoc, genericParams) let oldDeclContext = declContext declContext = out.declContext defer { declContext = oldDeclContext } let underlying = self.visit(node.initializer.value).rawValue TypeAliasDecl_setUnderlyingTypeRepr(out.nominalDecl, underlying) return .decl(out.decl) } public func visit(_ node: StructDeclSyntax) -> ASTNode { let loc = self.base.advanced(by: node.position.utf8Offset).raw var nameText = node.identifier.text let name = nameText.withUTF8 { buf in return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) } let genericParams = node.genericParameterClause .map { self.visit($0).rawValue } let out = StructDecl_create(ctx, loc, name, loc, genericParams, declContext) let oldDeclContext = declContext declContext = out.declContext defer { declContext = oldDeclContext } node.members.members .map { self.visit($0).rawValue } .withBridgedArrayRef { ref in NominalTypeDecl_setMembers(out.nominalDecl, ref) } return .decl(out.decl) } public func visit(_ node: ClassDeclSyntax) -> ASTNode { let loc = self.base.advanced(by: node.position.utf8Offset).raw var nameText = node.identifier.text let name = nameText.withUTF8 { buf in return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) } let out = ClassDecl_create(ctx, loc, name, loc, declContext) let oldDeclContext = declContext declContext = out.declContext defer { declContext = oldDeclContext } node.members.members .map { self.visit($0).rawValue } .withBridgedArrayRef { ref in NominalTypeDecl_setMembers(out.nominalDecl, ref) } return .decl(out.decl) } public func visit(_ node: VariableDeclSyntax) -> ASTNode { let pattern = visit(node.bindings.first!.pattern).rawValue let initializer = visit(node.bindings.first!.initializer!).rawValue let loc = self.base.advanced(by: node.position.utf8Offset).raw let isStateic = false // TODO: compute this let isLet = node.letOrVarKeyword.tokenKind == .letKeyword // TODO: don't drop "initializer" on the floor. return .decl( SwiftVarDecl_create( ctx, pattern, initializer, loc, isStateic, isLet, declContext)) } public func visit(_ node: FunctionParameterSyntax) -> ASTNode { let loc = self.base.advanced(by: node.position.utf8Offset).raw let firstName: UnsafeMutableRawPointer? let secondName: UnsafeMutableRawPointer? let type: UnsafeMutableRawPointer? if let nodeFirstName = node.firstName { var text = nodeFirstName.text firstName = text.withUTF8 { buf in SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) } } else { firstName = nil } if let nodeSecondName = node.secondName { var text = nodeSecondName.text secondName = text.withUTF8 { buf in SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) } } else { secondName = nil } if let typeSyntax = node.type { type = visit(typeSyntax).rawValue } else { type = nil } return .decl(ParamDecl_create(ctx, loc, loc, firstName, loc, secondName, type, declContext)) } public func visit(_ node: FunctionDeclSyntax) -> ASTNode { let loc = self.base.advanced(by: node.position.utf8Offset).raw var nameText = node.identifier.text let name = nameText.withUTF8 { buf in return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) } let body: ASTNode? if let nodeBody = node.body { body = visit(nodeBody) } else { body = nil } let returnType: ASTNode? if let output = node.signature.output { returnType = visit(output.returnType) } else { returnType = nil } let params = node.signature.input.parameterList.map { visit($0) } return .decl( params.withBridgedArrayRef { ref in FuncDecl_create( ctx, loc, false, loc, name, loc, false, nil, false, nil, loc, ref, loc, body?.rawValue, returnType?.rawValue, declContext) }) } }
apache-2.0
8001431653c420f4a281e8d027b73904
31.569536
97
0.684221
4.017974
false
false
false
false
soapyigu/LeetCode_Swift
String/TextJustification.swift
1
2302
/** * Question Link: https://leetcode.com/problems/text-justification/ * Primary idea: Iterate the words, keep track of the index of first word and the length * of the line. Insert spaces with fix spaces and extra spaces. * Time Complexity: O(n), Space Complexity: O(n) */ class TextJustification { func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] { var res = [String]() var last = 0, currentLineLength = 0 for (i, word) in words.enumerated() { if currentLineLength + word.count + (i - last) > maxWidth { res.append(buildLine(words, last, i - 1, maxWidth, currentLineLength)) last = i currentLineLength = 0 } currentLineLength += word.count } res.append(buildLastLine(words, last, words.count - 1, maxWidth)) return res } fileprivate func buildLine(_ words: [String], _ start: Int, _ end: Int, _ maxWidth: Int, _ currentLineLength: Int) -> String { var line = "" var extraSpaceNum = 0, spaceNum = 0 if end > start { extraSpaceNum = (maxWidth - currentLineLength) % (end - start) spaceNum = (maxWidth - currentLineLength) / (end - start) } else { spaceNum = maxWidth - currentLineLength } for i in start...end { line.append(words[i]) if start != end && i == end { break } for _ in 0..<spaceNum { line.append(" ") } if extraSpaceNum > 0 { line.append(" ") extraSpaceNum -= 1 } } return line } fileprivate func buildLastLine(_ words: [String], _ start: Int, _ end: Int, _ maxWidth: Int) -> String { var line = "" for i in start...end { line.append(words[i]) if i < end { line.append(" ") } } while line.count < maxWidth { line.append(" ") } return line } }
mit
23aa226f3093ea040169d0f62d1ac2f6
28.512821
130
0.466551
4.726899
false
false
false
false
h3rald/mal
swift/printer.swift
29
802
//****************************************************************************** // MAL - printer //****************************************************************************** import Foundation var MalValPrintReadably = true func with_print_readably<T>(print_readably: Bool, fn: () -> T) -> T { let old = MalValPrintReadably MalValPrintReadably = print_readably let result = fn() MalValPrintReadably = old return result } func pr_str(m: MalVal, _ print_readably: Bool = MalValPrintReadably) -> String { return with_print_readably(print_readably) { if is_string(m) { return print_readably ? escape(m.description) : m.description } if is_keyword(m) { return ":\(m.description)" } return m.description } }
mpl-2.0
e0df596d709793b3ded07747b7bfff8a
28.703704
80
0.497506
4.358696
false
false
false
false
achimk/Cars
Carthage/Checkouts/Validator/Validator/ValidatorTests/Rules/ValidationRuleComparisonTests.swift
1
2324
/* ValidationRuleComparisonTests.swift Validator Created by @adamwaite. Copyright (c) 2015 Adam Waite. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest @testable import Validator class ValidationRuleComparisonTests: XCTestCase { func testThatItCanValidateUsingAnIntegerRange() { let rule = ValidationRuleComparison<Int>(min: 5, max: 10, error: testError) let tooSmall = Validator.validate(input: 4, rule: rule) XCTAssertFalse(tooSmall.isValid) let tooLarge = Validator.validate(input: 11, rule: rule) XCTAssertFalse(tooLarge.isValid) for n in (5...10) { let valid = Validator.validate(input: n, rule: rule) XCTAssertTrue(valid.isValid) } } func testThatItCanValidateUsingADoubleRange() { let rule = ValidationRuleComparison<Double>(min: 5.0, max: 10.0, error: testError) let tooSmall = Validator.validate(input: 4.0, rule: rule) XCTAssertFalse(tooSmall.isValid) let tooLarge = Validator.validate(input: 10.1, rule: rule) XCTAssertFalse(tooLarge.isValid) for n in [5.4, 6.2, 7.7, 8.3, 9.1, 10.0] { let valid = Validator.validate(input: n, rule: rule) XCTAssertTrue(valid.isValid) } } }
mit
30616c2409bffcfc43161279733c83d0
32.681159
90
0.712134
4.393195
false
true
false
false
cornerstonecollege/402
Jorge_Juri/Mi_Ejemplo/CustomViews/CustomViews/CircleView.swift
2
2338
// // CircleView.swift // CustomViews // // Created by Luiz on 2016-10-13. // Copyright © 2016 Ideia do Luiz. All rights reserved. // import UIKit extension UIBezierPath { // create a custom method for the pen func setStrokeColor(color:UIColor) { color.setStroke() } func setFillColor(color:UIColor) { color.setFill() } } class CircleView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // the code below is in case that you will need an initial point // let initialPoint: CGPoint // // init(frame: CGRect, point: CGPoint) { // super.init(frame:frame) // self.initialPoint = point // } // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { let pen = UIBezierPath() let center = CGPoint(x: rect.size.width / 2, y: rect.size.height / 2) // make the circle let twoPi = CGFloat(M_PI) * 2 pen.addArc(withCenter: center, radius: rect.size.width / 2 - 5, startAngle: 0.0, endAngle: twoPi, clockwise: true) // configure and paint it //pen.lineWidth = 10.0 //pen.setStrokeColor(color: UIColor.clear) //pen.stroke() pen.setFillColor(color: UIColor.blue) pen.fill() //make the triangle let lastPoint = CGPoint(x: rect.size.width, y: rect.size.height) pen.move(to: lastPoint) pen.addLine(to: center) pen.addLine(to: CGPoint(x: center.x, y: center.y + 20)) pen.addLine(to: lastPoint) pen.close() // configure and paint it //pen.lineWidth = 10.0 //pen.setStrokeColor(color: UIColor.clear) //pen.stroke() pen.setFillColor(color: UIColor.blue) pen.fill() // pen.move(to: rect.origin) // pen.addLine(to: CGPoint(x: rect.width, y: rect.height)) // pen.lineWidth = 10.0 // // We are avoiding to do UIColor.black.setStroke() // pen.setStrokeColor(color: UIColor.black) // pen.stroke() } }
gpl-3.0
c6fcb6c948904bcea0b88bf4f7727aa1
28.2125
122
0.590929
3.88206
false
false
false
false
diatrevolo/GameplaykitPDA
GameplaykitPDA/GameplaykitPDA_ios/GameViewController.swift
1
1438
// // GameViewController.swift // GameplaykitPDA_ios // // Created by Roberto Osorio Goenaga on 8/13/15. // Copyright (c) 2015 Roberto Osorio Goenaga. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene(fileNamed:"GameScene") { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
apache-2.0
b97a42c3d683b4b1e4583bc51a63b7fe
26.132075
94
0.609179
5.44697
false
false
false
false
nwspeete-ibm/openwhisk
mobile/iOS/starterapp/OpenWhiskStarterApp/FilterForecast.swift
1
1926
/* * Copyright 2015-2016 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation func main(args:[String:Any]) -> [String:Any] { let NumDays = 2 var filteredForecasts = [[String:Any]]() #if os(Linux) if let forecasts = args["forecasts"] as? [Any] { for day in 0...(NumDays - 1) { if let forecast = forecasts[day] as? [String:Any] { var terse = [String:Any]() terse["dow"] = forecast["dow"] terse["narrative"] = forecast["narrative"] terse["min_temp"] = forecast["min_temp"] terse["max_temp"] = forecast["max_temp"] filteredForecasts.append(terse) } } } #else if let forecasts = args["forecasts"] as? [[String:AnyObject]] { for day in 0...(NumDays - 1) { let forecast = forecasts[day] as [String:AnyObject] var terse = [String:Any]() terse["dow"] = forecast["dow"] terse["narrative"] = forecast["narrative"] terse["min_temp"] = forecast["min_temp"] terse["max_temp"] = forecast["max_temp"] filteredForecasts.append(terse) } } #endif return [ "forecasts": filteredForecasts ] }
apache-2.0
cd8087dc4b5e0496576cffe3327c589d
35.339623
75
0.553998
4.214442
false
false
false
false
natecook1000/swift
stdlib/public/core/Join.swift
1
6108
//===--- Join.swift - Protocol and Algorithm for concatenation ------------===// // // 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 // //===----------------------------------------------------------------------===// /// A sequence that presents the elements of a base sequence of sequences /// concatenated using a given separator. @_fixed_layout // lazy-performance public struct JoinedSequence<Base : Sequence> where Base.Element : Sequence { public typealias Element = Base.Element.Element @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base @usableFromInline // FIXME(sil-serialize-all) internal var _separator: ContiguousArray<Element> /// Creates an iterator that presents the elements of the sequences /// traversed by `base`, concatenated using `separator`. /// /// - Complexity: O(`separator.count`). @inlinable // FIXME(sil-serialize-all) public init<Separator : Sequence>(base: Base, separator: Separator) where Separator.Element == Element { self._base = base self._separator = ContiguousArray(separator) } } extension JoinedSequence { /// An iterator that presents the elements of the sequences traversed /// by a base iterator, concatenated using a given separator. @_fixed_layout // lazy-performance public struct Iterator { @usableFromInline // lazy-performance internal var _base: Base.Iterator @usableFromInline // lazy-performance internal var _inner: Base.Element.Iterator? @usableFromInline // lazy-performance internal var _separatorData: ContiguousArray<Element> @usableFromInline // lazy-performance internal var _separator: ContiguousArray<Element>.Iterator? @_frozen // lazy-performance @usableFromInline // lazy-performance internal enum JoinIteratorState { case start case generatingElements case generatingSeparator case end } @usableFromInline // lazy-performance internal var _state: JoinIteratorState = .start /// Creates a sequence that presents the elements of `base` sequences /// concatenated using `separator`. /// /// - Complexity: O(`separator.count`). @inlinable // lazy-performance public init<Separator: Sequence>(base: Base.Iterator, separator: Separator) where Separator.Element == Element { self._base = base self._separatorData = ContiguousArray(separator) } } } extension JoinedSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element.Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. @inlinable // lazy-performance public mutating func next() -> Element? { while true { switch _state { case .start: if let nextSubSequence = _base.next() { _inner = nextSubSequence.makeIterator() _state = .generatingElements } else { _state = .end return nil } case .generatingElements: let result = _inner!.next() if _fastPath(result != nil) { return result } _inner = _base.next()?.makeIterator() if _inner == nil { _state = .end return nil } if !_separatorData.isEmpty { _separator = _separatorData.makeIterator() _state = .generatingSeparator } case .generatingSeparator: let result = _separator!.next() if _fastPath(result != nil) { return result } _state = .generatingElements case .end: return nil } } } } extension JoinedSequence: Sequence { /// Return an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // lazy-performance public func makeIterator() -> Iterator { return Iterator(base: _base.makeIterator(), separator: _separator) } @inlinable // lazy-performance public func _copyToContiguousArray() -> ContiguousArray<Element> { var result = ContiguousArray<Element>() let separatorSize: Int = numericCast(_separator.count) let reservation = _base._preprocessingPass { () -> Int in var r = 0 for chunk in _base { r += separatorSize + chunk.underestimatedCount } return r - separatorSize } if let n = reservation { result.reserveCapacity(numericCast(n)) } if separatorSize == 0 { for x in _base { result.append(contentsOf: x) } return result } var iter = _base.makeIterator() if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append(contentsOf: _separator) result.append(contentsOf: next) } } return result } } extension Sequence where Element : Sequence { /// Returns the concatenated elements of this sequence of sequences, /// inserting the given separator between each element. /// /// This example shows how an array of `[Int]` instances can be joined, using /// another `[Int]` instance as the separator: /// /// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] /// let joined = nestedNumbers.joined(separator: [-1, -2]) /// print(Array(joined)) /// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]" /// /// - Parameter separator: A sequence to insert between each of this /// sequence's elements. /// - Returns: The joined sequence of elements. @inlinable // lazy-performance public func joined<Separator : Sequence>( separator: Separator ) -> JoinedSequence<Self> where Separator.Element == Element.Element { return JoinedSequence(base: self, separator: separator) } }
apache-2.0
ea3d6284c8624700018990450ad2ef76
30.647668
80
0.640144
4.585586
false
false
false
false
natecook1000/swift
test/IRGen/type_layout.swift
2
7377
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize -DINT=i%target-ptrsize class C {} struct SSing { var x: Int64 } struct SMult { var x, y: Int64 } struct SMult2 { var x, y: C } struct SMult3 { var x, y: C } struct GSing<T> { var x: T } struct GMult<T> { var x, y: T } enum ESing { case X(Int64) } enum EMult { case X(Int64), Y(Int64) } @_alignment(4) struct CommonLayout { var x,y,z,w: Int8 } struct FourInts { var x,y,z,w: Int32 } @_alignment(16) struct AlignedFourInts { var x: FourInts } // CHECK: @"$S11type_layout14TypeLayoutTestVMn" = hidden constant {{.*}} @"$S11type_layout14TypeLayoutTestVMP" // CHECK: define internal %swift.type* @"$S11type_layout14TypeLayoutTestVMi" // CHECK: define internal swiftcc %swift.metadata_response @"$S11type_layout14TypeLayoutTestVMr" struct TypeLayoutTest<T> { // CHECK: [[TUPLE_LAYOUT_M:%.*]] = alloca %swift.full_type_layout, // CHECK: [[TUPLE_LAYOUT_N:%.*]] = alloca %swift.full_type_layout, // CHECK: [[TUPLE_LAYOUT_O:%.*]] = alloca %swift.full_type_layout, // CHECK: [[TUPLE_ELT_LAYOUTS_O:%.*]] = alloca i8**, [[INT]] 4, // -- dynamic layout, projected from metadata // CHECK: [[T0:%.*]] = call{{( tail)?}} swiftcc %swift.metadata_response @swift_checkMetadataState([[INT]] 319, %swift.type* %T) // CHECK: [[T_CHECKED:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: [[T_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1 // CHECK: [[T_OK:%.*]] = icmp ule [[INT]] [[T_STATUS]], 63 // CHECK: br i1 [[T_OK]], // CHECK: [[T0:%.*]] = bitcast %swift.type* [[T_CHECKED]] to i8*** // CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], {{i32|i64}} -1 // CHECK: [[T_VALUE_WITNESSES:%.*]] = load i8**, i8*** [[T1]] // CHECK: [[T_LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: store i8** [[T_LAYOUT]] var z: T // -- native class, use standard NativeObject value witness // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$SBoWV", i32 8) var a: C // -- Single-element struct, shares layout of its field (Builtin.Int64) // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$SBi64_WV", i32 8) var c: SSing // -- Multi-element structs use open-coded layouts // CHECK: store i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @type_layout_16_8_0_pod, i32 0, i32 0) var d: SMult // CHECK-64: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_16_8_[[REF_XI:[0-9a-f]+]]_bt, i32 0, i32 0) // CHECK-32: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_8_4_[[REF_XI:[0-9a-f]+]]_bt, i32 0, i32 0) var e: SMult2 // CHECK-64: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_16_8_[[REF_XI]]_bt, i32 0, i32 0) // CHECK-32: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_8_4_[[REF_XI]]_bt, i32 0, i32 0) var f: SMult3 // -- Single-case enum, shares layout of its field (Builtin.Int64) // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$SBi64_WV", i32 8) var g: ESing // -- Multi-case enum, open-coded layout // CHECK: store i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @type_layout_9_8_0_pod, i32 0, i32 0) var h: EMult // -- Single-element generic struct, shares layout of its field (T) // CHECK: [[T_LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: store i8** [[T_LAYOUT]] var i: GSing<T> // -- Multi-element generic struct, need to derive from metadata // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$S11type_layout5GMultVMa"([[INT]] 319, %swift.type* [[T_CHECKED]]) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_STATUS:%.*]] = extractvalue %swift.metadata_response [[TMP]], 1 // CHECK: [[METADATA_OK:%.*]] = icmp ule [[INT]] [[METADATA_STATUS]], 63 // CHECK: br i1 [[METADATA_OK]], // CHECK: [[T0:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], {{i32|i64}} -1 // CHECK: [[VALUE_WITNESSES:%.*]] = load i8**, i8*** [[T1]] // CHECK: [[LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[VALUE_WITNESSES]], i32 8 // CHECK: store i8** [[LAYOUT]] var j: GMult<T> // -- Common layout, reuse common value witness table layout // CHECK: store i8** getelementptr (i8*, i8** @"$SBi32_WV", i32 8) var k: CommonLayout // -- Single-field aggregate with alignment // CHECK: store i8** getelementptr (i8*, i8** @"$SBi128_WV", i32 8) var l: AlignedFourInts // -- Tuple with two elements // CHECK: [[T_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: [[T_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: call swiftcc [[INT]] @swift_getTupleTypeLayout2(%swift.full_type_layout* [[TUPLE_LAYOUT_M]], i8** [[T_LAYOUT_1]], i8** [[T_LAYOUT_2]]) // CHECK: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT_M]] to i8** // CHECK: store i8** [[T0]] var m: (T, T) // -- Tuple with three elements // CHECK: [[T_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: [[T_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: [[T_LAYOUT_3:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: call swiftcc { [[INT]], [[INT]] } @swift_getTupleTypeLayout3(%swift.full_type_layout* [[TUPLE_LAYOUT_N]], i8** [[T_LAYOUT_1]], i8** [[T_LAYOUT_2]], i8** [[T_LAYOUT_3]]) // CHECK: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT_N]] to i8** // CHECK: store i8** [[T0]] var n: (T, T, T) // -- Tuple with four elements // CHECK: [[T_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: store i8** [[T_LAYOUT_1]], i8*** [[TUPLE_ELT_LAYOUTS_O]], // CHECK: [[T_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: [[T0:%.*]] = getelementptr inbounds i8**, i8*** [[TUPLE_ELT_LAYOUTS_O]], i32 1 // CHECK: store i8** [[T_LAYOUT_2]], i8*** [[T0]], // CHECK: [[T_LAYOUT_3:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: [[T0:%.*]] = getelementptr inbounds i8**, i8*** [[TUPLE_ELT_LAYOUTS_O]], i32 2 // CHECK: store i8** [[T_LAYOUT_3]], i8*** [[T0]], // CHECK: [[T_LAYOUT_4:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: [[T0:%.*]] = getelementptr inbounds i8**, i8*** [[TUPLE_ELT_LAYOUTS_O]], i32 3 // CHECK: store i8** [[T_LAYOUT_4]], i8*** [[T0]], // CHECK: call swiftcc void @swift_getTupleTypeLayout(%swift.full_type_layout* [[TUPLE_LAYOUT_O]], i32* null, [[INT]] 4, i8*** [[TUPLE_ELT_LAYOUTS_O]]) // CHECK: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT_O]] to i8** // CHECK: store i8** [[T0]] var o: (T, T, T, T) }
apache-2.0
f6d5186e136d373367ef1078172bce93
61.516949
186
0.577199
3.08532
false
false
false
false
crossrails/compiler
tests/swift/src/src.swift
1
3509
import Foundation var this: JSInstance = try! JSContext().eval(Bundle(identifier: "io.xrails.src")!.path(forResource: "src", ofType: "js")!) extension JSProperty { static let booleanConst: JSProperty = "booleanConst" static let numberConst: JSProperty = "numberConst" static let stringConst: JSProperty = "stringConst" static let numberOrNullArrayConst: JSProperty = "numberOrNullArrayConst" static let numberArrayConst: JSProperty = "numberArrayConst" static let stringArrayArrayConst: JSProperty = "stringArrayArrayConst" static let anyConst: JSProperty = "anyConst" static let optionalBooleanConst: JSProperty = "optionalBooleanConst" static let optionalNumberConst: JSProperty = "optionalNumberConst" static let optionalStringConst: JSProperty = "optionalStringConst" static let optionalNumberArrayConst: JSProperty = "optionalNumberArrayConst" static let optionalNullAnyConst: JSProperty = "optionalNullAnyConst" static let optionalNonNullAnyConst: JSProperty = "optionalNonNullAnyConst" static let booleanVar: JSProperty = "booleanVar" static let numberVar: JSProperty = "numberVar" static let stringVar: JSProperty = "stringVar" static let numberArrayVar: JSProperty = "numberArrayVar" static let anyVar: JSProperty = "anyVar" static let stringArrayArrayVar: JSProperty = "stringArrayArrayVar" static let optionalBooleanVar: JSProperty = "optionalBooleanVar" static let optionalNumberVar: JSProperty = "optionalNumberVar" static let optionalStringVar: JSProperty = "optionalStringVar" static let optionalNumberArrayVar: JSProperty = "optionalNumberArrayVar" static let optionalAnyVar: JSProperty = "optionalAnyVar" static let voidNoArgFunctionCalled: JSProperty = "voidNoArgFunctionCalled" static let voidNoArgFunction: JSProperty = "voidNoArgFunction" static let stringNoArgFunction: JSProperty = "stringNoArgFunction" static let numberMultipleArgFunction: JSProperty = "numberMultipleArgFunction" static let stringNoArgLambda: JSProperty = "stringNoArgLambda" static let throwSimpleError: JSProperty = "throwSimpleError" static let SpecialError: JSProperty = "SpecialError" static let message: JSProperty = "message" static let throwSpecialError: JSProperty = "throwSpecialError" static let SimpleObject: JSProperty = "SimpleObject" static let staticVoidNoArgMethodCalled: JSProperty = "staticVoidNoArgMethodCalled" static let methodToOverrideCalled: JSProperty = "methodToOverrideCalled" static let staticVoidNoArgMethod: JSProperty = "staticVoidNoArgMethod" static let numberSingleObjectArgMethod: JSProperty = "numberSingleObjectArgMethod" static let callOverriddenMethod: JSProperty = "callOverriddenMethod" static let methodToOverride: JSProperty = "methodToOverride" static let upcastThisToObject: JSProperty = "upcastThisToObject" static let simpleObjectInstance: JSProperty = "simpleObjectInstance" static let anyObjectInstance: JSProperty = "anyObjectInstance" static let optionalAnyObjectInstance: JSProperty = "optionalAnyObjectInstance" static let simpleInterfaceInstanceCalled: JSProperty = "simpleInterfaceInstanceCalled" static let SimpleInterface: JSProperty = "SimpleInterface" static let voidNoArgMethod: JSProperty = "voidNoArgMethod" static let simpleInterfaceInstance: JSProperty = "simpleInterfaceInstance" static let acceptSimpleInterface: JSProperty = "acceptSimpleInterface" }
agpl-3.0
37d935b5dfb1474b34e2da549638d806
61.678571
122
0.791109
4.533592
false
false
false
false
alexanderedge/Toolbelt
Toolbelt/Toolbelt/Contacts.swift
1
3149
// // Contacts.swift // Toolbelt // // Created by Alexander G Edge on 07/08/2015. // Copyright © 2015 Alexander Edge. All rights reserved. // import Contacts // iOS 9 import AddressBook // iOS 8 @available(iOS 2.0, *) public func NSLocalizedStringFromName(_ givenName : String?, familyName : String?) -> String { if #available(iOS 9.0, *) { let contact = CNMutableContact() if let name = givenName { contact.givenName = name } if let name = familyName { contact.familyName = name } return CNContactFormatter.string(from: contact, style: .fullName)! } else { let record = ABPersonCreate().takeRetainedValue() if let name = givenName { ABRecordSetValue(record, kABPersonFirstNameProperty, name as CFTypeRef!, nil) } if let name = familyName { ABRecordSetValue(record, kABPersonLastNameProperty, name as CFTypeRef!, nil) } return ABRecordCopyCompositeName(record).takeRetainedValue() as String } } public struct Contacts { public enum AuthorisationStatus { case authorised, denied, restricted } public static func requestAccess(_ completion : ((AuthorisationStatus) -> Void)?) { if #available(iOS 9, *) { switch CNContactStore.authorizationStatus(for: .contacts) { case .notDetermined: CNContactStore().requestAccess(for: .contacts) { success, error in DispatchQueue.main.async { if success { completion?(.authorised) } else { completion?(.denied) } } } break case .authorized: DispatchQueue.main.async { completion?(.authorised) } break case .denied: DispatchQueue.main.async { completion?(.denied) } break case .restricted: DispatchQueue.main.async { completion?(.restricted) } break } } else { switch ABAddressBookGetAuthorizationStatus() { case .notDetermined: ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()) { granted, error in DispatchQueue.main.async { if granted { completion?(.authorised) } else { completion?(.denied) } } } break case .authorized: DispatchQueue.main.async { completion?(.authorised) } break case .denied: DispatchQueue.main.async { completion?(.denied) } break case .restricted: DispatchQueue.main.async { completion?(.restricted) } break } } } }
mit
053f2fb2c843c04d20fb81ff2cef9dd5
32.136842
138
0.513342
5.82963
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Settings/Cells/TeamSettingsHeaderCell.swift
1
5055
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import UIKit struct TeamSettingsHeaderCellContext: CellContext { let identifier: String = TeamSettingsHeaderCell.identifier let team: String let event: String let isLead: Bool } protocol TeamSettingsHeaderCellDelegate: AnyObject { func editImageButtonPressed(cell: TeamSettingsHeaderCell) } class TeamSettingsHeaderCell: ConfigurableTableViewCell { static let identifier = "TeamSettingsHeaderCell" weak var delegate: TeamSettingsHeaderCellDelegate? let teamImageView: WebImageView = { let webImageView = WebImageView() webImageView.layer.cornerRadius = 32 webImageView.image = Assets.uploadImageIcon.image webImageView.layer.borderWidth = 1 webImageView.layer.borderColor = UIColor.lightGray.cgColor webImageView.clipsToBounds = true webImageView.contentMode = .center return webImageView }() private let editImageButton: UIButton = { let button = UIButton(type: .custom) button.setTitle(Strings.TeamSettings.editImage, for: .normal) button.setTitleColor(Style.Colors.blue, for: .normal) button.backgroundColor = .red button.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .regular) button.layer.backgroundColor = .none return button }() let teamLabel = UILabel(typography: .title) private let eventLabel = UILabel(typography: .bodyRegular) override func commonInit() { super.commonInit() backgroundColor = Style.Colors.white teamLabel.textAlignment = .center eventLabel.textAlignment = .center contentView.addSubview(teamImageView) { $0.height.width.equalTo(Style.Size.s64) $0.top.equalToSuperview().offset(Style.Padding.p16) $0.leading.equalToSuperview().offset(Style.Padding.p32) } contentView.addSubview(editImageButton) { $0.top.equalTo(teamImageView.snp.bottom).offset(Style.Padding.p4) $0.width.equalTo(Style.Size.s96) $0.height.equalTo(Style.Size.s24) $0.centerX.equalTo(teamImageView.snp.centerX) // $0.bottom.equalToSuperview().inset(Style.Padding.p32) } contentView.addSubview(teamLabel) { $0.leading.equalTo(teamImageView.snp.trailing).offset(Style.Padding.p32) $0.top.equalToSuperview().offset(Style.Padding.p24) } contentView.addSubview(eventLabel) { $0.top.equalTo(teamLabel.snp.bottom).offset(Style.Padding.p8) $0.leading.equalTo(teamImageView.snp.trailing).offset(Style.Padding.p32) } editImageButton.addTarget(self, action: #selector(editImageButtonTapped), for: .touchUpInside) } func configure(context: CellContext) { guard let context = context as? TeamSettingsHeaderCellContext else { return } let teamImageURLString = AZSClient.buildImageURL(from: context.team) teamImageView.fadeInImage(imageURL: URL(string: teamImageURLString), placeHolderImage: Assets.uploadImageIcon.image) { (success) in if success { self.teamImageView.contentMode = .scaleAspectFill } else { self.teamImageView.contentMode = .center } } if context.isLead { editImageButton.alpha = 1 editImageButton.snp.makeConstraints { (make) in make.bottom.equalToSuperview().inset(Style.Padding.p8) } } else { editImageButton.alpha = 0 eventLabel.snp.makeConstraints { (make) in make.bottom.equalToSuperview().inset(Style.Padding.p24) } } contentView.layoutIfNeeded() teamLabel.text = context.team eventLabel.text = context.event } @objc func editImageButtonTapped() { delegate?.editImageButtonPressed(cell: self) } }
bsd-3-clause
7d23f37f1d813b3db46ca9e3ea2de3ca
37.580153
135
0.736644
4.30494
false
false
false
false
sarvex/SwiftRecepies
Basics/Displaying Long Lines of Text with UITextView/Displaying Long Lines of Text with UITextView/ViewController.swift
1
3321
// // ViewController.swift // Displaying Long Lines of Text with UITextView // // Created by Vandad Nahavandipoor on 6/29/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 /* 1 */ //import UIKit // //class ViewController: UIViewController { // // var textView: UITextView? // //} /* 2 */ //import UIKit // //class ViewController: UIViewController { // // var textView: UITextView? // // override func viewDidLoad() { // super.viewDidLoad() // // textView = UITextView(frame: view.bounds) // if let theTextView = textView{ // theTextView.text = "Some text goes here..." // // theTextView.contentInset = // UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) // // theTextView.font = UIFont.systemFontOfSize(16) // view.addSubview(theTextView) // } // // } // //} /* 3 */ import UIKit class ViewController: UIViewController { var textView: UITextView? let defaultContentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) func handleKeyboardDidShow (notification: NSNotification){ /* Get the frame of the keyboard */ let keyboardRectAsObject = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue /* Place it in a CGRect */ var keyboardRect = CGRectZero keyboardRectAsObject.getValue(&keyboardRect) /* Give a bottom margin to our text view that makes it reach to the top of the keyboard */ textView!.contentInset = UIEdgeInsets(top: defaultContentInset.top, left: 0, bottom: keyboardRect.height, right: 0) } func handleKeyboardWillHide(notification: NSNotification){ textView!.contentInset = defaultContentInset } override func viewDidLoad() { super.viewDidLoad() textView = UITextView(frame: view.bounds) if let theTextView = textView{ theTextView.text = "Some text goes here..." theTextView.font = UIFont.systemFontOfSize(16) theTextView.contentInset = defaultContentInset view.addSubview(theTextView) NSNotificationCenter.defaultCenter().addObserver( self, selector: "handleKeyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: "handleKeyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } }
isc
32ef96dcd70b4fe70d3542ec5dcfe7ab
26.229508
83
0.672388
4.341176
false
false
false
false
MrAlek/JSQDataSourcesKit
Source/TableViewDataSourceProvider.swift
1
7339
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://jessesquires.com/JSQDataSourcesKit // // // GitHub // https://github.com/jessesquires/JSQDataSourcesKit // // // License // Copyright © 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import CoreData import Foundation import UIKit /** A `TableViewDataSourceProvider` is responsible for providing a data source object for a table view. - warning: **Clients are responsbile for the following:** - Registering cells with the table view - Adding, removing, or reloading cells and sections as the provider's `sections` are modified. */ public final class TableViewDataSourceProvider<SectionInfo: SectionInfoProtocol, CellFactory: CellFactoryProtocol where CellFactory.Item == SectionInfo.Item, CellFactory.Cell: UITableViewCell>: CustomStringConvertible { // MARK: Typealiases /// The type of elements for the data source provider. public typealias Item = SectionInfo.Item // MARK: Properties /// The sections in the table view public var sections: [SectionInfo] /// Returns the cell factory for this data source provider. public let cellFactory: CellFactory /// Returns the object that provides the data for the table view. public var dataSource: UITableViewDataSource { return bridgedDataSource } // MARK: Initialization /** Constructs a new data source provider for a table view. - parameter sections: The sections to display in the table view. - parameter cellFactory: The cell factory from which the table view data source will dequeue cells. - parameter tableView: The table view whose data source will be provided by this provider. - returns: A new `TableViewDataSourceProvider` instance. */ public init(sections: [SectionInfo], cellFactory: CellFactory, tableView: UITableView? = nil) { self.sections = sections self.cellFactory = cellFactory tableView?.dataSource = dataSource } // MARK: Subscripts /** - parameter index: The index of the section to return. - returns: The section at `index`. */ public subscript (index: Int) -> SectionInfo { get { return sections[index] } set { sections[index] = newValue } } /** - parameter indexPath: The index path of the item to return. - returns: The item at `indexPath`. */ public subscript (indexPath: NSIndexPath) -> Item { get { return sections[indexPath.section].items[indexPath.row] } set { sections[indexPath.section].items[indexPath.row] = newValue } } // MARK: CustomStringConvertible /// :nodoc: public var description: String { get { return "<\(TableViewDataSourceProvider.self): sections=\(sections)>" } } // MARK: Private private lazy var bridgedDataSource: BridgedDataSource = { let dataSource = BridgedDataSource( numberOfSections: { [unowned self] () -> Int in return self.sections.count }, numberOfItemsInSection: { [unowned self] (section) -> Int in return self.sections[section].items.count }) dataSource.tableCellForRowAtIndexPath = { [unowned self] (tableView, indexPath) -> UITableViewCell in let item = self.sections[indexPath.section].items[indexPath.row] return self.cellFactory.cellFor(item: item, parentView: tableView, indexPath: indexPath) } dataSource.tableTitleForHeaderInSection = { [unowned self] (section) -> String? in return self.sections[section].headerTitle } dataSource.tableTitleForFooterInSection = { [unowned self] (section) -> String? in return self.sections[section].footerTitle } return dataSource }() } /** A `TableViewFetchedResultsDataSourceProvider` is responsible for providing a data source object for a table view that is backed by an `NSFetchedResultsController` instance. - warning: The `CellFactory.Item` type should correspond to the type of objects that the `NSFetchedResultsController` fetches. - note: Clients are responsbile for registering cells with the table view. */ public final class TableViewFetchedResultsDataSourceProvider <CellFactory: CellFactoryProtocol where CellFactory.Cell: UITableViewCell>: CustomStringConvertible { // MARK: Typealiases /// The type of elements for the data source provider. public typealias Item = CellFactory.Item // MARK: Properties /// Returns the fetched results controller that provides the data for the table view data source. public let fetchedResultsController: NSFetchedResultsController /// Returns the cell factory for this data source provider. public let cellFactory: CellFactory /// Returns the object that provides the data for the table view. public var dataSource: UITableViewDataSource { return bridgedDataSource } // MARK: Initialization /** Constructs a new data source provider for the table view. - parameter fetchedResultsController: The fetched results controller that provides the data for the table view. - parameter cellFactory: The cell factory from which the table view data source will dequeue cells. - parameter tableView: The table view whose data source will be provided by this provider. - returns: A new `TableViewFetchedResultsDataSourceProvider` instance. */ public init(fetchedResultsController: NSFetchedResultsController, cellFactory: CellFactory, tableView: UITableView? = nil) { assert(fetchedResultsController: fetchedResultsController, fetchesObjectsOfClass: Item.self as! AnyClass) self.fetchedResultsController = fetchedResultsController self.cellFactory = cellFactory tableView?.dataSource = dataSource } // MARK: CustomStringConvertible /// :nodoc: public var description: String { get { return "<\(TableViewFetchedResultsDataSourceProvider.self): fetchedResultsController=\(fetchedResultsController)>" } } // MARK: Private private lazy var bridgedDataSource: BridgedDataSource = { let dataSource = BridgedDataSource( numberOfSections: { [unowned self] () -> Int in return self.fetchedResultsController.sections?.count ?? 0 }, numberOfItemsInSection: { [unowned self] (section) -> Int in return (self.fetchedResultsController.sections?[section])?.numberOfObjects ?? 0 }) dataSource.tableCellForRowAtIndexPath = { [unowned self] (tableView, indexPath) -> UITableViewCell in let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Item return self.cellFactory.cellFor(item: item, parentView: tableView, indexPath: indexPath) } dataSource.tableTitleForHeaderInSection = { [unowned self] (section) -> String? in return (self.fetchedResultsController.sections?[section])?.name } return dataSource }() }
mit
4f15778f0386d844c52c113287f65ec7
32.66055
162
0.680294
5.407517
false
false
false
false
alexdrone/AmazonS3RequestManager
AmazonS3RequestManager/AmazonS3RequestManager.swift
1
10450
// // AmazonS3RequestManager.swift // AmazonS3RequestManager // // Based on `AFAmazonS3Manager` by `Matt Thompson` // // Created by Anthony Miller. 2015. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Alamofire // MARK: - Information /** MARK: Amazon S3 Regions The possible Amazon Web Service regions for the client. - USStandard: N. Virginia or Pacific Northwest - USWest1: Oregon - USWest2: N. California - EUWest1: Ireland - EUCentral1: Frankfurt - APSoutheast1: Singapore - APSoutheast2: Sydney - APNortheast1: Toyko - SAEast1: Sao Paulo */ public enum AmazonS3Region: String { case USStandard = "s3.amazonaws.com", USWest1 = "s3-us-west-1.amazonaws.com", USWest2 = "s3-us-west-2.amazonaws.com", EUWest1 = "s3-eu-west-1.amazonaws.com", EUCentral1 = "s3-eu-central-1.amazonaws.com", APSoutheast1 = "s3-ap-southeast-1.amazonaws.com", APSoutheast2 = "s3-ap-southeast-2.amazonaws.com", APNortheast1 = "s3-ap-northeast-1.amazonaws.com", SAEast1 = "s3-sa-east-1.amazonaws.com" } /** MARK: Amazon S3 Storage Classes The possible Amazon Web Service Storage Classes for an upload. For more information about these classes and when you might want to use one over the other, including the pros and cons of each selection, see https://aws.amazon.com/blogs/aws/new-amazon-s3-reduced-redundancy-storage-rrs/ - Standard: Default storage class for all uploads. "If you store 10,000 objects with us, on average we may lose one of them every 10 million years or so. This storage is designed in such a way that we can sustain the concurrent loss of data in two separate storage facilities." - ReducedRedundancy: Reduced Redundancy storage class. "If you store 10,000 objects with us, on average we may lose one of them every year. RRS is designed to sustain the loss of data in a single facility." */ public enum AmazonS3StorageClass: String { case Standard = "STANDARD", ReducedRedundancy = "REDUCED_REDUNDANCY" } /** MARK: - AmazonS3RequestManager `AmazonS3RequestManager` manages the serialization of requests and responses to the Amazon S3 service using `Alamofire.Manager`. */ public class AmazonS3RequestManager { // MARK: - Instance Properties public var requestSerializer: AmazonS3RequestSerializer /** The `Alamofire.Manager` instance to use for network requests. :note: This defaults to the shared instance of `Manager` used by top-level Alamofire requests. */ public var requestManager: Alamofire.Manager = Alamofire.Manager.sharedInstance // MARK: - Initialization /** Initalizes an `AmazonS3RequestManager` with the given Amazon S3 credentials. - parameter bucket: The Amazon S3 bucket for the client - parameter region: The Amazon S3 region for the client - parameter accessKey: The Amazon S3 access key ID for the client - parameter secret: The Amazon S3 secret for the client - returns: An `AmazonS3RequestManager` with the given Amazon S3 credentials and a default configuration. */ required public init(bucket: String?, region: AmazonS3Region, accessKey: String, secret: String) { requestSerializer = AmazonS3RequestSerializer(accessKey: accessKey, secret: secret, region: region, bucket: bucket) } // MARK: - GET Object Requests /** Gets and object from the Amazon S3 service and returns it as the response object without saving to file. :note: This method performs a standard GET request and does not allow use of progress blocks. - parameter path: The object path - returns: A GET request for the object */ public func getObject(path: String) -> Request { return requestManager.request(requestSerializer.amazonURLRequest(.GET, path: path)) .responseS3Data { (response) -> Void in } } /** Gets an object from the Amazon S3 service and saves it to file. :note: The user for the manager's Amazon S3 credentials must have read access to the object :dicussion: This method performs a download request that allows for a progress block to be implemented. For more information on using progress blocks, see `Alamofire`. - parameter path: The object path - parameter destinationURL: The `NSURL` to save the object to - returns: A download request for the object */ public func downloadObject(path: String, saveToURL destinationURL: NSURL) -> Request { return requestManager.download( requestSerializer.amazonURLRequest(.GET, path: path), destination: { (_, _) -> (NSURL) in return destinationURL }) } // MARK: PUT Object Requests /** Uploads an object to the Amazon S3 service with a given local file URL. :note: The user for the manager's Amazon S3 credentials must have read access to the bucket - parameter fileURL: The local `NSURL` of the file to upload - parameter destinationPath: The desired destination path, including the file name and extension, in the Amazon S3 bucket - parameter acl: The optional access control list to set the acl headers for the request. For more information see `AmazonS3ACL`. - returns: An upload request for the object */ public func putObject(fileURL: NSURL, destinationPath: String, acl: AmazonS3ACL? = nil, storageClass: AmazonS3StorageClass = .Standard) -> Request { let putRequest = requestSerializer.amazonURLRequest(.PUT, path: destinationPath, acl: acl, storageClass: storageClass) return requestManager.upload(putRequest, file: fileURL) } /** Uploads an object to the Amazon S3 service with the given data. :note: The user for the manager's Amazon S3 credentials must have read access to the bucket - parameter data: The `NSData` for the object to upload - parameter destinationPath: The desired destination path, including the file name and extension, in the Amazon S3 bucket - parameter acl: The optional access control list to set the acl headers for the request. For more information see `AmazonS3ACL`. - parameter storageClass: The optional storage class to use for the object to upload. If none is specified, standard is used. For more information see `AmazonS3StorageClass`. - returns: An upload request for the object */ public func putObject(data: NSData, destinationPath: String, acl: AmazonS3ACL? = nil, storageClass: AmazonS3StorageClass = .Standard) -> Request { let putRequest = requestSerializer.amazonURLRequest(.PUT, path: destinationPath, acl: acl, storageClass: storageClass) return requestManager.upload(putRequest, data: data) } // MARK: DELETE Object Request /** Deletes an object from the Amazon S3 service. :warning: Once an object has been deleted, there is no way to restore or undelete it. - parameter path: The object path - returns: The delete request */ public func deleteObject(path: String) -> Request { let deleteRequest = requestSerializer.amazonURLRequest(.DELETE, path: path) return requestManager.request(deleteRequest) } // MARK: ACL Requests /** Gets the access control list (ACL) for the current `bucket` :note: To use this operation, you must have the `AmazonS3ACLPermission.ReadACL` for the bucket. :see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETacl.html" - returns: A GET request for the bucket's ACL */ public func getBucketACL() -> Request { return requestManager.request(requestSerializer.amazonURLRequest(.GET, path: "", subresource: "acl", acl: nil)) } /** Sets the access control list (ACL) for the current `bucket` :note: To use this operation, you must have the `AmazonS3ACLPermission.WriteACL` for the bucket. :see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html" - returns: A PUT request to set the bucket's ACL */ public func setBucketACL(acl: AmazonS3ACL) -> Request { return requestManager.request(requestSerializer.amazonURLRequest(.PUT, path: "", subresource: "acl", acl: acl)) } /** Gets the access control list (ACL) for the object at the given path. :note: To use this operation, you must have the `AmazonS3ACLPermission.ReadACL` for the object. :see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETacl.html" - parameter path: The object path - returns: A GET request for the object's ACL */ public func getACL(forObjectAtPath path:String) -> Request { return requestManager.request(requestSerializer.amazonURLRequest(.GET, path: path, subresource: "acl")) } /** Sets the access control list (ACL) for the object at the given path. :note: To use this operation, you must have the `AmazonS3ACLPermission.WriteACL` for the object. :see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUTacl.html" - returns: A PUT request to set the objects's ACL */ public func setACL(forObjectAtPath path: String, acl: AmazonS3ACL) -> Request { return requestManager.request(requestSerializer.amazonURLRequest(.PUT, path: path, subresource: "acl", acl: acl)) } }
mit
a5dc452ab6469379b9488f2ea1e0fa2e
39.351351
280
0.73177
4.234198
false
false
false
false
yukiasai/Shoyu
ShoyuTests/SectionTests.swift
1
10274
// // SectionTest.swift // Shoyu // // Created by Asai.Yuki on 2015/12/14. // Copyright © 2015年 yukiasai. All rights reserved. // import XCTest class SectionTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testAddSingleRow() { let section = Section().add(row: Row()) XCTAssertEqual(section.rows.count, 1) } func testAddMultiRow() { let section = Section() section.add(row: Row()).add(row: Row()) XCTAssertEqual(section.rows.count, 2) // Method chain section.add(row: Row()).add(row: Row()).add(row: Row()) XCTAssertEqual(section.rows.count, 5) } func testAddRows() { let section = Section() section.add(rows: [Row(), Row()]) XCTAssertEqual(section.rows.count, 2) // Method chain section.add(rows: [Row(), Row(), Row()]) XCTAssertEqual(section.rows.count, 5) } func testCreateSingleRow() { let section = Section() { section in section.createRow { _ in } } XCTAssertEqual(section.rows.count, 1) } func testCreateMultiRow() { let section = Section() { section in section.createRow { _ in } section.createRow { _ in } } XCTAssertEqual(section.rows.count, 2) } func testCreateCountRows() { let count = UInt(10) let section = Section() { section in section.createRows(for: count) { _ in } } XCTAssertEqual(section.rows.count, Int(count)) } func testCreateMapArrayRows() { let items = [1, 2, 3] let section = Section() { section in section.createRows(for: items) { _ in } } XCTAssertEqual(section.rows.count, items.count) } func testCreateHeader() { let section = Section() { section in section.createHeader { _ in } } XCTAssertNotNil(section.header) } func testCreateFooter() { let section = Section() { section in section.createFooter { _ in } } XCTAssertNotNil(section.footer) } func testCreateHeaderFooter() { let section = Section() { section in section.createHeader { _ in } section.createFooter { _ in } } XCTAssertNotNil(section.header) XCTAssertNotNil(section.footer) } func testCreateHeaderGeneric() { let section = Section() { (section: Section<UILabel, UIButton>) in section.createHeader { header -> Void in header.configureView = { label, info in label.text = "label" } } section.createFooter { footer -> Void in footer.configureView = { button, info in button.titleLabel!.text = "button" } } } XCTAssertNotNil(section.header) XCTAssertNotNil(section.footer) } func testCreateRowsAndHeaderFooter() { let count = UInt(2) let items = [1, 2, 3] let section = Section() { section in section .createRow { _ in } .createRows(for: count) { _ in } .createRows(for: items) { _ in } .createHeader { _ in } .createFooter { _ in } } XCTAssertEqual(section.rows.count, 1 + Int(count) + items.count) XCTAssertNotNil(section.header) XCTAssertNotNil(section.footer) } func testRemoveRow() { let count = 10 let section = Section() { section in section.createRows(for: UInt(count)) { index, row in row.reuseIdentifier = String(index) } } XCTAssertEqual(section.rowCount, count) // Remove let removeIndex = 1 let row = section.removeRow(removeIndex) XCTAssertNotNil(row) XCTAssertEqual(section.rowCount, count - 1) // Validation section.rows.forEach { row in print(row.reuseIdentifier) XCTAssertNotEqual(Int(row.reuseIdentifier), removeIndex) } } func testInsertRow() { let count = 10 let section = Section() { section in section.createRows(for: UInt(count)) { _, _ in } } XCTAssertEqual(section.rowCount, count) section.insertRow(Row() { $0.reuseIdentifier = "last" }, index: count) section.insertRow(Row() { $0.reuseIdentifier = "first" }, index: 0) // Validation XCTAssertEqual(section.rowCount, count + 2) XCTAssertEqual(section.rows.first?.reuseIdentifier, "first") XCTAssertEqual(section.rows.last?.reuseIdentifier, "last") } func testConfigureHeaderFooterHeight() { let section = Section() // Initialized XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.heightFor(UITableView(), section: 0), nil) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.heightFor(UITableView(), section: 0), nil) // Constant section .createHeader { header in header.height = 10 } .createFooter { footer in footer.height = 11 } XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.heightFor(UITableView(), section: 0), 10) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.heightFor(UITableView(), section: 0), 11) // Configure height section .createHeader { header in header.heightFor = { _ -> CGFloat? in return 20 } } .createFooter { footer in footer.heightFor = { _ -> CGFloat? in return 21 } } XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.heightFor(UITableView(), section: 0), 20) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.heightFor(UITableView(), section: 0), 21) // Configure nil height section .createHeader { header in header.height = 30 header.heightFor = { _ -> CGFloat? in return nil } } .createFooter { footer in footer.height = 31 footer.heightFor = { _ -> CGFloat? in return nil } } XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.heightFor(UITableView(), section: 0), 30) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.heightFor(UITableView(), section: 0), 31) } func testConfigureHeaderFooterTitle() { let section = Section() let constantHeaderTitle = "header title" let constantFooterTitle = "footer title" let variableHeaderTitle = "header title for" let variableFooterTitle = "footer title for" // Initialized XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), nil) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), nil) // Constant section .createHeader { header in header.title = constantHeaderTitle }.createFooter { footer in footer.title = constantFooterTitle } XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), constantHeaderTitle) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), constantFooterTitle) // Title for section .createHeader { header in header.titleFor = { _ -> String? in return variableHeaderTitle } } .createFooter { footer in footer.titleFor = { _ -> String? in return variableFooterTitle } } XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), variableHeaderTitle) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), variableFooterTitle) // Both section .createHeader { header in header.title = constantHeaderTitle header.titleFor = { _ -> String? in return variableHeaderTitle } } .createFooter { footer in footer.title = constantFooterTitle footer.titleFor = { _ -> String? in return variableFooterTitle } } XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), variableHeaderTitle) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), variableFooterTitle) // Title for nil section .createHeader { header in header.title = constantHeaderTitle header.titleFor = { _ -> String? in return nil } } .createFooter { footer in footer.title = constantFooterTitle footer.titleFor = { _ -> String? in return nil } } XCTAssertEqual((section.header as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), constantHeaderTitle) XCTAssertEqual((section.footer as? SectionHeaderFooterDelegateType)?.titleFor(UITableView(), section: 0), constantFooterTitle) } }
mit
1a9eb06665005594e064b4d0aea5c50f
33.816949
134
0.556032
5.237634
false
true
false
false
Constructor-io/constructorio-client-swift
AutocompleteClientTests/FW/Logic/Worker/ConstructorIOSearchTests.swift
1
18961
// // ConstructorIOSearchTests.swift // AutocompleteClientTests // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import XCTest import ConstructorAutocomplete class ConstructorIOSearchTests: XCTestCase { var constructor: ConstructorIO! override func setUp() { super.setUp() self.constructor = ConstructorIO(config: TestConstants.testConfig) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSearch_CreatesValidRequest() { let query = CIOSearchQuery(query: "potato") let builder = CIOBuilder(expectation: "Calling Search should send a valid request.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=key_OucJxxrfiTVUQx0C&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_WithValidRequest_ReturnsNonNilResponse() { let expectation = self.expectation(description: "Calling Search with valid parameters should return a non-nil response.") let query = CIOSearchQuery(query: "potato") let dataToReturn = TestResource.load(name: TestResource.Response.searchJSONFilename) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), http(200, data: dataToReturn)) self.constructor.search(forQuery: query, completionHandler: { response in XCTAssertNotNil(response.data, "Calling Search with valid parameters should return a non-nil response.") expectation.fulfill() }) self.wait(for: expectation) } func testSearch_ReturnsErrorObject_IfAPIReturnsInvalidResponse() { let expectation = self.expectation(description: "Calling Search returns non-nil error if API errors out.") let query = CIOSearchQuery(query: "potato") stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), http(404)) self.constructor.search(forQuery: query, completionHandler: { response in XCTAssertNotNil(response.error, "Calling Search returns non-nil error if API errors out.") expectation.fulfill() }) self.wait(for: expectation) } func testSearch_AttachesPageParameter() { let query = CIOSearchQuery(query: "potato", page: 5) let builder = CIOBuilder(expectation: "Calling Search should send a valid request.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=5&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_AttachesCustomSectionParameter() { let customSection = "customSection" let query = CIOSearchQuery(query: "potato", section: customSection) let builder = CIOBuilder(expectation: "Calling Search should send a valid request.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=\(customSection)"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testRedirect_hasCorrectURL() { let exp = self.expectation(description: "Redirect response should have a correct URL.") stub(regex("https://ac.cnstrc.com/search/dior?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), http(200, data: TestResource.load(name: TestResource.Response.searchJSONRedirectFile))) self.constructor.search(forQuery: CIOSearchQuery(query: "dior")) { response in guard let redirectInfo = response.data?.redirectInfo else { XCTFail("Invalid response") return } XCTAssertEqual(redirectInfo.url, "/brand/dior") exp.fulfill() } self.waitForExpectationWithDefaultHandler() } func testRedirect_hasCorrectMatchID() { let exp = self.expectation(description: "Redirect response should have a correct Match ID.") stub(regex("https://ac.cnstrc.com/search/dior?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), http(200, data: TestResource.load(name: TestResource.Response.searchJSONRedirectFile))) self.constructor.search(forQuery: CIOSearchQuery(query: "dior")) { response in guard let redirectInfo = response.data?.redirectInfo else { XCTFail("Invalid response") return } XCTAssertEqual(redirectInfo.matchID, 16257) exp.fulfill() } self.waitForExpectationWithDefaultHandler() } func testRedirect_hasCorrectRuleID() { let exp = self.expectation(description: "Redirect response should have a correct Rule ID.") stub(regex("https://ac.cnstrc.com/search/dior?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), http(200, data: TestResource.load(name: TestResource.Response.searchJSONRedirectFile))) self.constructor.search(forQuery: CIOSearchQuery(query: "dior")) { response in guard let redirectInfo = response.data?.redirectInfo else { XCTFail("Invalid response") return } XCTAssertEqual(redirectInfo.ruleID, 8860) exp.fulfill() } self.waitForExpectationWithDefaultHandler() } func testSearch_AttachesGroupFilter() { let query = CIOSearchQuery(query: "potato", filters: CIOQueryFilters(groupFilter: "151", facetFilters: nil)) let builder = CIOBuilder(expectation: "Calling Search with a group filter should have a group_id URL query item.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&filters%5Bgroup_id%5D=151&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_AttachesFacetFilter() { let facetFilters = [(key: "facet1", value: "Organic")] let query = CIOSearchQuery(query: "potato", filters: CIOQueryFilters(groupFilter: nil, facetFilters: facetFilters)) let builder = CIOBuilder(expectation: "Calling Search with a facet filter should have a facet filter URL query item.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&filters%5Bfacet1%5D=Organic&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_AttachesMultipleFacetFilters() { let facetFilters = [(key: "facet1", value: "Organic"), (key: "facet2", value: "Natural"), (key: "facet10", value: "Whole-grain")] let query = CIOSearchQuery(query: "potato", filters: CIOQueryFilters(groupFilter: nil, facetFilters: facetFilters)) let builder = CIOBuilder(expectation: "Calling Search with multiple facet filters should have a multiple facet URL query items.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&filters%5Bfacet10%5D=Whole-grain&filters%5Bfacet1%5D=Organic&filters%5Bfacet2%5D=Natural&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_AttachesMultipleFacetFiltersWithSameNameButDifferentValues() { let facetFilters = [(key: "facetOne", value: "Organic"), (key: "facetOne", value: "Natural"), (key: "facetOne", value: "Whole-grain")] let query = CIOSearchQuery(query: "potato", filters: CIOQueryFilters(groupFilter: nil, facetFilters: facetFilters)) let builder = CIOBuilder(expectation: "Calling Search with multiple facet filters with the same name should have a multiple facet URL query items", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&filters%5BfacetOne%5D=Natural&filters%5BfacetOne%5D=Organic&filters%5BfacetOne%5D=Whole-grain&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_AttachesVariationsMap() { let groupByOptions = [GroupByOption(name: "Country", field: "data.facets.Country")] let valueOption = ValueOption(aggregation: "min", field: "data.facets.price") let query = CIOSearchQuery(query: "potato", variationsMap: CIOQueryVariationsMap(GroupBy: groupByOptions, Values: ["price" : valueOption], Dtype: "array")) let builder = CIOBuilder(expectation: "Calling Search with variations map should have a URL query variations map", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products&variations_map=%7B%22dtype%22:%22array%22,%22group_by%22:%5B%7B%22name%22:%22Country%22,%22field%22:%22data.facets.Country%22%7D%5D,%22values%22:%7B%22price%22:%7B%22field%22:%22data.facets.price%22,%22aggregation%22:%22min%22%7D%7D%7D"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_WithPlusSignInQueryParams_ShouldBeEncoded() { let facetFilters = [ (key: "size", value: "6+"), (key: "age", value: "10+") ] let queryFilters = CIOQueryFilters(groupFilter: nil, facetFilters: facetFilters) let query = CIOSearchQuery(query: "potato", filters: queryFilters) let builder = CIOBuilder(expectation: "Calling Search with 200 should return a response", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&filters%5Bage%5D=10%2B&filters%5Bsize%5D=6%2B&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query) { _ in } self.wait(for: builder.expectation) } func testSearch_AttachesGroupsSortOption() { let groupsSortOption = CIOGroupsSortOption(sortBy: .value, sortOrder: .ascending) let query = CIOSearchQuery(query: "potato", groupsSortOption: groupsSortOption) let builder = CIOBuilder(expectation: "Calling Search with 200 should return a response", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&fmt_options%5Bgroups_sort_by%5D=value&fmt_options%5Bgroups_sort_order%5D=ascending&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query) { _ in } self.wait(for: builder.expectation) } func testSearch_UsingSearchQueryBuilder_WithValidRequest_ReturnsNonNilResponse() { let query = CIOSearchQueryBuilder(query: "potato").build() let builder = CIOBuilder(expectation: "Calling Search with valid parameters should return a non-nil response.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_UsingSearchQueryBuilder_AttachesPageParams() { let query = CIOSearchQueryBuilder(query: "potato") .setPage(5) .setPerPage(50) .build() let builder = CIOBuilder(expectation: "Calling Search with valid parameters should return a non-nil response.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=50&page=5&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_UsingSearchQueryBuilder_AttachesSortOption() { let sortOption = CIOSortOption(json: [ "sort_by": "relevance", "sort_order": "descending", "status": "selected", "display_name": "Relevance" ]) let query = CIOSearchQueryBuilder(query: "potato") .setSortOption(sortOption!) .build() let builder = CIOBuilder(expectation: "Calling Search with valid parameters should return a non-nil response.", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products&sort_by=relevance&sort_order=descending"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_UsingSearchQueryBuilder_AttachesFacetFilters() { let facetFilters = [(key: "facetOne", value: "Organic"), (key: "facetOne", value: "Natural"), (key: "facetOne", value: "Whole-grain")] let query = CIOSearchQueryBuilder(query: "potato") .setPage(5) .setPerPage(50) .setFilters(CIOQueryFilters(groupFilter: nil, facetFilters: facetFilters)) .build() let builder = CIOBuilder(expectation: "Calling Search with multiple facet filters with the same name should have a multiple facet URL query items", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&filters%5BfacetOne%5D=Natural&filters%5BfacetOne%5D=Organic&filters%5BfacetOne%5D=Whole-grain&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=50&page=5&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_UsingSearchQueryBuilder_AttachesHiddenFields() { let hiddenFields = ["hidden_field_1", "hidden_field_2"] let query = CIOSearchQueryBuilder(query: "potato") .setHiddenFields(hiddenFields) .build() let builder = CIOBuilder(expectation: "Calling Search with multiple facet filters with the same name should have a multiple facet URL query items", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&fmt_options%5Bhidden_fields%5D=hidden_field_1&fmt_options%5Bhidden_fields%5D=hidden_field_2&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_UsingSearchQueryBuilder_AttachesHiddenFacets() { let hiddenFacets = ["hidden_facet_1", "hidden_facet_2"] let query = CIOSearchQueryBuilder(query: "potato") .setHiddenFacets(hiddenFacets) .build() let builder = CIOBuilder(expectation: "Calling Search with multiple facet filters with the same name should have a multiple facet URL query items", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&fmt_options%5Bhidden_facets%5D=hidden_facet_1&fmt_options%5Bhidden_facets%5D=hidden_facet_2&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query, completionHandler: { response in }) self.wait(for: builder.expectation) } func testSearch_UsingSearchQueryBuilder_AttachesGroupsSortOption() { let groupsSortOption = CIOGroupsSortOption(sortBy: .value, sortOrder: .ascending) let query = CIOSearchQueryBuilder(query: "potato") .setGroupsSortOption(groupsSortOption) .build() let builder = CIOBuilder(expectation: "Calling Search with 200 should return a response", builder: http(200)) stub(regex("https://ac.cnstrc.com/search/potato?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&fmt_options%5Bgroups_sort_by%5D=value&fmt_options%5Bgroups_sort_order%5D=ascending&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&num_results_per_page=30&page=1&s=\(kRegexSession)&section=Products"), builder.create()) self.constructor.search(forQuery: query) { _ in } self.wait(for: builder.expectation) } }
mit
2e9491ec8a9d4b017e46bb650adb0dee
57.69969
470
0.695886
3.941788
false
true
false
false
marklin2012/JDUtil
JDUtilDemo/JDUtilDemo/JDUtil/JDUIView.swift
3
3836
// // JDUIView.swift // JDUtilDemo // // Created by O2.LinYi on 15/12/24. // Copyright © 2015年 jd.com. All rights reserved. // import UIKit // MARK: - View Tree public extension UIView { public func topView () -> UIView? { var topView = superview while topView != nil && topView?.superview != nil { topView = topView!.superview } return topView } public func removeSubviews () { removeSubViews(self.subviews) } public func removeSubViews (views: [UIView]) { for view in views { view.removeFromSuperview() } } } // MARK: - Borders public extension UIView { public func addTopBorderWithColor(color: UIColor, width: CGFloat) { let border = CALayer() border.backgroundColor = color.CGColor border.frame = CGRectMake(0, 0, self.frame.size.width, width) self.layer.addSublayer(border) } public func addRightBorderWithColor(color: UIColor, width: CGFloat) { let border = CALayer() border.backgroundColor = color.CGColor border.frame = CGRectMake(self.frame.size.width - width, 0, width, self.frame.size.height) self.layer.addSublayer(border) } public func addBottomBorderWithColor(color: UIColor, width: CGFloat) { let border = CALayer() border.backgroundColor = color.CGColor border.frame = CGRectMake(0, self.frame.size.height - width, self.frame.size.width, width) self.layer.addSublayer(border) } public func addLeftBorderWithColor(color: UIColor, width: CGFloat) { let border = CALayer() border.backgroundColor = color.CGColor border.frame = CGRectMake(0, 0, width, self.frame.size.height) self.layer.addSublayer(border) } } // MARK: - Layers public extension UIView { public func getIndicator () -> UIActivityIndicatorView { var indicator: UIActivityIndicatorView! for subview in self.subviews { indicator = subview as? UIActivityIndicatorView if indicator != nil { break } } if indicator == nil { indicator = UIActivityIndicatorView(activityIndicatorStyle: .White) indicator.frame = self.frame indicator.center = self.center self.addSubview(indicator) } return indicator } public func getBlackDrop () -> CALayer { let BlackLayerName = "blackLayer" var blackLayer: CALayer! if self.layer.sublayers != nil { for layer in self.layer.sublayers! { if layer.name == BlackLayerName { blackLayer = layer break } } } if blackLayer == nil { blackLayer = CALayer() blackLayer.bounds = self.bounds blackLayer.frame.origin = CGPointZero blackLayer.backgroundColor = UIColor.blackColor().CGColor blackLayer.name = BlackLayerName self.layer.addSublayer(blackLayer) } return blackLayer } } // MARK: - Effects public extension UIView { public func flashScreen(duration: NSTimeInterval = 0.5) { let aView = UIView(frame: self.frame) aView.backgroundColor = UIColor.whiteColor() self.addSubview(aView) UIView.animateWithDuration( duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { aView.alpha = 0.0 }, completion: { done in aView.removeFromSuperview() }) } }
mit
77ab48ca3bfdafaac379849486568f0f
25.804196
98
0.572398
4.914103
false
false
false
false
sagardoshi/huddle
Huddle/huddleScratchPaper.playground/Contents.swift
1
2969
//: Playground - noun: a place where people can play import UIKit enum huddleColors { case huddleGreen case huddlePurple case huddlePink case huddleYellow case huddleGray case huddleWhite } extension huddleColors { var pickThisColor: UIColor { get { switch self { case .huddleGreen: return UIColor(red:0.26, green:0.71, blue:0.27, alpha:1.0) case .huddlePurple: return UIColor(red:0.30, green:0.31, blue:0.63, alpha:1.0) case .huddlePink: return UIColor(red:0.76, green:0.25, blue:0.36, alpha:1.0) case .huddleYellow: return UIColor(red:0.76, green:0.62, blue:0.24, alpha:1.0) case .huddleGray: return UIColor(red:0.35, green:0.35, blue:0.36, alpha:1.0) case .huddleWhite: return UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0) } } } } huddleColors.huddleWhite.pickThisColor enum quiz1Responses: String { case firstFail = "KEEP EXPERIMENTING!\n\nSaying anything to offer support is always better than saying nothing.\n\nDepending on the situation, starting a conversation with \"Are you okay?\" can often lead to a defensive answer, like \"I'm fine,\" which might shut down an avenue for help.\n\nWhen beginning a conversation to offer support, try asking a more open-ende question or a more direct offer to help that does not center on the person's need to be okay." case secondSucceed = "NICELY DONE!\n\nThis is a great way to lend a hand.\n\nIn a situation where someone might be suffering from a more serious condition, asking an open-ended question or being direct about your concern and desire to help is always a useful strategy.\n\nYou're off to a great start!" case thirdFail = "TRY AGAIN!\n\nSaying anything to offer support is always better than saying nothing.\n\nEspecially when a friend is in a specific situation where they're in need, immediately suggesting alternative advice without pursuing understanding first can often shut down the conversation or make them feel they cannot be trusted or that they lack control.\n\nThe most effective way to approach this situation is to express concern first." case fourthFail = "TRY AGAIN!\n\nSaying anything to offer support is always better than saying nothing.\n\nIt's possible that you are the only one who was in a position to notice something was wrong.\n\nWhen a friend might be dealing with a more serious situation, there will certainly be people who can offer professional support. However, you can be a medium between your friend and these resources that they may not know of or have the ability to access." case fifthOther = "NICE!\n\nSaying anything to offer support is always better than saying nothing.\n\nWhen beginning a conversation to offer support, asking open-ended questions or more direct offers to help are often effective strategies." } quiz1Responses.firstFail.rawValue
mit
b0021d4d3e8fa856e56eaad98af61396
59.591837
449
0.729539
3.816195
false
false
false
false
BurntCaramel/BurntCocoaUI
BurntCocoaUI/Target.swift
1
735
// // Target.swift // BurntCocoaUI // // Created by Patrick Smith on 27/04/2016. // Copyright © 2016 Burnt Caramel. All rights reserved. // import Cocoa public class Target : NSObject { fileprivate var onPerform: (_ sender: AnyObject?) -> () public init(onPerform: @escaping (_ sender: AnyObject?) -> ()) { self.onPerform = onPerform } @objc public func performed(_ sender: AnyObject?) { onPerform(sender) } public var action: Selector = #selector(Target.performed(_:)) } extension NSControl { public func setActionHandler(_ onPerform: @escaping (_ sender: AnyObject?) -> ()) -> Target { let target = Target(onPerform: onPerform) self.target = target self.action = target.action return target } }
mit
035b7b4abbc2fc6c57742fd770e41cfb
20.588235
94
0.678474
3.563107
false
false
false
false
AlexMcArdle/LooseFoot
LooseFoot/Views/AMCommentHeaderCellNode.swift
1
21259
// // AMCommentHeaderCellNode.swift // LooseFoot // // Created by Alexander McArdle on 2/17/17. // Copyright © 2017 Alexander McArdle. All rights reserved. // import AsyncDisplayKit import ChameleonFramework import FontAwesome_swift import UIColor_Hex_Swift import Toaster class AMCommentHeaderCellNode: ASCellNode { let link: AMLink let redditLoader: RedditLoader fileprivate let titleNode = ASTextNode() fileprivate let authorNode = ASTextNode() fileprivate let imageNode = ASNetworkImageNode() fileprivate let pointsNode = ASTextNode() fileprivate let commentsNode = ASTextNode() fileprivate let subredditNode = ASTextNode() fileprivate let authorFlairNode = ASTextNode() fileprivate let linkFlairNode = ASTextNode() fileprivate let goldNode = ASTextNode() fileprivate let nsfwNode = ASTextNode() fileprivate let spoilerNode = ASTextNode() fileprivate let voteNode = ASTextNode() fileprivate let distinguishedNode = ASTextNode() fileprivate let stickyNode = ASTextNode() fileprivate let overlayNode = ASDisplayNode() let middleStackSpec = ASStackLayoutSpec.vertical() let horizontalStackSpec = ASStackLayoutSpec.horizontal() let rightSideStackSpec = ASStackLayoutSpec.vertical() let leftSideStackSpec = ASStackLayoutSpec.vertical() let topRowStackSpec = ASStackLayoutSpec.horizontal() let bottomRowStackSpec = ASStackLayoutSpec.horizontal() var myView = UIView() var upvoteView = UILabel() var downvoteView = UILabel() var leftView = UILabel() var rightView = UILabel() var pointerView = UILabel() let linkFlairBackground = ASDisplayNode() let authorFlairBackground = ASDisplayNode() var linkFlairOverlay: ASBackgroundLayoutSpec? var authorFlairOverlay: ASBackgroundLayoutSpec? var topRowChildren: [ASLayoutElement]? var bottomRowChildren: [ASLayoutElement]? var leftSideChildren: [ASLayoutElement]? var horizontalStackChildren: [ASLayoutElement]? func followSwipeGesture(_ gestureRecognizer: UISwipeGestureRecognizer) { if gestureRecognizer.direction == .left { Toast(text: "swipe left: \(link.l.author)").show() redditLoader.vote(link: self.link, direction: .up) } else if gestureRecognizer.direction == .right { Toast(text: "swipe right: \(link.l.author)").show() redditLoader.vote(link: self.link, direction: .down) } } func setSelected() { //overlayNode.bounds = self.bounds overlayNode.layer.shadowColor = UIColor.white.cgColor overlayNode.layer.shadowOpacity = 0.75 overlayNode.layer.shadowOffset = CGSize(width: 0, height: -self.frame.height) overlayNode.layer.shadowRadius = 10 overlayNode.layer.shadowPath = UIBezierPath(rect: self.frame).cgPath } func setUnselected() { overlayNode.layer.shadowOpacity = 0 } func holdGesture(_ gestureRecognizer: UILongPressGestureRecognizer) { let location = gestureRecognizer.location(in: owningNode?.view) let state = gestureRecognizer.state setSelected() if(state == .began) { myView.frame = CGRect(x: 0, y: 0, width: 150, height: 150) upvoteView = UILabel() upvoteView.frame = CGRect(x: 50, y: 0, width: 50, height: 50) upvoteView.backgroundColor = .clear upvoteView.font = UIFont.fontAwesome(ofSize: 50) upvoteView.text = String.fontAwesomeIcon(name: .arrowUp) upvoteView.textColor = .orange downvoteView = UILabel() downvoteView.frame = CGRect(x: 50, y: 100, width: 50, height: 50) downvoteView.backgroundColor = .clear downvoteView.font = UIFont.fontAwesome(ofSize: 50) downvoteView.text = String.fontAwesomeIcon(name: .arrowDown) downvoteView.textColor = .flatSkyBlueDark rightView = UILabel() rightView.frame = CGRect(x: 100, y: 50, width: 50, height: 50) rightView.backgroundColor = .clear rightView.font = UIFont.fontAwesome(ofSize: 50) rightView.text = String.fontAwesomeIcon(name: .share) rightView.textColor = .flatWhite leftView = UILabel() leftView.frame = CGRect(x: 0, y: 50, width: 50, height: 50) leftView.backgroundColor = .clear leftView.font = UIFont.fontAwesome(ofSize: 50) leftView.text = String.fontAwesomeIcon(name: .ellipsisH) leftView.textColor = .flatWhiteDark pointerView.frame = CGRect(x: 74, y: 74, width: 2, height: 2) pointerView.text = "" pointerView.textColor = .clear pointerView.backgroundColor = .clear myView.center = CGPoint(x: location.x, y: location.y) myView.backgroundColor = .clear myView.addSubview(upvoteView) myView.addSubview(downvoteView) myView.addSubview(leftView) myView.addSubview(rightView) myView.addSubview(pointerView) owningNode?.view.addSubview(myView) } else if(state == .changed) { let insideLocation = gestureRecognizer.location(in: myView) //print(insideLocation) // //myView.center = CGPoint(x: location.x, y: location.y - 50) pointerView.center = gestureRecognizer.location(in: myView) for subview in myView.subviews { let pointerCenter = pointerView.center let subViewCenter = subview.center let xDist = pointerCenter.x - subViewCenter.x let yDist = pointerCenter.y - subViewCenter.y let distance = sqrt((xDist * xDist) + (yDist * yDist)) if(distance <= 40.0) { pointerView.center = subview.center subview.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) } else { subview.transform = CGAffineTransform(scaleX: 1, y: 1) } } } else { var distances: [CGFloat] = [] for subview in myView.subviews { if(subview == pointerView) { continue } let pointerCenter = pointerView.center let subViewCenter = subview.center let xDist = pointerCenter.x - subViewCenter.x let yDist = pointerCenter.y - subViewCenter.y let distance = sqrt((xDist * xDist) + (yDist * yDist)) if(distance <= 15.0) { print("selected: \(myView.subviews.index(of: subview)!)") } } pointerView.removeFromSuperview() for subview in myView.subviews { subview.removeFromSuperview() } myView.removeFromSuperview() myView = UIView() setUnselected() } } func addTouchRecognizers() { self.view.isUserInteractionEnabled = true // // Left Swipe // let leftRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(followSwipeGesture(_:))) // leftRecognizer.direction = .left // self.view.addGestureRecognizer(leftRecognizer) // // // Right Swipe // let rightRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(followSwipeGesture(_:))) // rightRecognizer.direction = .right // self.view.addGestureRecognizer(rightRecognizer) // Hold Gesture let holdRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(holdGesture(_:))) //holdRecognizer.numberOfTapsRequired = 1 //holdRecognizer.numberOfTouchesRequired = 1 holdRecognizer.allowableMovement = 10.0 holdRecognizer.minimumPressDuration = 0.35 self.view.addGestureRecognizer(holdRecognizer) // Touch Gesture //let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGesture(_:))) //self.view.addGestureRecognizer(tapRecognizer) // Pan gesture //let pangGesture = UIGestureRecognizer(target: self, action: #selector(panGesture2(_:))) // let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture(_:))) // panRecognizer.maximumNumberOfTouches = 1 // panRecognizer.minimumNumberOfTouches = 1 // // self.view.addGestureRecognizer(panRecognizer) } init(link: AMLink, loader: RedditLoader) { self.link = link self.redditLoader = loader // init the super super.init() addTouchRecognizers() topRowChildren = [subredditNode] bottomRowChildren = [authorNode] leftSideChildren = [imageNode] horizontalStackChildren = [middleStackSpec, rightSideStackSpec] self.automaticallyManagesSubnodes = true backgroundColor = .flatBlack // Check for vote switch link.l.likes { case .down: let text = NSMutableAttributedString(string: String.fontAwesomeIcon(name: .arrowDown), attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 15), NSForegroundColorAttributeName: UIColor.flatSkyBlue]) voteNode.attributedText = text case .up: let text = NSMutableAttributedString(string: String.fontAwesomeIcon(name: .arrowUp), attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 15), NSForegroundColorAttributeName: UIColor.orange]) voteNode.attributedText = text case .none: break } // Check for Image imageNode.shouldRenderProgressImages = true if(link.l.thumbnail.hasPrefix("http")) { imageNode.url = URL(string: link.l.thumbnail) horizontalStackChildren?.insert(imageNode, at: 0) } titleNode.attributedText = NSAttributedString.attributedString(string: link.l.title, fontSize: 16, color: .flatWhiteDark) subredditNode.attributedText = NSAttributedString.attributedString(string: link.l.subreddit, fontSize: 12, color: UIColor.flatSkyBlue) // Author node setup // Check for distinguishments (is that a word?) let authorColor: UIColor if let distinguish = link.l.distinguished { let string: NSAttributedString switch distinguish { case "moderator": string = NSAttributedString(string: String.fontAwesomeIcon(name: .shield), attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 12), NSForegroundColorAttributeName: UIColor.flatGreen]) authorColor = .flatGreen case "admin": string = NSAttributedString(string: String.fontAwesomeIcon(name: .idBadge), attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 12), NSForegroundColorAttributeName: UIColor.flatRed]) authorColor = .flatRed case "special": string = NSAttributedString(string: "S", attributes: [NSFontAttributeName: AppFont(size: 15, bold: true), NSForegroundColorAttributeName: UIColor.flatYellowDark]) authorColor = .flatYellowDark default: string = NSAttributedString(string: "") authorColor = .flatSand } if(string.string != "") { distinguishedNode.attributedText = string bottomRowChildren?.append(distinguishedNode) } } else { authorColor = .flatSand } authorNode.attributedText = NSAttributedString.attributedString(string: link.l.author, fontSize: 12, color: authorColor) var scoreString = String(link.l.score) if(link.l.score >= 1000) { scoreString = link.l.score.getFancyNumber()! } pointsNode.attributedText = NSAttributedString.attributedString(string: scoreString, fontSize: 12, color: .orange) commentsNode.attributedText = NSAttributedString.attributedString(string: String(link.l.numComments), fontSize: 12, color: .flatGray) // Check for Link Flair if(link.l.linkFlairText != "") { let flairString = link.l.linkFlairText.checkForBrackets() linkFlairNode.attributedText = NSAttributedString.attributedString(string: flairString, fontSize: 8, color: .flatWhite) linkFlairNode.textContainerInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) //linkFlairNode.borderWidth = 1.0 //linkFlairNode.borderColor = UIColor.flatWhiteDark.cgColor //linkFlairNode.cornerRadius = 10.0 linkFlairNode.truncationMode = .byTruncatingTail linkFlairNode.maximumNumberOfLines = 1 linkFlairBackground.clipsToBounds = true linkFlairBackground.borderColor = UIColor.flatGrayDark.cgColor linkFlairBackground.borderWidth = 5.0 linkFlairBackground.cornerRadius = 5 linkFlairBackground.backgroundColor = .flatGrayDark linkFlairOverlay = ASBackgroundLayoutSpec(child: linkFlairNode, background: linkFlairBackground) topRowChildren?.append(linkFlairOverlay!) } // Check for Author Flair if(link.l.authorFlairText != "") { let flairString = link.l.authorFlairText.checkForBrackets() authorFlairNode.attributedText = NSAttributedString.attributedString(string: flairString, fontSize: 8, color: .flatWhite) authorFlairNode.textContainerInset = UIEdgeInsets(top: 0, left: 2, bottom: 1, right: 2) // authorFlairNode.borderWidth = 1.0 // authorFlairNode.borderColor = UIColor.flatGrayDark.cgColor // authorFlairNode.cornerRadius = 3.0 authorFlairNode.truncationMode = .byTruncatingTail authorFlairNode.maximumNumberOfLines = 1 authorFlairBackground.clipsToBounds = true authorFlairBackground.borderColor = UIColor.flatGrayDark.cgColor authorFlairBackground.borderWidth = 5.0 authorFlairBackground.cornerRadius = 5 authorFlairBackground.backgroundColor = .flatGrayDark authorFlairOverlay = ASBackgroundLayoutSpec(child: authorFlairNode, background: authorFlairBackground) bottomRowChildren?.append(authorFlairOverlay!) } // Check for NSFW if(link.l.over18) { nsfwNode.attributedText = NSAttributedString.attributedString(string: "NSFW", fontSize: 10, color: .flatRedDark) nsfwNode.textContainerInset = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2) nsfwNode.borderWidth = 1.0 nsfwNode.borderColor = UIColor.flatRedDark.cgColor nsfwNode.cornerRadius = 3.0 topRowChildren?.insert(nsfwNode, at: 0) } // Check for Spoiler if(link.l.spoiler) { spoilerNode.attributedText = NSAttributedString.attributedString(string: "SPOILER", fontSize: 10, color: .flatWhite) spoilerNode.textContainerInset = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2) spoilerNode.borderWidth = 1.0 spoilerNode.borderColor = UIColor.flatWhite.cgColor spoilerNode.cornerRadius = 3.0 topRowChildren?.insert(spoilerNode, at: 0) } // Check for Gold if(link.l.gilded > 0) { //goldNode.attributedText = NSAttributedString.attributedString(string: String(link.l.gilded), fontSize: 12, color: UIColor("#ffd700")) let goldSymbol = NSMutableAttributedString(string: String.fontAwesomeIcon(name: .star), attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 12)]) let text: NSMutableAttributedString = goldSymbol // Add count if more than one (disabled) //if(link.l.gilded > 1) { let count = NSMutableAttributedString(string: "x\(link.l.gilded)", attributes: [NSFontAttributeName: AppFont(size: 12, bold: false)]) text.append(count) //} text.addAttribute(NSForegroundColorAttributeName, value: UIColor(hexString: "FFD700")!, range: NSRange(location: 0, length: text.length)) goldNode.attributedText = text as NSAttributedString topRowChildren?.append(goldNode) } // Check for Sticky if(link.l.stickied) { stickyNode.attributedText = NSAttributedString(string: String.fontAwesomeIcon(name: .thumbTack), attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 12), NSForegroundColorAttributeName: UIColor.flatSkyBlue]) topRowChildren?.insert(stickyNode, at: 0) } // Setup Overlay //overlayNode.layer.shadowPath = UIBezierPath(rect: overlayNode.bounds).cgPath } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { //debugPrint(constrainedSize) // Make the images pretty if(link.l.thumbnail.hasPrefix("http")) { let imageSize = CGSize(width: 60, height: 60) imageNode.style.preferredSize = imageSize imageNode.imageModificationBlock = { image in let width: CGFloat var color: UIColor? = nil if(self.link.l.over18) { width = 5 color = UIColor.flatRed } else { width = 0 } return image.makeRoundedImage(size: imageSize, borderWidth: width, color: color) } } else { imageNode.style.preferredSize = CGSize(width: 0, height: 0) } let voteNodeSpec = ASRelativeLayoutSpec() let pointsNodeSpec = ASRelativeLayoutSpec() let commentsNodeSpec = ASRelativeLayoutSpec() let overlayStackSpec = ASOverlayLayoutSpec() let overlayCenterSpec = ASCenterLayoutSpec() linkFlairNode.style.flexGrow = 1.0 linkFlairNode.style.flexShrink = 1.0 authorFlairNode.style.flexGrow = 1.0 authorFlairNode.style.flexShrink = 1.0 topRowStackSpec.alignItems = .center topRowStackSpec.spacing = 5.0 topRowStackSpec.children = topRowChildren topRowStackSpec.style.flexShrink = 1.0 topRowStackSpec.style.flexGrow = 1.0 middleStackSpec.alignItems = .start middleStackSpec.spacing = 5.0 middleStackSpec.children = [topRowStackSpec, titleNode, bottomRowStackSpec] middleStackSpec.style.flexShrink = 1.0 middleStackSpec.style.flexGrow = 1.0 bottomRowStackSpec.alignItems = .center bottomRowStackSpec.spacing = 5.0 bottomRowStackSpec.children = bottomRowChildren bottomRowStackSpec.style.flexShrink = 1.0 bottomRowStackSpec.style.flexGrow = 1.0 leftSideStackSpec.alignItems = .center leftSideStackSpec.spacing = 5.0 leftSideStackSpec.children = [imageNode] pointsNodeSpec.verticalPosition = .start pointsNodeSpec.children = [pointsNode] pointsNodeSpec.horizontalPosition = .start commentsNodeSpec.verticalPosition = .start commentsNodeSpec.children = [commentsNode] commentsNodeSpec.horizontalPosition = .start voteNodeSpec.verticalPosition = .end voteNodeSpec.children = [voteNode] voteNodeSpec.horizontalPosition = .end rightSideStackSpec.alignItems = .center rightSideStackSpec.spacing = 5.0 rightSideStackSpec.children = [pointsNodeSpec, commentsNodeSpec, voteNodeSpec] horizontalStackSpec.alignItems = .start horizontalStackSpec.spacing = 5.0 horizontalStackSpec.children = horizontalStackChildren overlayNode.style.flexGrow = 1.0 overlayNode.style.flexShrink = 0 overlayCenterSpec.centeringOptions = .XY overlayCenterSpec.child = overlayNode overlayStackSpec.child = horizontalStackSpec overlayStackSpec.overlay = overlayCenterSpec return ASInsetLayoutSpec(insets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5), child: overlayStackSpec) } }
gpl-3.0
725e3c343ae214334250a1a72dc927cf
42.650924
166
0.618638
5.422959
false
false
false
false
bradhilton/Allegro
Sources/Metadata.swift
1
6275
// // Metadata.swift // Allegro // // Created by Bradley Hilton on 3/4/16. // Copyright © 2016 Brad Hilton. All rights reserved. // private var is64BitPlatform: Bool { return sizeof(Int) == sizeof(Int64) } protocol MetadataType { static var requiredKind: Metadata.Kind? { get } var pointer: UnsafePointer<Int> { get } } extension MetadataType { static var requiredKind: Metadata.Kind? { return nil } var valueWitnessTable: ValueWitnessTable { return ValueWitnessTable(pointer: UnsafePointer<Int>(bitPattern: pointer[-1])) } var kind: Metadata.Kind { return Metadata.Kind(flag: pointer[0]) } init?(type: Any.Type) { func cast<T>(type: Any.Type) -> T { return unsafeBitCast(type, T.self) } self = cast(type) if let requiredKind = self.dynamicType.requiredKind { guard kind == requiredKind else { return nil } } } } func instanceValue(instance: Any, isOfType type: Any.Type) -> Bool { if instance.dynamicType == type { return true } guard var subclass = Metadata.Class(type: instance.dynamicType), let superclass = Metadata.Class(type: type) else { return false } while let parentClass = subclass.superclass { if parentClass == superclass { return true } subclass = parentClass } return false } func ==(lhs: Any.Type, rhs: Any.Type) -> Bool { return Metadata(type: lhs) == Metadata(type: rhs) } func ==(lhs: MetadataType, rhs: MetadataType) -> Bool { return lhs.pointer == rhs.pointer } protocol NominalType : MetadataType { var nominalTypeDescriptor: NominalTypeDescriptor { get } } extension NominalType { var fieldTypes: [Any.Type]? { guard let function = nominalTypeDescriptor.fieldTypesAccessor else { return nil } return (0..<nominalTypeDescriptor.numberOfFields).map { unsafeBitCast(function(pointer).advancedBy($0).memory, Any.Type.self) } } var fieldOffsets: [Int]? { let vectorOffset = nominalTypeDescriptor.fieldOffsetVectorOffset guard vectorOffset != 0 else { return nil } return (0..<nominalTypeDescriptor.numberOfFields).map { pointer[vectorOffset + $0] } } } struct Metadata : MetadataType { let pointer: UnsafePointer<Int> init(type: Any.Type) { self = unsafeBitCast(type, Metadata.self) } enum Kind { case Struct case Class case Other init(flag: Int) { switch flag { case 1: self = .Struct case let x where x > 4096: self = .Class default: self = .Other } } } var metadataType: MetadataType? { switch kind { case .Struct: return unsafeBitCast(self, Struct.self) case .Class: return unsafeBitCast(self, Class.self) default: return nil } } var nominalType: NominalType? { switch kind { case .Struct: return unsafeBitCast(self, Struct.self) case .Class: return unsafeBitCast(self, Class.self) default: return nil } } struct Struct : NominalType { static var requiredKind = Kind.Struct let pointer: UnsafePointer<Int> var nominalTypeDescriptor: NominalTypeDescriptor { return NominalTypeDescriptor(pointer: UnsafePointer(bitPattern: pointer[1])) } } struct Class : NominalType { static var requiredKind = Kind.Class let pointer: UnsafePointer<Int> var superclass: Class? { return pointer[1] != 0 ? Class(pointer: UnsafePointer<Int>(bitPattern: pointer[1])) : nil } var nominalTypeDescriptor: NominalTypeDescriptor { return NominalTypeDescriptor(pointer: UnsafePointer(bitPattern: pointer[is64BitPlatform ? 8 : 11])) } } } // https://github.com/apple/swift/blob/40867560fd4229bfac812eda2a05c279faa76753/lib/IRGen/ValueWitness.h struct ValueWitnessTable { let pointer: UnsafePointer<Int> var size: Int { return pointer[17] } private var alignmentMask: Int { return 0x0FFFF } var align: Int { return (pointer[18] & alignmentMask) + 1 } var stride: Int { return pointer[19] } } struct NominalTypeDescriptor { let pointer: UnsafePointer<Int> enum Kind : Int { case Class, Struct } var kind: Kind? { return Kind(rawValue: pointer[0]) } var mangledName: String? { return String.fromCString(UnsafePointer<CChar>(bitPattern: pointer[1])) } var numberOfFields: Int { return Int(UnsafePointer<Int8>(pointer.advancedBy(2))[0]) } var fieldOffsetVectorOffset: Int { return Int(UnsafePointer<Int8>(pointer.advancedBy(2))[4]) } var fieldNames: [String] { var pointer = UnsafePointer<CChar>(bitPattern: self.pointer[is64BitPlatform ? 3 : 4]) return (0..<numberOfFields).map { _ in defer { while pointer.memory != 0 { pointer.advance() } pointer.advance() } return String.fromCString(pointer) ?? "" } } typealias FieldsTypeAccessor = @convention(c) UnsafePointer<Int> -> UnsafePointer<UnsafePointer<Int>> var fieldTypesAccessor: FieldsTypeAccessor? { return UnsafePointer<FieldsTypeAccessor?>(pointer.advancedBy(is64BitPlatform ? 4 : 5)).memory } } struct AnyExistentialContainer { var buffer: (Int, Int, Int) var type: Any.Type init(type: Any.Type, pointer: UnsafePointer<UInt8>) { self.type = type if sizeof(type) <= 3 * sizeof(Int) { self.buffer = UnsafePointer<(Int, Int, Int)>(pointer).memory } else { self.buffer = (pointer.hashValue, 0, 0) } } var any: Any { return unsafeBitCast(self, Any.self) } }
mit
2dd5406a71640e162ce65429be46046d
24.40081
119
0.586707
4.497491
false
false
false
false
Coderian/SwiftedGPX
SwiftedGPX/Elements/AGeoFdGPSData.swift
1
1581
// // AGeoFdGPSData.swift // SwiftedGPX // // Created by 佐々木 均 on 2016/02/16. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// GPX AGeoFdGPSData /// /// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd) /// /// <xsd:element name="ageofdgpsdata" type="xsd:decimal" minOccurs="0"> /// <xsd:annotation> /// <xsd:documentation> /// Number of seconds since last DGPS update. /// </xsd:documentation> /// </xsd:annotation> /// </xsd:element> public class AGeoFdGPSData : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue { public static var elementName: String = "ageofdgpsdata" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as WayPoint: v.value.ageofdgpsdata = self case let v as TrackPoint: v.value.ageofdgpsdata = self case let v as RoutePoint: v.value.ageofdgpsdata = self default: break } } } } public var value: Double! public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ self.value = Double(contents) self.parent = parent return parent } public required init(attributes:[String:String]){ super.init(attributes: attributes) } }
mit
2eaaec335aeaf21acd0b644c906afced
31.446809
90
0.603675
3.699029
false
false
false
false
gribozavr/swift
test/decl/var/variables.swift
1
4942
// RUN: %target-typecheck-verify-swift var t1 : Int var t2 = 10 var t3 = 10, t4 = 20.0 var (t5, t6) = (10, 20.0) var t7, t8 : Int var t9, t10 = 20 // expected-error {{type annotation missing in pattern}} var t11, t12 : Int = 20 // expected-error {{type annotation missing in pattern}} var t13 = 2.0, t14 : Int var (x = 123, // expected-error {{expected ',' separator}} {{7-7=,}} expected-error {{expected pattern}} y = 456) : (Int,Int) var bfx : Int, bfy : Int _ = 10 var self1 = self1 // expected-error {{variable used within its own initial value}} var self2 : Int = self2 // expected-error {{variable used within its own initial value}} var (self3) : Int = self3 // expected-error {{variable used within its own initial value}} var (self4) : Int = self4 // expected-error {{variable used within its own initial value}} var self5 = self5 + self5 // expected-error 2 {{variable used within its own initial value}} var self6 = !self6 // expected-error {{variable used within its own initial value}} var (self7a, self7b) = (self7b, self7a) // expected-error 2 {{variable used within its own initial value}} var self8 = 0 func testShadowing() { var self8 = self8 // expected-error {{variable used within its own initial value}} } var (paren) = 0 var paren2: Int = paren struct Broken { var b : Bool = True // expected-error{{use of unresolved identifier 'True'}} } // rdar://16252090 - Warning when inferring empty tuple type for declarations var emptyTuple = testShadowing() // expected-warning {{variable 'emptyTuple' inferred to have type '()'}} \ // expected-note {{add an explicit type annotation to silence this warning}} {{15-15=: ()}} // rdar://15263687 - Diagnose variables inferenced to 'AnyObject' var ao1 : AnyObject var ao2 = ao1 var aot1 : AnyObject.Type var aot2 = aot1 // expected-warning {{variable 'aot2' inferred to have type 'AnyObject.Type', which may be unexpected}} \ // expected-note {{add an explicit type annotation to silence this warning}} {{9-9=: AnyObject.Type}} for item in [AnyObject]() { // No warning in for-each loop. _ = item } // <rdar://problem/16574105> Type inference of _Nil very coherent but kind of useless var ptr = nil // expected-error {{'nil' requires a contextual type}} func testAnyObjectOptional() -> AnyObject? { let x = testAnyObjectOptional() return x } // SR-11511 Warning for inferring an array of empty tuples var arrayOfEmptyTuples = [""].map { print($0) } // expected-warning {{variable 'arrayOfEmptyTuples' inferred to have type '[()]'}} \ // expected-note {{add an explicit type annotation to silence this warning}} {{23-23=: [()]}} var maybeEmpty = Optional(arrayOfEmptyTuples) // expected-warning {{variable 'maybeEmpty' inferred to have type '[()]?'}} \ // expected-note {{add an explicit type annotation to silence this warning}} {{15-15=: [()]?}} var shouldWarnWithoutSugar = (arrayOfEmptyTuples as Array<()>) // expected-warning {{variable 'shouldWarnWithoutSugar' inferred to have type 'Array<()>'}} \ // expected-note {{add an explicit type annotation to silence this warning}} {{27-27=: Array<()>}} class SomeClass {} // <rdar://problem/16877304> weak let's should be rejected weak let V = SomeClass() // expected-error {{'weak' must be a mutable variable, because it may change at runtime}} let a = b ; let b = a // expected-error@-1 {{circular reference}} // expected-note@-2 {{through reference here}} // expected-note@-3 {{through reference here}} // expected-note@-4 {{through reference here}} // expected-note@-5 {{through reference here}} // expected-note@-6 {{through reference here}} // <rdar://problem/17501765> Swift should warn about immutable default initialized values let uselessValue : String? func tuplePatternDestructuring(_ x : Int, y : Int) { let (b: _, a: h) = (b: x, a: y) _ = h // <rdar://problem/20392122> Destructuring tuple with labels doesn't work let (i, j) = (b: x, a: y) _ = i+j // <rdar://problem/20395243> QoI: type variable reconstruction failing for tuple types let (x: g1, a: h1) = (b: x, a: y) // expected-error {{cannot convert value of type '(b: Int, a: Int)' to specified type '(x: Int, a: Int)'}} } // <rdar://problem/21057425> Crash while compiling attached test-app. func test21057425() -> (Int, Int) { let x: Int = "not an int!", y = 0 // expected-error{{cannot convert value of type 'String' to specified type 'Int'}} return (x, y) } // rdar://problem/21081340 func test21081340() { func foo() { } let (x: a, y: b): () = foo() // expected-error{{tuple pattern has the wrong length for tuple type '()'}} } // <rdar://problem/22322266> Swift let late initialization in top level control flow statements if true { let s : Int s = 42 // should be valid. _ = s }
apache-2.0
11b7d6a8ce482e995674ae87b34b1600
39.842975
156
0.654593
3.636497
false
true
false
false
dsmatter/SwiftSortUtils
Pod/Classes/NSSortDescriptor+CompareFunction.swift
1
976
// // NSSortDescriptor+CompareFunction.swift // Pods // // Created by Daniel Strittmatter on 06/10/15. // // import Foundation public extension NSSortDescriptor { /** Generates a compare function (suitable for Swift Arrays' sort methods) from a NSSortDescriptor. - returns: the generate compare function */ func toCompareFunction<T: AnyObject>() -> ((T, T) -> Bool) { return { (a, b) in self.compare(a, to: b) == ComparisonResult.orderedAscending } } } public extension Sequence where Self.Iterator.Element == NSSortDescriptor { /** Generates a compare function (suitable for Swift Arrays' sort methods) from a list of NSSortDescriptors - returns: the generated compare function */ func toCompareFunction<T: AnyObject>() -> ((T, T) -> Bool) { let compareFunctions: [(T, T) -> Bool] = map { $0.toCompareFunction() } return compareFunctions.reduce(identityCompareFunction(), combineCompareFunctions) } }
mit
dd28a998e20fc828a37a002bf9b1ab1f
23.4
86
0.684426
4.10084
false
false
false
false
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Mapping/Assortment+Convertible.swift
1
5797
// // Assortment+Convertible.swift // MoyskladNew // // Created by Anton Efimenko on 28.10.16. // Copyright © 2016 Andrey Parshakov. All rights reserved. // import Foundation //import Money extension MSAssortment { public static func from(dict: Dictionary<String, Any>) -> MSEntity<MSAssortment>? { guard let meta = MSMeta.from(dict: dict.msValue("meta"), parent: dict) else { return nil } return MSEntity.entity(MSAssortment(meta: meta, id: MSID(dict: dict), accountId: dict.value("accountId") ?? "", owner: MSEmployee.from(dict: dict.msValue("owner")), shared: dict.value("shared") ?? false, group: MSGroup.from(dict: dict.msValue("group")), info: MSInfo(dict: dict), code: dict.value("code"), externalCode: dict.value("externalCode"), archived: dict.value("archived") ?? false, pathName: dict.value("pathName"), vat: dict.value("vat"), effectiveVat: dict.value("effectiveVat"), productFolder: MSProductFolder.from(dict: dict.msValue("productFolder")), uom: MSUOM.from(dict: dict.msValue("uom")), image: MSImage.from(dict: dict.msValue("image")), minPrice: (dict.value("minPrice") ?? 0.0).toMoney(), buyPrice: MSPrice.from(dict: dict.msValue("buyPrice"), priceTypeOverride: LocalizedStrings.buyPrice.value), salePrices: (dict["salePrices"] as? [Any] ?? []).map { MSPrice.from(dict: $0 as? Dictionary<String, Any> ?? [:]) }.compactMap { $0 }, supplier: MSAgent.from(dict: dict.msValue("supplier")), country: MSCountry.from(dict: dict.msValue("country")), article: dict.value("article"), weighed: dict.value("weighed") ?? false, weight: dict.value("weight") ?? 0, volume: dict.value("volume") ?? 0, barcodes: stringsToBarcodes(values: (dict.value("barcodes") ?? [])), alcohol: MSAlcohol.from(dict: dict.msValue("alcoholic")), modificationsCount: dict.value("modificationsCount"), minimumBalance: dict.value("minimumBalance"), isSerialTrackable: dict.value("isSerialTrackable") ?? false, stock: dict.value("stock"), reserve: dict.value("reserve"), inTransit: dict.value("inTransit"), quantity: dict.value("quantity"), product: MSAssortment.from(dict: dict.msValue("product")), attributes: dict.msArray("attributes").map { MSAttribute.from(dict: $0) }.compactMap { $0 }, packs: (dict["packs"] as? [Any] ?? []).map { MSPack.from(dict: $0 as? Dictionary<String, Any> ?? [:]) }.compactMap { $0 }, localImage: nil, characteristics: dict.msArray("characteristics").map { MSVariantAttribute.from(dict: $0) }.compactMap { $0 }, components: dict.msValue("components").msArray("rows").map { MSBundleComponent.from(dict: $0) }.removeNils(), overhead: MSBundleOverhead.from(dict: dict.msValue("overhead")), assortment: MSAssortment.from(dict: dict.msValue("assortment")))) } public static func stringsToBarcodes(values: [String]) -> [MSBarcode] { return values.map({ return MSBarcode(value: $0, id: UUID().uuidString) }) } } extension MSAlcohol { public static func from(dict: Dictionary<String, Any>) -> MSAlcohol? { guard dict.keys.count > 0 else { return nil } return MSAlcohol(excise: dict.value("excise") ?? false, type: dict.value("type"), strength: dict.value("strength"), volume: dict.value("volume")) } } extension MSVariantAttribute { public static func from(dict: Dictionary<String, Any>) -> MSEntity<MSVariantAttribute>? { guard let meta = MSMeta.from(dict: dict.msValue("meta"), parent: dict) else { return nil } return MSEntity.entity(MSVariantAttribute(meta: meta, id: MSID(dict: dict), name: dict.value("name"), value: dict.value("value"), type: dict.value("type"), required: dict.value("required") ?? false)) } } extension MSProductFolder : DictConvertable { public func dictionary(metaOnly: Bool) -> Dictionary<String, Any> { var dict = [String: Any]() if meta.href.count > 0 { dict["meta"] = meta.dictionary() } return dict } public static func from(dict: Dictionary<String, Any>) -> MSEntity<MSProductFolder>? { guard dict.keys.count > 0 else { return nil } guard let meta = MSMeta.from(dict: dict.msValue("meta"), parent: dict) else { return nil } guard let name: String = dict.value("name"), name.count > 0 else { return MSEntity.meta(meta) } return MSEntity.entity(MSProductFolder(meta: meta, id: MSID(dict: dict), accountId: dict.value("accountId") ?? "", shared: dict.value("shared") ?? false, info: MSInfo(dict: dict), externalCode: dict.value("externalCode") ?? "", pathName: dict.value("pathName"))) } }
mit
3b1a9f74efa1db6b62f570c3a6112bad
46.121951
148
0.535542
4.264901
false
false
false
false
colemancda/Pedido
Pedido Admin/Pedido Admin/NetworkActivityIndicatorManager.swift
1
3902
// // NetworkActivityIndicatorManager.swift // PedidoAdmin // // Created by Alsey Coleman Miller on 1/30/15. // Copyright (c) 2015 ColemanCDA. All rights reserved. // import Foundation import UIKit final public class NetworkActivityIndicatorManager { // MARK: - Properties public let URLSession: NSURLSession public var managingNetworkActivityIndicator: Bool = false { didSet { if managingNetworkActivityIndicator == true { if self.timer == nil { self.timer = NSTimer(timeInterval: self.updateInterval, target: self, selector: "updateNetworkActivityIndicator", userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes) } self.timer!.fire() } else { self.timer?.invalidate() self.timer = nil } } } public let updateInterval: NSTimeInterval /** The minimum amount of time the activity indicator must be visible. Prevents blinks. */ public var minimumNetworkActivityIndicatorVisiblityInterval: NSTimeInterval // MARK: - Private Properties private var timer: NSTimer? private var lastNetworkActivityIndicatorVisibleState: Bool = false private var lastNetworkActivityIndicatorVisibleStateTransitionToTrue: NSDate? // MARK: - Initialization class var sharedManager: NetworkActivityIndicatorManager { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : NetworkActivityIndicatorManager? = nil } dispatch_once(&Static.onceToken) { Static.instance = NetworkActivityIndicatorManager() } return Static.instance! } public init(URLSession: NSURLSession = NSURLSession.sharedSession(), updateInterval: NSTimeInterval = 0.001, minimumNetworkActivityIndicatorVisiblityInterval: NSTimeInterval = 1) { self.URLSession = URLSession self.updateInterval = updateInterval self.minimumNetworkActivityIndicatorVisiblityInterval = minimumNetworkActivityIndicatorVisiblityInterval } // MARK: - Private Methods @objc private func updateNetworkActivityIndicator() { if self.lastNetworkActivityIndicatorVisibleStateTransitionToTrue != nil { let timeInterval = NSDate().timeIntervalSinceDate(lastNetworkActivityIndicatorVisibleStateTransitionToTrue!) if timeInterval < minimumNetworkActivityIndicatorVisiblityInterval { return } else { lastNetworkActivityIndicatorVisibleStateTransitionToTrue = nil } } self.URLSession.getTasksWithCompletionHandler { (dataTasks: [AnyObject]!, uploadTasks: [AnyObject]!, downloadTasks: [AnyObject]!) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in let networkActivityIndicatorVisible = Bool(dataTasks.count) if self.lastNetworkActivityIndicatorVisibleState == false && networkActivityIndicatorVisible == true { self.lastNetworkActivityIndicatorVisibleStateTransitionToTrue = NSDate() } UIApplication.sharedApplication().networkActivityIndicatorVisible = networkActivityIndicatorVisible self.lastNetworkActivityIndicatorVisibleState = networkActivityIndicatorVisible }) } } }
mit
a94bf68261138de8b500164477b30b62
33.848214
184
0.611225
6.845614
false
false
false
false
ntnhon/Learn-Swift-With-Playground
LearnSwiftWithPlayground.playground/Pages/Enum.xcplaygroundpage/Contents.swift
1
3938
/** https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html */ /********** 1st Example *************/ /** - Explicit define enums - If no type is provided, "Int" will be the default one but no default initializer is created. - By default the value of an enum is equal to it's name and hashValue (type "Int") starts from 0 */ enum CompassPoint { case North case South case East case West } /** CompassPoint(rawValue: 0) causes compile error because no default initializer is given */ print("Value of \(CompassPoint.North) is \(CompassPoint.North.hashValue)") // Prints "Value of North is 0" print("Value of \(CompassPoint.West) is \(CompassPoint.West.hashValue)") // Prints "Value of West is 3" /********** 2nd Example *************/ // Define enum with explicit "Int" type // No 1st default value => start from 0 enum Planet: Int { case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } // Create Earth Planet(rawValue: 2) // With 1st default value => start from given value enum Ocean: Int { case Pacific = 2, Atlantic, Indian, Southern, Arctic } // Create Indian Ocean(rawValue: 4) // Default value is set to enum other than the 1st one enum Season: Int { case Spring, Summer, Autumn = 6, Winter } print("Value of \(Season.Spring) is \(Season.Spring.rawValue)") // Prints "Value of Spring is 0" print("Value of \(Season.Summer) is \(Season.Summer.rawValue)") // Prints "Value of Summer is 1" print("Value of \(Season.Winter) is \(Season.Winter.rawValue)") // Prints "Value of Winter is 7" /********** 3rd Example *************/ // Define enum with explicit "String" type and initializer enum WebError: String { case BadRequest = "Bad request. Please check given request header." case PageNotFound = "The requested page is not existed." case Unknown = "Unknown error." init(errorCode: Int) { switch errorCode { case 400: self = .BadRequest case 404: self = .PageNotFound default: self = .Unknown } } } // BadRequest let requestError1 = WebError(errorCode: 400) // PageNotFound let requestError2 = WebError(errorCode: 404) // Unknown let requestError3 = WebError(errorCode: 500) /********** 4th Example *************/ /** Enum with associated value Enum can have functions and */ enum PostalCode { case Detail(cityCode: Int, localCode: Int) case Brief(String) func detailToBriefString() -> String { if case let PostalCode.Detail(cityCode, localCode) = self { return "\(cityCode + localCode)" } return self.toString() } func toDetail() -> PostalCode { if case let PostalCode.Brief(briefCode) = self { if let code = Int(briefCode) { let localCode = code % 1000 let cityCode = code - localCode return PostalCode.Detail(cityCode: cityCode, localCode: localCode) } // Better throw error return self } return self } func toString() -> String { switch self { case .Detail(_, _): return detailToBriefString() case .Brief(let briefCode): return briefCode } } } // Paris 13e let paris13eDetail = PostalCode.Detail(cityCode: 75000, localCode: 13) print(paris13eDetail.toString()) // Prints "75013" // Paris 20e let paris20eBrief = PostalCode.Brief("75020") print(paris20eBrief.toString()) // Prints "75020" // Create a detail postal code let paris20eDetail = paris20eBrief.toDetail() /********** 5th Example *************/ // Enum as a namespace containing constants enum Math { static let e = 2.718281828459045235360287 static let pi = 3.141592653589793238462643 } Math.e Math.pi
mit
66022f2183409c7a65a5b17103b3c0ec
23.159509
116
0.624683
3.868369
false
false
false
false
Zig1375/SwiftClickHouse
Sources/SwiftClickHouse/Core/Block/Columns/ColumnArray.swift
1
1594
import Foundation class ColumnArray { static func load(num_rows : UInt64, type : ClickHouseType, socketReader : SocketReader, nulls: [Bool]? = nil) -> [ClickHouseValue]? { let in_array_code : ClickHouseType; switch (type) { case let .Array(in_array) : in_array_code = in_array; default : return nil; } // Получаем смещения var offsets = [UInt64](); var prev_offset : UInt64 = 0; for _ in 0..<num_rows { if let offset : UInt64 = socketReader.readInt() { offsets.append(offset - prev_offset); prev_offset = offset; } } var list = [ClickHouseValue](); for i in 0..<num_rows { if let values = Block.loadColumnByType(num_rows: offsets[Int(i)], code: in_array_code, socketReader: socketReader) { list.append(ClickHouseValue(type : type, array : values)); } else { return nil; } } return list; } static func save (buffer : ByteBuffer, type : ClickHouseType, row : ClickHouseValue) { let in_array_code : ClickHouseType; switch (type) { case let .Array(in_array) : in_array_code = in_array; default : return; } let size = UInt64(row.val_array!.count); buffer.add(size); ClickHouseBlock.saveColumn(buffer: buffer, type: in_array_code, column: row.val_array!); } }
mit
5f293b014395abb480c9f5c6a3ccfed6
29.960784
137
0.520913
4.208
false
false
false
false
russbishop/Swift-Flow
SwiftFlow/CoreTypes/Store.swift
1
4329
// // Store.swift // SwiftFlow // // Created by Benjamin Encz on 11/28/15. // Copyright © 2015 DigiTales. All rights reserved. // import Foundation public protocol Store { init(reducer: AnyReducer, appState: StateType) init(reducer: AnyReducer, appState: StateType, middleware: [Middleware]) /// The current state stored in the store var appState: StateType { get } /** The main dispatch function that is used by all convenience `dispatch` methods. This dispatch function can be extended by providing middlewares. */ var dispatchFunction: DispatchFunction! { get } /** Subscribes the provided subscriber to this store. Subscribers will receive a call to `newState` whenever the state in this store changes. - parameter subscriber: Subscriber that will receive store updates */ func subscribe(subscriber: AnyStoreSubscriber) /** Unsubscribes the provided subscriber. The subscriber will no longer receive state updates from this store. - parameter subscriber: Subscriber that will be unsubscribed */ func unsubscribe(subscriber: AnyStoreSubscriber) /** Dispatches an action. This is the simplest way to modify the stores state. Example of dispatching an action: ```swift store.dispatch( CounterAction.IncreaseCounter ) ``` - parameter action: The action that is being dispatched to the store - returns: By default returns the dispatched action, but middlewares can change the return type, e.g. to return promises */ func dispatch(action: Action) -> Any /** Dispatches an action creator to the store. Action creators are functions that generate actions. They are called by the store and receive the current state of the application and a reference to the store as their input. Based on that input the action creator can either return an action or not. Alternatively the action creator can also perform an asynchronous operation and dispatch a new action at the end of it. Example of an action creator: ```swift func deleteNote(noteID: Int) -> ActionCreator { return { state, store in // only delete note if editing is enabled if (state.editingEnabled == true) { return NoteDataAction.DeleteNote(noteID) } else { return nil } } } ``` This action creator can then be dispatched as following: ```swift store.dispatch( noteActionCreatore.deleteNote(3) ) ``` - returns: By default returns the dispatched action, but middlewares can change the return type, e.g. to return promises */ func dispatch(actionCreatorProvider: ActionCreator) -> Any /** Dispatches an async action creator to the store. An async action creator generates an action creator asynchronously. Use this method if you want to wait for the state change triggered by the asynchronously generated action creator. */ func dispatch(asyncActionCreatorProvider: AsyncActionCreator) /** Dispatches an action and calls the callback as soon as the action has been processed. You will receive the updated store state as part of this callback. Example of dispatching an action and implementing a callback: ```swift store.dispatch( CounterAction.IncreaseCounter ) { state in print("New state: \(state)") } ``` - parameter action: The action that is being dispatched to the store - returns: By default returns the dispatched action, but middlewares can change the return type, e.g. to return promises */ func dispatch(action: Action, callback: DispatchCallback?) -> Any func dispatch(actionCreatorProvider: ActionCreator, callback: DispatchCallback?) -> Any func dispatch(asyncActionCreatorProvider: AsyncActionCreator, callback: DispatchCallback?) } public typealias DispatchCallback = (StateType) -> Void public typealias ActionCreator = (state: StateType, store: Store) -> Action? /// AsyncActionCreators allow the developer to wait for the completion of an async action public typealias AsyncActionCreator = (state: StateType, store: Store, actionCreatorCallback: ActionCreator -> Void) -> Void
mit
3fe8a66680a70813cbdb20daf4fe829c
35.066667
94
0.699168
5.079812
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/Bubble/NewBubbleResponseHandler.swift
1
2168
// // NewBubbleResponseHandler.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 UIKit import ObjectMapper class NewBubbleResponseHandler: ResponseHandler { fileprivate let completion: BubbleClousure? init(completion: BubbleClousure?) { self.completion = completion } override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) { if let response = response, let mapper = Mapper<BubbleMapper>().map(JSON: response["data"] as! [String : Any]) { let metadata = MappingUtils.metadataFromResponse(response) let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata) let bubble = Bubble(mapper: mapper, dataMapper: dataMapper) executeOnMainQueue { self.completion?(bubble, ErrorTransformer.errorFromResponse(response, error: error)) } } else { executeOnMainQueue { self.completion?(nil, ErrorTransformer.errorFromResponse(response, error: error)) } } } }
mit
661dd58aa33131a8ddbca00f7a50e948
44.166667
119
0.724631
4.662366
false
false
false
false
abdullah-chhatra/iDispatch
Example/Example/ViewController.swift
1
7954
// // ViewController.swift // Example // // Created by Abdulmunaf Chhatra on 5/20/15. // Copyright (c) 2015 Abdulmunaf Chhatra. All rights reserved. // import UIKit import iDispatch class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! let ITEM_CELL = "ITEM_CELL" let items = [ "Main Queue", "Global Queues", "Serial Queus", "Concurrent Queues", "Concurrent Queues - Barrier", "Concurrent Queues - Apply Sync", "Concurrent Queues - Apply Async", "Concurrent Queues - Map Sync", "Concurrent Queues - Map Async"] let printQueue = SerialQueue(label: "print_queue") let serialQueue1 = SerialQueue(label: "serial_queue_1") let concurrentQueue1 = ConcurrentQueue(label: "concurrent_queue_1") override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: ITEM_CELL) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(ITEM_CELL, forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = items[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row { case 0: showAlertInMainQueue() break case 1: exampleGlobalQueues() break case 2: exampleSerialQueues() break case 3: exampleConcurrentQueue() break case 4: exampleConcurrentBarrier() break case 5: exampleConcurrentApplySync() break case 6: exampleConcurrentApplyAsync() break case 7: exampleConcurrentMapSync() break case 8: exampleConcurrentMapAsync() break default: break } } func showAlertInMainQueue() { MainQueue.dispatchAsync { let ac = UIAlertController(title: "iDispatch Example", message: "This is shown from Main Queue", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } } func exampleGlobalQueues() { BackgroundQueue.dispatchAsync { self.printMessage("Background Queue - Example Global Queue", times: 10) } LowPriorityQueue.dispatchAsync { self.printMessage("Low Priority Queue - Example Global Queue", times: 10) } DefaultPriorityQueue.dispatchAsync { self.printMessage("Default Priority Queue - Example Global Queue", times: 10) } HighPrioriytQueue.dispatchAsync { self.printMessage("High Priority Queue - Example Global Queue", times: 10) } } func exampleSerialQueues() { serialQueue1.dispatchAfterSeconds(1) { self.printMessage("Serial Queue after 5 sec - Serial Queue", times: 5) } serialQueue1.dispatchAsync { self.printMessage("Serial Queue Async - Serial Queue", times: 5) } printMessage("This will be printed before Async") serialQueue1.dispatchSync { self.printMessage("Serial Queue Sync - Serial Queue", times: 5) } printMessage("This will be printed after Sync") } func exampleConcurrentQueue() { concurrentQueue1.dispatchAfterSeconds(5) { self.printMessage("Concurrent Queue after 5 sec - Concurrent Queue", times: 5) } concurrentQueue1.dispatchAsync { self.printMessage("Serial Queue Async 1 - Concurrent Queue", times: 5) } printMessage("This will be printed before Async 1") concurrentQueue1.dispatchAsync { self.printMessage("Serial Queue Async 2 - Concurrent Queue", times: 5) } printMessage("This will be printed before Async 2") concurrentQueue1.dispatchSync { self.printMessage("Serial Queue Sync - Concurrent Queue", times: 5) } printMessage("This will be printed after Sync") } func exampleConcurrentBarrier() { concurrentQueue1.dispatchAsync { self.printMessage("Serial Queue Async 1 - Concurrent Queue", times: 5) } concurrentQueue1.dispatchAsync { self.printMessage("Serial Queue Async 2 - Concurrent Queue", times: 5) } concurrentQueue1.dispatchBarrierAsync { self.printMessage("Serial Queue Barrier Async - Concurrent Queue", times: 5) } concurrentQueue1.dispatchAsync { self.printMessage("Serial Queue Async 3 - Concurrent Queue", times: 5) } concurrentQueue1.dispatchBarrierSync { self.printMessage("Serial Queue Barrier Sync - Concurrent Queue", times: 5) } concurrentQueue1.dispatchAsync { self.printMessage("Serial Queue Async 4 - Concurrent Queue", times: 5) } } func exampleConcurrentApplySync() { var messages = ["Message - 1", "Message - 2", "Message - 3", "Message - 4", "Message - 5"] concurrentQueue1.applySync(messages) { (imageFile) -> Void in } concurrentQueue1.applySync(messages, block: { (t) -> Void in self.printMessage(t) }) printMessage("This will be printed after interations") } func exampleConcurrentApplyAsync() { var messages = ["Message - 1", "Message - 2", "Message - 3", "Message - 4", "Message - 5"] concurrentQueue1.applyAsync(messages, block: { (t) -> Void in self.printMessage(t) }) { self.printMessage("All the interations are completed") } printMessage("This will be printed before interations") } func exampleConcurrentMapSync() { var messages = ["Message - 1", "Message - 2", "Message - 3", "Message - 4", "Message - 5"] var mapped = concurrentQueue1.mapSync(messages, block: { (t) -> String in self.printMessage(t) return "Mapped \(t)" }) for m in mapped { println(m) } } func exampleConcurrentMapAsync() { var messages = ["Message - 1", "Message - 2", "Message - 3", "Message - 4", "Message - 5"] concurrentQueue1.mapAsync(messages, block: { (t) -> String in self.printMessage(t) return "Mapped \(t)" }) { (mapped) -> Void in for m in mapped { println(m) } } } func printMessage(message: String, times: UInt) { for i in 1...times { printMessage(message) } } func printMessage(message: String) { printQueue.dispatchSync { sleep(1) println(message) } } }
mit
12ea69664853845c8dda5adb38736c61
31.072581
132
0.559593
5.222587
false
false
false
false
SquidKit/SquidKit
SquidKit/ProgressBar.swift
1
3289
// // ProgressBar.swift // SquidKit // // Created by Mike Leavy on 2/22/19. // Copyright © 2019 Squid Store, LLC. All rights reserved. // import UIKit open class ProgressBar: UIView { public enum Style: Int { case round case flat } public enum Direction: Int { case horizontal case vertical } open var style: Style = .round open var direction: Direction = .horizontal @IBInspectable open var styleAdapter: Int { get { return style.rawValue } set { style = Style(rawValue: newValue) ?? .round } } @IBInspectable open var directionAdapter: Int { get { return direction.rawValue } set { direction = Direction(rawValue: newValue) ?? .horizontal } } @IBInspectable open var startColor: UIColor = .blue { didSet { updateLayout() } } @IBInspectable open var endColor: UIColor = .red { didSet { updateLayout() } } @IBInspectable open var borderColor: UIColor? { didSet { updateLayout() } } @IBInspectable open var borderWidth: CGFloat = 0 { didSet { updateLayout() } } @IBInspectable open var value: CGFloat = 0 { didSet { value = max(0, value) value = min(value, 1) updateGradientStops() } } private var gradientLayer: CAGradientLayer? open override func awakeFromNib() { updateLayout() } open override func layoutSubviews() { super.layoutSubviews() updateLayout() } private func updateLayout() { switch style { case .round: layer.cornerRadius = direction == .horizontal ? bounds.height / 2 : bounds.width / 2 layer.masksToBounds = true case .flat: layer.cornerRadius = 0 layer.masksToBounds = true } layer.borderColor = borderColor?.cgColor layer.borderWidth = borderWidth applyGradient() } private func applyGradient() { gradientLayer?.removeFromSuperlayer() gradientLayer = CAGradientLayer() gradientLayer?.frame = bounds gradientLayer?.colors = [startColor.cgColor, endColor.cgColor, backgroundColor?.cgColor ?? UIColor.white.cgColor] let startX: CGFloat = direction == .horizontal ? 0.0 : 0.5 let startY: CGFloat = direction == .horizontal ? 0.5 : 0.0 let endX: CGFloat = direction == .horizontal ? 1.0 : 0.5 let endY: CGFloat = direction == .horizontal ? 0.5 : 1.0 gradientLayer?.startPoint = CGPoint(x: startX, y: startY) gradientLayer?.endPoint = CGPoint(x: endX, y: endY) if direction == .vertical { gradientLayer?.transform = CATransform3DMakeRotation(CGFloat.pi, 0, 0, 1) } layer.insertSublayer(gradientLayer!, at: 0) updateGradientStops() } private func updateGradientStops() { let currentValue = NSNumber(value: Double(value)) gradientLayer?.locations = [0.0, currentValue, currentValue, 1.0] } }
mit
7538df072eb508f30590318118fbf06f
25.95082
121
0.565389
4.936937
false
false
false
false
artsy/eigen
ios/ArtsyTests/View_Controller_Tests/Auction/AuctionInformationViewControllerTests.swift
1
5414
import Quick import Nimble import Nimble_Snapshots import UIKit @testable import Artsy class AuctionInformationViewControllerSpec: QuickSpec { override func spec() { let past = ARStandardDateFormatter.shared().date(from: "2016-02-18T10:00:00+00:00")! let past2 = ARStandardDateFormatter.shared().date(from: "2016-02-19T10:00:00+00:00")! let future = ARStandardDateFormatter.shared().date(from: "2025-02-18T23:59:00+00:00")! let description = "On Thursday, November 12, Swiss Institute will host their Annual Benefit Dinner & Auction–the most important fundraising event of the year–with proceeds going directly towards supporting their innovative exhibitions and programs. Since 1986, Swiss Institute has been dedicated to promoting forward-thinking and experimental art." var sale: Sale! = try! Sale(dictionary: ["saleID": "the-tada-sale", "name": "Sotheby’s Boundless Contemporary", "saleDescription": description, "startDate": past, "endDate": future ], error: Void()) var saleViewModel: SaleViewModel! = SaleViewModel(sale: sale, saleArtworks: [], bidders: [], me: User()) let markdown = "# Other Requests\n## Can you tell me the worth of my artwork?\n\nArtsy does not provide appraisal or authentication services for individual sellers. We recommend reaching out to professional dealers, galleries, and auction houses for assistance.\n\nFor any further questions, please contact [[email protected]](mailto:[email protected])." var navigationController: ARSerifNavigationViewController! var informationController: AuctionInformationViewController! // Ensure there is a key window for all of the tests var window: UIWindow? beforeSuite { window = UIWindow() window?.makeKeyAndVisible() } func commonSetup() { ARUserManager.stubAndSetupUser() informationController = AuctionInformationViewController(saleViewModel: saleViewModel) navigationController = ARSerifNavigationViewController(rootViewController: informationController) for entry in informationController.FAQEntries { OHHTTPStubs.stubJSONResponse(atPath: "/api/v1/page/\(entry.slug)", withResponse:["published":true, "content": markdown]) } } // TODO: These are failing only on Circle CI. Investigate why. xcontext("a current sale") { beforeEach { sale = try! Sale(dictionary: ["saleID": "the-tada-sale", "name": "Sotheby’s Boundless Contemporary", "saleDescription": description, "startDate": past, "endDate": future ], error: Void()) saleViewModel = SaleViewModel(sale: sale, saleArtworks: [], bidders: [], me: User()) commonSetup() } ["iPhone": ARDeviceType.phone6.rawValue, "iPad": ARDeviceType.pad.rawValue].forEach { (deviceName, deviceType) in it("has a root view that shows information about the auction and looks good on \(deviceName)") { ARTestContext.use(ARDeviceType(rawValue: deviceType)!) { expect(navigationController).to( haveValidSnapshot(usesDrawRect: true) ) } } } it("shows a button for buyer's premium when needed") { let sale = try! Sale(dictionary: ["saleID": "the-tada-sale", "name": "Sotheby’s Boundless Contemporary", "saleDescription": description, "startDate": past, "endDate": future, "buyersPremium" : [] ], error: Void()) let saleViewModel = SaleViewModel(sale: sale, saleArtworks: [], bidders: [], me: User()) informationController = AuctionInformationViewController(saleViewModel: saleViewModel) navigationController = ARSerifNavigationViewController(rootViewController: informationController) for entry in informationController.FAQEntries { OHHTTPStubs.stubJSONResponse(atPath: "/api/v1/page/\(entry.slug)", withResponse:["published":true, "content": markdown]) } expect(navigationController).to( haveValidSnapshot(usesDrawRect: true) ) } it("has a FAQ view that answers questions about the auction") { let FAQController = informationController.showFAQ(false) expect(navigationController).to( haveValidSnapshot(named: "FAQ Initial Entry", usesDrawRect: true) ) for (index, view) in FAQController.entryViews.enumerated() { view.didTap() let entry = FAQController.entries[index] expect(navigationController).to( haveValidSnapshot(named: "FAQ Entry: \(entry.name)", usesDrawRect: true)) } } } context("a closed sale") { beforeEach { sale = try! Sale(dictionary: ["saleID": "the-tada-sale", "name": "Sotheby’s Boundless Contemporary", "saleDescription": description, "startDate": past, "endDate": past2 ], error: Void()) saleViewModel = SaleViewModel(sale: sale, saleArtworks: [], bidders: [], me: User()) commonSetup() } it("shows the sale is closed") { expect(navigationController).to( haveValidSnapshot() ) } } } }
mit
b523161eaf86cb91f3e8731a2d428b7b
55.863158
362
0.645131
4.705575
false
false
false
false
gkaimakas/SwiftyFormsUI
SwiftyFormsUI/Classes/TableViews/FormTableView.swift
1
1969
// // FormTableView.swift // Pods // // Created by Γιώργος Καϊμακάς on 14/06/16. // // import Foundation import UIKit open class FormTableView: UITableView { fileprivate enum KeyboardState: Int { case visible = 0 case notVisible = 1 } fileprivate var originalBottonContentInset: CGFloat = 0 fileprivate var keyboardState: KeyboardState = .notVisible public override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) handleKeyboard() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) handleKeyboard() } open func handleKeyboard() { NotificationCenter.default .addObserver(self, selector: #selector(FormTableView.handleKeyboardShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default .addObserver(self, selector: #selector(FormTableView.handleKeyboardHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func handleKeyboardShow(_ notification: Notification){ self.layoutIfNeeded() if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size { if keyboardState == .notVisible { originalBottonContentInset = self.contentInset.bottom } self.contentInset = UIEdgeInsets(top: self.contentInset.top, left: self.contentInset.left, bottom: 0 + keyboardSize.height, right: self.contentInset.right) } UIView.animate(withDuration: 0.5, animations: { () -> Void in self.layoutIfNeeded() self.keyboardState = .visible }) } @objc func handleKeyboardHide(_ notification: Notification){ self.layoutIfNeeded() self.contentInset = UIEdgeInsets(top: self.contentInset.top, left: self.contentInset.left, bottom: self.originalBottonContentInset, right: self.contentInset.right) UIView.animate(withDuration: 0.5, animations: { () -> Void in self.layoutIfNeeded() self.keyboardState = .notVisible }) } }
mit
5bb79cb9a10d3d2b59da6e8eb2143220
27.735294
165
0.748721
3.854043
false
false
false
false
KrishMunot/swift
test/Prototypes/CollectionsMoveIndices.swift
2
62656
// XFAIL: * // TODO: failing it for now as it is work in progress. // RUN: %target-run-simple-swift // REQUIRES: executable_test // https://bugs.swift.org/browse/SR-122 // // Summary // ======= // // This file implements a prototype for a collection model where // indices can't move themselves forward or backward. Instead, the // corresponding collection moves the indices. // // Problem // ======= // // Swift standard library defines three kinds of collection indices: // forward, bidirectional and random access. A collection uses one of // these indices based on the capabilities of the backing data // structure. For example, a singly-linked list can only have forward // indices, a tree with parent pointers has bidirectional indices, and // Array and Deque has random access indices. // // It turned out that in practice, every implementation of the // non-random-access indices needs to hold a reference to the // collection it traverses, or to some part of it, to implement // `.successor()` and `.predecessor()`. This introduces extra // complexity in implementations and presumably translates into // less-efficient code that does reference counting on indices. // // Indices keeping references to collections also conflict with COW -- // a live index makes collection's storage non-uniquely referenced, // causing unnecessary copies. In the standard library, `Dictionary` // and `Set` have to use a double-indirection trick to avoid these // extra copies in these cases. // // This data that we gathered from experience working with the current // collection protocols suggests that we should consider other schemes // that don't require such double-indirection tricks or other undue // performance burdens. // // Proposed Solution // ================= // // We propose to allow implementing collections whose indices don't // have reference-countable stored properties. // // For the API this implies that indices can't be moved forward or // backward by themselves (`i.successor()` is not allowed). Only the // corresponding collection instance can move indices (e.g., // `c.next(i)`). This API change reduces the requirements on the // amount of information indices need to store or reference. // // In this model indices can store the minimal amount of information // only about the element position in the collection. Usually index // can be represented as one or a couple of word-sized integers that // efficiently encode the "path" in the data structure from the root // to the element. Since one is free to choose the encoding of the // "path", we think that it should be possible to choose it in such a // way that indices are cheaply comparable. // // In the proposed model indices don't have any method or property // requirements (these APIs were moved to Collection), so index // protocols are eliminated. Instead, we are introducing // `BidirectionalCollectionType` and `RandomAccessCollectionType`. // These protocols naturally compose with existing // `MutableCollectionType` and `RangeReplaceableCollectionType` to // describe the collection's capabilities: // // protocol SequenceType {} // protocol CollectionType : SequenceType {} // // protocol MutableCollectionType : CollectionType {} // protocol RangeReplaceableCollectionType : CollectionType {} // // [new] protocol BidirectionalCollectionType : CollectionType {} // [new] protocol RandomAccessCollectionType : BidirectionalCollectionType {} // // Analysis // ======== // // Advantages: // // * Indices don't need to keep a reference to the collection. // - Indices are simpler to implement. // - Indices are not reference-countable, and thus cheaper to // handle. // - Handling indices does not cause refcounting, and does not block // optimizations. // // * The hierarchy of index protocols is removed, and instead we add // protocols for forward, bidirectional and random-access // collections. // - This is closer to how people generally talk about collections. // - Writing a generic constraint for bidirectional and // random-access collections becomes simpler. // // * Indices can conform to `Comparable` without incurring extra // memory overhead. Indices need to store all the necessary data // anyway. // // * While this model allows to design indices that are not // reference-countable, it does not prohibit defining indices that // *are* reference countable. // - All existing collection designs are still possible to // implement, but some are less efficient than the new model allows. // - If there is a specialized collection that needs // reference-countable indices for algorithmic or memory // efficiency, where such tradeoff is reasonable, such a // collection is still possible to implement in the new model. // See the discussion of trees below, the tree design (2)(c). // // Neutral as compared to the current collections: // * A value-typed linked list still can't conform to CollectionType. // A reference-typed one can. // // Disadvantages: // * Advancing an index forward or backward becomes harder -- the // statement now includes two entities (collection and index): // // j = c.next(i) vs. j = i.successor() // // In practice though, we found that when the code is doing such // index manipulations, the collection is typically still around // stored in a variable, so the code does not need to reach out for // it non-trivially. // // * Collection's API now includes methods for advancing indices. // // Impact on the source code // ========================= // // Code that works with `Array`, its indices (`Int`s), moves indices, // does not need to change at all. // // Code that operates on collections and indices, but does not move // indices, does not need to change at all. // // Iteration over collection's indices with `c.indices` does not // change: // // for i in c.indices { ... } // No change. // // API of collection algorithms does not change, even for algorithms that // accept indices as parameters or return indices (e.g., `index(of:)`, // `index(where:)`, `min()`, `sort()`, `prefix()`, `prefixUpTo()` etc.) // // Code that moves indices (`i.successor()`, `i.predecessor()`, // `i.advancedBy()`) needs to change to use a method on the // collection. // // // Before: // var i = c.index { $0 % 2 == 0 } // i = i.successor() // print(c[i]) // // // After: // var i = c.index { $0 % 2 == 0 } // No change in algorithm API. // i = c.next(i) // Advancing an index requires a collection instance. // print(c[i]) // No change in subscripting. // // Implementation difficulties // =========================== // // 1. Conflicting requirements for `MyRange`: // // * range bounds need to be comparable and incrementable, in order // for `MyRange` to conform to `MyForwardCollectionType`, // // * we frequently want to use `MyRange` as a "transport" data // type, just to carry a pair of indices around. Indices are // neither comparable nor incrementable. // // Possible solution: conditional conformance for `MyRange` to // `MyForwardCollectionType` when the bounds are comparable and // incrementable (when the bounds conform to // `MyRandomAccessCollectionType`?). // // 2. We can't specify constraints on associated types. This forces many // trivial algorithms to specify useless constraints. // // Solution: constraints on associated types are a desirable // language feature, part of the Swift generics model. This issue // will be fixed by compiler improvements. // // 3. To implement `for i in c.indices {}` efficiently, we would need some // support from the optimizer for unowned references. Either from ARC // optimizer to eliminate unowned retains/releases, or support in alias // analysis and a new pass to promote needless unowned references to use the // original strong reference that is still in scope. // // Trees // ===== // // Trees are very interesting data structures with many unique // requirements. We are interested in allowing efficient and // memory-safe implementations of collections based on a search trees // (e.g., RB trees or B-trees). The specific list of requirements is // as follows. // // - The collection and indices should be memory-safe. They should // provide good QoI in the form of precondition traps. Ensuring // memory-safety shouldn't cause unreasonable performance or memory // overhead. // // - Collection instances should be able to share nodes on mutation // (persistent data structures). // // - Subscript on an index should be at worst amortized O(1). // // - Advancing an index to the next or previous position should cost // at worst amortized O(1). // // - Indices should not contain reference countable stored properties. // // - Mutating or deleting an element in the collection should not // invalidate indices pointing at other elements. // // This design constraint needs some extra motivation, because it // might not be obvious. Preserving index validity across mutation // is important for algorithms that iterate over the tree and mutate // it in place, for example, removing a subrange of elements between // two indices, or removing elements that don't satisfy a predicate. // When implementing such an algorithm, you would typically have an // index that points to the current element. You can copy the // index, advance it, and then remove the previous element using its // index. If the mutation of the tree invalidates all indices, // it is not possible to continue the iteration. Thus, it is // desired to invalidate just one index for the element that was // deleted. // // It is not possible to satisfy all of these requirements at the same // time. Designs that cover some of the requirements are possible. // // 1. Persistent trees with O(log n) subscripting and advancing, and // strict index invalidation. // // If we choose to make a persistent data structure with node // reuse, then the tree nodes can't have parent pointers (a node // can have multiple different parents in different trees). This // means that it is not possible to advance an index in O(1). If // we need to go up the tree while advancing the index, without // parent pointers we would need to traverse the tree starting from // the root in O(log n). // // Thus, index has to essentially store a path through the tree // from the root to the node (it is usually possible to encode this // path in a 64-bit number). Since the index stores the path, // subscripting on such an index would also cost O(log n). // // We should note that persistent trees typically use B-trees, so // the base of the logarithm would be typically large (e.g., 32). // We also know that the size of the RAM is limited. Thus, we // could treat the O(log n) complexity as effectively constant for // all practical purposes. But the constant factor will be much // larger than in other designs. // // Swift's collection index model does not change anything as // compared to other languages. The important point is that the // proposed index model allows such implementations of persistent // collections. // // 2. Trees with O(1) subscripting and advancing. // // If we want subscripting to be O(1), then the index has to store // a pointer to a tree node. Since we want avoid reference // countable properties in indices, the node pointer should either // be `unsafe(unowned)` or an `UnsafePointer`. These pointers // can't be dereferenced safely without knowing in advance that it // is safe to do so. We need some way to quickly check if it is // safe to dereference the pointer stored in the node. // // A pointer to a tree node can become invalid when the node was // deallocated. A tree node can be deallocated if the // corresponding element is removed from the tree. // // (a) Trees with O(1) subscripting and advancing, and strict index // invalidation. // // One simple way to perform the safety check when // dereferencing the unsafe pointer stored within the index // would be to detect any tree mutation between the index // creation and index use. It is simple to do with version // numbers: we add an ID number to every tree. This ID would // be unique among all trees created within the process, and it // would be re-generated on every mutation. The tree ID is // copied into every index. When the index is used with the // collection, we check that the ID of the tree matches the // tree ID stored in the index. This fast check ensures memory // safety. // // (b) Trees with O(1) subscripting and advancing, permissive index // invalidation, and extra storage to ensure memory safety. // // Another way to perform the safety check would be to directly // check if the unsafe pointer stored in the index is actually // linked into the tree. To do that with acceptable time // complexity, we would need to have an extra data structure // for every tree, for example, a hash table-based set of all // node pointers. With this design, all index operations get // an O(1) hit for the hash table lookup for the safety check, // but we get an O(log n) memory overhead for the extra data // structure. On the other hand, a tree already has O(log n) // memory overhead for allocating nodes themselves, thus the // extra data structure would only increase the constant factor // on memory overhead. // // | (1) | (2)(a) | (2)(b) // -------------------------------------+----------+---------+------- // memory-safe | Yes | Yes | Yes // indices are not reference-counted | Yes | Yes | Yes // shares nodes | Yes | No | No // subscripting on an index | O(log n) | O(1) | O(1) // advancing an index | O(log n) | O(1) | O(1) // deleting does not invalidate indices | No | No | Yes // requires extra O(n) storage just ... | | | // for safety checks | No | No | Yes // // Each of the designs discussed above has its uses, but the intuition // is that (2)(a) is the one most commonly needed in practice. (2)(a) // does not have the desired index invalidation properties. There is // a small number of commonly used algorithms that require that // property, and they can be provided as methods on the collection, // for example removeAll(in: Range<Index>) and // removeAll(_: (Element)->Bool). // // If we were to allow reference-counted indices (basically, the // current collections model), then an additional design is possible // -- let's call it (2)(c) for the purpose of discussion. This design // would be like (2)(b), but won't require extra storage that is used // only for safety checks. Instead, every index would pay a RC // penalty and carry a strong reference to the tree node. // // Note that (2)(c) is still technically possible to implement in the // new collection index model, it just goes against a goal of having // indices free of reference-counted stored properties. infix operator ...* { associativity none precedence 135 } infix operator ..<* { associativity none precedence 135 } public protocol MyGeneratorType { associatedtype Element mutating func next() -> Element? } public protocol MySequenceType { associatedtype Generator : MyGeneratorType associatedtype SubSequence /* : MySequenceType */ func generate() -> Generator @warn_unused_result func map<T>( @noescape _ transform: (Generator.Element) throws -> T ) rethrows -> [T] @warn_unused_result func dropFirst(_ n: Int) -> SubSequence @warn_unused_result func dropLast(_ n: Int) -> SubSequence @warn_unused_result func prefix(_ maxLength: Int) -> SubSequence @warn_unused_result func suffix(_ maxLength: Int) -> SubSequence } extension MySequenceType { @warn_unused_result public func map<T>( @noescape _ transform: (Generator.Element) throws -> T ) rethrows -> [T] { var result: [T] = [] for element in OldSequence(self) { result.append(try transform(element)) } return result } @warn_unused_result public func dropFirst(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") fatalError("implement") } @warn_unused_result public func dropLast(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") fatalError("implement") } @warn_unused_result public func prefix(_ maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a collection") fatalError("implement") } @warn_unused_result public func suffix(_ maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a collection") fatalError("implement") } } //------------------------------------------------------------------------ // Bridge between the old world and the new world struct OldSequence<S : MySequenceType> : SequenceType { let _base: S init(_ base: S) { self._base = base } func generate() -> OldGenerator<S.Generator> { return OldGenerator(_base.generate()) } } struct OldGenerator<G : MyGeneratorType> : GeneratorType { var _base: G init(_ base: G) { self._base = base } mutating func next() -> G.Element? { return _base.next() } } // End of the bridge //------------------------------------------------------------------------ public protocol MyIndexableType { associatedtype Index : Comparable associatedtype _Element associatedtype UnownedHandle var startIndex: Index { get } var endIndex: Index { get } subscript(i: Index) -> _Element { get } init(from handle: UnownedHandle) var unownedHandle: UnownedHandle { get } @warn_unused_result func next(_ i: Index) -> Index func _nextInPlace(_ i: inout Index) func _failEarlyRangeCheck(_ index: Index, bounds: MyRange<Index>) func _failEarlyRangeCheck2( rangeStart rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) } extension MyIndexableType { @inline(__always) public func _nextInPlace(_ i: inout Index) { i = next(i) } } public protocol MyForwardCollectionType : MySequenceType, MyIndexableType { associatedtype Generator = DefaultGenerator<Self> associatedtype Index : Comparable associatedtype SubSequence : MySequenceType /* : MyForwardCollectionType */ = MySlice<Self> associatedtype UnownedHandle = Self // DefaultUnownedForwardCollection<Self> associatedtype IndexRange : MyIndexRangeType, MySequenceType, MyIndexableType /* : MyForwardCollectionType */ // FIXME: where IndexRange.Generator.Element == Index // FIXME: where IndexRange.Index == Index = DefaultForwardIndexRange<Self> associatedtype IndexDistance : SignedIntegerType = Int var startIndex: Index { get } var endIndex: Index { get } subscript(i: Index) -> Generator.Element { get } subscript(bounds: MyRange<Index>) -> SubSequence { get } init(from handle: UnownedHandle) var unownedHandle: UnownedHandle { get } @warn_unused_result func next(_ i: Index) -> Index @warn_unused_result func advance(_ i: Index, by: IndexDistance) -> Index @warn_unused_result func advance(_ i: Index, by: IndexDistance, limit: Index) -> Index @warn_unused_result func distanceFrom(_ start: Index, to: Index) -> IndexDistance func _failEarlyRangeCheck(_ index: Index, bounds: MyRange<Index>) func _failEarlyRangeCheck2( rangeStart rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) var indices: IndexRange { get } @warn_unused_result func _customIndexOfEquatableElement(_ element: Generator.Element) -> Index?? var first: Generator.Element? { get } var isEmpty: Bool { get } var count: IndexDistance { get } } extension MyForwardCollectionType { /// Do not use this method directly; call advancedBy(n) instead. @inline(__always) @warn_unused_result internal func _advanceForward(_ i: Index, by n: IndexDistance) -> Index { _precondition(n >= 0, "Only BidirectionalIndexType can be advanced by a negative amount") var i = i for var offset: IndexDistance = 0; offset != n; offset = offset + 1 { _nextInPlace(&i) } return i } /// Do not use this method directly; call advancedBy(n, limit) instead. @inline(__always) @warn_unused_result internal func _advanceForward( _ i: Index, by n: IndexDistance, limit: Index ) -> Index { _precondition(n >= 0, "Only BidirectionalIndexType can be advanced by a negative amount") var i = i for var offset: IndexDistance = 0; offset != n && i != limit; offset = offset + 1 { _nextInPlace(&i) } return i } @warn_unused_result public func advance(_ i: Index, by n: IndexDistance) -> Index { return self._advanceForward(i, by: n) } @warn_unused_result public func advance(_ i: Index, by n: IndexDistance, limit: Index) -> Index { return self._advanceForward(i, by: n, limit: limit) } @warn_unused_result public func distanceFrom(_ start: Index, to end: Index) -> IndexDistance { var start = start var count: IndexDistance = 0 while start != end { count = count + 1 _nextInPlace(&start) } return count } public func _failEarlyRangeCheck( _ index: Index, bounds: MyRange<Index>) { // Can't perform range checks in O(1) on forward indices. } public func _failEarlyRangeCheck2( rangeStart rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index ) { // Can't perform range checks in O(1) on forward indices. } @warn_unused_result public func _customIndexOfEquatableElement( _ element: Generator.Element ) -> Index?? { return nil } public var first: Generator.Element? { return isEmpty ? nil : self[startIndex] } public var isEmpty: Bool { return startIndex == endIndex } public var count: IndexDistance { return distanceFrom(startIndex, to: endIndex) } @warn_unused_result public func dropFirst(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let start = advance(startIndex, by: numericCast(n), limit: endIndex) return self[start..<*endIndex] } @warn_unused_result public func dropLast(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let amount = max(0, numericCast(count) - n) let end = advance(startIndex, by: numericCast(amount), limit: endIndex) return self[startIndex..<*end] } @warn_unused_result public func prefix(_ maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = advance(startIndex, by: numericCast(maxLength), limit: endIndex) return self[startIndex..<*end] } @warn_unused_result public func suffix(_ maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = max(0, numericCast(count) - maxLength) let start = advance(startIndex, by: numericCast(amount), limit: endIndex) return self[start..<*endIndex] } } extension MyForwardCollectionType where Generator == DefaultGenerator<Self> { public func generate() -> DefaultGenerator<Self> { return DefaultGenerator(self) } } extension MyForwardCollectionType where UnownedHandle == Self // where UnownedHandle == DefaultUnownedForwardCollection<Self> { public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } } extension MyForwardCollectionType where SubSequence == MySlice<Self> { public subscript(bounds: MyRange<Index>) -> SubSequence { return MySlice(base: self, start: bounds.startIndex, end: bounds.endIndex) } } extension MyForwardCollectionType where IndexRange == DefaultForwardIndexRange<Self> { public var indices: IndexRange { return DefaultForwardIndexRange( collection: self, startIndex: startIndex, endIndex: endIndex) } } extension MyForwardCollectionType where Index : MyStrideable, Index.Distance == IndexDistance { @warn_unused_result public func next(_ i: Index) -> Index { return advance(i, by: 1) } @warn_unused_result public func advance(_ i: Index, by n: IndexDistance) -> Index { _precondition(n >= 0, "Can't advance an Index of MyForwardCollectionType by a negative amount") return i.advancedBy(n) } @warn_unused_result public func advance(_ i: Index, by n: IndexDistance, limit: Index) -> Index { _precondition(n >= 0, "Can't advance an Index of MyForwardCollectionType by a negative amount") let d = i.distanceTo(limit) _precondition(d >= 0, "The specified limit is behind the index") if d <= n { return limit } return i.advancedBy(n) } } extension MyForwardCollectionType where Generator.Element : Equatable, IndexRange.Generator.Element == Index // FIXME { public func index(of element: Generator.Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } for i in OldSequence(self.indices) { if self[i] == element { return i } } return nil } public func indexOf_optimized(_ element: Generator.Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } var i = startIndex while i != endIndex { if self[i] == element { return i } _nextInPlace(&i) } return nil } } extension MyForwardCollectionType where SubSequence == Self { @warn_unused_result public mutating func popFirst() -> Generator.Element? { guard !isEmpty else { return nil } let element = first! self = self[MyRange(start: self.next(startIndex), end: endIndex)] return element } } public protocol MyBidirectionalCollectionType : MyForwardCollectionType { @warn_unused_result func previous(_ i: Index) -> Index func _previousInPlace(_ i: inout Index) } extension MyBidirectionalCollectionType { @inline(__always) public func _previousInPlace(_ i: inout Index) { i = previous(i) } @warn_unused_result public func advance(_ i: Index, by n: IndexDistance) -> Index { if n >= 0 { return _advanceForward(i, by: n) } var i = i for var offset: IndexDistance = n; offset != 0; offset = offset + 1 { _previousInPlace(&i) } return i } @warn_unused_result public func advance(_ i: Index, by n: IndexDistance, limit: Index) -> Index { if n >= 0 { return _advanceForward(i, by: n, limit: limit) } var i = i for var offset: IndexDistance = n; offset != 0 && i != limit; offset = offset + 1 { _previousInPlace(&i) } return i } } extension MyBidirectionalCollectionType where Index : MyStrideable, Index.Distance == IndexDistance { @warn_unused_result public func previous(_ i: Index) -> Index { return advance(i, by: -1) } @warn_unused_result public func advance(_ i: Index, by n: IndexDistance) -> Index { return i.advancedBy(n) } @warn_unused_result public func advance(_ i: Index, by n: IndexDistance, limit: Index) -> Index { let d = i.distanceTo(limit) if d == 0 || (d > 0 ? d <= n : d >= n) { return limit } return i.advancedBy(n) } } public protocol MyRandomAccessCollectionType : MyBidirectionalCollectionType { associatedtype Index : MyStrideable // FIXME: where Index.Distance == IndexDistance } public struct DefaultUnownedForwardCollection<Collection : MyForwardCollectionType> { internal let _collection: Collection public init(_ collection: Collection) { self._collection = collection } } public struct DefaultForwardIndexRange<Collection : MyIndexableType /* MyForwardCollectionType */> : MyForwardCollectionType, MyIndexRangeType { internal let _unownedCollection: Collection.UnownedHandle public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection.Index public typealias Generator = DefaultForwardIndexRangeGenerator<Collection> public typealias Index = Collection.Index public typealias SubSequence = DefaultForwardIndexRange<Collection> public typealias UnownedHandle = DefaultForwardIndexRange<Collection> internal init( _unownedCollection: Collection.UnownedHandle, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = _unownedCollection self.startIndex = startIndex self.endIndex = endIndex } public init( collection: Collection, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = collection.unownedHandle self.startIndex = startIndex self.endIndex = endIndex } // FIXME: use DefaultGenerator when the type checker bug is fixed. public func generate() -> Generator { return DefaultForwardIndexRangeGenerator( Collection(from: _unownedCollection), start: startIndex, end: endIndex) } public subscript(i: Collection.Index) -> Collection.Index { return i } public subscript(bounds: MyRange<Index>) -> DefaultForwardIndexRange<Collection> { fatalError("implement") } public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } @warn_unused_result public func next(_ i: Index) -> Index { return Collection(from: _unownedCollection).next(i) } } // FIXME: use DefaultGenerator when the type checker bug is fixed. public struct DefaultForwardIndexRangeGenerator<Collection : MyIndexableType /* MyForwardCollectionType */> : MyGeneratorType { internal let _collection: Collection internal var _i: Collection.Index internal var _endIndex: Collection.Index public init( _ collection: Collection, start: Collection.Index, end: Collection.Index ) { self._collection = collection self._i = collection.startIndex self._endIndex = end } public mutating func next() -> Collection.Index? { if _i == _endIndex { return nil } let result = _i _i = _collection.next(_i) return result } } public struct MyRange<Index : Comparable> : MyIndexRangeType { public let startIndex: Index public let endIndex: Index public init(start: Index, end: Index) { _precondition(start <= end, "Can't form a backwards MyRange") self.startIndex = start self.endIndex = end } public subscript(i: Index) -> Index { return i } } public func ..<* <Index : Comparable>(lhs: Index, rhs: Index) -> MyRange<Index> { return MyRange(start: lhs, end: rhs) } // FIXME: replace this type with a conditional conformance on MyRange. public struct MyIterableRange<Index : MyStrideable> : MyBidirectionalCollectionType { public let startIndex: Index public let endIndex: Index public init(start: Index, end: Index) { _precondition(start <= end, "Can't form a backwards MyIterableRange") self.startIndex = start self.endIndex = end } @warn_unused_result public func next(_ i: Index) -> Index { let result = i.advancedBy(1) _precondition(startIndex <= result, "can't advance past endIndex") return i.advancedBy(1) } @warn_unused_result public func previous(_ i: Index) -> Index { let result = i.advancedBy(-1) _precondition(result <= endIndex, "can't advance before startIndex") return result } public subscript(i: Index) -> Index { return i } } public func ..<* <Index : MyStrideable>(lhs: Index, rhs: Index) -> MyIterableRange<Index> { return MyIterableRange(start: lhs, end: rhs) } // FIXME: in order for all this to be usable, we need to unify MyRange and // MyHalfOpenInterval. We can do that by constraining the Bound to comparable, // and providing a conditional conformance to collection when the Bound is // strideable. public struct MyHalfOpenInterval<Bound : Comparable> { public let start: Bound public let end: Bound } public struct MySlice<Collection : MyIndexableType /* : MyForwardCollectionType */> : MyForwardCollectionType // : MyIndexableType { internal let _base: Collection public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection._Element public typealias Index = Collection.Index public init( base: Collection, start: Collection.Index, end: Collection.Index) { self._base = base self.startIndex = start self.endIndex = end } public subscript(i: Collection.Index) -> Collection._Element { _base._failEarlyRangeCheck( i, bounds: MyRange(start: startIndex, end: endIndex)) return _base[i] } public typealias Generator = DefaultGenerator<MySlice> public func generate() -> Generator { return DefaultGenerator(self) } public typealias SubSequence = MySlice public subscript(bounds: MyRange<Index>) -> SubSequence { _base._failEarlyRangeCheck2( rangeStart: bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return MySlice(base: _base, start: bounds.startIndex, end: bounds.endIndex) } @warn_unused_result public func next(_ i: Index) -> Index { return _base.next(i) } public func _failEarlyRangeCheck(_ index: Index, bounds: MyRange<Index>) { fatalError("FIXME") } public func _failEarlyRangeCheck2( rangeStart rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index ) { fatalError("FIXME") } // FIXME: use Collection.UnownedHandle instead. public typealias UnownedHandle = MySlice public var unownedHandle: UnownedHandle { return self } public init(from handle: UnownedHandle) { self = handle } // FIXME: use DefaultForwardIndexRange instead. public typealias IndexRange = MySliceIndexRange<MySlice> public var indices: IndexRange { return MySliceIndexRange( collection: self, startIndex: startIndex, endIndex: endIndex) } } public struct MySliceIndexRange<Collection : MyIndexableType /* MyForwardCollectionType */> //: MyForwardCollectionType : MyIndexRangeType, MySequenceType, MyIndexableType { internal let _unownedCollection: Collection.UnownedHandle public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection.Index public typealias Generator = DefaultForwardIndexRangeGenerator<Collection> public typealias Index = Collection.Index public typealias SubSequence = MySliceIndexRange<Collection> public typealias UnownedHandle = MySliceIndexRange<Collection> internal init( _unownedCollection: Collection.UnownedHandle, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = _unownedCollection self.startIndex = startIndex self.endIndex = endIndex } public init( collection: Collection, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = collection.unownedHandle self.startIndex = startIndex self.endIndex = endIndex } public func generate() -> Generator { return DefaultForwardIndexRangeGenerator( Collection(from: _unownedCollection), start: startIndex, end: endIndex) } public subscript(i: Collection.Index) -> Collection.Index { return i } public subscript(bounds: MyRange<Index>) -> MySliceIndexRange<Collection> { fatalError("implement") } public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } @warn_unused_result public func next(_ i: Index) -> Index { return Collection(from: _unownedCollection).next(i) } public func _failEarlyRangeCheck(_ index: Index, bounds: MyRange<Index>) { } public func _failEarlyRangeCheck2( rangeStart rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index ) { } public typealias IndexRange = MySliceIndexRange public var indices: IndexRange { return self } } public struct MyMutableSlice<Collection : MyMutableCollectionType> {} public struct MyAnyGenerator<Element> : MyGeneratorType { public init<G : MyGeneratorType>(_ g: G) { fatalError("FIXME") } public mutating func next() -> Element? { fatalError("FIXME") } } public struct MyAnySequence<Element> : MySequenceType { public typealias SubSequence = MyAnySequence<Element> public init<S : MySequenceType>(_ s: S) { fatalError("FIXME") } public func generate() -> MyAnyGenerator<Element> { fatalError("FIXME") } } public struct DefaultGenerator<Collection : MyIndexableType> : MyGeneratorType { internal let _collection: Collection internal var _i: Collection.Index public init(_ collection: Collection) { self._collection = collection self._i = collection.startIndex } public mutating func next() -> Collection._Element? { if _i == _collection.endIndex { return nil } let result = _collection[_i] _i = _collection.next(_i) return result } } public protocol MyMutableCollectionType : MyForwardCollectionType { associatedtype SubSequence : MyForwardCollectionType = MyMutableSlice<Self> subscript(i: Index) -> Generator.Element { get set } } public protocol MyIndexRangeType : Equatable { associatedtype Index : Equatable var startIndex: Index { get } var endIndex: Index { get } } public func == <IR : MyIndexRangeType> (lhs: IR, rhs: IR) -> Bool { return lhs.startIndex == rhs.startIndex && lhs.endIndex == rhs.endIndex } /* public protocol MyRandomAccessIndexType : MyBidirectionalIndexType, MyStrideable, _RandomAccessAmbiguity { @warn_unused_result func distanceTo(_ other: Self) -> Distance @warn_unused_result func advancedBy(_ n: Distance) -> Self @warn_unused_result func advancedBy(_ n: Distance, limit: Self) -> Self } extension MyRandomAccessIndexType { public func _failEarlyRangeCheck(_ index: Self, bounds: MyRange<Self>) { _precondition( bounds.startIndex <= index, "index is out of bounds: index designates a position before bounds.startIndex") _precondition( index < bounds.endIndex, "index is out of bounds: index designates the bounds.endIndex position or a position after it") } public func _failEarlyRangeCheck2( rangeStart rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self ) { let range = MyRange(startIndex: rangeStart, endIndex: rangeEnd) let bounds = MyRange(startIndex: boundsStart, endIndex: boundsEnd) _precondition( bounds.startIndex <= range.startIndex, "range.startIndex is out of bounds: index designates a position before bounds.startIndex") _precondition( bounds.startIndex <= range.endIndex, "range.endIndex is out of bounds: index designates a position before bounds.startIndex") _precondition( range.startIndex <= bounds.endIndex, "range.startIndex is out of bounds: index designates a position after bounds.endIndex") _precondition( range.endIndex <= bounds.endIndex, "range.startIndex is out of bounds: index designates a position after bounds.endIndex") } @transparent @warn_unused_result public func advancedBy(_ n: Distance, limit: Self) -> Self { let d = self.distanceTo(limit) if d == 0 || (d > 0 ? d <= n : d >= n) { return limit } return self.advancedBy(n) } } */ //------------------------------------------------------------------------ // Bubble sort extension MyMutableCollectionType where IndexRange.Generator.Element == Index, IndexRange.Index == Index { public mutating func bubbleSortInPlace( @noescape isOrderedBefore: (Generator.Element, Generator.Element) -> Bool ) { if isEmpty { return } if next(startIndex) == endIndex { return } while true { var swapped = false for i in OldSequence(indices) { if i == endIndex { break } let ni = next(i) if ni == endIndex { break } if isOrderedBefore(self[ni], self[i]) { swap(&self[i], &self[ni]) swapped = true } } if !swapped { break } } } } extension MyMutableCollectionType where Generator.Element : Comparable, IndexRange.Generator.Element == Index, IndexRange.Index == Index { public mutating func bubbleSortInPlace() { bubbleSortInPlace { $0 < $1 } } } //------------------------------------------------------------------------ // Bubble sort extension MyRandomAccessCollectionType where IndexRange.Generator.Element == Index, IndexRange.Index == Index { public func lowerBoundOf( _ element: Generator.Element, @noescape isOrderedBefore: (Generator.Element, Generator.Element) -> Bool ) -> Index { var low = startIndex var subrangeCount = count while subrangeCount != 0 { let midOffset = subrangeCount / 2 let mid = advance(low, by: midOffset) if isOrderedBefore(self[mid], element) { low = next(mid) subrangeCount -= midOffset + 1 } else { subrangeCount = midOffset } } return low } } extension MyRandomAccessCollectionType where Generator.Element : Comparable, IndexRange.Generator.Element == Index, IndexRange.Index == Index { public func lowerBoundOf(_ element: Generator.Element) -> Index { return lowerBoundOf(element) { $0 < $1 } } } //------------ public protocol MyStrideable : Comparable { associatedtype Distance : SignedNumberType @warn_unused_result func distanceTo(_ other: Self) -> Distance @warn_unused_result func advancedBy(_ n: Distance) -> Self } extension Int : MyStrideable {} //------------------------------------------------------------------------ // Array public struct MyArray<Element> : MyForwardCollectionType, MyRandomAccessCollectionType, MyMutableCollectionType { internal var _elements: [Element] = [] init() {} init(_ elements: [Element]) { self._elements = elements } public var startIndex: Int { return _elements.startIndex } public var endIndex: Int { return _elements.endIndex } public subscript(i: Int) -> Element { get { return _elements[i] } set { _elements[i] = newValue } } } //------------------------------------------------------------------------ // Simplest Forward Collection public struct MySimplestForwardCollection<Element> : MyForwardCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } public var startIndex: MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(_elements.endIndex) } @warn_unused_result public func next(_ i: MySimplestForwardCollectionIndex) -> MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(i._index + 1) } public subscript(i: MySimplestForwardCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestForwardCollectionIndex : Comparable { internal let _index: Int internal init(_ index: Int) { self._index = index } } public func == ( lhs: MySimplestForwardCollectionIndex, rhs: MySimplestForwardCollectionIndex ) -> Bool { return lhs._index == rhs._index } public func < ( lhs: MySimplestForwardCollectionIndex, rhs: MySimplestForwardCollectionIndex ) -> Bool { return lhs._index < rhs._index } //------------------------------------------------------------------------ // Simplest Bidirectional Collection public struct MySimplestBidirectionalCollection<Element> : MyBidirectionalCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } public var startIndex: MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(_elements.endIndex) } @warn_unused_result public func next(_ i: MySimplestBidirectionalCollectionIndex) -> MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(i._index + 1) } @warn_unused_result public func previous(_ i: MySimplestBidirectionalCollectionIndex) -> MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(i._index - 1) } public subscript(i: MySimplestBidirectionalCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestBidirectionalCollectionIndex : Comparable { internal let _index: Int internal init(_ index: Int) { self._index = index } } public func == ( lhs: MySimplestBidirectionalCollectionIndex, rhs: MySimplestBidirectionalCollectionIndex ) -> Bool { return lhs._index == rhs._index } public func < ( lhs: MySimplestBidirectionalCollectionIndex, rhs: MySimplestBidirectionalCollectionIndex ) -> Bool { return lhs._index < rhs._index } //------------------------------------------------------------------------ // Simplest Bidirectional Collection public struct MySimplestRandomAccessCollection<Element> : MyRandomAccessCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } // FIXME: 'typealias Index' should be inferred. public typealias Index = MySimplestRandomAccessCollectionIndex public var startIndex: MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_elements.endIndex) } public subscript(i: MySimplestRandomAccessCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestRandomAccessCollectionIndex : MyStrideable { internal let _index: Int internal init(_ index: Int) { self._index = index } @warn_unused_result public func distanceTo(_ other: MySimplestRandomAccessCollectionIndex) -> Int { return other._index - _index } @warn_unused_result public func advancedBy(_ n: Int) -> MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_index + n) } } public func == ( lhs: MySimplestRandomAccessCollectionIndex, rhs: MySimplestRandomAccessCollectionIndex ) -> Bool { return lhs._index == rhs._index } public func < ( lhs: MySimplestRandomAccessCollectionIndex, rhs: MySimplestRandomAccessCollectionIndex ) -> Bool { return lhs._index < rhs._index } //------------------------------------------------------------------------ // Simplest Strideable public struct MySimplestStrideable : MyStrideable { internal let _value: Int internal init(_ value: Int) { self._value = value } @warn_unused_result public func distanceTo(_ other: MySimplestStrideable) -> Int { return _value.distanceTo(other._value) } @warn_unused_result public func advancedBy(_ n: Int) -> MySimplestStrideable { return MySimplestStrideable(_value.advancedBy(n)) } } public func == ( lhs: MySimplestStrideable, rhs: MySimplestStrideable ) -> Bool { return lhs._value == rhs._value } public func < ( lhs: MySimplestStrideable, rhs: MySimplestStrideable ) -> Bool { return lhs._value < rhs._value } //------------------------------------------------------------------------ // FIXME: how does AnyCollection look like in the new scheme? //------------------------------------------------------------------------ // A simple binary tree internal final class _NodePayload<Element : Comparable> { internal var _parent: _UnownedUnsafeNodeReference<Element>? internal var _leftChild: _NodeReference<Element>? internal var _rightChild: _NodeReference<Element>? internal var _data: Element internal init( _data: Element, parent: _NodeReference<Element>?, leftChild: _NodeReference<Element>? = nil, rightChild: _NodeReference<Element>? = nil ) { self._data = _data self._parent = parent.map { _UnownedUnsafeNodeReference($0) } self._leftChild = leftChild self._rightChild = rightChild } } extension _NodePayload : CustomReflectable { internal func customMirror() -> Mirror { if let lc = _leftChild, rc = _rightChild { return Mirror(self, children: [ "left": lc, "data": _data, "right": rc ]) } if let lc = _leftChild { return Mirror(self, children: [ "left": lc, "data": _data ]) } if let rc = _rightChild { return Mirror(self, children: [ "data": _data, "right": rc ]) } return Mirror(self, children: [ "data": _data ]) } } internal struct _NodeReference<Element : Comparable> { internal var _payload: _NodePayload<Element> internal var _parent: _NodeReference<Element>? { get { return _payload._parent.map { _NodeReference($0) } } set { _payload._parent = newValue.map { _UnownedUnsafeNodeReference($0) } } } internal var _leftChild: _NodeReference<Element>? { get { return _payload._leftChild } set { _payload._leftChild = newValue } } internal var _rightChild: _NodeReference<Element>? { get { return _payload._rightChild } set { _payload._rightChild = newValue } } internal var _data: Element { get { return _payload._data } set { _payload._data = newValue } } internal init(_payload: _NodePayload<Element>) { self._payload = _payload } internal init( _data: Element, parent: _NodeReference<Element>? = nil, leftChild: _NodeReference<Element>? = nil, rightChild: _NodeReference<Element>? = nil ) { self._payload = _NodePayload( _data: _data, parent: parent, leftChild: leftChild, rightChild: rightChild) self._leftChild?._parent = self self._rightChild?._parent = self } } internal func === <Element : Comparable>( lhs: _NodeReference<Element>?, rhs: _NodeReference<Element>? ) -> Bool { return lhs?._payload === rhs?._payload } extension _NodeReference : CustomReflectable { internal func customMirror() -> Mirror { return Mirror(reflecting: _payload) } } /// Swift does not currently support optionals of unowned references. This /// type provides a workaround. <rdar://problem/17277899> internal struct _UnownedUnsafe<Instance : AnyObject> { internal unowned(unsafe) var _reference: Instance internal init(_ instance: Instance) { self._reference = instance } } internal struct _UnownedUnsafeNodeReference<Element : Comparable> { internal var _payload: _UnownedUnsafe<_NodePayload<Element>> internal init(_ ownedNode: _NodeReference<Element>) { self._payload = _UnownedUnsafe(ownedNode._payload) } } extension _NodeReference { internal init(_ unownedNode: _UnownedUnsafeNodeReference<Element>) { self._payload = unownedNode._payload._reference } } internal let _myBinaryTreeNextTreeID: _stdlib_AtomicInt = _stdlib_AtomicInt() // FIXME: implement value semantics. public struct MyBinaryTree<Element : Comparable> { internal var _treeID: Int internal var _root: _NodeReference<Element>? internal init(_root: _NodeReference<Element>?) { self._treeID = _myBinaryTreeNextTreeID.fetchAndAdd(1) self._root = _root } public init() { self = MyBinaryTree(_root: nil) } public mutating func insert(_ element: Element) { self = MyBinaryTree(_root: MyBinaryTree._insert(element, into: _root)) } internal static func _insert( _ element: Element, into root: _NodeReference<Element>? ) -> _NodeReference<Element> { guard let root = root else { // The tree is empty, create a new one. return _NodeReference(_data: element) } if element < root._data { // Insert into the left subtree. return _NodeReference( _data: root._data, leftChild: _insert(element, into: root._leftChild), rightChild: root._rightChild) } if element > root._data { // Insert into the right subtree. return _NodeReference( _data: root._data, leftChild: root._leftChild, rightChild: _insert(element, into: root._rightChild)) } // We found the element in the tree, update it (to preserve reference // equality). _precondition(element == root._data) return _NodeReference( _data: element, leftChild: root._leftChild, rightChild: root._rightChild) } } internal struct _MyBinaryTreePath { internal var _path: UInt internal var parent: _MyBinaryTreePath { let distanceToParent = (_path | (_path &+ 1)) ^ _path let newPath = (_path | (_path &+ 1)) & ~(distanceToParent << 1) return _MyBinaryTreePath(_path: newPath) } internal var leftChild: _MyBinaryTreePath { let delta = ~_path & (_path &+ 1) let newPath = _path &- (delta >> 1) return _MyBinaryTreePath(_path: newPath) } internal var rightChild: _MyBinaryTreePath { let delta = ~_path & (_path &+ 1) let newPath = _path &+ (delta >> 1) return _MyBinaryTreePath(_path: newPath) } internal static var root: _MyBinaryTreePath { return _MyBinaryTreePath(_path: UInt(Int.max)) } internal static var endIndex: _MyBinaryTreePath { return _MyBinaryTreePath(_path: UInt.max) } } public struct MyBinaryTreeIndex<Element : Comparable> : Comparable { internal var _treeID: Int internal var _path: _MyBinaryTreePath internal var _unsafeNode: _UnownedUnsafeNodeReference<Element>? } public func == <Element : Comparable>( lhs: MyBinaryTreeIndex<Element>, rhs: MyBinaryTreeIndex<Element> ) -> Bool { _precondition( lhs._treeID == rhs._treeID, "can't compare indices from different trees") return lhs._path._path == rhs._path._path } public func < <Element : Comparable>( lhs: MyBinaryTreeIndex<Element>, rhs: MyBinaryTreeIndex<Element> ) -> Bool { _precondition( lhs._treeID == rhs._treeID, "can't compare indices from different trees") return lhs._path._path < rhs._path._path } extension MyBinaryTree : MyBidirectionalCollectionType { public typealias Index = MyBinaryTreeIndex<Element> public var startIndex: Index { guard var root = _root else { return endIndex } var path = _MyBinaryTreePath.root while let lc = root._leftChild { root = lc path = path.leftChild } return Index( _treeID: _treeID, _path: path, _unsafeNode: _UnownedUnsafeNodeReference(root)) } public var endIndex: Index { return Index( _treeID: _treeID, _path: _MyBinaryTreePath.endIndex, _unsafeNode: nil) } public subscript(i: Index) -> Element { _precondition( i._treeID == _treeID, "can't use index from another tree") guard let node = i._unsafeNode.map({ _NodeReference($0) }) else { fatalError("can't subscript with endIndex") } return node._data } @warn_unused_result public func next(_ i: Index) -> Index { _precondition( i._treeID == _treeID, "can't use index from another tree") guard var node = i._unsafeNode.map({ _NodeReference($0) }) else { fatalError("can't increment endIndex") } var path = i._path if let rightChild = node._rightChild { node = rightChild path = path.rightChild while let lc = node._leftChild { node = lc path = path.leftChild } return Index( _treeID: i._treeID, _path: path, _unsafeNode: _UnownedUnsafeNodeReference(node)) } while true { guard let parent = node._parent else { return endIndex } let isLeftChild = parent._leftChild === node node = parent path = path.parent if isLeftChild { return Index( _treeID: i._treeID, _path: path, _unsafeNode: _UnownedUnsafeNodeReference(node)) } } } @warn_unused_result public func previous(_ i: Index) -> Index { _precondition( i._treeID == _treeID, "can't use index from another tree") var path = i._path guard var node = i._unsafeNode.map({ _NodeReference($0) }) else { // We are decrementing endIndex. guard var root = _root else { // The tree is empty. fatalError("can't decrement startIndex") } path = _MyBinaryTreePath.root while let rc = root._rightChild { root = rc path = path.rightChild } return Index( _treeID: _treeID, _path: path, _unsafeNode: _UnownedUnsafeNodeReference(root)) } if let leftChild = node._leftChild { node = leftChild path = path.leftChild while let rc = node._rightChild { node = rc path = path.rightChild } return Index( _treeID: i._treeID, _path: path, _unsafeNode: _UnownedUnsafeNodeReference(node)) } while true { guard let parent = node._parent else { return startIndex } let isRightChild = parent._rightChild === node node = parent path = path.parent if isRightChild { return Index( _treeID: i._treeID, _path: path, _unsafeNode: _UnownedUnsafeNodeReference(node)) } } } } //------------------------------------------------------------------------ import StdlibUnittest var NewCollection = TestSuite("NewCollection") NewCollection.test("index") { expectEqual(1, MyArray([1,2,3]).index(of: 2)) expectEmpty(MyArray([1,2,3]).index(of: 42)) } NewCollection.test("bubbleSortInPlace") { var a = MyArray([4,3,2,1]) a.bubbleSortInPlace() expectEqual([1,2,3,4], a._elements) } NewCollection.test("lowerBoundOf/empty") { var a = MyArray<Int>([]) expectEqual(0, a.lowerBoundOf(3)) } NewCollection.test("lowerBoundOf/one") { var a = MyArray<Int>([10]) expectEqual(0, a.lowerBoundOf(9)) expectEqual(0, a.lowerBoundOf(10)) expectEqual(1, a.lowerBoundOf(11)) } NewCollection.test("lowerBoundOf") { var a = MyArray([1,2,2,3,3,3,3,3,3,3,3,4,5,6,7]) expectEqual(3, a.lowerBoundOf(3)) } NewCollection.test("first") { expectOptionalEqual(1, MyArray([1,2,3]).first) expectEmpty(MyArray<Int>().first) } NewCollection.test("count") { expectEqual(3, MyArray([1,2,3]).count) expectEqual(0, MyArray<Int>().count) } NewCollection.test("isEmpty") { expectFalse(MyArray([1,2,3]).isEmpty) expectTrue(MyArray<Int>().isEmpty) } NewCollection.test("popFirst") { let c = MyArray([1,2,3]) var s0 = c[c.startIndex..<*c.endIndex] var s = c[MyRange(start: c.startIndex, end: c.endIndex)] expectOptionalEqual(1, s.popFirst()) expectOptionalEqual(2, s.popFirst()) expectOptionalEqual(3, s.popFirst()) expectEmpty(s.popFirst()) } NewCollection.test("dropFirst") { do { let c = MySimplestForwardCollection([] as Array<Int>) let s = c.dropFirst(3) expectEqualSequence([], OldSequence(s)) } do { let c = MySimplestForwardCollection([10, 20, 30, 40, 50]) let s = c.dropFirst(3) expectEqualSequence([40, 50], OldSequence(s)) } } NewCollection.test("dropLast") { do { let c = MySimplestForwardCollection([] as Array<Int>) let s = c.dropLast(3) expectEqualSequence([], OldSequence(s)) } do { let c = MySimplestForwardCollection([10, 20, 30, 40, 50]) let s = c.dropLast(3) expectEqualSequence([10, 20], OldSequence(s)) } } NewCollection.test("prefix") { do { let c = MySimplestForwardCollection([] as Array<Int>) let s = c.prefix(3) expectEqualSequence([], OldSequence(s)) } do { let c = MySimplestForwardCollection([10, 20, 30, 40, 50]) let s = c.prefix(3) expectEqualSequence([10, 20, 30], OldSequence(s)) } do { let c = MySimplestForwardCollection([10, 20, 30, 40, 50]) let s = c.prefix(Int.max) expectEqualSequence([10, 20, 30, 40, 50], OldSequence(s)) } } NewCollection.test("suffix") { do { let c = MySimplestForwardCollection([] as Array<Int>) let s = c.suffix(3) expectEqualSequence([], OldSequence(s)) } do { let c = MySimplestForwardCollection([10, 20, 30, 40, 50]) let s = c.suffix(3) expectEqualSequence([30, 40, 50], OldSequence(s)) } do { let c = MySimplestForwardCollection([10, 20, 30, 40, 50]) let s = c.suffix(Int.max) expectEqualSequence([10, 20, 30, 40, 50], OldSequence(s)) } } NewCollection.test("RangeLiterals") { let comparable = MinimalComparableValue(0) let strideable = MySimplestStrideable(0) var comparableRange = comparable..<*comparable expectType(MyRange<MinimalComparableValue>.self, &comparableRange) var strideableRange = strideable..<*strideable expectType(MyIterableRange<MySimplestStrideable>.self, &strideableRange) for _ in OldSequence(0..<*10) {} } NewCollection.test("MyBinaryTree.init()") { _ = MyBinaryTree<Int>() } NewCollection.test("MyBinaryTree.insert(_:)") { var t = MyBinaryTree<Int>() t.insert(20) t.insert(10) t.insert(30) dump(t) do { var i = t.startIndex expectEqual(10, t[i]) i = t.next(i) expectEqual(20, t[i]) i = t.next(i) expectEqual(30, t[i]) i = t.next(i) expectEqual(t.endIndex, i) } do { var i = t.endIndex i = t.previous(i) dump(i, name: "30") expectEqual(30, t[i]) i = t.previous(i) dump(i, name: "20") expectEqual(20, t[i]) i = t.previous(i) dump(i, name: "10") expectEqual(10, t[i]) expectEqual(t.startIndex, i) } } runAllTests()
apache-2.0
a0877ff8d23e9402b8ca2c597984d6b2
28.751187
111
0.672928
4.124276
false
false
false
false
akuraru/PureViewIcon
Sample/ViewController.swift
1
759
// // ViewController.swift // Sample // // Created by akuraru on 2017/02/11. // // import UIKit import PureViewIcon class ViewController: UIViewController { @IBOutlet weak var slider: UISlider! weak var viewController: CollectionViewController! @IBAction func changeSlider(_ sender: Any) { let value = CGFloat(self.slider.value) viewController.size = CGSize(width: value, height: value) viewController.collectionView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "collection" { if let controller = segue.destination as? CollectionViewController { viewController = controller } } } }
mit
112c6b4c26e373012ebb7e9ec248dbfb
24.3
80
0.653491
4.74375
false
false
false
false
samodom/CoreDataSwagger
CoreDataSwaggerTests/Tools/TestingHelpers.swift
1
1656
// // TestingHelpers.swift // CoreDataSwagger // // Created by Sam Odom on 10/29/14. // Copyright (c) 2014 Swagger Soft. All rights reserved. // import CoreData internal var DocumentsDirectoryURL: NSURL { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let basePath = paths[0] as String return NSURL(fileURLWithPath: basePath)! } internal func URLofFileInDocumentsDirectory(named filename: String) -> NSURL? { let path = DocumentsDirectoryURL.path!.stringByAppendingPathComponent(filename) return NSURL(fileURLWithPath: path) } internal func DeleteFile(atURL URL: NSURL) { let fileManager = NSFileManager.defaultManager() if !URL.fileURL { return } let filePath = URL.path! if fileManager.fileExistsAtPath(filePath) { fileManager.removeItemAtPath(filePath, error: nil) } } internal func URLofBundledFile(named filename: String, ofType type: String) -> NSURL? { for bundle in NSBundle.allBundles() as [NSBundle] { let URL = bundle.URLForResource(filename, withExtension: type) if URL != nil { return URL } } return nil } internal func BundleForModel(named modelName: String) -> NSBundle! { let allBundles = NSBundle.allBundles() as [NSBundle] for bundle in allBundles { if bundle.bundleURL.path!.rangeOfString(modelName) != nil { return bundle } } return nil } internal func LoadModel(named name: String) -> NSManagedObjectModel! { let URL = URLofBundledFile(named: name, ofType: "momd")! return NSManagedObjectModel(contentsOfURL: URL)! }
mit
9b298e17c710823d45f00b2d4b577ead
27.067797
94
0.695048
4.392573
false
false
false
false
tkremenek/swift
test/IRGen/async/weak_availability.swift
2
550
// RUN: %target-swift-frontend -enable-implicit-dynamic -target %target-cpu-apple-macosx11 -Onone -emit-ir %s | %FileCheck --check-prefix=MAYBE-AVAILABLE %s // REQUIRES: OS=macosx && CPU=x86_64 @available(macOS 12.0, *) public func f<S: AsyncSequence>(_ s: S) async throws -> Any.Type { for try await _ in s { } typealias Fn = @MainActor () -> S.Element return Fn.self } // MAYBE-AVAILABLE: @"$sScI4next7ElementQzSgyYaKFTjTu" = extern_weak global // MAYBE-AVAILABLE: declare{{.*}} extern_weak{{.*}} @swift_getFunctionTypeMetadataGlobalActor
apache-2.0
8e3560713d6bba47bb63ba2264578dda
41.307692
156
0.705455
3.27381
false
false
false
false
mcrollin/safecaster
safecaster/SCRImportsHistoryDetailedTableViewCell.swift
1
2941
// // SCRImportsHistoryDetailedTableViewCell.swift // safecaster // // Created by Marc Rollin on 7/23/15. // Copyright (c) 2015 safecast. All rights reserved. // import UIKit import ReactiveCocoa import KVNProgress class SCRImportsHistoryDetailedTableViewCell: UITableViewCell { @IBOutlet var nameLabel: UILabel! @IBOutlet var statusLabel: UILabel! @IBOutlet var detailsLabel: UILabel! @IBOutlet var actionButton: UIButton! var viewModel: SCRImportsHistoryViewModel? var logImport: SCRImport? { didSet { if let logImport = logImport { let color = logImport.hasAction ? UIApplication.sharedApplication().keyWindow!.tintColor : UIColor.lightGrayColor() nameLabel.text = logImport.name statusLabel.text = logImport.status?.uppercaseString detailsLabel.text = logImport.fullDetails nameLabel.sizeToFit() statusLabel.layer.cornerRadius = CGRectGetHeight(statusLabel.frame) / 2 actionButton.layer.cornerRadius = statusLabel.frame.size.height / 2 actionButton.layer.borderColor = color.CGColor actionButton.clipsToBounds = true actionButton.enabled = logImport.hasAction actionButton.setTitle(logImport.actionName, forState: .Normal) actionButton.setTitleColor(color, forState: .Normal) actionButton.roundBorder(color.colorWithAlphaComponent(0.8)) lastImportActionButtonTapped() UIView.animateWithDuration(0.3, animations: { self.actionButton.alpha = 1 }) } } } override func awakeFromNib() { super.awakeFromNib() self.actionButton.alpha = 0 } private func lastImportActionButtonTapped() { actionButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { _ in self.actionButton.enabled = false KVNProgress.show() UIView.animateWithDuration(0.3, animations: { self.actionButton.alpha = 0 }) self.logImport?.actionSignal() .subscribeNext({ result in log("NEXT \(result)") }, error: { error in UIView.animateWithDuration(0.3, animations: { self.actionButton.alpha = 1 }) KVNProgress.showError() log("ERROR \(error)") }, completed: { _ in KVNProgress.showSuccess() self.viewModel?.updateImports() }) } } }
cc0-1.0
0e717f23920574c094251735aa7d4aa0
34.865854
131
0.548453
5.766667
false
false
false
false
yikaicao/FoodTracker
FoodTracker/ViewController.swift
1
2647
// // ViewController.swift // FoodTracker // // Created by Yikai Cao on 1/30/17. // Copyright © 2017 Yikai Cao. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { //MARK: Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var mealNameLabel: UILabel! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var ratingControl: RatingControl! override func viewDidLoad() { super.viewDidLoad() // Handle the text field’s user input through delegate callbacks. nameTextField.delegate = self } //MARK: UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Hide the keyboard. textField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { mealNameLabel.text = textField.text } //MARK: UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { // Dismiss the picker if the user canceled. dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // The info dictionary may contain multiple representations of the image. You want to use the original. guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { fatalError("Expected a dictionary containing an image, but was provided the following: \(info)") } // Set photoImageView to display the selected image. photoImageView.image = selectedImage // Dismiss the picker. dismiss(animated: true, completion: nil) } //MARK: Actions @IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) { // Hide the keyboard. nameTextField.resignFirstResponder() // UIImagePickerController is a view controller that lets a user pick media from their photo library. let imagePickerController = UIImagePickerController() // Only allow photos to be picked, not taken. imagePickerController.sourceType = .photoLibrary // Make sure ViewController is notified when the user picks an image. imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } }
mit
e39b93c1d9dc0f78dc83c9e65f368be8
33.789474
126
0.677761
5.995465
false
false
false
false
xwu/swift
test/IRGen/retroactive_conformance_path.swift
2
1316
// RUN: %empty-directory(%t) // RUN: %target-build-swift -module-name=test %s -o %t/a.out -requirement-machine=verify // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test // REQUIRES: CPU=arm64 || CPU=x86_64 // Check that the ASTMangler does not crash when mangling a retroactive conformance // and also do a executable test to make sure the code works as expected. extension Result: RandomAccessCollection, BidirectionalCollection, Collection, Sequence where Success: RandomAccessCollection, Success.Index == Int { public typealias Element = Result<Success.Element, Failure> public typealias Index = Int public var startIndex: Int { switch self { case .success(let array): return array.startIndex case .failure: return 0 } } public var endIndex: Int { switch self { case .success(let array): return array.endIndex case .failure: return 1 } } public subscript(position: Int) -> Result<Success.Element, Failure> { switch self { case .success(let array): return .success(array[position]) case .failure(let error): return .failure(error) } } } let coll: [Int] = [4, 8, 15, 16, 23, 42] let result: Result<[Int], Error> = .success(coll) // CHECK: success(15) print(result[2])
apache-2.0
8af4f5fafaaa416da130b441fb4b5ac0
30.333333
149
0.668693
3.792507
false
true
false
false
acort3255/Emby.ApiClient.Swift
Emby.ApiClient/model/dto/BaseItemDto.swift
1
12689
// // BaseItemDto.swift // Emby.ApiClient // import Foundation public class BaseItemDto : Codable { public var name: String? public var serverId: String? public var id: String? public var etag: String? public var playlistItemid: String? public var dateCreated: Date? public var dateLastMediaAdded: Date? public var extraType: ExtraType? public var airsBeforeSeasonNumber: Int? public var airsAfterSeasonNumber: Int? public var airsBeforeEpisodeNumber: Int? public var absoluteEpisodeNumber: Int? public var displaySpecialWithSeasons: Bool? public var canDelete: Bool? public var canDownload: Bool? public var hasSubtitles: Bool? public var preferredMetadataLanguage: String? public var preferredMetadataCountryCode: String? public var awardSummary: String? public var shareUrl: String? public var metascore: Float? public var hasDynamicCategories: Bool? public var animeSeriesIndex: Int? public var supportsSync: Bool? public var hasSyncJob: Bool? public var isSynced: Bool? public var syncStatus: SyncJobStatus? public var syncPercent: Double? public var dvdSeasonNumber: Int? public var dvdEpisodeNumber: Int? public var sortName: String? public var forcedSortName: String? public var video3dFormat: Video3DFormat? public var premierDate: Date? public var externalUrls: [ExternalUrl]? public var mediaSources: [MediaSourceInfo]? public var criticRating: Float? public var gameSystem: String? public var criticRatingSummary: String? public var multiPartGameFiles: [String]? public var path: String? public var officialRating: String? public var customRating: String? public var channelId: String? public var channelName: String? public var overview: String? public var shortOverview: String? public var tmdbCollectionName: String? public var tagLines: [String]? public var genres: [String]? public var seriesGenres: [String]? public var communityRating: Float? public var voteCount: Int? public var cumulativeRunTimeTicks: Int? public var originalRunTimeTicks: Int? public var runTimeTicks: Int? // public var playAccess: PlayAccess? public var aspectRation: String? public var productionYear: Int? public var players: Int? public var isPlaceHolder: Bool? public var indexNumber: Int? public var indexNumberEnd: Int? public var parentIndexNumber: Int? public var remoteTrailers: [MediaUrl]? public var soundtrackIds: [String]? public var providerIds: [String:String]? public var isHd: Bool? public var isFolder: Bool? public var parentId: String? public var type: String? public var people: [BaseItemPerson]? public var studios: [StudioDto]? public var parentLogoItemId: String? public var parentBackdropItemId: String? public var parentBackdropImageTags: [String]? public var localTrailerCount: Int? public var userData: UserItemDataDto? public var seasonUserData: UserItemDataDto? public var recursiveItemCount: Int? public var childCount: Int? public var seriesName: String? public var seriesId: String? public var seasonId: String? public var specialFeatureCount: Int? public var displayPreferencesId: String? public var status: String? public var seriesStatus: SeriesStatus? { get { if let status = self.status { return SeriesStatus(rawValue: status) } else { return nil } } set { status = newValue!.rawValue } } public var recordingStatus: RecordingStatus? { get { if let status = self.status { return RecordingStatus(rawValue: status) } else { return nil } } set { status = newValue!.rawValue } } public var airTime: String? public var airDays: [String]? public var indexOptions: [String]? public var tags: [String]? public var keywords: [String]? public var primaryImageAspectRatio: Double? public var originalPrimaryImageAspectRatio: Double? public var artists: [String]? public var artistItems: [NameIdPair]? public var album: String? public var collectionType: String? public var displayOrder: String? public var albumId: String? public var albumPrimaryImageTag: String? public var seriesPrimaryImageTag: String? public var albumArtist: String? public var albumArtists: [NameIdPair]? public var seasonName: String? public var mediaStreams: [MediaStream]? public var videoType: VideoType? public var displayMediaType: String? public var partCount: Int? public var mediaSourceCount: Int? public var supportsPlayLists: Bool { get { return (runTimeTicks != nil) || ((isFolder != nil) && isFolder!) || isGenre || isMusicGenre || isArtist } } public func isType(type: String) -> Bool { return self.type == type } /* TODO: The problem is that Dictionary's Codable conformance can currently only properly handle String and Int keys. For a dictionary with any other Key type (where that Key is Encodable/Decodable), it is encoded and decoded with an unkeyed container (JSON array) with alternating key values. For now just use a string dictionary Source: https://stackoverflow.com/questions/44725202/swift-4-decodable-dictionary-with-enum-as-key?rq=1 */ // public var imageTags: [ImageType: String]? public var imageTags: [String: String]? public var backdropImageTags: [String]? public var screenshotImageTags: [String]? public var parentLogoImageTag: String? public var parentArtItemId: String? public var parentArtImageTag: String? public var seriesThumbImageTag: String? public var seriesStudio: String? public var parentThumbItemId: String? public var parentThumbImageTag: String? public var parentPrimaryImageItemId: String? public var parentPrimaryImageTag: String? public var chapters: [ChapterInfoDto]? public var locationType: LocationType? public var isoType: IsoType? public var mediaType: String? public var endDate: Date? public var homePageUrl: String? public var productionLocations: [String]? public var budget: Double? public var revenue: Double? public var lockedFields: [MetadataFields]? public var movieCount: Int? public var seriesCount: Int? public var episodeCount: Int? public var gameCount: Int? public var songCount: Int? public var albumCount: Int? public var musicVideoCount: Int? public var lockData: Bool? public var width: Int? public var height: Int? public var cameraMake: String? public var cameraModel: String? public var software: String? public var exposureTime: Double? public var focalLength: Double? public var imageOrientation: ImageOrientation? public var aperture: Double? public var shutterSpeed: Double? public var latitude: Double? public var longitude: Double? public var altitude: Double? public var isoSpeedRating: Int? public var recordingCount: Int? public var seriesTimerId: String? public var canResume: Bool { get { if let playbackPositionTicks = userData?.playbackPositionTicks { return playbackPositionTicks > 0 } else { return false } } } public var resumePositionTicks: Int { get { if let playbackPositionTicks = userData?.playbackPositionTicks { return playbackPositionTicks } else { return 0 } } } public var backdropCount: Int { get { return (backdropImageTags != nil) ? backdropImageTags!.count : 0 } } public var screenshotCount: Int { get { return (screenshotImageTags != nil) ? screenshotImageTags!.count : 0 } } public var hasBanner: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Banner.rawValue] != nil : false } } public var hasArtImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Art.rawValue] != nil : false } } public var hasLogo: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Logo.rawValue] != nil : false } } public var hasThumb: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Thumb.rawValue] != nil : false } } public var hasPrimaryImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Primary.rawValue] != nil : false } } public var hasDiscImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Disc.rawValue] != nil : false } } public var hasBoxImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Box.rawValue] != nil : false } } public var hasBoxRearImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.BoxRear.rawValue] != nil : false } } public var hasMenuImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Menu.rawValue] != nil : false } } public var isVideo: Bool { get { return mediaType == MediaType.Video.rawValue } } public var isGame: Bool { get { return mediaType == MediaType.Game.rawValue } } public var isPerson: Bool { get { return mediaType == "Person" } } public var isRoot: Bool { get { return mediaType == "AggregateFolder" } } public var isMusicGenre: Bool { get { return mediaType == "MusicGenre" } } public var isGameGenre: Bool { get { return mediaType == "GameGenre" } } public var isGenre: Bool { get { return mediaType == "Genre" } } public var isArtist: Bool { get { return mediaType == "MusicArtist" } } public var isAlbum: Bool { get { return mediaType == "MusicAlbum" } } public var IsStudio: Bool { get { return mediaType == "Studio" } } public var supportsSimilarItems: Bool { get { return isType(type: "Movie") || isType(type: "Series") || isType(type: "MusicAlbum") || isType(type: "MusicArtist") || isType(type: "Program") || isType(type: "Recording") || isType(type: "ChannelVideoItem") || isType(type: "Game") } } public var programId: String? public var channelPrimaryImageTag: String? public var startDate: Date? public var completionPercentage: Double? public var isRepeat: Bool? public var episodeTitle: String? public var channelType: ChannelType? public var audio: ProgramAudio? public var isMovie: Bool? public var isSports: Bool? public var isSeries: Bool? public var isLive: Bool? public var isNews: Bool? public var isKids: Bool? public var isPremiere: Bool? public var timerId: String? public var currentProgram: BaseItemDto? public required init?(jSON: JSON_Object) { //fatalError("init(jSON:) has not been implemented: \(jSON)") self.name = jSON["Name"] as? String self.id = jSON["Id"] as? String } enum CodingKeys: String, CodingKey { case name = "Name" case serverId = "ServerId" case id = "Id" case productionYear = "ProductionYear" case runTimeTicks = "RunTimeTicks" case officialRating = "OfficialRating" case communityRating = "CommunityRating" case criticRating = "CriticRating" case tagLines = "Taglines" case overview = "Overview" case people = "People" case imageTags = "ImageTags" case seriesName = "SeriesName" case seriesId = "SeriesId" case seasonId = "SeasonId" case indexNumber = "IndexNumber" case genres = "Genres" case seriesGenres = "SeriesGenres" } }
mit
031ce107dc1b83e62db156fdf2f75390
30.330864
334
0.62897
4.494864
false
false
false
false
andrewcar/hoods
Project/hoods/hoods/BubbleView.swift
1
2391
// // BubbleView.swift // hoods // // Created by Andrew Carvajal on 12/7/17. // Copyright © 2017 YugeTech. All rights reserved. // import UIKit class BubbleView: UIView { let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.white label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.numberOfLines = 1 label.adjustsFontSizeToFitWidth = true label.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 100) addSubview(label) let constraints: [NSLayoutConstraint] = [ label.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), label.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 5), label.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -5), label.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor) ] NSLayoutConstraint.activate(constraints) } init(frame: CGRect, text: String) { super.init(frame: frame) backgroundColor = UIColor.white label.text = text label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.numberOfLines = 0 label.adjustsFontSizeToFitWidth = true label.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 100) addSubview(label) let constraints: [NSLayoutConstraint] = [ label.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), label.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 5), label.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -5), label.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor) ] NSLayoutConstraint.activate(constraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
472b9b0dae05859cb3506adf92c71097
32.194444
96
0.649791
5.287611
false
false
false
false
zerovagner/iOS-Studies
Pokedex/Pokedex/csv.swift
1
2512
// // CSV // Modified by Mark Price on 08/14/15 // import Foundation public class CSV { public var headers: [String] = [] public var rows: [Dictionary<String, String>] = [] public var columns = Dictionary<String, [String]>() var delimiter = CharacterSet(charactersIn: ",") public init(content: String?, delimiter: CharacterSet, encoding: UInt) throws{ if let csvStringToParse = content{ self.delimiter = delimiter let newline = CharacterSet.newlines var lines: [String] = [] csvStringToParse.trimmingCharacters(in: newline).enumerateLines { line, stop in lines.append(line) } self.headers = self.parseHeaders(fromLines: lines) self.rows = self.parseRows(fromLines: lines) self.columns = self.parseColumns(fromLines: lines) } } public convenience init(contentsOfURL url: String) throws { let comma = CharacterSet(charactersIn: ",") let csvString: String? do { csvString = try String(contentsOfFile: url, encoding: String.Encoding.utf8) } catch _ { csvString = nil }; try self.init(content: csvString,delimiter:comma, encoding:String.Encoding.utf8.rawValue) } func parseHeaders(fromLines lines: [String]) -> [String] { return lines[0].components(separatedBy: self.delimiter) } func parseRows(fromLines lines: [String]) -> [Dictionary<String, String>] { var rows: [Dictionary<String, String>] = [] for (lineNumber, line) in lines.enumerated() { if lineNumber == 0 { continue } var row = Dictionary<String, String>() let values = line.components(separatedBy: self.delimiter) for (index, header) in self.headers.enumerated() { if index < values.count { row[header] = values[index] } else { row[header] = "" } } rows.append(row) } return rows } func parseColumns(fromLines lines: [String]) -> Dictionary<String, [String]> { var columns = Dictionary<String, [String]>() for header in self.headers { let column = self.rows.map { row in row[header] != nil ? row[header]! : "" } columns[header] = column } return columns } }
gpl-3.0
48f865280ae4a69b024f0fde91dc54bb
31.623377
112
0.558519
4.67784
false
false
false
false
ptiz/bender
BenderTests/BenderOutputTests.swift
1
14988
// // BenderOutputTests.swift // Bender // // Created by Evgenii Kamyshanov on 24.01.16. // Copyright © 2016 Evgenii Kamyshanov. // // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest import Quick import Nimble import Bender extension Passports { convenience init(numbers: [Int], items: [Passport]) { self.init() self.items = items self.numbers = numbers } } extension Passport { convenience init(number: Int?, issuedBy: String, valid: Bool) { self.init() self.issuedBy = issuedBy self.number = number self.valid = valid } } extension Person { convenience init(passport: Passport) { self.init() self.passport = passport } } class AtomicTypes { var i: Int? var i8: Int8? var i16: Int16? var i32: Int32? var i64: Int64? var ui: UInt? var ui8: UInt8? var ui16: UInt16? var ui32: UInt32? var ui64: UInt64? var flt: Float? var dbl: Double? var b: Bool? var s: String? init(i: Int = 0, i8: Int8 = 0, i16: Int16 = 0, i32: Int32 = 0, i64: Int64 = 0, ui: UInt = 0, ui8: UInt8 = 0, ui16: UInt16 = 0, ui32: UInt32 = 0, ui64: UInt64 = 0, flt: Float = 0, dbl: Double = 0, b: Bool = false, s: String = "") { self.i = i self.i8 = i8 self.i16 = i16 self.i32 = i32 self.i64 = i64 self.ui = ui self.ui8 = ui8 self.ui16 = ui16 self.ui32 = ui32 self.ui64 = ui64 self.flt = flt self.dbl = dbl self.b = b self.s = s } } class BenderOutTests: QuickSpec { override func spec() { describe("Atomic types dump") { it("Should support all the types listed in AtomicTypes struct") { var atomicRule = ClassRule(AtomicTypes()) .optional("i", IntRule) { $0.i } .optional("i8", Int8Rule) { $0.i8 } .optional("i16", Int16Rule) { $0.i16 } .optional("i32", Int32Rule) { $0.i32 } .optional("i64", Int64Rule) { $0.i64 } .optional("ui", UIntRule) { $0.ui } .optional("ui8", UInt8Rule) { $0.ui8 } //Compiler goes mad trying to parse all the expression, so we just split it into two atomicRule = atomicRule .optional("ui16", UInt16Rule) { $0.ui16 } .optional("ui32", UInt32Rule) { $0.ui32 } .optional("ui64", UInt64Rule) { $0.ui64 } .optional("flt", FloatRule) { $0.flt } .optional("dbl", DoubleRule) { $0.dbl } .optional("b", BoolRule) { $0.b } .optional("s", StringRule) { $0.s } let a = AtomicTypes(i: -1, i8: -2, i16: -3, i32: -4, i64: -5, ui: 6, ui8: 7, ui16: 8, ui32: 9, ui64: 10, flt: 11.1, dbl: 12121212.1212121212, b: true, s: "the string") let passString = try! StringifiedJSONRule(nestedRule: atomicRule).dump(a) as! String expect(passString).to(contain("\"i\":-1")) expect(passString).to(contain("\"i8\":-2")) expect(passString).to(contain("\"i16\":-3")) expect(passString).to(contain("\"i32\":-4")) expect(passString).to(contain("\"i64\":-5")) expect(passString).to(contain("\"ui\":6")) expect(passString).to(contain("\"ui8\":7")) expect(passString).to(contain("\"ui16\":8")) expect(passString).to(contain("\"ui32\":9")) expect(passString).to(contain("\"ui64\":10")) expect(passString).to(contain("\"flt\":11.1")) expect(passString).to(contain("\"dbl\":12121212.12121212")) expect(passString).to(contain("\"b\":true")) expect(passString).to(contain("\"s\":\"the string\"")) } } describe("Basic struct dump") { it("should perform nested struct output to dict") { let folderRule = StructRule(ref(Folder(name: "", size: 0, folders: nil))) .expect("name", StringRule, { $0.value.name = $1 }) { $0.name } .expect("size", Int64Rule, { $0.value.size = $1 }) { $0.size } let _ = folderRule .optional("folders", ArrayRule(itemRule: folderRule), { $0.value.folders = $1 }) { $0.folders } let f = Folder(name: "Folder 1", size: 10, folders: [ Folder(name: "Folder 21", size: 11, folders: nil), Folder(name: "Folder 22", size: 12, folders: nil) ]) let d = try! folderRule.dumpData(f) let newF = try! folderRule.validateData(d) expect(newF.name).to(equal("Folder 1")) expect(newF.size).to(equal(10)) expect(newF.folders!.count).to(equal(2)) } it("should allow only dump structs") { let folderRule = StructRule(ref(Folder(name: "", size: 0, folders: nil))) .expect("name", StringRule) { $0.name } .expect("size", Int64Rule) { $0.size } let _ = folderRule .optional("folders", ArrayRule(itemRule: folderRule)) { $0.folders } let f = Folder(name: "Folder 1", size: 10, folders: [ Folder(name: "Folder 21", size: 11, folders: nil), Folder(name: "Folder 22", size: 12, folders: nil) ]) let d = try! folderRule.dump(f) as! [String: AnyObject] let name = d["name"] as! String expect(name).to(equal("Folder 1")) let folders = d["folders"] as! [AnyObject] expect(folders.count).to(equal(2)) } it("should be able to dump 'null' values with expect") { let passportRule = ClassRule(Passport()) .expect("issuedBy", StringRule) { $0.issuedBy } .expect("number", IntRule) { $0.number } .expect("valid", BoolRule) { $0.valid } let pass = Passport(number: nil, issuedBy: "One", valid: false) let passJson = try! passportRule.dump(pass) as! [String: AnyObject] expect(passJson["issuedBy"] as? String).to(equal("One")) expect(passJson["number"] as? NSNull).toNot(beNil()) let passString = try! StringifiedJSONRule(nestedRule: passportRule).dump(pass) as! String expect(passString).to(contain("\"number\":null")) } it("should be able to dump 'null' values with forceOptional") { let passportRule = ClassRule(Passport()) .expect("issuedBy", StringRule) { $0.issuedBy } .forceOptional("number", IntRule) { $0.number } .expect("valid", BoolRule) { $0.valid } let pass = Passport(number: nil, issuedBy: "One", valid: false) do { let passJson = try passportRule.dump(pass) as! [String: Any] expect(passJson["issuedBy"] as? String).to(equal("One")) expect(passJson["number"] as? NSNull).toNot(beNil()) let passString = try StringifiedJSONRule(nestedRule: passportRule).dump(pass) as! String expect(passString).to(contain("\"number\":null")) } catch { expect(error).to(beNil()) } } it("should be able to work with tuples") { let rule = StructRule(ref(("", 0))) .expect("name", StringRule) { $0.0 } .expect("number", IntRule) { $0.1 } do { let str = try StringifiedJSONRule(nestedRule: rule).dump(("Test13", 13)) as! String expect(str).to(contain("\"number\":13")) expect(str).to(contain("\"name\":\"Test13\"")) } catch { expect(error).to(beNil()) } } it("should be able to dump value at JSON path") { let userStruct = User(id: "123456", name: nil) let m = StructRule(ref(User(id: nil, name: nil))) .expect("message"/"payload"/"createdBy"/"user"/"id", StringRule, { $0.value.id = $1 }) { $0.id } .optional("message"/"payload"/"createdBy"/"user"/"login", StringRule) { $0.value.name = $1 } do { let data = try m.dump(userStruct) let user = try m.validate(data) expect(user).toNot(beNil()) expect(user.id).to(equal(userStruct.id)) } catch { expect(error).to(beNil()) } } } describe("Array dump") { it("should perform array dump as field in struct") { let passportRule = ClassRule(Passport()) .expect("issuedBy", StringRule, { $0.issuedBy = $1 }) { $0.issuedBy } .optional("number", IntRule) { $0.number = $1 } .expect("number", IntRule) { $0.number } .expect("valid", BoolRule, { $0.valid = $1 }) { $0.valid } let passportArrayRule = ArrayRule(itemRule: passportRule) let passportsRule = ClassRule(Passports()) .expect("passports", passportArrayRule, { $0.items = $1 }) { $0.items } .expect("numbers", ArrayRule(itemRule: IntRule), { $0.numbers = $1 }) { $0.numbers } let passports = Passports(numbers: [1, 2, 3, 14], items: [ Passport(number: 1, issuedBy: "One", valid: false), Passport(number: 2, issuedBy: "Two", valid: true), Passport(number: 13, issuedBy: "Nobody", valid: true) ]) let d = try! passportsRule.dump(passports) let newP = try! passportsRule.validate(d) expect(newP.numbers.count).to(equal(4)) expect(newP.items.count).to(equal(3)) expect(newP.items[2].number).to(equal(13)) expect(newP.items[2].issuedBy).to(equal("Nobody")) expect(newP.items[2].valid).to(equal(true)) } } describe("Enum dump") { it("should performs enum dump of any internal type") { let enumRule = EnumRule<IssuedBy>() .option("FMS", .fms) .option("SMS", .sms) .option("OPG", .opg) .option(0, .unknown) let intEnumRule = EnumRule<Active>() .option(0, .inactive) .option(1, .active) let testRule = StructRule(ref(Pass())) .expect("issuedBy", enumRule, { $0.value.issuedBy = $1 }) { $0.issuedBy } .expect("active", intEnumRule, { $0.value.active = $1 }) { $0.active } let testRules = ArrayRule(itemRule: testRule) let rules = [ Pass(issuedBy: .fms, active: .active), Pass(issuedBy: .opg, active: .inactive), Pass(issuedBy: .unknown, active: .inactive) ] let d = try! testRules.dump(rules) let newRules = try! testRules.validate(d) expect(newRules.count).to(equal(3)) expect(newRules[2].issuedBy).to(equal(IssuedBy.unknown)) expect(newRules[2].active).to(equal(Active.inactive)) } } describe("Stringified JSON dump") { it("should perform dump in accordance with the nested rule") { let passportRule = ClassRule(Passport()) .expect("issuedBy", StringRule, { $0.issuedBy = $1 }) { $0.issuedBy } .optional("number", IntRule, { $0.number = $1 }) { $0.number } .expect("valid", BoolRule, { $0.valid = $1 }) { $0.valid } let personRule = ClassRule(Person()) .expect("passport", StringifiedJSONRule(nestedRule: passportRule), { $0.passport = $1 }) { $0.passport } .optional("passports", StringifiedJSONRule(nestedRule: ArrayRule(itemRule: passportRule)), { $0.nested = $1 }) { $0.nested } let person = Person(passport: Passport(number: 101, issuedBy: "FMSS", valid: true)) let d = try! personRule.dump(person) let newP = try! personRule.validate(d) expect(newP.passport.number).to(equal(101)) expect(newP.passport.issuedBy).to(equal("FMSS")) } } } }
mit
a557190190115937e89c223f7e65e0a8
41.576705
183
0.484086
4.173489
false
false
false
false
GYLibrary/A_Y_T
GYVideo/Pods/EZPlayer/EZPlayer/AVAsset+EZPlayer.swift
1
3661
// // AVAsset+EZPlayer.swift // EZPlayer // // Created by yangjun zhu on 2016/12/28. // Copyright © 2016年 yangjun zhu. All rights reserved. // import AVFoundation public extension AVAsset { public var title: String? { var error: NSError? let status = self.statusOfValue(forKey: "commonMetadata", error: &error) if error != nil { return nil } if status == .loaded{ let metadataItems = AVMetadataItem.metadataItems(from: self.commonMetadata, withKey: AVMetadataCommonKeyTitle, keySpace: AVMetadataKeySpaceCommon) if metadataItems.count > 0 { let titleItem = metadataItems.first return titleItem?.value as? String } } return nil } public var closedCaption: [AVMediaSelectionOption]? { var closedCaptions = [AVMediaSelectionOption]() if let mediaSelectionGroup = self.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristicLegible){ for option in mediaSelectionGroup.options { if option.mediaType == "clcp" { closedCaptions.append(option) } } } if closedCaptions.count > 0{ return closedCaptions } return nil } public var subtitles: [(subtitle: AVMediaSelectionOption,localDisplayName: String)]? { var subtitles = [(subtitle: AVMediaSelectionOption,localDisplayName: String)]() if let mediaSelectionGroup = self.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristicLegible){ for option in mediaSelectionGroup.options { if !option.hasMediaCharacteristic(AVMediaCharacteristicContainsOnlyForcedSubtitles) { if let localDisplayName = self.localDisplayName(forMediaSelectionOption: option){ subtitles.append((option,localDisplayName)) } } } } if subtitles.count > 0{ return subtitles } return nil } public var audios: [(audio: AVMediaSelectionOption,localDisplayName: String)]? { var audios = [(audio: AVMediaSelectionOption,localDisplayName: String)]() if let mediaSelectionGroup = self.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristicAudible){ for option in mediaSelectionGroup.options { if let localDisplayName = self.localDisplayName(forMediaSelectionOption: option){ audios.append((option,localDisplayName)) } } if audios.count > 0{ return audios } } return nil } public func localDisplayName(forMediaSelectionOption subtitle: AVMediaSelectionOption) -> String?{ var title: String? = nil var metadataItems = AVMetadataItem.metadataItems(from: subtitle.commonMetadata, withKey: AVMetadataCommonKeyTitle, keySpace: AVMetadataKeySpaceCommon) if metadataItems.count > 0 { let preferredLanguages = NSLocale.preferredLanguages for language: String in preferredLanguages { let locale = Locale(identifier: language) var titlesForLocale = AVMetadataItem.metadataItems(from: metadataItems, with: locale) if titlesForLocale.count > 0 { title = titlesForLocale[0].stringValue break } } if title == nil { title = metadataItems[0].stringValue } } return title } }
mit
cb29fa5882f7fc7cdd949346852cfce3
37.505263
158
0.611536
5.387334
false
false
false
false
fiveagency/ios-five-persistence
Example/Classes/ViewControllers/ContentCell/ContentCell.swift
1
5571
// // ContentCell.swift // Example // // Created by Miran Brajsa on 10/04/16. // Copyright © 2016 Five Agency. All rights reserved. // import Foundation import UIKit class ContentCell: UITableViewCell, UIImagePickerControllerDelegate { private let imagePickerController = UIImagePickerController() private var viewModel: ContentCellViewModel? @IBOutlet private weak var headerView: UIView! @IBOutlet private weak var headerMarkerView: UIView! @IBOutlet private weak var exampleNumberLabel: UILabel! @IBOutlet private weak var descriptionView: UIView! @IBOutlet private weak var descriptionLabel: UILabel! @IBOutlet private weak var resultTitleLabel: UILabel! @IBOutlet private weak var resultLabel: UILabel! @IBOutlet private weak var actionButtonView: UIView! @IBOutlet private weak var actionButton: UIButton! @IBOutlet private weak var readWriteView: UIView! @IBOutlet private weak var keyTitleLabel: UILabel! @IBOutlet private weak var keyText: UITextField! @IBOutlet private weak var writeActionButton: UIButton! @IBOutlet private weak var readActionButton: UIButton! @IBOutlet private weak var stringReadResultView: UIView! @IBOutlet private weak var readResultTitleLabel: UILabel! @IBOutlet private weak var readResultLabel: UILabel! override func awakeFromNib() { setupAppearance() setupImagePickerController() } func setup(withViewModel viewModel: ContentCellViewModel) { self.viewModel = viewModel setupContent() } private func setupImagePickerController() { imagePickerController.allowsEditing = false imagePickerController.sourceType = .photoLibrary } private func setupAppearance() { guard let headerTitleFont = UIFont.headerTitleText, let descriptionLabelFont = UIFont.descriptionText, let actionButtonFont = UIFont.buttonText, let resultLabelFont = UIFont.resultLabelText, let resultValueLabelFont = UIFont.resultValueText else { return } headerView.backgroundColor = UIColor.headerLightGray headerMarkerView.backgroundColor = UIColor.headerDarkGray exampleNumberLabel.font = headerTitleFont exampleNumberLabel.textColor = UIColor.headerTitleGray descriptionView.backgroundColor = UIColor.white descriptionLabel.font = descriptionLabelFont descriptionLabel.textColor = UIColor.descriptionDarkGray actionButtonView.backgroundColor = UIColor.white actionButton.titleLabel?.font = actionButtonFont actionButton.setTitleColor(UIColor.highlightRed, for: .normal) stringReadResultView.backgroundColor = UIColor.white resultTitleLabel.font = resultLabelFont resultTitleLabel.textColor = UIColor.descriptionLightGray resultLabel.font = resultValueLabelFont resultLabel.textColor = UIColor.descriptionDarkGray readWriteView.backgroundColor = UIColor.white keyTitleLabel.font = resultLabelFont keyTitleLabel.textColor = UIColor.descriptionLightGray keyText.font = resultValueLabelFont keyText.textColor = UIColor.descriptionDarkGray writeActionButton.backgroundColor = UIColor.white writeActionButton.titleLabel?.font = actionButtonFont writeActionButton.setTitleColor(UIColor.highlightRed, for: .normal) readActionButton.backgroundColor = UIColor.white readActionButton.titleLabel?.font = actionButtonFont readActionButton.setTitleColor(UIColor.highlightRed, for: .normal) readResultTitleLabel.font = resultLabelFont readResultTitleLabel.textColor = UIColor.descriptionLightGray readResultLabel.font = resultValueLabelFont readResultLabel.textColor = UIColor.descriptionDarkGray } private func setupContent() { guard let viewModel = viewModel else { return } keyText.placeholder = viewModel.keyTextPlaceholder keyText.text = viewModel.keyTextPlaceholder exampleNumberLabel.text = viewModel.exampleTitle descriptionLabel.text = viewModel.description actionButton.setTitle(viewModel.actionButtonTitle, for: .normal) resultLabel.text = viewModel.initialResult readActionButton.setTitle(viewModel.readActionButtonTitle, for: .normal) writeActionButton.setTitle(viewModel.writeActionButtonTitle, for: .normal) readResultLabel.text = "" } @IBAction private func actionButtonTapped(_ sender: AnyObject) { guard let viewModel = viewModel else { return } let result = viewModel.updateButtonTapResult() resultLabel.text = result } @IBAction private func readActionButtonTapped(_ sender: AnyObject) { guard let viewModel = viewModel, let keyPlaceholder = keyText.placeholder else { return } let key = keyText.text ?? keyPlaceholder if !viewModel.readData(forKey: key) { readResultLabel.text = "" return } readResultLabel.text = viewModel.storedDataAsString } @IBAction private func writeActionButtonTapped(_ sender: AnyObject) { guard let viewModel = viewModel, let keyPlaceholder = keyText.placeholder else { return } let key = keyText.text ?? keyPlaceholder viewModel.saveData(forKey: key) } }
mit
766e9ec52bb89a85e2a62c9cf4ce9587
37.413793
82
0.705027
5.666328
false
false
false
false
et007013/MeterVRPlayer
MetalVRPlayer/ViewController.swift
1
2630
// // ViewController.swift // MetalVRPlayer // // Created by 魏靖南 on 19/1/2017. // Copyright © 2017年 魏靖南. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var gradientView: UIView! var gradientLayer: CAGradientLayer! var colorSets = [[CGColor]]() var currentColorSet: Int! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.createColorSets() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTapGesture(gestureRecognizer:))) self.gradientView.addGestureRecognizer(tapGestureRecognizer) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) createGradientLayer() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } func createGradientLayer() { gradientLayer = CAGradientLayer() gradientLayer.frame = self.gradientView.bounds gradientLayer.locations = [0.0, 0.63] gradientLayer.colors = colorSets[currentColorSet]//[UIColor.init(red: 0, green: 0, blue: 0, alpha: 0).cgColor , UIColor.init(red: 0, green: 18, blue: 77, alpha: 1).cgColor] self.gradientView.layer.addSublayer(gradientLayer) } func createColorSets() { colorSets.append([UIColor.red.cgColor, UIColor.yellow.cgColor]) colorSets.append([UIColor.green.cgColor, UIColor.magenta.cgColor]) colorSets.append([UIColor.gray.cgColor, UIColor.lightGray.cgColor]) currentColorSet = 0 } @objc private func handleTapGesture(gestureRecognizer: UITapGestureRecognizer) { if currentColorSet < colorSets.count - 1 { currentColorSet! += 1 } else { currentColorSet = 0 } let colorChangeAnimation = CABasicAnimation(keyPath: "colors") colorChangeAnimation.duration = 2.0 colorChangeAnimation.toValue = colorSets[currentColorSet] colorChangeAnimation.fillMode = kCAFillModeForwards colorChangeAnimation.isRemovedOnCompletion = false gradientLayer.add(colorChangeAnimation, forKey: "colorChange") } }
gpl-3.0
5938572a1150ac155423c5fad7712232
30.506024
180
0.661568
5.028846
false
false
false
false
WeltN24/Carlos
Tests/CarlosTests/NSNumberFormatterTransformerTests.swift
1
5135
import Foundation import Nimble import Quick import Carlos import Combine final class NSNumberFormatterTransformerTests: QuickSpec { override func spec() { describe("NumberFormatter") { var formatter: NumberFormatter! var cancellable: AnyCancellable? beforeEach { formatter = NumberFormatter() formatter.locale = Locale(identifier: "us_US") formatter.numberStyle = .decimal formatter.maximumFractionDigits = 5 formatter.minimumFractionDigits = 3 } afterEach { cancellable?.cancel() cancellable = nil } context("when used as a transformer") { var error: Error! context("when transforming") { var result: String! afterEach { result = nil error = nil } context("when the number contains a valid number of fraction digits") { let originNumber = 10.1203 beforeEach { cancellable = formatter.transform(NSNumber(value: originNumber)) .sink(receiveCompletion: { completion in if case let .failure(e) = completion { error = e } }, receiveValue: { result = $0 }) } it("should call the success closure") { expect(result).toEventuallyNot(beNil()) } it("should not call the failure closure") { expect(error).toEventually(beNil()) } it("should return the expected string") { expect(result).toEventually(equal("10.1203")) } } context("when the number contains less fractions digits") { let originNumber = 10.12 beforeEach { cancellable = formatter.transform(NSNumber(value: originNumber)) .sink(receiveCompletion: { completion in if case let .failure(e) = completion { error = e } }, receiveValue: { result = $0 }) } it("should call the success closure") { expect(result).toEventuallyNot(beNil()) } it("should not call the failure closure") { expect(error).toEventually(beNil()) } it("should return the expected string") { expect(result).toEventually(equal("10.120")) } } context("when the number contains more fraction digits") { let originNumber = 10.120312 beforeEach { cancellable = formatter.transform(NSNumber(value: originNumber)) .sink(receiveCompletion: { completion in if case let .failure(e) = completion { error = e } }, receiveValue: { result = $0 }) } it("should call the success closure") { expect(result).toEventuallyNot(beNil()) } it("should not call the failure closure") { expect(error).toEventually(beNil()) } it("should return the expected string") { expect(result).toEventually(equal("10.12031")) } } } context("when inverse transforming") { var result: NSNumber! context("when the string is valid") { let originString = "10.1203" beforeEach { cancellable = formatter.inverseTransform(originString) .sink(receiveCompletion: { completion in if case let .failure(e) = completion { error = e } }, receiveValue: { result = $0 }) } afterEach { result = nil error = nil } it("should call the success closure") { expect(result).toEventuallyNot(beNil()) } it("should not call the failure closure") { expect(error).toEventually(beNil()) } it("should return the expected number") { expect(result.map { "\($0)" }).toEventually(equal(originString)) } } context("when the string is invalid") { beforeEach { cancellable = formatter.inverseTransform("not a number!") .sink(receiveCompletion: { completion in if case let .failure(e) = completion { error = e result = nil } }, receiveValue: { result = $0 }) } afterEach { result = nil error = nil } it("should not call the success closure") { expect(result).toEventually(beNil()) } it("should call the error closure") { expect(error).toEventuallyNot(beNil()) } } } } } } }
mit
c202ac857aec4ed206237b8e7da28ba6
27.848315
81
0.490555
5.655286
false
false
false
false
xdkoooo/LiveDemo
LiveDemo/LiveDemo/Classes/Home/ViewModel/RecommendViewModel.swift
1
4940
// // RecommendViewModel.swift // LiveDemo // // Created by xdkoo on 2017/2/26. // Copyright © 2017年 xdkoo. All rights reserved. // import UIKit class RecommendViewModel { // MARK:- 懒加载属性 lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() lazy var cycleModels : [CycleModel] = [CycleModel]() fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup() fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup() } // MARK:- 发送网络请求 extension RecommendViewModel { // 请求推荐数据 func requestData(finishCallBack : @escaping ()->()) { // 1.定义参数 let parameters = ["limit" : "4", "offset": "0", "time": NSDate.getCurrentTime()] // 2.创建loadDataGroup let dGroup = DispatchGroup() dGroup.enter() // 3.请求第一步部分推荐数据 // group.enter() NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : NSDate.getCurrentTime()]) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else {return} // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String: NSObject]] else {return} // 3.遍历数组,获取字典,并且将字典转成模型对象 // 3.1创建组 // let group = AnchorGroup() // 3.2设置组的属性 self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" // 3.3获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } dGroup.leave() } // 4.请求第二部分颜值数据 dGroup.enter() NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else {return} // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String: NSObject]] else {return} // 3.遍历数组,获取字典,并且将字典转成模型对象 // 3.1创建组 // let group = AnchorGroup() // 3.2设置组的属性 self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" // 3.3获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } dGroup.leave() } // 5.请求后面部分游戏数据 dGroup.enter() NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else {return} // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String: NSObject]] else {return} print(dataArray) // 3.遍历数组,获取字典,并且将字典转成模型对象 for dict in dataArray { let group = AnchorGroup(dict: dict) self.anchorGroups.append(group) } dGroup.leave() } // 6.所有的数据都请求到,之后进行排序 dGroup.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finishCallBack() } } // 请求无线轮播数据 func requestCycleData(finishCallBack : @escaping ()->()) { NetworkTools.requestData(type: .GET, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version": "2.300"]) { (result) in // 1.获取整体字典数据 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data的key获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.字典转模型对象 for dict in dataArray { self.cycleModels.append(CycleModel(dict: dict)) } print(result) finishCallBack() } } }
mit
733569231f32cfe2e1d13606cbfa85f4
33.253846
154
0.528183
4.581276
false
false
false
false
openHPI/xikolo-ios
iOS/Data/Model/Actions/CourseSection+Actions.swift
1
7592
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Common import UIKit extension CourseSection { private struct DownloadItemCounter { var numberOfDownloadableItems = 0 var numberOfDownloadingItems = 0 var numberOfDownloadedItems = 0 } private struct ItemCounter { var stream = DownloadItemCounter() var slides = DownloadItemCounter() } private static var actionDispatchQueue: DispatchQueue { return DispatchQueue(label: "section-actions", qos: .userInitiated) } var allVideosPreloaded: Bool { return !self.items.contains { item in return item.contentType == Video.contentType && item.content == nil } } var hasActions: Bool { return self.items.contains { item in return item.contentType == Video.contentType } } var actions: [Action] { var actions: [Action] = [] var itemCounter = ItemCounter() self.items.compactMap { item in return item.content as? Video }.forEach { video in if video.localFileBookmark != nil { itemCounter.stream.numberOfDownloadedItems += 1 } else if [.pending, .downloading].contains(StreamPersistenceManager.shared.downloadState(for: video)) { itemCounter.stream.numberOfDownloadingItems += 1 } else if video.streamURLForDownload != nil { itemCounter.stream.numberOfDownloadableItems += 1 } if video.localSlidesBookmark != nil { itemCounter.slides.numberOfDownloadedItems += 1 } else if [.pending, .downloading].contains(SlidesPersistenceManager.shared.downloadState(for: video)) { itemCounter.slides.numberOfDownloadingItems += 1 } else if video.slidesURL != nil { itemCounter.slides.numberOfDownloadableItems += 1 } } // user actions for stream if itemCounter.stream.numberOfDownloadableItems > 0, ReachabilityHelper.hasConnection { let downloadActionTitle = NSLocalizedString("course-section.stream-download-action.start-downloads.title", comment: "start stream downloads for all videos in section") actions.append(Action(title: downloadActionTitle, image: Action.Image.aggregatedDownload) { Self.actionDispatchQueue.async { StreamPersistenceManager.shared.startDownloads(for: self) } }) } if itemCounter.stream.numberOfDownloadedItems > 0 { let deleteActionTitle = NSLocalizedString("course-section.stream-download-action.delete-downloads.title", comment: "delete all downloaded streams downloads in section") actions.append(Action(title: deleteActionTitle, image: Action.Image.delete) { Self.actionDispatchQueue.async { StreamPersistenceManager.shared.deleteDownloads(for: self) } }) } if itemCounter.stream.numberOfDownloadingItems > 0 { let stopActionTitle = NSLocalizedString("course-section.stream-download-action.stop-downloads.title", comment: "stop all stream downloads in section") actions.append(Action(title: stopActionTitle, image: Action.Image.stop) { Self.actionDispatchQueue.async { StreamPersistenceManager.shared.cancelDownloads(for: self) } }) } // user actions for slides if itemCounter.slides.numberOfDownloadableItems > 0, ReachabilityHelper.hasConnection { let downloadActionTitle = NSLocalizedString("course-section.slides-download-action.start-downloads.title", comment: "start slides downloads for all videos in section") actions.append(Action(title: downloadActionTitle, image: Action.Image.aggregatedDownload) { Self.actionDispatchQueue.async { SlidesPersistenceManager.shared.startDownloads(for: self) } }) } if itemCounter.slides.numberOfDownloadedItems > 0 { let deleteActionTitle = NSLocalizedString("course-section.slides-download-action.delete-downloads.title", comment: "delete all downloaded slides downloads in section") actions.append(Action(title: deleteActionTitle, image: Action.Image.delete) { Self.actionDispatchQueue.async { SlidesPersistenceManager.shared.deleteDownloads(for: self) } }) } if itemCounter.slides.numberOfDownloadingItems > 0 { let stopActionTitle = NSLocalizedString("course-section.slides-download-action.stop-downloads.title", comment: "stop all slides downloads in section") actions.append(Action(title: stopActionTitle, image: Action.Image.stop) { Self.actionDispatchQueue.async { SlidesPersistenceManager.shared.cancelDownloads(for: self) } }) } // combined user actions if itemCounter.stream.numberOfDownloadableItems > 0, itemCounter.slides.numberOfDownloadableItems > 0, ReachabilityHelper.hasConnection { let downloadActionTitle = NSLocalizedString("course-section.combined-download-action.start-downloads.title", comment: "start all downloads for all videos in section") actions.append(Action(title: downloadActionTitle, image: Action.Image.aggregatedDownload) { Self.actionDispatchQueue.async { StreamPersistenceManager.shared.startDownloads(for: self) SlidesPersistenceManager.shared.startDownloads(for: self) } }) } if itemCounter.stream.numberOfDownloadedItems > 0, itemCounter.slides.numberOfDownloadedItems > 0 { let deleteActionTitle = NSLocalizedString("course-section.combined-download-action.delete-downloads.title", comment: "delete all downloads in section") actions.append(Action(title: deleteActionTitle, image: Action.Image.delete) { Self.actionDispatchQueue.async { StreamPersistenceManager.shared.deleteDownloads(for: self) SlidesPersistenceManager.shared.deleteDownloads(for: self) } }) } if itemCounter.stream.numberOfDownloadingItems > 0, itemCounter.slides.numberOfDownloadingItems > 0 { let stopActionTitle = NSLocalizedString("course-section.combined-download-action.stop-downloads.title", comment: "stop all downloads in section") actions.append(Action(title: stopActionTitle, image: Action.Image.stop) { Self.actionDispatchQueue.async { StreamPersistenceManager.shared.cancelDownloads(for: self) SlidesPersistenceManager.shared.cancelDownloads(for: self) } }) } return actions } }
gpl-3.0
ee6864a759a1656dd2fb89a06767d501
45.286585
145
0.60519
5.635486
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/AccountManager.swift
1
6410
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation private let log = ZMSLog(tag: "Accounts") public let AccountManagerDidUpdateAccountsNotificationName = Notification.Name("AccountManagerDidUpdateAccountsNotification") fileprivate extension UserDefaults { static let selectedAccountKey = "AccountManagerSelectedAccountKey" /// The identifier of the currently selected `Account` or `nil` if there is none. var selectedAccountIdentifier: UUID? { get { return string(forKey: UserDefaults.selectedAccountKey).flatMap(UUID.init) } set { set(newValue?.uuidString, forKey: UserDefaults.selectedAccountKey) } } } /// Class used to safely access and change stored accounts and the current selected account. @objcMembers public final class AccountManager: NSObject { private let defaults = UserDefaults.shared() private(set) public var accounts = [Account]() private(set) public var selectedAccount: Account? // The currently selected account or `nil` in case there is none private var store: AccountStore /// Returns the sum of unread conversations in all accounts. public var totalUnreadCount: Int { return accounts.reduce(0) { return $0 + $1.unreadConversationCount } } /// Creates a new `AccountManager`. /// - parameter sharedDirectory: The directory of the shared container. @objc(initWithSharedDirectory:) public init(sharedDirectory: URL) { store = AccountStore(root: sharedDirectory) super.init() updateAccounts() } /// Deletes all content stored by an `AccountManager` on disk at the given URL, including the selected account. @objc (deleteAtRoot:) static public func delete(at root: URL) { AccountStore.delete(at: root) UserDefaults.shared().selectedAccountIdentifier = nil } /// Adds an account to the manager and persists it. /// - parameter account: The account to add. @objc(addOrUpdateAccount:) public func addOrUpdate(_ account: Account) { store.add(account) updateAccounts() } /// Adds an account to the mananger and immediately and selects it. /// - parameter account: The account to add and select. @objc(addAndSelectAccount:) public func addAndSelect(_ account: Account) { addOrUpdate(account) select(account) } /// Removes an account from the manager and the persistence layer. /// - parameter account: The account to remove. @objc(removeAccount:) public func remove(_ account: Account) { store.remove(account) if selectedAccount == account { defaults?.selectedAccountIdentifier = nil } updateAccounts() } /// Selects a new account. /// - parameter account: The account to select. @objc(selectAccount:) public func select(_ account: Account) { precondition(accounts.contains(account), "Selecting an account without first adding it is not allowed") guard account != selectedAccount else { return } defaults?.selectedAccountIdentifier = account.userIdentifier updateAccounts() } // MARK: - Private Helper /// Updates the local accounts array and the selected account. /// This method should be called each time accounts are added or /// removed, or when the selectedAccountIdentifier has been changed. private func updateAccounts() { // since some objects (eg. AccountView) observe changes in the account, we must // make sure their object addresses are maintained after updating, i.e if // exisiting objects need to be updated from the account store, we just update // their properties and not replace the whole object. // var updatedAccounts = [Account]() for account in computeSortedAccounts() { if let existingAccount = self.account(with: account.userIdentifier) { existingAccount.updateWith(account) updatedAccounts.append(existingAccount) } else { updatedAccounts.append(account) } } accounts = updatedAccounts let computedAccount = computeSelectedAccount() if let account = computedAccount, let exisitingAccount = self.account(with: account.userIdentifier) { exisitingAccount.updateWith(account) selectedAccount = exisitingAccount } else { selectedAccount = computedAccount } NotificationCenter.default.post(name: AccountManagerDidUpdateAccountsNotificationName, object: self) } public func account(with id: UUID) -> Account? { return accounts.first(where: { return $0.userIdentifier == id }) } /// Loads and computes the locally selected account if any /// - returns: The currently selected account or `nil` if there is none. private func computeSelectedAccount() -> Account? { return defaults?.selectedAccountIdentifier.flatMap(store.load) } /// Loads and sorts the stored accounts. /// - returns: An Array consisting of the sorted accounts. Accounts without team will /// be first, sorted by their user name. Accounts with team will be last, /// sorted by their team name. private func computeSortedAccounts() -> [Account] { return store.load().sorted { lhs, rhs in switch (lhs.teamName, rhs.teamName) { case (.some, .none): return false case (.none, .some): return true case (.some(let leftName), .some(let rightName)): guard leftName != rightName else { fallthrough } return leftName < rightName default: return lhs.userName < rhs.userName } } } }
gpl-3.0
c5547edf8f80adc215f004f399d4af87
38.813665
125
0.679563
4.848714
false
false
false
false
jboullianne/EndlessTunes
EndlessSoundFeed/LoginViewController.swift
1
10088
// // LoginViewController.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 5/1/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import UIKit import FirebaseAuth import SkyFloatingLabelTextField import SwiftOverlays class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet var usernameField: SkyFloatingLabelTextField! @IBOutlet var passwordField: SkyFloatingLabelTextField! @IBOutlet var errorLabel:UILabel! @IBOutlet var newAccountButton: UIButton! @IBOutlet var loginButton: UIButton! @IBOutlet var backgroundImage: UIImageView! @IBOutlet var signupStackView: UIStackView! @IBOutlet var loginStackView: UIStackView! @IBOutlet var newEmailField: SkyFloatingLabelTextField! @IBOutlet var newDisplayNameField: SkyFloatingLabelTextField! @IBOutlet var newPasswordField: SkyFloatingLabelTextField! @IBOutlet var cancelSignupButton: UIButton! @IBOutlet var signupButton: UIButton! var gradientLayer:CAGradientLayer! override func viewDidLoad() { super.viewDidLoad() usernameField.delegate = self passwordField.delegate = self newEmailField.delegate = self newDisplayNameField.delegate = self newPasswordField.delegate = self passwordField.returnKeyType = .done newPasswordField.returnKeyType = .done passwordField.isSecureTextEntry = true newPasswordField.isSecureTextEntry = true /* if (FIRAuth.auth()?.currentUser) != nil { let manager = AccountManager.sharedInstance manager.loginUser(user: FIRAuth.auth()!.currentUser!) self.performSegue(withIdentifier: "LoginUser", sender: self) } */ newAccountButton.layer.cornerRadius = 3.0 loginButton.layer.cornerRadius = 3.0 cancelSignupButton.layer.cornerRadius = 3.0 signupButton.layer.cornerRadius = 3.0 cancelSignupButton.backgroundColor = UIColor.clear cancelSignupButton.layer.borderWidth = 2.0 cancelSignupButton.layer.borderColor = UIColor.white.cgColor let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = backgroundImage.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundImage.addSubview(blurEffectView) prepViews() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //createGradientLayer() usernameField.text = "" passwordField.text = "" newEmailField.text = "" newDisplayNameField.text = "" newPasswordField.text = "" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func prepViews() { backgroundImage.alpha = 0 loginStackView.alpha = 0 signupStackView.alpha = 0 } func showViews() { UIView.animate(withDuration: 0.5) { self.backgroundImage.alpha = 1.0 self.loginStackView.alpha = 1.0 } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func createGradientLayer(){ gradientLayer = CAGradientLayer() gradientLayer.frame = self.view.bounds let startColor = UIColor(red: 30/255, green: 60/255, blue: 109/255, alpha: 1.0).cgColor let endColor = UIColor(red: 11/255, green: 24/255, blue: 45/255, alpha: 1.0).cgColor gradientLayer.colors = [startColor, endColor] self.view.layer.insertSublayer(gradientLayer, at: 0) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == passwordField { textField.resignFirstResponder() return true } if textField == usernameField { let _ = passwordField.becomeFirstResponder() return true } if textField == newEmailField { newDisplayNameField.becomeFirstResponder() return true } if textField == newDisplayNameField { newPasswordField.becomeFirstResponder() return true } if textField == newPasswordField { newPasswordField.resignFirstResponder() return true } return true } @IBAction func createAccountPressed(_ sender: Any) { print("CREATE NEW ACCOUNT PRESSED") errorLabel.isHidden = true UIView.animate(withDuration: 0.3, animations: { self.loginStackView.alpha = 0.0 }) { (success) in if success { UIView.animate(withDuration: 0.3, animations: { self.signupStackView.alpha = 1.0 }) } } } @IBAction func loginPressed(_ sender: Any) { let email = usernameField.text let pass = passwordField.text self.showWaitOverlay() let manager = AccountManager.sharedInstance manager.loginUser(email: email, pass: pass) { (success, errorString) in if(success){ print("Successful Login: After Login Pressed") self.removeAllOverlays() self.performSegue(withIdentifier: "LoginUser", sender: self) } else { self.removeAllOverlays() self.errorLabel.isHidden = false self.errorLabel.text = errorString } } print("LOGIN PRESSED") } @IBAction func cancelPressed(_ sender: Any) { self.errorLabel.isHidden = true UIView.animate(withDuration: 0.3, animations: { self.signupStackView.alpha = 0.0 }) { (success) in if success { UIView.animate(withDuration: 0.3, animations: { self.loginStackView.alpha = 1.0 }) } } } @IBAction func signupPressed(_ sender: Any) { print("SIGNUP BUTTON PRESSED") self.showWaitOverlay() let email = newEmailField.text let pass = newPasswordField.text let displayName = newDisplayNameField.text if let count = displayName?.characters.count { if count <= 5 { self.errorLabel.isHidden = false self.errorLabel.text = "Display Name Too Short" self.removeAllOverlays() return } } if (email != nil) && (pass != nil) { FIRAuth.auth()?.createUser(withEmail: email!, password: pass!, completion: { (user, error) in if let err = error as NSError? { if let code = FIRAuthErrorCode(rawValue: err.code) { switch code { case .errorCodeInvalidEmail: //Invalid Email print("Invalid Email") self.errorLabel.isHidden = false self.errorLabel.text = "Invalid Email" case .errorCodeEmailAlreadyInUse: self.errorLabel.isHidden = false self.errorLabel.text = "Email Already In Use" case .errorCodeWeakPassword: self.errorLabel.isHidden = false self.errorLabel.text = "Too Weak of Password" default: print("Error Code Not Recognized") self.errorLabel.isHidden = false self.errorLabel.text = "Error Creating Account" } self.removeAllOverlays() } }else{ print("Firebase Signup Success") let changeRequest = FIRAuth.auth()?.currentUser?.profileChangeRequest() changeRequest?.displayName = displayName changeRequest?.commitChanges { (error) in if(error != nil){ print("Error Updating Display Name") self.removeAllOverlays() } else{ let manager = AccountManager.sharedInstance manager.setupNewUser(user: user!) self.removeAllOverlays() self.performSegue(withIdentifier: "SignupUser", sender: self) } } } }) } } @IBAction func backgroundTapped(_ sender: Any) { endUserInput() } @IBAction func logoTapped(_ sender: Any) { endUserInput() } func endUserInput() { if usernameField.isFirstResponder { usernameField.resignFirstResponder() }else if passwordField.isFirstResponder { passwordField.resignFirstResponder() }else{ } } // 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. print(segue.identifier!) } }
gpl-3.0
13b83a44ec8edb8c631c7af8c1723d3b
31.964052
106
0.561019
5.744305
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
DuckDuckGo/OnboaringSettings.swift
1
1251
// // OnboardingSettings.swift // DuckDuckGo // // Created by Mia Alexiou on 03/03/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import Foundation import Core struct OnboardingSettings { private let suit = "onboardingSettingsSuit" private struct Keys { static let hasSeenOnboarding = "hasSeenOnboarding" static let instructionsFirstLaunch = "instructionsFirstLaunch" } public var hasSeenOnboarding: Bool { get { guard let userDefaults = userDefaults() else { return false } return userDefaults.bool(forKey: Keys.hasSeenOnboarding, defaultValue: false) } set(newValue) { userDefaults()?.set(newValue, forKey: Keys.hasSeenOnboarding) } } public var instructionsFirstLaunch: Bool { get { guard let userDefaults = userDefaults() else { return true } return userDefaults.bool(forKey: Keys.instructionsFirstLaunch, defaultValue: true) } set(newValue) { userDefaults()?.set(newValue, forKey: Keys.instructionsFirstLaunch) } } private func userDefaults() -> UserDefaults? { return UserDefaults(suiteName: suit) } }
apache-2.0
5c7d915ad38765f7a1adf74862342ddc
27.409091
94
0.6392
5.02008
false
false
false
false
material-motion/material-motion-swift
src/operators/gestures/translationAddedTo.swift
2
1999
/* Copyright 2016-present The Material Motion Authors. 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 Foundation import UIKit extension MotionObservableConvertible where T: UIPanGestureRecognizer { /** Adds the current translation to the initial position and emits the result while the gesture recognizer is active. */ public func translation<O: MotionObservableConvertible>(addedTo initialPosition: O, in view: UIView) -> MotionObservable<CGPoint> where O.T == CGPoint { var cachedInitialPosition: CGPoint? var lastInitialPosition: CGPoint? return MotionObservable { observer in let initialPositionSubscription = initialPosition.subscribeToValue { lastInitialPosition = $0 } let upstreamSubscription = self.subscribeAndForward(to: observer) { value in if value.state == .began || (value.state == .changed && cachedInitialPosition == nil) { cachedInitialPosition = lastInitialPosition } else if value.state != .began && value.state != .changed { cachedInitialPosition = nil } if let cachedInitialPosition = cachedInitialPosition { let translation = value.translation(in: view) observer.next(CGPoint(x: cachedInitialPosition.x + translation.x, y: cachedInitialPosition.y + translation.y)) } } return { upstreamSubscription.unsubscribe() initialPositionSubscription.unsubscribe() } } } }
apache-2.0
d802647741d435c936058442102f9d0f
36.716981
154
0.713857
5.022613
false
false
false
false
QuaereVeritatem/FoodTracker
FoodTracker/FoodTracker/RegisterViewController.swift
1
3246
// // RegisterViewController.swift // BackendlessLogin // // Created by Kevin Harris on 9/26/16. // Copyright © 2016 Guild/SA. All rights reserved. // import UIKit class RegisterViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var passwordConfirmTextField: UITextField! @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var registerBtn: UIButton! let backendless = Backendless.sharedInstance()! override func viewDidLoad() { super.viewDidLoad() emailTextField.addTarget(self, action: #selector(LoginViewController.textFieldChanged(textField:)), for: UIControlEvents.editingChanged) passwordTextField.addTarget(self, action: #selector(LoginViewController.textFieldChanged(textField:)), for: UIControlEvents.editingChanged) passwordConfirmTextField.addTarget(self, action: #selector(LoginViewController.textFieldChanged(textField:)), for: UIControlEvents.editingChanged) } func textFieldChanged(textField: UITextField) { if emailTextField.text == "" || passwordTextField.text == "" || passwordConfirmTextField.text == "" { registerBtn.isEnabled = false } else { registerBtn.isEnabled = true } } @IBAction func register(_ sender: UIButton) { if passwordTextField.text != passwordConfirmTextField.text { Utility.showAlert(viewController: self, title: "Registration Error", message: "Password confirmation failed. Plase enter your password try again.") return } if !Utility.isValidEmail(emailAddress: emailTextField.text!) { Utility.showAlert(viewController: self, title: "Registration Error", message: "Please enter a valid email address.") return } spinner.startAnimating() let email = emailTextField.text! let password = passwordTextField.text! BackendlessManager.sharedInstance.registerUser(email: email, password: password, completion: { BackendlessManager.sharedInstance.loginUser(email: email, password: password, completion: { self.spinner.stopAnimating() self.performSegue(withIdentifier: "gotoMenuFromRegister", sender: sender) }, error: { message in self.spinner.stopAnimating() Utility.showAlert(viewController: self, title: "Login Error", message: message) }) }, error: { message in self.spinner.stopAnimating() Utility.showAlert(viewController: self, title: "Register Error", message: message) }) } @IBAction func cancel(_ sender: UIButton) { spinner.stopAnimating() dismiss(animated: true, completion: nil) } }
mit
faec0ff02173b5ea6c49f7b2727cde0a
35.875
159
0.6
6.031599
false
false
false
false
doronkatz/firefox-ios
Sync/Synchronizers/TabsSynchronizer.swift
2
8773
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred import SwiftyJSON private let log = Logger.syncLogger let TabsStorageVersion = 1 open class TabsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "tabs") } override var storageVersion: Int { return TabsStorageVersion } var tabsRecordLastUpload: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastTabsUpload") } get { return self.prefs.unsignedLongForKey("lastTabsUpload") ?? 0 } } fileprivate func createOwnTabsRecord(_ tabs: [RemoteTab]) -> Record<TabsPayload> { let guid = self.scratchpad.clientGUID let tabsJSON = JSON([ "id": guid, "clientName": self.scratchpad.clientName, "tabs": tabs.flatMap { $0.toDictionary() } ]) if Logger.logPII { log.verbose("Sending tabs JSON \(tabsJSON.stringValue() ?? "nil")") } let payload = TabsPayload(tabsJSON) return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds) } fileprivate func uploadOurTabs(_ localTabs: RemoteClientsAndTabs, toServer tabsClient: Sync15CollectionClient<TabsPayload>) -> Success { // check to see if our tabs have changed or we're in a fresh start let lastUploadTime: Timestamp? = (self.tabsRecordLastUpload == 0) ? nil : self.tabsRecordLastUpload if let lastUploadTime = lastUploadTime, lastUploadTime >= (Date.now() - (OneMinuteInMilliseconds)) { log.debug("Not uploading tabs: already did so at \(lastUploadTime).") return succeed() } return localTabs.getTabsForClientWithGUID(nil) >>== { tabs in if let lastUploadTime = lastUploadTime { // TODO: track this in memory so we don't have to hit the disk to figure out when our tabs have // changed and need to be uploaded. if tabs.every({ $0.lastUsed < lastUploadTime }) { return succeed() } } let tabsRecord = self.createOwnTabsRecord(tabs) log.debug("Uploading our tabs: \(tabs.count).") var uploadStats = SyncUploadStats() uploadStats.sent += 1 // We explicitly don't send If-Unmodified-Since, because we always // want our upload to succeed -- we own the record. return tabsClient.put(tabsRecord, ifUnmodifiedSince: nil) >>== { resp in if let ts = resp.metadata.lastModifiedMilliseconds { // Protocol says this should always be present for success responses. log.debug("Tabs record upload succeeded. New timestamp: \(ts).") self.tabsRecordLastUpload = ts } else { uploadStats.sentFailed += 1 } return succeed() } >>== effect({ self.statsSession.recordUpload(stats: uploadStats) }) } } open func synchronizeLocalTabs(_ localTabs: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { func onResponseReceived(_ response: StorageResponse<[Record<TabsPayload>]>) -> Success { func afterWipe() -> Success { var downloadStats = SyncDownloadStats() let doInsert: (Record<TabsPayload>) -> Deferred<Maybe<(Int)>> = { record in let remotes = record.payload.isValid() ? record.payload.remoteTabs : [] let ins = localTabs.insertOrUpdateTabsForClientGUID(record.id, tabs: remotes) // Since tabs are all sent within a single record, we don't count number of tabs applied // but number of records. In this case it's just one. downloadStats.applied += 1 ins.upon() { res in if let inserted = res.successValue { if inserted != remotes.count { log.warning("Only inserted \(inserted) tabs, not \(remotes.count). Malformed or missing client?") } downloadStats.applied += 1 } else { downloadStats.failed += 1 } } return ins } let ourGUID = self.scratchpad.clientGUID let records = response.value let responseTimestamp = response.metadata.lastModifiedMilliseconds log.debug("Got \(records.count) tab records.") // We can only insert tabs for clients that we know locally, so // first we fetch the list of IDs and intersect the two. // TODO: there's a much more efficient way of doing this. return localTabs.getClientGUIDs() >>== { clientGUIDs in let filtered = records.filter({ $0.id != ourGUID && clientGUIDs.contains($0.id) }) if filtered.count != records.count { log.debug("Filtered \(records.count) records down to \(filtered.count).") } let allDone = all(filtered.map(doInsert)) return allDone.bind { (results) -> Success in if let failure = results.find({ $0.isFailure }) { return deferMaybe(failure.failureValue!) } self.lastFetched = responseTimestamp! return succeed() } } >>== effect({ self.statsSession.downloadStats }) } // If this is a fresh start, do a wipe. if self.lastFetched == 0 { log.info("Last fetch was 0. Wiping tabs.") return localTabs.wipeRemoteTabs() >>== afterWipe } return afterWipe() } if let reason = self.reasonToNotSync(storageClient) { return deferMaybe(SyncStatus.notStarted(reason)) } let keys = self.scratchpad.keys?.value let encoder = RecordEncoder<TabsPayload>(decode: { TabsPayload($0) }, encode: { $0.json }) if let encrypter = keys?.encrypter(self.collection, encoder: encoder) { let tabsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter) statsSession.start() if !self.remoteHasChanges(info) { // upload local tabs if they've changed or we're in a fresh start. _ = uploadOurTabs(localTabs, toServer: tabsClient) return deferMaybe(completedWithStats) } return tabsClient.getSince(self.lastFetched) >>== onResponseReceived >>> { self.uploadOurTabs(localTabs, toServer: tabsClient) } >>> { deferMaybe(self.completedWithStats) } } log.error("Couldn't make tabs factory.") return deferMaybe(FatalError(message: "Couldn't make tabs factory.")) } /** * This is a dedicated resetting interface that does both tabs and clients at the * same time. */ open static func resetClientsAndTabsWithStorage(_ storage: ResettableSyncStorage, basePrefs: Prefs) -> Success { let clientPrefs = BaseCollectionSynchronizer.prefsForCollection("clients", withBasePrefs: basePrefs) let tabsPrefs = BaseCollectionSynchronizer.prefsForCollection("tabs", withBasePrefs: basePrefs) clientPrefs.removeObjectForKey("lastFetched") tabsPrefs.removeObjectForKey("lastFetched") return storage.resetClient() } } extension RemoteTab { public func toDictionary() -> Dictionary<String, Any>? { let tabHistory = history.flatMap { $0.absoluteString } if tabHistory.isEmpty { return nil } return [ "title": title, "icon": icon?.absoluteString as Any? ?? NSNull(), "urlHistory": tabHistory, "lastUsed": millisecondsToDecimalSeconds(lastUsed) ] } }
mpl-2.0
30a606ae12ba5efe8a2d4c3b7a47ce28
41.587379
155
0.576086
5.545512
false
false
false
false
RyoAbe/PARTNER
PARTNER/PARTNER/UI/AddPartner/QRReaderViewController.swift
1
7528
// // QRReaderViewController.swift // PARTNER // // Created by RyoAbe on 2014/09/07. // Copyright (c) 2014年 RyoAbe. All rights reserved. // import UIKit import AVFoundation class QRCodeReaderMaskView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { super.drawRect(rect) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, UIColor(white: 0, alpha: 0.5).CGColor) CGContextFillRect(context, rect) let width = rect.width * 0.8 let x = self.center.x - (width * 0.5) let y = self.center.y - (width * 0.5) + UIApplication.sharedApplication().statusBarFrame.height let frame = CGRectMake(x, y, width, width) let lineWidth = CGFloat(2) CGContextSetLineWidth(context, lineWidth) CGContextSetStrokeColorWithColor(context, UIColor.whiteColor().CGColor); CGContextStrokeRect(context, CGRectInset(frame, -lineWidth * 0.5, -lineWidth * 0.5)) CGContextSetFillColorWithColor(context, UIColor.clearColor().CGColor) CGContextSetBlendMode(context, kCGBlendModeClear) CGContextFillRect(context, frame) } } class QRReaderViewController: BaseViewController, AVCaptureMetadataOutputObjectsDelegate { // ???: Locationで友達になるパターンも実装 var session: AVCaptureSession! var maskView: QRCodeReaderMaskView! var previewLayer: AVCaptureVideoPreviewLayer! @IBOutlet weak var backButtonView: UIView! override func viewDidLoad() { super.viewDidLoad() if !UIImagePickerController.isSourceTypeAvailable(.Camera) { self.navigationController!.popViewControllerAnimated(true) return } assert(MyProfile.read().isAuthenticated) let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) switch status { case .Restricted: showErrorAlert(NSError.code(.Unknown)) return case .Denied: showErrorAlert(NSError.code(.Unknown)) return case .NotDetermined: AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { granted in dispatch_sync(dispatch_get_main_queue(), { if(granted){ self.congigCamera() return } self.navigationController!.popViewControllerAnimated(true) }) }) case .Authorized: congigCamera() } maskView = QRCodeReaderMaskView(frame: CGRectZero) self.view.addSubview(maskView) self.view.bringSubviewToFront(backButtonView) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if(maskView == nil){ return } maskView.frame = self.view.bounds previewLayer.frame = self.view.bounds } func congigCamera() -> Bool { let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) if(device == nil){ showErrorAlert(NSError.code(.Unknown)) return false } var error: NSErrorPointer = nil var input = AVCaptureDeviceInput.deviceInputWithDevice(device, error: error) as! AVCaptureInput if(error != nil){ showErrorAlert(NSError.code(.Unknown)) return false } let output = AVCaptureMetadataOutput() session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetPhoto session.addInput(input) session.addOutput(output) output.metadataObjectTypes = [AVMetadataObjectTypeQRCode] previewLayer = AVCaptureVideoPreviewLayer.layerWithSession(self.session) as! AVCaptureVideoPreviewLayer previewLayer.frame = view.bounds view.layer.addSublayer(previewLayer) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill session.startRunning() output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) return true } func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { for metadataObject in metadataObjects { if !metadataObject.isKindOfClass(AVMetadataMachineReadableCodeObject) || metadataObject.type != AVMetadataObjectTypeQRCode { continue } if !verifyPartnersId(metadataObject.stringValue) { continue } session.stopRunning() return } } func verifyPartnersId(id: String) -> Bool { let op = GetUserOperation(userId: id) op.completionBlock = { if let candidatePartner = op.result as? PFUser { self.confirmCandidatePartner(PFUser.currentPartner(candidatePartner.objectId!)!) return } // パートナーが見つからなかった場合 self.session.startRunning() } dispatchAsyncOperation(op) return true } func confirmCandidatePartner(candidatePartner: PFPartner) { // 自分のパートナーと読み取ったidが一致している場合 if let partnerId = Partner.read().id { if candidatePartner.objectId == partnerId { toastWithMessage(String(format: LocalizedString.key("AlreadyPartnerToast"), candidatePartner.username)) session.startRunning() return } } // どちらかにパートナーがいる if candidatePartner.hasPartner || MyProfile.read().hasPartner { becomePartner(candidatePartner, message: String(format: LocalizedString.key("AlreadyHavePartnerConfirmAlertMessage"), candidatePartner.username)) return } // 両方共パートナーなし becomePartner(candidatePartner, message: String(format: LocalizedString.key("AddPartnerConfirmAlertMessage"), candidatePartner.username)) return } func becomePartner(candidatePartner: PFPartner, message: String) { let alert = UIAlertController(title: LocalizedString.key("AlertConfirmTitle"), message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: LocalizedString.key("AlertCancelButton"), style: .Default) { action in self.session.startRunning() }) alert.addAction(UIAlertAction(title: LocalizedString.key("AddPartnerAlertAddButton"), style: .Default, handler:{ action in let op = AddPartnerOperation(candidatePartner: candidatePartner) op.completionBlock = { self.navigationController!.popViewControllerAnimated(true) return } self.dispatchAsyncOperation(op) })) presentViewController(alert, animated: true, completion: nil) } @IBAction func didTapBackButton(sender: AnyObject) { navigationController!.popViewControllerAnimated(true) } @IBAction func useLocation(sender: UIButton) { var query = PFQuery(className:PFUser.parseClassName()) } }
gpl-3.0
fcf31df9e23348ebad7d7f66726b10d8
35.514851
162
0.649675
5.387874
false
false
false
false
lotpb/iosSQLswift
mySQLswift/TransmitBeaconController.swift
1
4476
// // TransmitBeaconController.swift // mySQLswift // // Created by Peter Balsamo on 1/19/16. // Copyright © 2016 Peter Balsamo. All rights reserved. // import UIKit import QuartzCore import CoreLocation import CoreBluetooth class TransmitBeaconController: UIViewController, CBPeripheralManagerDelegate { @IBOutlet weak var btnAction: UIButton! @IBOutlet weak var lblStatus: UILabel! @IBOutlet weak var lblBTStatus: UILabel! @IBOutlet weak var txtMajor: UITextField! @IBOutlet weak var txtMinor: UITextField! let uuid = NSUUID(UUIDString: "F34A1A1F-500F-48FB-AFAA-9584D641D7B1") var beaconRegion: CLBeaconRegion! var bluetoothPeripheralManager: CBPeripheralManager! var isBroadcasting = false var dataDictionary = NSDictionary() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. btnAction.layer.cornerRadius = btnAction.frame.size.width / 2 let swipeDownGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(TransmitBeaconController.handleSwipeGestureRecognizer)) swipeDownGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Down view.addGestureRecognizer(swipeDownGestureRecognizer) bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Custom method implementation func handleSwipeGestureRecognizer(gestureRecognizer: UISwipeGestureRecognizer) { txtMajor.resignFirstResponder() txtMinor.resignFirstResponder() } // MARK: IBAction method implementation @IBAction func switchBroadcastingState(sender: AnyObject) { if txtMajor.text == "" || txtMinor.text == "" { return } if txtMajor.isFirstResponder() || txtMinor.isFirstResponder() { return } if !isBroadcasting { if bluetoothPeripheralManager.state == .PoweredOn { let major: CLBeaconMajorValue = UInt16(Int(txtMajor.text!)!) let minor: CLBeaconMinorValue = UInt16(Int(txtMinor.text!)!) beaconRegion = CLBeaconRegion(proximityUUID: uuid!, major: major, minor: minor, identifier: "com.TheLight.beacon") dataDictionary = beaconRegion.peripheralDataWithMeasuredPower(nil) bluetoothPeripheralManager.startAdvertising(dataDictionary as? [String : AnyObject]) btnAction.setTitle("Stop", forState: UIControlState.Normal) lblStatus.text = "Broadcasting..." txtMajor.enabled = false txtMinor.enabled = false isBroadcasting = true } } else { bluetoothPeripheralManager.stopAdvertising() btnAction.setTitle("Start", forState: UIControlState.Normal) lblStatus.text = "Stopped" txtMajor.enabled = true txtMinor.enabled = true isBroadcasting = false } } // MARK: CBPeripheralManagerDelegate method implementation func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { var statusMessage = "" switch peripheral.state { case CBPeripheralManagerState.PoweredOn: statusMessage = "Bluetooth Status: Turned On" case CBPeripheralManagerState.PoweredOff: if isBroadcasting { switchBroadcastingState(self) } statusMessage = "Bluetooth Status: Turned Off" case CBPeripheralManagerState.Resetting: statusMessage = "Bluetooth Status: Resetting" case CBPeripheralManagerState.Unauthorized: statusMessage = "Bluetooth Status: Not Authorized" case CBPeripheralManagerState.Unsupported: statusMessage = "Bluetooth Status: Not Supported" default: statusMessage = "Bluetooth Status: Unknown" } lblBTStatus.text = statusMessage } }
gpl-2.0
6cf54966a058e8b8cf45c816c64985ec
33.160305
153
0.630168
5.781654
false
false
false
false
zon/that-bus
ios/That Bus/TabBarController.swift
1
1174
import Foundation import UIKit class TabBarController : UITabBarController { let tickets: TicketsController let ticketsNavigation: UINavigationController let camera: CameraController let cameraNavigation: UINavigationController let profile: ProfileController let profileNavigation: UINavigationController required init() { tickets = TicketsController() ticketsNavigation = UINavigationController(rootViewController: tickets) camera = CameraController() cameraNavigation = UINavigationController(rootViewController: camera) profile = ProfileController() profileNavigation = UINavigationController(rootViewController: profile) super.init(nibName: nil, bundle: nil) viewControllers = [ticketsNavigation, cameraNavigation, profileNavigation] ticketsNavigation.tabBarItem.title = "Tickets" cameraNavigation.tabBarItem.title = "Camera" profileNavigation.tabBarItem.title = "Profile" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
fb3dbdb063e4d903ec2c1fb5a01d3df3
32.542857
82
0.70017
6.146597
false
false
false
false
keyOfVv/KEYExtension
KEYExtension/sources/UIViewExtension.swift
1
8673
// // keyOfVv+UIView.swift // Aura // // Created by keyOfVv on 11/4/15. // Copyright © 2015 com.sangebaba. All rights reserved. // import Foundation import UIKit // MARK: - 快速访问UIView尺寸位置的各项属性 public extension UIView { /// 原点横坐标 public var x: CGFloat { get { return self.frame.origin.x } set { self.frame.origin.x = newValue } } /// 原点纵坐标 public var y: CGFloat { get { return self.frame.origin.y } set { self.frame.origin.y = newValue } } /// 宽度 public var width: CGFloat { get { return self.frame.size.width } set { self.frame.size.width = newValue } } /// 高度 public var height: CGFloat { get { return self.frame.size.height } set { self.frame.size.height = newValue } } /// 原点 public var origin: CGPoint { get { return self.frame.origin } set { self.frame.origin = newValue } } /// 尺寸 public var size: CGSize { get { return self.frame.size } set { self.frame.size = newValue } } /// 最大横坐标 public var maxX: CGFloat { get { return self.x + self.width } set { self.frame.origin.x = newValue - self.width } } /// 最大纵坐标 public var maxY: CGFloat { get { return self.y + self.height } set { self.frame.origin.y = newValue - self.height } } /// 中点横坐标 public var centerX: CGFloat { get { return self.x + self.width * 0.5 } set { self.frame.origin.x = newValue - self.width * 0.5 } } /// 中点纵坐标 public var centerY: CGFloat { get { return self.y + self.height * 0.5 } set { self.frame.origin.y = newValue - self.height * 0.5 } } /// 中点 public var centre: CGPoint { get { return CGPoint(x: self.centerX, y: self.centerY) } set { self.centerX = newValue.x self.centerY = newValue.y } } } // MARK: - 快速设置阴影 public extension UIView { /// 默认的阴影色深 fileprivate var defaultShadowOpacity: Float { return Float(0.65) } /// 默认的阴影偏移量 - X轴 fileprivate var defaultShadowOffsetX: CGFloat { return 0.0.cgFloat } /// 默认的阴影偏移量 - Y轴 fileprivate var defaultShadowOffsetY: CGFloat { return 2.0.cgFloat } /// 默认的阴影发散度 fileprivate var defaultShadowRadius: CGFloat { return 3.0.cgFloat } /** 设置阴影, 使用默认值(不透明度0.65, 横轴偏移0.0, 纵轴偏移2.0, 羽化半径3.0) */ public func configShadow() { self.layer.shadowOpacity = self.defaultShadowOpacity self.layer.shadowOffset = CGSize(width: self.defaultShadowOffsetX, height: self.defaultShadowOffsetY) self.layer.shadowRadius = self.defaultShadowRadius } /** 设置阴影 - parameter opacity: 不透明度 - parameter offsetX: 横轴偏移 - parameter offsetY: 纵轴偏移 - parameter radius: 羽化半径 */ public func configShadow(opacity: Double?, offsetX: Double?, offsetY: Double?, radius: Double?) { self.layer.shadowOpacity = (opacity == nil) ? self.defaultShadowOpacity : Float(opacity!) self.layer.shadowOffset = CGSize( width: (offsetX == nil) ? self.defaultShadowOffsetX : offsetX!.cgFloat, height: (offsetY == nil) ? self.defaultShadowOffsetY : offsetY!.cgFloat ) self.layer.shadowRadius = (radius == nil) ? self.defaultShadowRadius : radius!.cgFloat } } // MARK: - 设置圆角半径和裁切 public extension UIView { /** 设置圆角半径和裁切 - parameter cornerRadius: 圆角半径 - parameter masksToBounds: 是否裁切 */ public func configCornerRadius(_ cornerRadius: Double, masksToBounds: Bool) { self.layer.cornerRadius = cornerRadius.cgFloat self.layer.masksToBounds = masksToBounds } } // MARK: - 设置右上角的图形角标 private let TAG_FOR_BADGE_LABEL = 999 public extension UIView { /** 在右上角添加图形角标 - parameter badgeValue: 角标文本 */ public func addBadge(_ badgeValue: String) { self.addBadge(badgeValue, at: CGPoint(x: 1.0, y: 0.0)) } /** 在指定位置添加圆角角标 - parameter badgeValue: 角标文本 - parameter at: 位置(0.0~1.0) */ public func addBadge(_ badgeValue: String, at: CGPoint) { self.addBadge(badgeValue, font: UIFont.systemFont(ofSize: 17.0), at: at) } /** add badge to a view - parameter badgeValue: text displayed in badge - parameter font: font for badge text - parameter at: badge position, recommended between 0.0 & 1.0, specified a value > 1.0 may cause the badge to detach the receiver */ public func addBadge(_ badgeValue: String, font: UIFont, at: CGPoint) { // 判断当前是否已经有角标 if let badge = self.viewWithTag(TAG_FOR_BADGE_LABEL) as? UILabel { badge.text = badgeValue return } // 创建label let badge = UILabel(frame: CGRect.zero) badge.tag = TAG_FOR_BADGE_LABEL // 设置文本 badge.text = badgeValue // 调整尺寸 badge.font = font badge.sizeToFitWithTextSizeLimits(CGSIZE_MAX, andInsets: UIEdgeInsets.zero) badge.width = max(badge.width, badge.height) // 宽度至少应该与高度一致, 保证字符串长度较短时, label以圆形的方式显示 // 设置各项属性 badge.layer.cornerRadius = badge.height * 0.5 badge.layer.masksToBounds = true badge.backgroundColor = UIColor.red badge.textColor = UIColor.white self.addSubview(badge) badge.centerX = self.width * at.x badge.centerY = self.height * at.y } /** 移除图形角标 */ public func removeBadges() { self.viewWithTag(999)?.removeFromSuperview() } } // MARK: - 设置控件的加载状态效果 public extension UIView { /** 开始加载, 在控件的中心会出现一个UIActivityIndicatorView, 附带动画效果 */ public func startLoading() { if self.isNowLoading() { return } let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) self.isHidden = true activityIndicator.centre = self.centre self.superview?.addSubview(activityIndicator) activityIndicator.startAnimating() } /** 停止加载, UIActivityIndicatorView消失 */ public func ceaseLoading() { if !self.isNowLoading() { return } if let superview = self.superview { for subview in superview.subviews { if subview.isKind(of: UIActivityIndicatorView.self) { let activityIndicator = subview as! UIActivityIndicatorView activityIndicator.stopAnimating() activityIndicator.removeFromSuperview() self.isHidden = false } } } } /** 控件是否处于加载效果显示状态 - returns: 布尔值 */ fileprivate func isNowLoading() -> Bool { if let superview = self.superview { for subview in superview.subviews { if subview.isKind(of: UIActivityIndicatorView.self) { let activityIndicator = subview as! UIActivityIndicatorView return activityIndicator.isAnimating } } } return false } } // MARK: - 控件截图 public extension UIView { /** 对控件进行截图 - returns: 返回截图 */ public func snapshot() -> UIImage? { var image: UIImage? UIGraphicsBeginImageContextWithOptions(size, false, 0.0) if let context = UIGraphicsGetCurrentContext() { self.layer.render(in: context) image = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() return image } /** 对控件进行截图, 支持设置边缘缩进 - parameter insets: 边缘缩进, 如缩进值为负数则视为0缩进 - returns: 返回裁切后的截图 */ public func snapshotWithEdgeInsets(_ insets: UIEdgeInsets) -> UIImage? { guard insets.top >= 0 && insets.left >= 0 && insets.bottom >= 0 && insets.right >= 0 else { return self.snapshotWithEdgeInsets(UIEdgeInsets.zero) } let fullW = self.width let fullH = self.height let fullS = CGSize(width: fullW, height: fullH) let clippedW = self.width - (insets.left + insets.right) let clippedH = self.height - (insets.top + insets.bottom) let clippedX = insets.left let clippedY = insets.top let clippedR = CGRect(x: clippedX, y: clippedY, width: clippedW, height: clippedH) UIGraphicsBeginImageContextWithOptions(fullS, false, 0.0) var fullImage: UIImage? if let ctx = UIGraphicsGetCurrentContext() { self.layer.render(in: ctx) fullImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() UIGraphicsBeginImageContextWithOptions(clippedR.size, false, 0.0) var clippedImage: UIImage? if let _ = UIGraphicsGetCurrentContext() { fullImage?.draw(in: CGRect(x: -clippedX, y: -clippedY, width: fullW, height: fullH)) clippedImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() return clippedImage } }
mit
368d044deb9b527d268b0d825abb8c49
22.861446
138
0.694522
3.196933
false
false
false
false
matthew-healy/TableControlling
TableControllingTests/ModelTests/TableSectionTests.swift
1
3237
import XCTest @testable import TableControlling class TableSectionTests: XCTestCase { // MARK: init tests func test_init_noArguments_headerNil() { let sut = TableSection<None, None, None>() XCTAssertNil(sut.header) } func test_init_noArguments_cellsIsEmpty() { let sut = TableSection<None, None, None>() XCTAssertTrue(sut.cells.isEmpty) } func test_init_noArguments_footerNil() { let sut = TableSection<None, None, None>() XCTAssertNil(sut.footer) } func test_init_headerIsABC_headerABC() { let expectedHeader = "ABC" let sut = TableSection<String, None, None>(header: expectedHeader) XCTAssertEqual(expectedHeader, sut.header) } func test_init_cellsAreABAndC_cellsAreABAndC() { let expectedCells = ["A", "B", "C"] let sut = TableSection<None, String, None>(cells: expectedCells) XCTAssertEqual(expectedCells, sut.cells) } func test_init_footerIsDEF_footerIsDEF() { let expectedFooter = "DEF" let sut = TableSection<None, None, String>(footer: expectedFooter) XCTAssertEqual(expectedFooter, sut.footer) } // MARK: equatable tests var lhs: TableSection<String, Int, Bool>! var rhs: TableSection<String, Int, Bool>! func test_equals_headerCellsAndFooterMatch_true() { (lhs, rhs) = (.create(), .create()) AssertSymmetricallyEqual(lhs, rhs) } func test_equals_headersDoNotMatch_false() { (lhs, rhs) = (.create(header: "A"), .create(header: "B")) AssertSymmetricallyNotEqual(lhs, rhs) } func test_equals_cellsDoNotMatch_false() { (lhs, rhs) = (.create(cells: [1, 2, 3]), .create()) AssertSymmetricallyNotEqual(lhs, rhs) } func test_equals_footersDoNotMatch_false() { (lhs, rhs) = (.create(footer: false), .create(footer: true)) AssertSymmetricallyNotEqual(lhs, rhs) } // MARK: numberOfItems tests func test_numberOfItems_cellsIsEmpty_returns0() { let sut = TableSection<None, String, None>() XCTAssertEqual(0, sut.numberOfItems) } func test_numberOfItems_cellsIsABCD_returns4() { let sut = TableSection<None, String, None>(cells: ["A", "B", "C", "D"]) XCTAssertEqual(4, sut.numberOfItems) } // MARK: item(atRow:_) tests func test_itemAtRow_noCellAtGivenRow_reutrnsNil() { let sut = TableSection<None, None, None>() XCTAssertNil(sut.item(atRow: 0)) } func test_itemAtRow_0_cellAIsAtRow0_returnsA() { let sut = TableSection<None, String, None>(cells: ["A"]) XCTAssertEqual("A", sut.item(atRow: 0)) } func test_itemAtRow_4_cell310IsAtRow4_returns310() { let sut = TableSection<None, Int, None>(cells: [0, 0, 0, 0, 310]) XCTAssertEqual(310, sut.item(atRow: 4)) } } extension TableSection { static func create( header: Header? = nil, cells: [Cell] = [], footer: Footer? = nil ) -> TableSection<Header, Cell, Footer> { return TableSection(header: header, cells: cells, footer: footer) } }
mit
016a091e447875f5c80b4dfbe60d2c9d
29.828571
79
0.610442
3.914148
false
true
false
false
sorenmortensen/SymondsTimetable
Sources/AddFriendViewController.swift
1
12457
// // AddFriendViewController.swift // SymondsTimetable // // Created by Søren Mortensen on 30/01/2017. // Copyright © 2017 Soren Mortensen. All rights reserved. // import UIKit import CloudKit /// Displays a table view and search bar, and retrieves and shows a list of /// `UserListing`s the user can choose from, in order to add people as friends. class AddFriendViewController: UITableViewController, UISearchBarDelegate { // MARK: - IBOutlets /// The search bar above the listings table view. @IBOutlet weak var searchBar: UISearchBar! // MARK: - Properties /// The global list of user listings returned by a query to the CloudKit /// database. var listings: [UserListing] = [] /// Only the user listings from `listings` that match the current search /// text in `searchBar`. private var filteredListings: [UserListing] = [] /// Tracks whether a search is currently in progress. private var searchActive = false { didSet { self.tableView.reloadData() } } /// A bar button the user can click to have new data downloaded from /// CloudKit and displayed in the table view. /// /// - Note: Pre-iOS 10.0 only. On iOS 10.0 and later, this is implemented /// using a `UIRefreshControl` at the top of the table view. private let refreshBarButton = UIBarButtonItem( barButtonSystemItem: .refresh, target: self, action: #selector(refreshUsers) ) /// An activity indicator to show the user that a network request is in /// progress. /// /// - Note: Pre-iOS 10.0 only. On iOS 10.0 and later, this is implemented /// using a `UIRefreshControl` at the top of the table view. private let activityIndicator = UIActivityIndicatorView( style: .gray) /// A bar button to contain `activityIndicator`. /// /// - Note: Pre-iOS 10.0 only. On iOS 10.0 and later, this is implemented /// using a `UIRefreshControl` at the top of the table view. private var activityIndicatorBarButton = UIBarButtonItem() // MARK: - Functions /// Sets up the refresh mechanism, using whichever mechanism is appropriate /// for the version of iOS the user is running. private func setUpRefresh() { if #available(iOS 10.0, *) { tableView.refreshControl = UIRefreshControl() tableView.refreshControl!.addTarget( self, action: #selector(refreshUsers), for: .valueChanged ) tableView.refreshControl!.layoutIfNeeded() } else { self.navigationItem.setLeftBarButton( refreshBarButton, animated: false) self.activityIndicatorBarButton = UIBarButtonItem( customView: activityIndicator) } } /// Starts animating the appropriate activity indicator or refresh control /// for the version of iOS the user is running. private func beginShowingRefresh() { if #available(iOS 10.0, *) { DispatchQueue.main.async { self.tableView.scrollRectToVisible( self.tableView.refreshControl!.frame, animated: true) self.tableView.refreshControl?.beginRefreshing() } } else { self.navigationItem.setLeftBarButton( activityIndicatorBarButton, animated: true) self.activityIndicator.startAnimating() } } /// Stops animating the appropriate activity indicator or refresh control /// for the version of iOS the user is running. private func endShowingRefresh() { if #available(iOS 10.0, *) { DispatchQueue.main.async { self.tableView.refreshControl?.endRefreshing() } } else { self.activityIndicator.stopAnimating() self.navigationItem.setLeftBarButton( refreshBarButton, animated: true) } } /// Retrieves a new list of user listings from CloudKit and stores them in /// the `listings` array. @objc func refreshUsers() { // Show a refresh to the user, because we're about to perform a big // network operation. self.beginShowingRefresh() // Grab a reference to the public database. let publicDatabase = CKContainer.default().publicCloudDatabase // The list of user listings should not include any users who are // already friends with the current user. let reference = CKRecord.Reference( recordID: PrimaryUser.shared.recordID, action: .none) let containsInFriendsPredicate = NSPredicate( format: "Friends contains %@", reference) let notContainsInFriendsPredicate = NSCompoundPredicate( notPredicateWithSubpredicate: containsInFriendsPredicate) // The list of user listings should also not contain the current user. let isUserPredicate = NSPredicate( format: "Id = %@", PrimaryUser.shared.id) let isNotUserPredicate = NSCompoundPredicate( notPredicateWithSubpredicate: isUserPredicate) // Combine those two conditions. let predicate = NSCompoundPredicate( andPredicateWithSubpredicates: [ notContainsInFriendsPredicate, isNotUserPredicate ]) // Create a query using the combined predicate. let query = CKQuery(recordType: "User", predicate: predicate) // Perform the query. publicDatabase.perform(query, inZoneWith: nil) { results, error in guard let results = results, error == nil else { // Something went wrong. Log the error and return. NSLog("Could not retrieve a list of users: \(error!)") return } // Create an array to contain UserListing objects as the records are // parsed. var listings: [UserListing] = [] // Create a UserListing from each record. for record in results { // Create the listing. let newListing = UserListing( id: record["Id"] as! String, forename: record["Forename"] as! String, surname: record["Surname"] as! String, username: record["Username"] as! String) // Add it to the array of listings. listings.append(newListing) } // Use mergeSort(_:_:) to sort the listings. listings = mergeSort(listings) { first, second in return first.surname < second.surname } // Update the listings in the table view, and do UI updates. DispatchQueue.main.async { self.listings = listings self.tableView.reloadData() self.endShowingRefresh() } } } // MARK: - UITableViewController /// :nodoc: override func viewDidLoad() { super.viewDidLoad() self.setUpRefresh() self.beginShowingRefresh() } /// :nodoc: override func viewDidAppear(_ animated: Bool) { self.refreshUsers() } /// :nodoc: override func numberOfSections(in tableView: UITableView) -> Int { return 1 } /// :nodoc: override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // If the user is currently performing a search, we need to use the // filteredListings array so we don't put empty cells in the list and/or // cause crashes in `tableView(_:cellForRowAt:)`. if searchActive { return filteredListings.count } else { return listings.count } } /// :nodoc: override func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { // Get the listing, searching differently depending on whether // there's an active search. let listing: UserListing if searchActive { listing = filteredListings[indexPath.row] } else { listing = listings[indexPath.row] } // Dequeue a cell so we can customise it. let cell = self.tableView.dequeueReusableCell( withIdentifier: "Listing", for: indexPath) as! ListingTableViewCell // Set the text in the name and username labels. cell.nameLabel.text = listing.name cell.usernameLabel.text = listing.username return cell } /// :nodoc: override func tableView( _ tableView: UITableView, heightForRowAt indexPath: IndexPath ) -> CGFloat { return 56 } /// :nodoc: override func tableView( _ tableView: UITableView, didSelectRowAt indexPath: IndexPath ) { // Get the listing, searching differently depending on whether // there's an active search. let listing: UserListing if searchActive { listing = filteredListings[indexPath.row] } else { listing = listings[indexPath.row] } // The title for the alert controller should include the user's name // and username. let title = "\(listing.name) (\(listing.username))" // Create an alert controller. let alertController = UIAlertController( title: title, message: nil, preferredStyle: .actionSheet ) // Create a "Send Friend Request" action. let sendAction = UIAlertAction(title: "Send Friend Request", style: .default) { action in // Tell the primary user to send a request to the user in the // listing. PrimaryUser.shared.sendRequest(toUser: listing) alertController.dismiss(animated: true, completion: nil) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { action in // Just dismiss the alert. alertController.dismiss(animated: true, completion: nil) } // Add the actions. alertController.addAction(sendAction) alertController.addAction(cancelAction) // Present the alert. self.present(alertController, animated: true, completion: nil) } // MARK: - UISearchBarDelegate /// :nodoc: func searchBar( _ searchBar: UISearchBar, textDidChange searchText: String ) { // Find all the listings that match the user's search text in either // the name or username. filteredListings = listings.filter({ listing -> Bool in let nameRange = listing.name.range( of: searchText, options: .caseInsensitive) let usernameRange = listing.username.range( of: searchText, options: .caseInsensitive) return nameRange != nil || usernameRange != nil }) // Set the search to active. if !self.searchActive { self.searchActive = true } // Reload the data - after having set searchActive to true, the table // view will load from the `filteredListings` array. self.tableView.reloadData() } /// :nodoc: func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { self.searchBar(searchBar, textDidChange: searchBar.text ?? "") } /// :nodoc: func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { self.searchActive = false } /// :nodoc: func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { self.searchActive = false } /// :nodoc: func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { self.searchActive = false } }
mit
274c5a70870176108601236d516650fe
33.985955
80
0.581132
5.453152
false
false
false
false
jxxcarlson/AsciidocEdit
playground.playground/section-1.swift
1
769
// Playground - noun: a place where people can play import Cocoa import Foundation extension String { func match( str: String) -> [String] { var err: NSError? let regex = NSRegularExpression(pattern: self, options: NSRegularExpressionOptions(0), error: &err) if err != nil { return [String]() } let nsstr = str as NSString let all = NSRange(location: 0, length: nsstr.length) var matches = [String]() regex!.enumerateMatchesInString(str, options: nil, range: all) { (result: NSTextCheckingResult!, _, _) in matches.append(nsstr.substringWithRange(result.range)) } return matches } } let str = "axx\n bxx.ad\n dfkdj cxx.ad/n" let pattern = ".ad" let m2 = pattern.match(str).count
mit
3f2053afd5293873a1490024188087a9
15.717391
103
0.643693
3.788177
false
false
false
false
vitkuzmenko/NetworkManager
Source/NetworkManager/Helpers.swift
1
729
// // Helpers.swift // Network Manager // // Created by Vitaliy Kuzmenko on 18/10/16. // Copyright © 2016 Vitaliy Kuzmenko. All rights reserved. // import Foundation public func removeNilValuesFromString(dictionary: [String: String?]) -> [String: String] { var cleanDictionary = [String: String]() for item in dictionary { if let value = item.1 { cleanDictionary[item.0] = value } } return cleanDictionary } public func removeNilValues<T: Any>(dictionary: [String: T?]) -> [String: T] { var cleanDictionary = [String: T]() for item in dictionary { if let value = item.1 { cleanDictionary[item.0] = value } } return cleanDictionary }
mit
0340c0455d9c99ac539d90ffc4bcfccd
24.103448
90
0.626374
3.893048
false
false
false
false
SeriousChoice/SCSwift
SCSwift/Utils/SCSystemInfo.swift
1
1552
// // SCSystemInfo.swift // SCSwift // // Created by Nicola Innocenti on 08/01/2022. // Copyright © 2022 Nicola Innocenti. All rights reserved. // import UIKit public struct SCSystemInfo { public var osName: String public var osVersion: String public var deviceType: String public var appVersion: String public var build: String public var appName: String public var batteryLevel: String public var totalDiskAvailable: String public var freeDiskAvailable: String init() { osName = UIDevice.current.systemName osVersion = UIDevice.current.systemVersion var sysinfo = utsname() uname(&sysinfo) // ignore return value deviceType = String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters) appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "" build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "Unavailable" appName = Bundle.main.appName batteryLevel = "\(UIDevice.current.batteryLevel*100.0*(-1))%" if let diskTotalSpace = UIDevice.current.diskTotalSpace { totalDiskAvailable = "\(diskTotalSpace) MB" } else { totalDiskAvailable = "Unavailable" } if let diskFreeSpace = UIDevice.current.diskFreeSpace { freeDiskAvailable = "\(diskFreeSpace) MB" } else { freeDiskAvailable = "Unavailable" } } }
mit
111355a7495fb9c418fbe1186472ebf1
34.25
153
0.658285
4.657658
false
false
false
false
vsqweHCL/DouYuZB
DouYuZB/DouYuZB/Classs/Tools/Common.swift
1
318
// // Common.swift // DouYuZB // // Created by HCL黄 on 16/11/3. // Copyright © 2016年 HCL黄. All rights reserved. // import UIKit let kStatusBarH: CGFloat = 20 let kNavigationBarH: CGFloat = 44 let kTabBarH: CGFloat = 49 let kScreenW = UIScreen.main.bounds.width let kScreenH = UIScreen.main.bounds.height
mit
f47f31452b9720a22ccfa21a0e71802b
18.4375
48
0.717042
3.273684
false
false
false
false
IvanVorobei/ParallaxTableView
ParallaxTableView - project/ParallaxTableView/Sparrow/UI/Views/Views/SPGradientView.swift
1
2601
// The MIT License (MIT) // Copyright © 2016 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPGradientView: UIView { fileprivate var gradient: CAGradientLayer! init() { super.init(frame: CGRect.zero) commonInit() } init(frame: CGRect, fromColor: UIColor, toColor: UIColor) { super.init(frame: frame) self.commonInit() self.setGradient(fromColor, toColor: toColor) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } fileprivate func commonInit() { self.gradient = CAGradientLayer(); self.layer.insertSublayer(self.gradient, at: 0) } func setGradient(_ fromColor: UIColor, toColor: UIColor, startPoint: CGPoint = CGPoint(x: 0.0, y: 0.0), endPoint: CGPoint = CGPoint(x: 1.0, y: 1.0)) { self.gradient = CAGradientLayer() self.gradient!.colors = [fromColor.cgColor, toColor.cgColor] self.gradient!.locations = [0.0, 1.0] self.gradient!.startPoint = startPoint self.gradient!.endPoint = endPoint self.gradient!.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height) self.layer.insertSublayer(self.gradient!, at: 0) } override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) self.gradient.frame = self.bounds } }
mit
2e931b297d6245efdee42b0a82242576
37.80597
115
0.67
4.40678
false
false
false
false
Miguel-Herrero/Swift
Rainy Shiny Cloudy/Rainy Shiny Cloudy/WeatherCell.swift
1
715
// // WeatherCell.swift // Rainy Shiny Cloudy // // Created by Miguel Herrero on 14/12/16. // Copyright © 2016 Miguel Herrero. All rights reserved. // import UIKit class WeatherCell: UITableViewCell { @IBOutlet weak var weatherIcon: UIImageView! @IBOutlet weak var dayLabel: UILabel! @IBOutlet weak var weatherType: UILabel! @IBOutlet weak var highTemp: UILabel! @IBOutlet weak var lowTemp: UILabel! func configureCell(forecast: Forecast) { lowTemp.text = forecast.lowTemp highTemp.text = forecast.highTemp weatherType.text = forecast.weatherType weatherIcon.image = UIImage(named: forecast.weatherType) dayLabel.text = forecast.date } }
gpl-3.0
ef3e5e882280d1ea7d445fa55a0db62d
26.461538
64
0.697479
4.2
false
false
false
false
martinomamic/CarBooking
CarBooking/Controllers/CarDetails/CarDetailsViewController.swift
1
2567
// // CarDetailsViewController.swift // CarBooking // // Created by Martino Mamic on 29/07/2017. // Copyright © 2017 Martino Mamic. All rights reserved. // import UIKit protocol CarDetailsDisplayDelegate: class { func displayCar(viewModel: CarDetailsUseCases.FetchCar.ViewModel) } //MARK: CarDetailsDisplayDelegate extension CarDetailsViewController: CarDetailsDisplayDelegate { func displayCar(viewModel: CarDetailsUseCases.FetchCar.ViewModel) { DispatchQueue.main.async { [unowned self] in self.carImage.loadImage(imageString: viewModel.displayedCar.image) self.carNameLabel.text = viewModel.displayedCar.name self.carDescriptionLabel.text = viewModel.displayedCar.info } } } class CarDetailsViewController: UIViewController { @IBOutlet weak var carImage: UIImageView! @IBOutlet weak var carNameLabel: UILabel! @IBOutlet weak var carDescriptionLabel: UILabel! var router: (NSObjectProtocol & CarDetailsRoutingDelegate & CarDetailsDataSource)? var interactor: CarDetailsBusinessDelegate? //MARK: View lifecycle required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialSetup() } override func viewDidLoad() { super.viewDidLoad() self.fetchCar() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Helper methods private func initialSetup() { let viewController = self let interactor = CarDetailsInteractor() let presenter = CarDetailsPresenter() viewController.interactor = interactor interactor.presenter = presenter presenter.viewController = viewController let router = CarDetailsRouter() viewController.router = router router.viewController = viewController router.dataStore = interactor } //MARK: Navigation&routing override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let scene = segue.identifier { let selector = NSSelectorFromString("routeTo\(scene)WithSegue:") if let router = router, router.responds(to: selector) { router.perform(selector, with: segue) } } } /// MARK: Data handling func fetchCar() { let request = CarDetailsUseCases.FetchCar.Request() interactor?.fetchCar(request: request) } }
mit
732e6c58809b1ff9c0f750f394b51b36
30.679012
86
0.682385
5.09127
false
false
false
false
matthewpalmer/Regift
Regift/Regift.swift
1
17155
// // Regift.swift // Regift // // Created by Matthew Palmer on 27/12/2014. // Copyright (c) 2014 Matthew Palmer. All rights reserved. // #if os(iOS) import UIKit import MobileCoreServices #elseif os(OSX) import AppKit #endif import ImageIO import AVFoundation public typealias TimePoint = CMTime public typealias ProgressHandler = (Double) -> Void /// Errors thrown by Regift public enum RegiftError: String, Error { case DestinationNotFound = "The temp file destination could not be created or found" case SourceFormatInvalid = "The source file does not appear to be a valid format" case AddFrameToDestination = "An error occurred when adding a frame to the destination" case DestinationFinalize = "An error occurred when finalizing the destination" } // Convenience struct for managing dispatch groups. private struct Group { let group = DispatchGroup() func enter() { group.enter() } func leave() { group.leave() } func wait() { let _ = group.wait(timeout: DispatchTime.distantFuture) } } /// Easily convert a video to a GIF. It can convert the whole thing, or you can choose a section to trim out. /// /// Synchronous Usage: /// /// let regift = Regift(sourceFileURL: movieFileURL, frameCount: 24, delayTime: 0.5, loopCount: 7) /// print(regift.createGif()) /// /// // OR /// /// let trimmedRegift = Regift(sourceFileURL: movieFileURL, startTime: 30, duration: 15, frameRate: 15) /// print(trimmedRegift.createGif()) /// /// Asynchronous Usage: /// /// let regift = Regift.createGIFFromSource(movieFileURL, frameCount: 24, delayTime: 0.5, loopCount: 7) { (result) in /// print(result) /// } /// /// // OR /// /// let trimmedRegift = Regift.createGIFFromSource(movieFileURL, startTime: 30, duration: 15, frameRate: 15, loopCount: 0) { (result) in /// print(result) /// } /// public struct Regift { // Static conversion methods, for convenient and easy-to-use API: /** Create a GIF from a movie stored at the given URL. This converts the whole video to a GIF meeting the requested output parameters. - parameters: - sourceFileURL: The source file to create the GIF from. - destinationFileURL: An optional destination file to write the GIF to. If you don't include this, a default path will be provided. - frameCount: The number of frames to include in the gif; each frame has the same duration and is spaced evenly over the video. - delayTime: The amount of time each frame exists for in the GIF. - loopCount: The number of times the GIF will repeat. This defaults to `0`, which means that the GIF will repeat infinitely. - size: The maximum size of generated GIF. This defaults to `nil`, which specifies the asset’s unscaled dimensions. Setting size will not change the image aspect ratio. - completion: A block that will be called when the GIF creation is completed. The `result` parameter provides the path to the file, or will be `nil` if there was an error. */ public static func createGIFFromSource( _ sourceFileURL: URL, destinationFileURL: URL? = nil, frameCount: Int, delayTime: Float, loopCount: Int = 0, size: CGSize? = nil, progress: ProgressHandler? = nil, completion: (_ result: URL?) -> Void) { let gift = Regift( sourceFileURL: sourceFileURL, destinationFileURL: destinationFileURL, frameCount: frameCount, delayTime: delayTime, loopCount: loopCount, size: size, progress: progress ) completion(gift.createGif()) } /** Create a GIF from a movie stored at the given URL. This allows you to choose a start time and duration in the source material that will be used to create the GIF which meets the output parameters. - parameters: - sourceFileURL: The source file to create the GIF from. - destinationFileURL: An optional destination file to write the GIF to. If you don't include this, a default path will be provided. - startTime: The time in seconds in the source material at which you want the GIF to start. - duration: The duration in seconds that you want to pull from the source material. - frameRate: The desired frame rate of the outputted GIF. - loopCount: The number of times the GIF will repeat. This defaults to `0`, which means that the GIF will repeat infinitely. - size: The maximum size of generated GIF. This defaults to `nil`, which specifies the asset’s unscaled dimensions. Setting size will not change the image aspect ratio. - completion: A block that will be called when the GIF creation is completed. The `result` parameter provides the path to the file, or will be `nil` if there was an error. */ public static func createGIFFromSource( _ sourceFileURL: URL, destinationFileURL: URL? = nil, startTime: Float, duration: Float, frameRate: Int, loopCount: Int = 0, size: CGSize? = nil, progress: ProgressHandler? = nil, completion: (_ result: URL?) -> Void) { let gift = Regift( sourceFileURL: sourceFileURL, destinationFileURL: destinationFileURL, startTime: startTime, duration: duration, frameRate: frameRate, loopCount: loopCount, size: size, progress: progress ) completion(gift.createGif()) } public static func createGIF( fromAsset asset: AVAsset, destinationFileURL: URL? = nil, startTime: Float, duration: Float, frameRate: Int, loopCount: Int = 0, completion: (_ result: URL?) -> Void) { let gift = Regift( asset: asset, destinationFileURL: destinationFileURL, startTime: startTime, duration: duration, frameRate: frameRate, loopCount: loopCount ) completion(gift.createGif()) } private struct Constants { static let FileName = "regift.gif" static let TimeInterval: Int32 = 600 static let Tolerance = 0.01 } /// A reference to the asset we are converting. private var asset: AVAsset /// The url for the source file. private var sourceFileURL: URL? /// The point in time in the source which we will start from. private var startTime: Float = 0 /// The desired duration of the gif. private var duration: Float /// The total length of the movie, in seconds. private var movieLength: Float /// The number of frames we are going to use to create the gif. private let frameCount: Int /// The amount of time each frame will remain on screen in the gif. private let delayTime: Float /// The number of times the gif will loop (0 is infinite). private let loopCount: Int /// The destination path for the generated file. private var destinationFileURL: URL? /// The handler to inform you about the current GIF export progress private var progress: ProgressHandler? /// The maximum width/height for the generated file. fileprivate let size: CGSize? /** Create a GIF from a movie stored at the given URL. This converts the whole video to a GIF meeting the requested output parameters. - parameters: - sourceFileURL: The source file to create the GIF from. - destinationFileURL: An optional destination file to write the GIF to. If you don't include this, a default path will be provided. - frameCount: The number of frames to include in the gif; each frame has the same duration and is spaced evenly over the video. - delayTime: The amount of time each frame exists for in the GIF. - loopCount: The number of times the GIF will repeat. This defaults to `0`, which means that the GIF will repeat infinitely. - size: The maximum size of generated GIF. This defaults to `nil`, which specifies the asset’s unscaled dimensions. Setting size will not change the image aspect ratio. */ public init(sourceFileURL: URL, destinationFileURL: URL? = nil, frameCount: Int, delayTime: Float, loopCount: Int = 0, size: CGSize? = nil, progress: ProgressHandler? = nil) { self.sourceFileURL = sourceFileURL self.asset = AVURLAsset(url: sourceFileURL, options: nil) self.movieLength = Float(asset.duration.value) / Float(asset.duration.timescale) self.duration = movieLength self.delayTime = delayTime self.loopCount = loopCount self.destinationFileURL = destinationFileURL self.frameCount = frameCount self.size = size self.progress = progress } /** Create a GIF from a movie stored at the given URL. This allows you to choose a start time and duration in the source material that will be used to create the GIF which meets the output parameters. - parameters: - sourceFileURL: The source file to create the GIF from. - destinationFileURL: An optional destination file to write the GIF to. If you don't include this, a default path will be provided. - startTime: The time in seconds in the source material at which you want the GIF to start. - duration: The duration in seconds that you want to pull from the source material. - frameRate: The desired frame rate of the outputted GIF. - loopCount: The number of times the GIF will repeat. This defaults to `0`, which means that the GIF will repeat infinitely. - size: The maximum size of generated GIF. This defaults to `nil`, which specifies the asset’s unscaled dimensions. Setting size will not change the image aspect ratio. */ public init(sourceFileURL: URL, destinationFileURL: URL? = nil, startTime: Float, duration: Float, frameRate: Int, loopCount: Int = 0, size: CGSize? = nil, progress: ProgressHandler? = nil) { self.sourceFileURL = sourceFileURL self.asset = AVURLAsset(url: sourceFileURL, options: nil) self.destinationFileURL = destinationFileURL self.startTime = startTime self.duration = duration // The delay time is based on the desired framerate of the gif. self.delayTime = (1.0 / Float(frameRate)) // The frame count is based on the desired length and framerate of the gif. self.frameCount = Int(duration * Float(frameRate)) // The total length of the file, in seconds. self.movieLength = Float(asset.duration.value) / Float(asset.duration.timescale) self.loopCount = loopCount self.size = size self.progress = progress } public init(asset: AVAsset, destinationFileURL: URL? = nil, startTime: Float, duration: Float, frameRate: Int, loopCount: Int = 0, size: CGSize? = nil, progress: ProgressHandler? = nil) { self.asset = asset self.destinationFileURL = destinationFileURL self.startTime = startTime self.duration = duration self.delayTime = (1.0 / Float(frameRate)) self.frameCount = Int(duration * Float(frameRate)) self.movieLength = Float(asset.duration.value) / Float(asset.duration.timescale) self.loopCount = loopCount self.size = size self.progress = progress } /** Get the URL of the GIF created with the attributes provided in the initializer. - returns: The path to the created GIF, or `nil` if there was an error creating it. */ public func createGif() -> URL? { let fileProperties = [kCGImagePropertyGIFDictionary as String:[ kCGImagePropertyGIFLoopCount as String: NSNumber(value: Int32(loopCount) as Int32)], kCGImagePropertyGIFHasGlobalColorMap as String: NSValue(nonretainedObject: true) ] as [String : Any] let frameProperties = [ kCGImagePropertyGIFDictionary as String:[ kCGImagePropertyGIFDelayTime as String:delayTime ] ] // How far along the video track we want to move, in seconds. let increment = Float(duration) / Float(frameCount) // Add each of the frames to the buffer var timePoints: [TimePoint] = [] for frameNumber in 0 ..< frameCount { let seconds: Float64 = Float64(startTime) + (Float64(increment) * Float64(frameNumber)) let time = CMTimeMakeWithSeconds(seconds, preferredTimescale: Constants.TimeInterval) timePoints.append(time) } do { return try createGIFForTimePoints(timePoints, fileProperties: fileProperties as [String : AnyObject], frameProperties: frameProperties as [String : AnyObject], frameCount: frameCount, size: size) } catch { return nil } } /** Create a GIF using the given time points in a movie file stored in this Regift's `asset`. - parameters: - timePoints: timePoints An array of `TimePoint`s (which are typealiased `CMTime`s) to use as the frames in the GIF. - fileProperties: The desired attributes of the resulting GIF. - frameProperties: The desired attributes of each frame in the resulting GIF. - frameCount: The desired number of frames for the GIF. *NOTE: This seems redundant to me, as `timePoints.count` should really be what we are after, but I'm hesitant to change the API here.* - size: The maximum size of generated GIF. This defaults to `nil`, which specifies the asset’s unscaled dimensions. Setting size will not change the image aspect ratio. - returns: The path to the created GIF, or `nil` if there was an error creating it. */ public func createGIFForTimePoints(_ timePoints: [TimePoint], fileProperties: [String: AnyObject], frameProperties: [String: AnyObject], frameCount: Int, size: CGSize? = nil) throws -> URL { // Ensure the source media is a valid file. guard asset.tracks(withMediaCharacteristic: .visual).count > 0 else { throw RegiftError.SourceFormatInvalid } var fileURL:URL? if self.destinationFileURL != nil { fileURL = self.destinationFileURL } else { let temporaryFile = (NSTemporaryDirectory() as NSString).appendingPathComponent(Constants.FileName) fileURL = URL(fileURLWithPath: temporaryFile) } guard let destination = CGImageDestinationCreateWithURL(fileURL! as CFURL, kUTTypeGIF, frameCount, nil) else { throw RegiftError.DestinationNotFound } CGImageDestinationSetProperties(destination, fileProperties as CFDictionary) let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true if let size = size { generator.maximumSize = size } let tolerance = CMTimeMakeWithSeconds(Constants.Tolerance, preferredTimescale: Constants.TimeInterval) generator.requestedTimeToleranceBefore = tolerance generator.requestedTimeToleranceAfter = tolerance // Transform timePoints to times for the async asset generator method. var times = [NSValue]() for time in timePoints { times.append(NSValue(time: time)) } // Create a dispatch group to force synchronous behavior on an asynchronous method. let gifGroup = Group() gifGroup.enter() var handledTimes: Double = 0 generator.generateCGImagesAsynchronously(forTimes: times, completionHandler: { (requestedTime, image, actualTime, result, error) in handledTimes += 1 guard let imageRef = image , error == nil else { print("An error occurred: \(String(describing: error)), image is \(String(describing: image))") if requestedTime == times.last?.timeValue { gifGroup.leave() } return } CGImageDestinationAddImage(destination, imageRef, frameProperties as CFDictionary) self.progress?(min(1.0, handledTimes/max(1.0, Double(times.count)))) if requestedTime == times.last?.timeValue { gifGroup.leave() } }) // Wait for the asynchronous generator to finish. gifGroup.wait() CGImageDestinationSetProperties(destination, fileProperties as CFDictionary) // Finalize the gif if !CGImageDestinationFinalize(destination) { throw RegiftError.DestinationFinalize } return fileURL! } }
mit
b8b9d150351e890c8e4435cf69117afa
42.849105
207
0.648177
4.837754
false
false
false
false
samodom/FoundationSwagger
FoundationSwagger/File/ClassPermissions.swift
1
1840
// // ClassPermissions.swift // FoundationSwagger // // Created by Sam Odom on 2/8/17. // Copyright © 2017 Swagger Soft. All rights reserved. // /// Type representing any combination of read, write and execute permissions on a file. public struct ClassPermissions: OptionSet { /// Bitmask representation of a class's permissions on a file. public let rawValue: UInt8 private static let readablePermission: UInt8 = 1 << 2 private static let writablePermission: UInt8 = 1 << 1 private static let executablePermission: UInt8 = 1 << 0 /// The readable-only class permission. public static let readable = ClassPermissions(rawValue: readablePermission) /// The writable-only class permission. public static let writable = ClassPermissions(rawValue: writablePermission) /// The executable-only class permission. public static let executable = ClassPermissions(rawValue: executablePermission) /// No class permissions. public static let none: ClassPermissions = [] /// All class permissions. public static let all: ClassPermissions = [readable, writable, executable] /// Produces only valid class permissions based on raw values of 1 through 7. /// Any values provided outside of that range produce empty class permission sets. public init(rawValue: UInt8) { self.rawValue = rawValue % 8 } /// Indicates whether these class permissions include the readable permission. public var isReadable: Bool { return contains(.readable) } /// Indicates whether these class permissions include the writable permission. public var isWritable: Bool { return contains(.writable) } /// Indicates whether these class permissions include the executable permission. public var isExecutable: Bool { return contains(.executable) } }
mit
893514401d88d3fe14a106abd2e05489
30.169492
87
0.723763
5.038356
false
false
false
false
morizotter/PhotoDiary
PhotoDiary/PhotoViewController.swift
1
894
// // PhotoViewController.swift // PhotoDiary // // Created by MORITANAOKI on 2016/01/08. // Copyright © 2016年 molabo. All rights reserved. // import UIKit class PhotoViewController: UIViewController { var item: [String: AnyObject]? let documentsDir = NSHomeDirectory() + "/Documents" @IBOutlet weak var photoImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() guard let item = item else { return } let id = item["ID"] as? String ?? "" let year = item["YEAR"] as? String ?? "" let day = item["DAY"] as? String ?? "" navigationItem.title = "\(year) \(day)" let image = UIImage(contentsOfFile: photoPath(id)) photoImageView.image = image } func photoPath(id: String) -> String { return documentsDir + "/" + id + ".jpg" } }
mit
c320507351183af740d68df6010c3c7e
25.205882
58
0.584736
4.389163
false
false
false
false
boland25/livePhotosViewer
LivePhotosViewer/LivePhotosViewer/Services/LivePhotoStore.swift
1
5924
// // LivePhotoStore.swift // LivePhotosViewer // // Created by boland on 12/29/16. // Copyright © 2016 mallocmedia. All rights reserved. // import UIKit import Photos #if os(iOS) import PhotosUI #endif enum Section: Int { case allPhotos = 0 case smartAlbums case userCollections static let count = 3 } class LivePhotoStore: NSObject { var allPhotos: PHFetchResult<PHAsset>! var livePhotos: [PHAsset]? var currentPhotoIndex: Int = 0 var targetSize: CGSize? var smartAlbums: PHFetchResult<PHAssetCollection>! var userCollections: PHFetchResult<PHCollection>! let sectionLocalizedTitles = ["", NSLocalizedString("Smart Albums", comment: ""), NSLocalizedString("Albums", comment: "")] public func configure(targetSize: CGSize) { print("configuring") self.targetSize = targetSize let allPhotosOptions = PHFetchOptions() allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] allPhotos = PHAsset.fetchAssets(with: allPhotosOptions) smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) userCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil) PHPhotoLibrary.shared().register(self as PHPhotoLibraryChangeObserver) } deinit { PHPhotoLibrary.shared().unregisterChangeObserver(self) } public func filter() -> Void { var onlyLivePhotos = [PHAsset]() allPhotos.enumerateObjects({ (asset, index, isLast) in if asset.mediaSubtypes == .photoLive { print("This is a live photo \(asset.mediaSubtypes)") onlyLivePhotos.append(asset) } }) //I think for now i'm just going to overwrite whats there //TODO: in the future I should probably check for something there first livePhotos = onlyLivePhotos if let livePhotos = livePhotos { currentPhotoIndex = livePhotos.count - 1 } } public func getLivePhoto(for index: Int, completionHandler: @escaping ((PHLivePhoto) -> Void)) -> Void { guard let onlyLivePhotos = livePhotos, let targetSize = targetSize else { return } let asset = onlyLivePhotos[index] let options = PHLivePhotoRequestOptions() options.deliveryMode = .highQualityFormat options.isNetworkAccessAllowed = true options.progressHandler = { progress, _, _, _ in // Handler might not be called on the main queue, so re-dispatch for UI work. DispatchQueue.main.async { //TODO: Add in the progress viewer here //self.progressView.progress = Float(progress) } } PHImageManager.default().requestLivePhoto(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: options, resultHandler: { livePhoto, info in // Hide the progress view now the request has completed. //self.progressView.isHidden = true // If successful, show the live photo view and display the live photo. guard let livePhoto = livePhoto else { return } completionHandler(livePhoto) }) } public func getResource(for index: Int) -> Void { guard let onlyLivePhotos = livePhotos else { return } let asset = onlyLivePhotos[index] let resourceMan = PHAssetResourceManager.default() let assetResources = PHAssetResource.assetResources(for: asset) assetResources.forEach { (resource) in if resource.type == .pairedVideo { resourceMan.requestData(for: resource, options: nil, dataReceivedHandler: { (data) in print("here is the data that I need to do something with \(data)") //the asset itself should have a PHLIvePHotoView and I should be able to control it somehow //TODO: **START HERE GREG*** I can probably just play this data in an AVPLauer and call it a day }, completionHandler: { (error) in if let error = error { print("error \(error)") } }) } } } public func getNextPhoto(completionHandler: @escaping ((PHLivePhoto) -> Void)) -> Void { guard let livePhotos = livePhotos else { return } getLivePhoto(for: currentPhotoIndex, completionHandler:completionHandler) currentPhotoIndex -= 1 } } // MARK: PHPhotoLibraryChangeObserver extension LivePhotoStore: PHPhotoLibraryChangeObserver { func photoLibraryDidChange(_ changeInstance: PHChange) { // Change notifications may be made on a background queue. Re-dispatch to the // main queue before acting on the change as we'll be updating the UI. DispatchQueue.main.sync { // Check each of the three top-level fetches for changes. if let changeDetails = changeInstance.changeDetails(for: allPhotos) { // Update the cached fetch result. allPhotos = changeDetails.fetchResultAfterChanges // (The table row for this one doesn't need updating, it always says "All Photos".) } // Update the cached fetch results, and reload the table sections to match. if let changeDetails = changeInstance.changeDetails(for: smartAlbums) { smartAlbums = changeDetails.fetchResultAfterChanges } if let changeDetails = changeInstance.changeDetails(for: userCollections) { userCollections = changeDetails.fetchResultAfterChanges } } } }
mit
0a73e5a3960018c0f26240c376b81b62
37.212903
164
0.62367
5.264889
false
false
false
false
lyngbym/SwiftGraph
SwiftGraphLib/SwiftGraphLib/WeightedEdge.swift
3
1891
// // WeightedEdge.swift // SwiftGraph // // Copyright (c) 2014-2016 David Kopec // // 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. /// This protocol is needed for Dijkstra's algorithm - we need weights in weighted graphs /// to be able to be added together public protocol Summable { static func +(lhs: Self, rhs: Self) -> Self } extension Int: Summable {} extension Double: Summable {} extension Float: Summable {} extension String: Summable {} /// A weighted edge, who's weight subscribes to Comparable. open class WeightedEdge<W: Comparable & Summable>: UnweightedEdge { public override var weighted: Bool { return true } public let weight: W public override var reversed:Edge { return WeightedEdge(u: v, v: u, directed: directed, weight: weight) } public init(u: Int, v: Int, directed: Bool, weight: W) { self.weight = weight super.init(u: u, v: v, directed: directed) } //Implement Printable protocol public override var description: String { if directed { return "\(u) \(weight)> \(v)" } return "\(u) <\(weight)> \(v)" } //MARK: Operator Overloads static public func ==<W>(lhs: WeightedEdge<W>, rhs: WeightedEdge<W>) -> Bool { return lhs.u == rhs.u && lhs.v == rhs.v && lhs.directed == rhs.directed && lhs.weight == rhs.weight } }
apache-2.0
52e4bda27f3ed46e53989e87f91b303a
33.381818
107
0.662612
3.890947
false
false
false
false
ipagong/PGTabBar-Swift
Example/PGTabBar/ViewController.swift
1
3192
// // ViewController.swift // PGTabBar // // Created by damon.park on 04/19/2017. // Copyright (c) 2017 damon.park. All rights reserved. // import UIKit import PGTabBar class ViewController: UIViewController, TabContainerDelegate { @IBOutlet weak var tabContainer: TabContainer! override func viewDidLoad() { super.viewDidLoad() tabContainer.indicator = TabIndicator() tabContainer.option.bounces = false tabContainer.delegate = self // tabContainer.option.interItemSpacing = 3 // tabContainer.option.lineSpacing = 1 tabContainer.option.aspect = .fitable tabContainer.option.alignment = .center var tabList = [TabItem]() tabList.append(TabItem(title: TabText.title("YouTube").boldFont(size: 18).attrText, selectedTitle: TabText.title("YouTube").boldFont(size: 18).color(.red).attrText, cellClazz: TabCell.self )) tabList.append(TabItem(title: TabText.title("Facebook").boldFont(size: 18).attrText, selectedTitle: TabText.title("Facebook").boldFont(size: 18).color(.red).attrText, cellClazz: TabCell.self )) tabList.append(TabItem(title: TabText.title("A").boldFont(size: 18).attrText, selectedTitle: TabText.title("A").boldFont(size: 18).color(.red).attrText, cellClazz: TabCell.self )) tabList.append(TabItem(title: TabText.title("Na").boldFont(size: 18).attrText, selectedTitle: TabText.title("Na").boldFont(size: 18).color(.red).attrText, cellClazz: TabCell.self )) // tabList.append(TabItem(title: TabText.title("Instagram").boldFont(size: 18).attrText, // selectedTitle: TabText.title("Instagram").boldFont(size: 18).color(.red).attrText, // cellClazz: TabCell.self )) // tabList.append(TabItem(title: TabText.title("Twitch").boldFont(size: 18).attrText, // selectedTitle: TabText.title("Twitch").boldFont(size: 18).color(.red).attrText, // cellClazz: TabCell.self )) // tabList.append(TabItem(title: TabText.title("Pinterest").boldFont(size: 18).attrText, // selectedTitle: TabText.title("Pinterest").boldFont(size: 18).color(.red).attrText, // cellClazz: TabCell.self )) tabContainer.tabList = tabList } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.tabContainer.setNeedsUpdateConstraints() } /* func indexWithTabContainer(_ container:TabContainer) -> NSInteger? { return 0 } func didSelectedTabContainer(_ container:TabContainer, index:NSInteger, item:TabItemProtocol, tabCell:TabCellProtocol) { } func didDeselectedTabContainer(_ container:TabContainer, index:NSInteger, item:TabItemProtocol, tabCell:TabCellProtocol) { } */ }
mit
d6bd6fad7a6591eb249ff25fa2ce1995
41.56
126
0.597118
4.673499
false
false
false
false
kfix/MacPin
Sources/MacPinOSX/AppDelegateOSX.swift
1
26020
import AppKit import ObjectiveC import WebKitPrivates import Darwin //import Bookmarks //@NSApplicationMain // doesn't work without NIBs, using main.swift instead public class MacPinAppDelegateOSX: NSObject, MacPinAppDelegate { var browserController: BrowserViewController = BrowserViewControllerOSX() var windowController: WindowController? // optional so app can run "headless" if desired // FIXME: these menus are singletons for the App, but should really be tied to windows .... let shortcutsMenu = NSMenuItem(title: "Shortcuts", action: nil, keyEquivalent: "") let tabListMenu = NSMenuItem(title: "Tabs", action: nil, keyEquivalent: "") var prompter: Prompter? = nil public override init() { // gotta set these before MacPin()->NSWindow() UserDefaults.standard.register(defaults: [ //"NSQuitAlwaysKeepsWindows": true, // insist on Window-to-Space/fullscreen persistence between launches "NSInitialToolTipDelay": 1, // get TTs in 1ms instead of 3s "NSInitialToolTipFontSize": 12.0, // NSUserDefaults for NetworkProcesses: // https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/WebProcessPoolCocoa.mm // WebKit2HTTPProxy, WebKit2HTTPSProxy, WebKitOmitPDFSupport, all the cache directories ... // https://lists.webkit.org/pipermail/webkit-dev/2016-May/028233.html //"URLParserEnabled": "" // JS: new URL() // wish there was defaults for: // https://github.com/WebKit/webkit/blob/master/Source/WebKit2/NetworkProcess/mac/NetworkProcessMac.mm overrideSystemProxies() // SOCKS (kCFProxyTypeSOCKS) // PAC URL (kCFProxyTypeAutoConfigurationURL + kCFProxyAutoConfigurationURLKey) // PAC script (kCFProxyTypeAutoConfigurationJavaScript + kCFProxyAutoConfigurationJavaScriptKey) //_CFNetworkSetOverrideSystemProxySettings(CFDict) ]) UserDefaults.standard.removeObject(forKey: "__WebInspectorPageGroupLevel1__.WebKit2InspectorStartsAttached") // #13 fixed if #available(OSX 10.12, *) { // Sierra: don't coalesce windows into forced tabs NSWindow.allowsAutomaticWindowTabbing = false } AppScriptRuntime.shared.setBrowserWindowClass(BrowserViewControllerOSX.self) super.init() } // handle URLs passed by open @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor!, replyEvent: NSAppleEventDescriptor?) { if let urlstr = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))!.stringValue { warn("`\(urlstr)` -> AppScriptRuntime.shared.jsdelegate.launchURL()") AppScriptRuntime.shared.emit(.launchURL, urlstr) //replyEvent == ?? } //replyEvent == ?? } @objc func aboutPopup() { if #available(macOS 10.13, *) { //let verstr = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "?.?.?" NSApp.orderFrontStandardAboutPanel(options: [ .applicationVersion: """ WebKit (\(WebKit_version.major).\(WebKit_version.minor).\(WebKit_version.tiny)) Safari (\(Safari_version)) MacPin """ ]) } else { NSApp.orderFrontStandardAboutPanel() } } } @objc extension MacPinAppDelegateOSX: ApplicationDelegate { public func applicationDockMenu(_ sender: NSApplication) -> NSMenu? { warn() // high sierra seems to cache a *copy* of the tabMenu (containing tabviewitems holding refs to webViews' props) thru NSCopying // until its clicked on *or* until it garbage-collect itself every minute or so // causes webview to be retained after close, beacuse the copied menu is stale after tabs are closed and the master menu is updated return browserController.tabMenu } public func applicationShouldOpenUntitledFile(_ app: NSApplication) -> Bool { return false } //public func application(sender: AnyObject, openFileWithoutUI filename: String) -> Bool {} // app terminates on return! //public func application(theApplication: NSApplication, printFile filename: String) -> Bool {} // app terminates on return //public func finishLaunching() { super.finishLaunching() } // app activates, NSOpen files opened public func applicationWillFinishLaunching(_ notification: Notification) { // dock icon bounces, also before self.openFile(foo.bar) is called warn() NSUserNotificationCenter.default.delegate = self let app = notification.object as? NSApplication //let appname = Bundle.main.objectForInfoDictionaryKey("CFBundleName") ?? ProcessInfo.processInfo().processName let appname = NSRunningApplication.current.localizedName ?? ProcessInfo.processInfo.processName app!.mainMenu = NSMenu() let appMenu = NSMenuItem() appMenu.submenu = NSMenu() appMenu.submenu?.addItem(MenuItem("About \(appname)", #selector(type(of: self).aboutPopup))) appMenu.submenu?.addItem(MenuItem("Restart \(appname)", #selector(AppScriptRuntime.loadMainScript))) appMenu.submenu?.addItem(NSMenuItem.separator()) appMenu.submenu?.addItem(MenuItem("Hide \(appname)", "hide:", "h", [.command])) appMenu.submenu?.addItem(MenuItem("Hide Others", "hideOtherApplications:", "H", [.command, .shift])) appMenu.submenu?.addItem(NSMenuItem.separator()) //appMenu.submenu?.addItem(MenuItem("Edit App...", "editSiteApp")) // can't modify signed apps' Resources app!.mainMenu?.addItem(appMenu) // 1st item shows up as CFPrintableName app!.servicesMenu = NSMenu() let svcMenu = NSMenuItem(title: "Services", action: nil, keyEquivalent: "") svcMenu.submenu = app!.servicesMenu! appMenu.submenu?.addItem(svcMenu) appMenu.submenu?.addItem(MenuItem("Quit \(appname)", "terminate:", "q")) let editMenu = NSMenuItem() //NSTextArea funcs // plutil -p /System/Library/Frameworks/AppKit.framework/Resources/StandardKeyBinding.dict editMenu.submenu = NSMenu() editMenu.submenu?.title = "Edit" // https://github.com/WebKit/webkit/commit/f53fbb8b6c206c3cdd8d010267b8d6c430a02dab // & https://github.com/WebKit/webkit/commit/a580e447224c51e7cb28a1d03ca96d5ff851e6e1 editMenu.submenu?.addItem(MenuItem("Cut", "cut:", "x", [.command])) editMenu.submenu?.addItem(MenuItem("Copy", "copy:", "c", [.command])) editMenu.submenu?.addItem(MenuItem("Paste", "paste:", "v", [.command])) editMenu.submenu?.addItem(MenuItem("Select All", "selectAll:", "a", [.command])) editMenu.submenu?.addItem(NSMenuItem.separator()) let findMenu = MenuItem("Find") findMenu.submenu = NSMenu() findMenu.submenu?.title = "Find" findMenu.submenu?.addItem(MenuItem("Find...", "performTextFinderAction:", "f", [.command], tag: NSTextFinder.Action.showFindInterface.rawValue)) //wvc findMenu.submenu?.addItem(MenuItem("Find Next", "performTextFinderAction:", tag: NSTextFinder.Action.nextMatch.rawValue)) //wvc findMenu.submenu?.addItem(MenuItem("Find Previous", "performTextFinderAction:", tag: NSTextFinder.Action.previousMatch.rawValue)) //wvc findMenu.submenu?.addItem(MenuItem("Find and Replace...", "performTextFinderAction:", tag: NSTextFinder.Action.showReplaceInterface.rawValue)) //wvc findMenu.submenu?.addItem(MenuItem("Search within Selection", "performTextFinderAction:", tag: NSTextFinder.Action.selectAllInSelection.rawValue)) //wvc editMenu.submenu?.addItem(findMenu) app!.mainMenu?.addItem(editMenu) let tabMenu = NSMenuItem() //WebViewController and WKWebView funcs tabMenu.submenu = NSMenu() tabMenu.submenu?.title = "Tab" tabMenu.submenu?.addItem(MenuItem("Zoom In", #selector(WebViewControllerOSX.zoomIn), "+", [.command])) tabMenu.submenu?.addItem(MenuItem("Zoom Out", #selector(WebViewControllerOSX.zoomOut), "-", [.command])) tabMenu.submenu?.addItem(MenuItem("Zoom Text Only", #selector(WebViewControllerOSX.zoomText))) tabMenu.submenu?.addItem(MenuItem("Toggle Translucency", #selector(WebViewControllerOSX.toggleTransparency))) tabMenu.submenu?.addItem(MenuItem("Toggle Appearance", #selector(WebViewControllerOSX.toggleAppearance))) tabMenu.submenu?.addItem(MenuItem("Toggle Status Bar", #selector(WebViewControllerOSX.toggleStatusBar))) tabMenu.submenu?.addItem(NSMenuItem.separator()) tabMenu.submenu?.addItem(MenuItem("Show JS Console", #selector(MPWebView.console), "c", [.option, .command])) tabMenu.submenu?.addItem(MenuItem("Show Web Inspector", #selector(WebViewControllerOSX.toggleWebInspector), "i", [.option, .command])) tabMenu.submenu?.addItem(MenuItem("Reload", #selector(MPWebView.reload(_:)), "r", [.command])) tabMenu.submenu?.addItem(MenuItem("Uncache & Reload", #selector(MPWebView.reloadFromOrigin(_:)), "R", [.command, .shift])) tabMenu.submenu?.addItem(MenuItem("Go Back", #selector(MPWebView.goBack(_:)), "[", [.command])) tabMenu.submenu?.addItem(MenuItem("Go Forward", #selector(MPWebView.goForward(_:)), "]", [.command])) tabMenu.submenu?.addItem(MenuItem("Stop Loading", #selector(MPWebView.stopLoading(_:)), ".", [.command])) tabMenu.submenu?.addItem(MenuItem("Toggle Caching", #selector(WebViewControllerOSX.toggleCaching))) tabMenu.submenu?.addItem(NSMenuItem.separator()) tabMenu.submenu?.addItem(MenuItem("Print Page...", #selector(MPWebView.printWebView), "p", [.command])) tabMenu.submenu?.addItem(MenuItem("Save Web Archive...", #selector(MPWebView.saveWebArchive), "s", [.command, .shift])) tabMenu.submenu?.addItem(MenuItem("Save Page...", #selector(MPWebView.savePage), "s", [.command])) tabMenu.submenu?.addItem(MenuItem("Open with Default Browser", #selector(WebViewControllerOSX.askToOpenCurrentURL), "d", [.command])) tabMenu.submenu?.addItem(NSMenuItem.separator()) tabMenu.submenu?.addItem(MenuItem("Clone via Proxy...", #selector(WebViewControllerOSX.selectProxies))) app!.mainMenu?.addItem(tabMenu) let winMenu = NSMenuItem() //BrowserViewController and NSWindow funcs winMenu.submenu = NSMenu() winMenu.submenu?.title = "Window" winMenu.submenu?.addItem(MenuItem("Enter URL", #selector(BrowserViewControllerOSX.revealOmniBox), "l", [.command])) winMenu.submenu?.addItem(MenuItem(nil, #selector(NSWindow.toggleFullScreen(_:)))) winMenu.submenu?.addItem(MenuItem(nil, #selector(NSWindow.toggleToolbarShown(_:)))) winMenu.submenu?.addItem(MenuItem("Toggle Titlebar", #selector(WindowController.toggleTitlebar))) //winMenu.submenu?.addItem(MenuItem("Edit Toolbar", "runToolbarCustomizationPalette:")) winMenu.submenu?.addItem(MenuItem("New Tab", #selector(BrowserViewControllerOSX.newTabPrompt), "t", [.command])) winMenu.submenu?.addItem(MenuItem("New Isolated Tab", #selector(BrowserViewControllerOSX.newIsolatedTabPrompt))) winMenu.submenu?.addItem(MenuItem("New Private Tab", #selector(BrowserViewControllerOSX.newPrivateTabPrompt), "t", [.control, .command])) winMenu.submenu?.addItem(MenuItem("Close Tab", #selector(BrowserViewControllerOSX.closeTab(_:)), "w", [.command])) winMenu.submenu?.addItem(MenuItem("Duplicate Tab", #selector(BrowserViewControllerOSX.duplicateTab(_:)))) winMenu.submenu?.addItem(MenuItem("Show Next Tab", #selector(NSTabView.selectNextTabViewItem(_:)), String(format:"%c", NSTabCharacter), [.control])) winMenu.submenu?.addItem(MenuItem("Show Previous Tab", #selector(NSTabView.selectPreviousTabViewItem(_:)), String(format:"%c", NSTabCharacter), [.control, .shift])) if #available(macOS 10.13, iOS 10, *) { winMenu.submenu?.addItem(MenuItem("Show Tab Overview", #selector(WebViewControllerOSX.snapshotButtonClicked(_:)), "\\", [.shift, .command])) } app!.mainMenu?.addItem(winMenu) tabListMenu.isHidden = true app!.mainMenu?.addItem(tabListMenu) // Tuck these under the app menu? shortcutsMenu.isHidden = true app!.mainMenu?.addItem(shortcutsMenu) /* let bookMenu = NSMenuItem() bookMenu.submenu = NSMenu() bookMenu.submenu?.title = "Bookmarks" let bookmarks = Bookmark.readFrom("~/Library/Safari/Bookmarks.plist") app!.mainMenu?.addItem(bookMenu) // https://github.com/peckrob/FRBButtonBar */ let dbgMenu = NSMenuItem() dbgMenu.submenu = NSMenu() dbgMenu.submenu?.title = "Debug" //dbgMenu.submenu?.autoenablesItems = false dbgMenu.submenu?.addItem(MenuItem("Highlight TabView Constraints", "highlightConstraints")) //bc dbgMenu.submenu?.addItem(MenuItem("Randomize TabView Layout", "exerciseAmbiguityInLayout")) //bc dbgMenu.submenu?.addItem(MenuItem("Replace contentView With Tab", "replaceContentView")) //bc dbgMenu.submenu?.addItem(MenuItem("Dismiss VC", "dismissController:")) //bc #if DBGMENU #else dbgMenu.isHidden = true #endif app!.mainMenu?.addItem(dbgMenu) // https://developer.apple.com/documentation/appkit/nsappearancecustomization/choosing_a_specific_appearance_for_your_app#2993819 // NSApp.appearance = NSAppearance(named: .darkAqua) // NSApp.effectiveAppearance NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(MacPinAppDelegateOSX.handleGetURLEvent(_:replyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) //route registered url schemes warn() if !AppScriptRuntime.shared.loadMainScript() { // load main.js, if present self.browserController.extend(AppScriptRuntime.shared.exports) // expose our default browser instance early on, because legacy BrowserViewControllerOSX.self.exportSelf(AppScriptRuntime.shared.context.globalObject) // & the type for self-setup AppScriptRuntime.shared.exports.setObject(MPWebView.self, forKeyedSubscript: "WebView" as NSString) // because legacy AppScriptRuntime.shared.exports.setObject("", forKeyedSubscript: "launchedWithURL" as NSString) AppScriptRuntime.shared.loadSiteApp() // load app.js, if present } while (AppScriptRuntime.shared.scriptState == .Promised) { usleep(100000) // 100ms // need to wait for an async-imported main script to resolve // its app.on(.AppWillFinishLaunching) callback may replace the browserController } AppScriptRuntime.shared.emit(.AppWillFinishLaunching, self) // allow JS to replace our browserController self.shortcutsMenu.submenu = self.browserController.shortcutsMenu // update the menu from browserController self.shortcutsMenu.submenu?.title = "Shortcuts" // FIXME: allow JS to customize title? self.shortcutsMenu.isHidden = !(self.browserController.shortcutsMenu.numberOfItems > 0) self.tabListMenu.submenu = self.browserController.tabMenu self.tabListMenu.submenu?.title = "Tabs" self.tabListMenu.isHidden = false AppScriptRuntime.shared.context.evaluateScript("eval = null;") // security thru obscurity } public func applicationDidFinishLaunching(_ notification: Notification) { //dock icon stops bouncing AppScriptRuntime.shared.emit(.AppFinishedLaunching, "FIXME: provide real launch URLs") /* http://stackoverflow.com/a/13621414/3878712 NSSetUncaughtExceptionHandler { exception in print(exception) print(exception.callStackSymbols) prompter = nil // deinit prompter to cleanup the TTY } */ /////////////////////////////////////////////////////////////////////////////////////////// // "The Eskimo!" says this junk isn't worth using: https://developer.apple.com/forums/thread/678125 /////////////////////////////////////////////////////////////////////////////////////////// /* NSSetUncaughtExceptionHandler { (exception) in let source:String = exception.callStackSymbols[4] let separatorSet = CharacterSet(charactersIn: " -[]+?,") var array:[String] = source.components(separatedBy: separatorSet) array = array.filter({ $0 != "" }) let exceptionStr:String = array[3]; let exceptionArr=exceptionStr.split(separator: "\\d+") print("filename : \(exceptionArr[2])") print("method : \(exceptionArr[3])") } */ if let default_html = Bundle.main.url(forResource: "default", withExtension: "html") { warn("loading initial page from app bundle: \(default_html)") browserController.tabSelected = MPWebView(url: default_html) } if let userNotification = notification.userInfo?["NSApplicationLaunchUserNotificationKey"] as? NSUserNotification { userNotificationCenter(NSUserNotificationCenter.default, didActivate: userNotification) } let launched = CommandLine.arguments.dropFirst().first?.hasPrefix("-psn_0_") ?? false // Process Serial Number from LaunchServices open() warn(CommandLine.arguments.description) for (idx, arg) in CommandLine.arguments.dropFirst().enumerated() { switch (arg) { case "-i": //open a JS console on the terminal, if present if AppScriptRuntime.shared.eventCallbacks[.printToREPL, default: []].isEmpty { if let repl_js = Bundle.main.url(forResource: "app_repl", withExtension: "js") { warn("injecting TTY REPL") AppScriptRuntime.shared.eventCallbacks[.printToREPL] = [ AppScriptRuntime.shared.loadCommonJSScript(repl_js.absoluteString).objectForKeyedSubscript("repl") ] } } prompter = AppScriptRuntime.shared.REPL() // case "-s": // would like to natively implement a simple remote console for webkit-using osx apps, Valence only targets IOS-usbmuxd based stuff. // https://www.webkit.org/blog/1875/announcing-remote-debugging-protocol-v1-0/ // https://bugs.webkit.org/show_bug.cgi?id=124613 // `sudo launchctl print user/com.apple.webinspectord` // https://github.com/google/ios-webkit-debug-proxy/blob/master/src/ios_webkit_debug_proxy.c just connect to local com.apple.webinspectord // https://github.com/WebKit/webkit/tree/master/Source/JavaScriptCore/inspector/protocol // https://github.com/WebKit/webkit/blob/master/Source/JavaScriptCore/inspector/remote/RemoteInspector.mm // https://github.com/WebKit/webkit/blob/master/Source/JavaScriptCore/inspector/remote/RemoteInspectorConstants.h // https://github.com/siuying/IGJavaScriptConsole // [PlayStation] Restructuring Remote Inspector classes to support multiple platform. https://bugs.webkit.org/show_bug.cgi?id=197030 // webkit/Source/JavaScriptCore/inspector/remote/socket/RemoteInspectorServer.cpp // webkit/Source/JavaScriptCore/inspector/remote/socket/RemoteInspectorSocketEndpoint.cpp case "-t": if idx + 1 >= CommandLine.arguments.count { // no arg after this one prompter = browserController.tabs.first?.REPL() //open a JS console for the first tab WebView on the terminal, if present break } if let tabnum = Int(CommandLine.arguments[idx + 1]), browserController.tabs.count >= tabnum { // next argv should be tab number prompter = browserController.tabs[tabnum].REPL() // open a JS Console on the requested tab number // FIXME skip one more arg } else { prompter = browserController.tabs.first?.REPL() //open a JS console for the first tab WebView on the terminal, if present } // ooh, pretty: https://github.com/Naituw/WBWebViewConsole // https://github.com/Naituw/WBWebViewConsole/blob/master/WBWebViewConsole/Views/WBWebViewConsoleInputView.m case let _ where !launched && (arg.hasPrefix("http:") || arg.hasPrefix("https:") || arg.hasPrefix("about:") || arg.hasPrefix("file:")): warn("launched: \(launched) -> \(arg)") application(NSApp, openFile: arg) // LS will openFile AND argv.append() fully qualified URLs default: // FIXME unqualified URL from cmdline get openFile()d for some reason warn("unrecognized argv[\(idx)]: `\(arg)`") } } prompter?.start() //NSApp.setServicesProvider(ServiceOSX()) self.windowController = self.browserController.presentBrowser() if let wc = self.windowController, let window = wc.window, let fr = window.firstResponder { // window.makeFirstResponder(self.browserController.view) // scripts may have already added tabs which would have changed win's responders warn("focus is on: `\(fr)`") //warn(obj: fr) // crashes if any nils are in the responder chain! } } public func applicationDidBecomeActive(_ notification: Notification) { //if application?.orderedDocuments?.count < 1 { showApplication(self) } } public func application(_ application: NSApplication, willPresentError error: Error) -> Error { // not in iOS: http://stackoverflow.com/a/13083203/3878712 // NOPE, this can cause loops warn("`\(error.localizedDescription)` [\(error.domain)] [\(error.code)] `\(error.localizedFailureReason ?? String())` : \(error.userInfo)") switch error { case let error as URLError: if let url = error.failingURL?.absoluteString { //error.errorUserInfo[NSLocalizedDescriptionKey] = "\(error.localizedDescription)\n\n\(url)" // add failed url to error message return error } fallthrough default: return error } } public func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { warn() windowController?.close() // kill the window if it still exists windowController?.window = nil windowController = nil // deinit the wc browserController.close() // kill any zombie tabs // unfocus app? #if arch(x86_64) || arch(i386) // !TARGET_OS_EMBEDDED || TARGET_OS_SIMULATOR if let prompter = prompter, prompter.running { warn("prompt still active! \(prompter.running)") return .terminateLater } #endif AppScriptRuntime.shared.emit(.AppShouldTerminate, self) // allow JS to clean up its refs AppScriptRuntime.shared.resetStates() // then run a GC return .terminateNow } public func applicationWillTerminate(_ notification: Notification) { warn() UserDefaults.standard.synchronize() #if arch(x86_64) || arch(i386) if let prompter = prompter, prompter.running { warn("waiting on prompter to cleanup") prompter.wait() warn("prompter done") } #endif } public func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool { return true } @available(OSX 10.13, *) // High Sierra does this in lieu of HandleGetURLEvent public func application(_ application: NSApplication, open urls: [URL]) { warn(obj: urls) //AppScriptRuntime.shared.emit(.launchURL, urlstr) } // handles drag-to-dock-badge, /usr/bin/open and argv[1:] requests specifiying urls & local pathnames // https://github.com/WebKit/webkit/commit/3e028543b95387e8ac73e9947a5cef4dd1ac90f2 public func application(_ theApplication: NSApplication, openFile filename: String) -> Bool { warn(filename) if let ftype = try? NSWorkspace.shared.type(ofFile: filename) { warn(ftype) switch ftype { // check file:s for spaces and urlescape them //case "public.data": //case "public.folder": case "com.apple.web-internet-location": //.webloc http://stackoverflow.com/questions/146575/crafting-webloc-file if let webloc = NSDictionary(contentsOfFile: filename), let urlstr = webloc.value(forKey: "URL") as? String { if AppScriptRuntime.shared.anyHandled(.handleDragAndDroppedURLs, [urlstr]) { return true // app.js indicated it handled drag itself } else if let url = validateURL(urlstr) { browserController.tabSelected = MPWebView(url: url) return true } } return false case "public.html": warn(filename) browserController.tabSelected = MPWebView(url: URL(string:"file://\(filename)")!) return true case "com.netscape.javascript-source": //.js warn(filename) if #available(macOS 10.15, iOS 13.0, *) { AppScriptRuntime.shared.loadAppJSScript("file://\(filename)") } else { AppScriptRuntime.shared.loadAppScript("file://\(filename)") } AppScriptRuntime.shared.emit(.AppFinishedLaunching) return true // FIXME: make a custom .macpinjs ftype // when opened, offer to edit, test, or package as MacPin app // package will use JXA scripts to do the heavy lifting, port Makefile to use them default: break; } } // handles public.url if let url = validateURL(filename) { warn("opening public.url: \(url)") browserController.tabSelected = MPWebView(url: url) return true } warn("not opening: \(filename)") return false // will generate modal error popup } } extension MacPinAppDelegateOSX: NSUserNotificationCenterDelegate { //didDeliverNotification public func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) { warn("user clicked notification for app") // FIXME should be passing a [:] if AppScriptRuntime.shared.anyHandled(.handleClickedNotification, [ "title": (notification.title ?? "") as NSString, "subtitle": (notification.subtitle ?? "") as NSString, "body": (notification.informativeText ?? "") as NSString, "id": (notification.identifier ?? "") as NSString ]) { warn("handleClickedNotification fired!") center.removeDeliveredNotification(notification) } if let info = notification.userInfo, let type = info["type"] as? Int, let origin = info["origin"] as? String, let tabHash = info["tabHash"] as? UInt { if let webview = browserController.tabs.filter({ UInt($0.hash) == tabHash }).first { if let idstr = notification.identifier, let id = UInt64(idstr) { webview.notifier?.clicked(id: id) // let the webview know we sent it warn("app notification is for tab: \(webview)") browserController.tabSelected = webview center.removeDeliveredNotification(notification) } } } } // always display notifcations, even if app is active in foreground (for alert sounds) public func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool { return true } } extension MacPinAppDelegateOSX: NSWindowRestoration { // https://developer.apple.com/library/mac/documentation/General/Conceptual/MOSXAppProgrammingGuide/CoreAppDesign/CoreAppDesign.html#//apple_ref/doc/uid/TP40010543-CH3-SW35 public static func restoreWindow(withIdentifier identifier: NSUserInterfaceItemIdentifier, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Void) { if let app = MacPinApp.shared.appDelegate, let window = app.browserController.view.window, identifier.rawValue == "browser" { completionHandler(window, nil) //WKWebView._restoreFromSessionStateData ... } else { completionHandler(nil, nil) } } }
gpl-3.0
9e7ac5f4238f23b8c0b5272bdef1bd1e
50.321499
246
0.730669
3.923402
false
false
false
false
facemelters/data-science
ARKit/MattcedesBenz/MattcedesBenz/ViewController.swift
1
2179
// // ViewController.swift // MattcedesBenz // // Created by Michael Portanova on 7/7/17. // Copyright © 2017 Michael Portanova. All rights reserved. // import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene let scene = SCNScene(named: "art.scnassets/ship.scn")! // Set the scene to the view sceneView.scene = scene } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARWorldTrackingSessionConfiguration() // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } // MARK: - ARSCNViewDelegate /* // Override to create and configure nodes for anchors added to the view's session. func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { let node = SCNNode() return node } */ func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } }
gpl-2.0
6506c095963e0502afa583945e5c819a
26.225
103
0.628099
5.351351
false
true
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01136-getselftypeforcontainer.swift
1
1396
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { } class d: f{ class func i {} protocol A { func b(b: X.Type) { } init(foo: T) { } func a<d>() -> [c<d>] { } protocol a { } } class b<h, i> { } protocol c { } class A: A { } class B : C { } func ^(a: Boolean, Bool) -> Bool { } class a<f : b, g : b where f.d == g> { } protocol b { } struct c<h : b> : b { } func f<T : Boolean>(b: T) { } protocol A { } class C<D> { init <A: A where A.B == D>(e: A.B) { } } protocol A { } class B { func d() -> String { } } class C: B, A { override func d() -> String { } func c() -> String { } } func e<T where T: A, T: B>(t: T) { } func i(c: () -> ()) { } class a { var _ = i() { } } enum S<T> { } class a { } protocol A { } struct B : A { } struct C<D, E: A where D.C == E> { } protocol b { } struct c { func e() { } } func c<d { enum c { } } protocol a { } class b: a { } (b() as a).dyprefix(with: String) -> <T>(() -> T) -> String { } func a<T>() { enum b { } } protocol c : b { func b
apache-2.0
bd5e065f2ec3e317b6de477c38c52a56
12.553398
79
0.553009
2.386325
false
false
false
false