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
telldus/telldus-live-mobile-v3
ios/HomescreenWidget/UIViews/SensorWidget/SensorClass.swift
1
883
// // SensorClass.swift // TelldusLiveApp // // Created by Rimnesh Fernandez on 23/10/20. // Copyright © 2020 Telldus Technologies AB. All rights reserved. // import Foundation class SensorClass { static let intervalOne: Dictionary<String, Any> = [ "id": "1", "label": "Update every 5 minutes", "valueInMin": 5, ] static let intervalTwo: Dictionary<String, Any> = [ "id": "2", "label": "Update every 10 minutes", "valueInMin": 10, ] static let intervalThree: Dictionary<String, Any> = [ "id": "3", "label": "Update every 30 minutes", "valueInMin": 30, ] static let intervalFour: Dictionary<String, Any> = [ "id": "4", "label": "Update every 1 hour", "valueInMin": 60, ] static let SensorUpdateInterval: [Dictionary<String, Any>] = [ intervalOne, intervalTwo, intervalThree, intervalFour ] }
gpl-3.0
a208389466504b52e85adf875fb36c17
21.615385
66
0.628118
3.445313
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKElectro/NKEProtocol/NKE_ProtocolFileDecode.swift
1
3972
/* * nodekit.io * * Copyright (c) 2016-7 OffGrid Networks. 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 class NKE_ProtocolFileDecode: NSObject { var resourcePath: NSString? // The path to the bundle resource var urlPath: NSString // The relative path from root var fileName: NSString // The filename, with extension var fileBase: NSString // The filename, without the extension var fileExtension: NSString // The file extension var mimeType: NSString? // The mime type var textEncoding: NSString? // The text encoding init(url: NSURL) { resourcePath = nil var _fileTypes: [NSString: NSString] = [ "html": "text/html" , "js" : "text/plain" , "css": "text/css", "svg": "image/svg+xml"] urlPath = (url.path! as NSString).stringByDeletingLastPathComponent if urlPath.substringToIndex(1) == "/" { urlPath = urlPath.substringFromIndex(1) } urlPath = (("app" as NSString).stringByAppendingPathComponent(url.host!) as NSString).stringByAppendingPathComponent(urlPath as String) fileExtension = url.pathExtension!.lowercaseString fileName = url.lastPathComponent! if (fileExtension.length == 0) { fileBase = fileName } else { fileBase = fileName.substringToIndex(fileName.length - fileExtension.length - 1) } mimeType = nil textEncoding = nil super.init() if (fileName.length > 0) { resourcePath = urlPath.stringByAppendingPathComponent(fileName as String) if (!NKStorage.exists(resourcePath as! String)) { resourcePath = nil } if ((resourcePath == nil) && (fileExtension.length > 0)) { resourcePath = (("app" as NSString).stringByAppendingPathComponent(urlPath as String) as NSString).stringByAppendingPathComponent(fileName as String) if (!NKStorage.exists(resourcePath as! String)) { resourcePath = nil } } if ((resourcePath == nil) && (fileExtension.length == 0)) { resourcePath = (("app" as NSString).stringByAppendingPathComponent(urlPath as String) as NSString).stringByAppendingPathComponent((fileBase as String) + ".html") if (!NKStorage.exists(resourcePath as! String)) { resourcePath = nil } } if ((resourcePath == nil) && (fileExtension.length == 0)) { resourcePath = (("app" as NSString).stringByAppendingPathComponent(urlPath as String) as NSString).stringByAppendingPathComponent("index.html") if (!NKStorage.exists(resourcePath as! String)) { resourcePath = nil } } mimeType = _fileTypes[fileExtension] if (mimeType != nil) { if mimeType!.hasPrefix("text") { textEncoding = "utf-8" } } } } func exists() -> Bool { return (resourcePath != nil) } }
apache-2.0
536a13d280da53ea0403d9b07749fb86
29.553846
177
0.566465
5.382114
false
false
false
false
AthensWorks/OBWapp-iOS
Brew Week/Brew Week/EstablishmentViewController.swift
1
13676
// // EstablishmentViewController.swift // Brew Week // // Created by Ben Lachman on 5/29/15. // Copyright (c) 2015 Ohio Brew Week. All rights reserved. // import UIKit import CoreData import Alamofire class EstablishmentViewController: UITableViewController, NSFetchedResultsControllerDelegate, ManagedObjectViewController, UISearchResultsUpdating { let searchController = UISearchController(searchResultsController: nil) var managedObjectContext: NSManagedObjectContext? = nil var filteredEstablishments = [Establishment]() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar // Request beers Alamofire.request(.GET, Endpoint(path: "beers")).validate().responseJSON { response in switch response.result { case .Success(let beersJSON as [String: AnyObject]): Beer.beersFromJSON(beersJSON) guard let guid = UIDevice.currentDevice().identifierForVendor?.UUIDString else { return } var params: [String: AnyObject] = ["device_guid": guid]; let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate // { // "beer_id": 123, // "device_guid": "GUID", // "age": 35, // "lat": "Y", // "lon": "X", // } if let drinker = appDelegate?.drinker { params["age"] = drinker.ageInYears } if let location = appDelegate?.locationManager?.location { params["lat"] = location.coordinate.latitude params["lon"] = location.coordinate.longitude } // Request establishmets after successful beers response, // as establishments will omit any beers not already in the store Alamofire.request(.GET, Endpoint(path: "establishments"), parameters: params, encoding: .URL).validate().responseJSON { response in switch response.result { case .Success(let value as [String: AnyObject]): Establishment.establishmentsFromJSON(value) case .Failure(let error): print("Establishments response is error: \(error)") default: print("Establishments response is incorrectly typed") } } case .Failure(let error): print("Beers response is error: \(error)") default: print("Beers response is incorrectly typed") } } // Request breweries Alamofire.request(.GET, Endpoint(path: "breweries")).validate().responseJSON { response in switch response.result { case .Success(let breweriesJSON as [String: AnyObject]): Brewery.breweriesFromJSON(breweriesJSON) case .Failure(let error): print("Breweries response is error: \(error)") default: print("Breweries response is incorrectly typed") } } } override func viewDidAppear(animated: Bool) { if (UIApplication.sharedApplication().delegate as? AppDelegate)?.drinker == nil { let modal = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("UserVerificationViewController") as! UserVerificationViewController modal.modalTransitionStyle = .CoverVertical self.presentViewController(modal, animated: true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: insertNewObject @IBAction func insertNewObject(sender: AnyObject) { let context = self.fetchedResultsController.managedObjectContext let entity = self.fetchedResultsController.fetchRequest.entity! let 🏬 = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as! Establishment // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. 🏬.name = "Dive Bar" 🏬.address = "12 Grimey Lane" // Save the context. do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } } // MARK: - Actions @IBAction func refreshEstablishments(sender: UIRefreshControl) { // /establishment/:establishment_id/beer_statuses Alamofire.request(.GET, Endpoint(path: "establishments")).validate().responseJSON { establishmentsResponse in switch establishmentsResponse.result { case .Success(let establishmentsJSON as [String: [AnyObject]]): Establishment.establishmentsFromJSON(establishmentsJSON) case .Failure(let error): print("Establishments response is error: \(error)") default: print("Establishments response is incorrectly typed") } self.refreshControl?.endRefreshing() } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showBeers" { if let indexPath = self.tableView.indexPathForSelectedRow { let selectedEstablishment: Establishment if filtering { selectedEstablishment = filteredEstablishments[indexPath.row] } else { selectedEstablishment = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Establishment } _ = selectedEstablishment.beerStatuses let controller = segue.destinationViewController as! BeersTableViewController controller.managedObjectContext = managedObjectContext controller.establishment = selectedEstablishment } } else if segue.identifier == "showMap" { let controller = segue.destinationViewController as! MapViewController controller.managedObjectContext = managedObjectContext } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if filtering { return filteredEstablishments.count } let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("EstablishmentCell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let 🏬: Establishment if filtering { 🏬 = filteredEstablishments[indexPath.row] } else { 🏬 = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Establishment } cell.textLabel?.text = 🏬.name var displayAddress = 🏬.address if let rangeOfAthens = displayAddress.rangeOfString(", Athens", options: .CaseInsensitiveSearch) { displayAddress = displayAddress.substringWithRange(displayAddress.startIndex ..< rangeOfAthens.startIndex).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } cell.detailTextLabel?.text = displayAddress } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Establishment", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 50 // Edit the sort key as appropriate. //TODO: we need to sort based on the order sent by the server. add index generated from the order received from the server. let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Establishments") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController NSFetchedResultsController.deleteCacheWithName("Establishments") do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil /* func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) default: return } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } */ // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } // MARK: - Filtering var filtering: Bool { return searchController.active && searchController.searchBar.text != "" } func filterContentForSearchText(searchText: String, scope: String = "All") { let substrings = searchText.componentsSeparatedByString(" ") .filter { $0.isEmpty == false } .map { $0.lowercaseString } filteredEstablishments = fetchedResultsController.fetchedObjects? .flatMap { $0 as? Establishment } .filter { establishment in let lowercaseName = establishment.name.lowercaseString for substring in substrings { if lowercaseName.containsString(substring) == false { return false } } return true } ?? [Establishment]() tableView.reloadData() } func updateSearchResultsForSearchController(searchController: UISearchController) { guard let searchText = searchController.searchBar.text else { return } filterContentForSearchText(searchText) } }
apache-2.0
97324c64936ee97f81f90f646b3ec01c
38.005714
356
0.676677
5.402454
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Tools/NetworkTools.swift
1
954
// // NetworkTools.swift // DYZB // // Created by xiudou on 16/9/20. // Copyright © 2016年 xiudo. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { class func requestData(_ type : MethodType,URLString : String,parameters:[String : Any]? = nil,finishCallBack : @escaping (_ result : Any) -> ()){ // 确定请求类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post // 发送网络请求 Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in if let url = response.request?.url{ print("请求的URL = \(url)") } // 守护结果 guard let result = response.result.value else{ debugLog("没有结果") return } finishCallBack(result: result) } } }
mit
fc5d5e429ba8749d63cbad6526e2036f
22.815789
150
0.565746
4.330144
false
false
false
false
illescasDaniel/Questions
Questions/ViewControllers/LicensesViewController.swift
1
2900
import UIKit class LicensesViewController: UIViewController { @IBOutlet weak var textView: UITextView! private lazy var licensesAttributedText: NSAttributedString = { let headlineFontStyle = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .headline)] let subheadFontStyle = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .subheadline)] let bgMusicBensound = "Royalty Free Music from Bensound:\n".attributedStringWith(headlineFontStyle) let bgMusicBensoundLink = "http://www.bensound.com/royalty-free-music/track/the-lounge\n".attributedStringWith(subheadFontStyle) let correctSound = "\nCorrect.mp3, creator: LittleRainySeasons:\n".attributedStringWith(headlineFontStyle) let correctSoundLink = "https://www.freesound.org/people/LittleRainySeasons/sounds/335908\n".attributedStringWith(subheadFontStyle) let incorrectSound = "\nGame Sound Wrong.wav, creator: Bertrof\n\"This work is licensed under the Attribution License.\": \n".attributedStringWith(headlineFontStyle) let incorrectSoundLink = "https://www.freesound.org/people/Bertrof/sounds/131657/\n https://creativecommons.org/licenses/by/3.0/legalcode\n".attributedStringWith(subheadFontStyle) let sideVolumeHUD = "\nSideVolumeHUD - illescasDaniel. Licensed under the MIT License\n".attributedStringWith(headlineFontStyle) let sideVolumeHUDLink = "https://github.com/illescasDaniel/SideVolumeHUD\n".attributedStringWith(subheadFontStyle) let icons = "\nIcons 8\n".attributedStringWith(headlineFontStyle) let icon1 = "https://icons8.com/icon/1054/screenshot".attributedStringWith(subheadFontStyle) let icon2 = "https://icons8.com/icon/8186/create-filled".attributedStringWith(subheadFontStyle) let icon3 = "https://icons8.com/icon/2897/cloud-filled".attributedStringWith(subheadFontStyle) let attributedText = bgMusicBensound + bgMusicBensoundLink + correctSound + correctSoundLink + incorrectSound + incorrectSoundLink + sideVolumeHUD + sideVolumeHUDLink + icons + icon1 + icon2 + icon3 return attributedText }() // MARK: View life cycle override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = L10n.Settings_Options_Licenses self.textView.attributedText = licensesAttributedText self.textView.textAlignment = .center self.textView.textContainerInset = UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10) self.loadCurrentTheme() self.textView.frame = UIScreen.main.bounds self.textView.autoresizingMask = [.flexibleWidth, .flexibleHeight] } // MARK: Convenience @IBAction internal func loadCurrentTheme() { textView.tintColor = .themeStyle(dark: .warmColor, light: .coolBlue) if UserDefaultsManager.darkThemeSwitchIsOn { textView.backgroundColor = .themeStyle(dark: .black, light: .white) textView.textColor = .themeStyle(dark: .white, light: .black) } } }
mit
8e2117d6b879e79ef40af68327c82168
46.540984
200
0.778966
3.851262
false
false
false
false
shanksyang/SwiftRegex
SwiftRegex/SwiftRegex.swift
1
4323
// // SwiftRegex.swift // SwiftRegex // // Created by Gregory Todd Williams on 6/7/14. // Copyright (c) 2014 Gregory Todd Williams. All rights reserved. // import Foundation //extension String { // func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? { // let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex) // let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex) // if let from = String.Index(from16, within: self), // let to = String.Index(to16, within: self) { // return from ..< to // } // return nil // } //} // // //extension String { // func NSRangeFromRange(range : Range<String.Index>) -> NSRange { // let utf16view = self.utf16 // let from = String.UTF16View.Index(range.startIndex, within: utf16view) // let to = String.UTF16View.Index(range.endIndex, within: utf16view) // return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to)) // } //} infix operator =~ {} func =~ (value : String, pattern : String) -> RegexMatchResult { let nsstr = value as NSString // we use this to access the NSString methods like .length and .substringWithRange(NSRange) let options : NSRegularExpressionOptions = [] do { let re = try NSRegularExpression(pattern: pattern, options: options) let all = NSRange(location: 0, length: nsstr.length) var matches : Array<String> = [] var captureResult : [RegexCaptureResult] = [RegexCaptureResult]() re.enumerateMatchesInString(value, options: [], range: all) { (result, flags, ptr) -> Void in guard let result = result else { return } var captureItems : [String] = [] for i in 0..<result.numberOfRanges { let range = result.rangeAtIndex(i) print(range) let string = nsstr.substringWithRange(range) if(i > 0) { captureItems.append(string) continue } matches.append(string) } captureResult.append(RegexCaptureResult(items: captureItems)) print(matches) } return RegexMatchResult(items: matches, captureItems: captureResult) } catch { return RegexMatchResult(items: [], captureItems: []) } } struct RegexMatchCaptureGenerator : GeneratorType { var items: Array<String> mutating func next() -> String? { if items.isEmpty { return nil } let ret = items[0] items = Array(items[1..<items.count]) return ret } } struct RegexMatchResult : SequenceType, BooleanType { var items: Array<String> var captureItems: [RegexCaptureResult] func generate() -> RegexMatchCaptureGenerator { print(items) return RegexMatchCaptureGenerator(items: items) } var boolValue: Bool { return items.count > 0 } subscript (i: Int) -> String { return items[i] } } struct RegexCaptureResult { var items: Array<String> } class SwiftRegex { //是否包含 class func containsMatch(pattern: String, inString string: String) -> Bool { let options : NSRegularExpressionOptions = [] let matchOptions : NSMatchingOptions = [] let regex = try! NSRegularExpression(pattern: pattern, options: options) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: matchOptions, range: range) != nil } //匹配 class func match(pattern: String, inString string: String) -> RegexMatchResult { return string =~ pattern } //替换 class func replaceMatches(pattern: String, inString string: String, withString replacementString: String) -> String? { let options : NSRegularExpressionOptions = [] let matchOptions : NSMatchingOptions = [] let regex = try! NSRegularExpression(pattern: pattern, options: options) let range = NSMakeRange(0, string.characters.count) return regex.stringByReplacingMatchesInString(string, options: matchOptions, range: range, withTemplate: replacementString) } }
bsd-3-clause
5666a89041fe1285347feca186ff8492
32.648438
131
0.621082
4.417436
false
false
false
false
maxbritto/cours-ios11-swift4
Niveau_avance/Objectif 2/Safety First/Safety First/Model/Vault.swift
1
1354
// // CredentialsManager.swift // Safety First // // Created by Maxime Britto on 05/09/2017. // Copyright © 2017 Maxime Britto. All rights reserved. // import Foundation import RealmSwift class Vault { private let _realm:Realm private let _credentialList:Results<Credentials> init(withRealm realm:Realm) { _realm = realm _credentialList = _realm.objects(Credentials.self) } func addCredentials(title:String, login:String, password:String, url:String) -> Credentials { let newCredential = Credentials() newCredential.title = title newCredential.login = login newCredential.password = password newCredential.url = url try? _realm.write { _realm.add(newCredential) } return newCredential } func getCredentialCount() -> Int { return _credentialList.count } func getCredential(atIndex index:Int) -> Credentials? { guard index >= 0 && index < getCredentialCount() else { return nil } return _credentialList[index] } func deleteCredential(atIndex index:Int) { if let credToDelete = getCredential(atIndex: index) { try? _realm.write { _realm.delete(credToDelete) } } } }
apache-2.0
d7ed8de4fb6de8bc2a01646917eb997a
22.327586
97
0.599409
4.602041
false
false
false
false
AL333Z/Words-MVVM-Android-iOS
Words-iOS/Words/Util/UIKitExtensions.swift
2
2079
// // Util.swift // ReactiveTwitterSearch // // Created by Colin Eberhardt on 10/05/2015. // Copyright (c) 2015 Colin Eberhardt. All rights reserved. // import UIKit import ReactiveCocoa struct AssociationKey { static var hidden: UInt8 = 1 static var alpha: UInt8 = 2 static var text: UInt8 = 3 } // lazily creates a gettable associated property via the given factory func lazyAssociatedProperty<T: AnyObject>(host: AnyObject, key: UnsafePointer<Void>, factory: ()->T) -> T { return objc_getAssociatedObject(host, key) as? T ?? { let associatedProperty = factory() objc_setAssociatedObject(host, key, associatedProperty, UInt(OBJC_ASSOCIATION_RETAIN)) return associatedProperty }() } func lazyMutableProperty<T>(host: AnyObject, key: UnsafePointer<Void>, setter: T -> (), getter: () -> T) -> MutableProperty<T> { return lazyAssociatedProperty(host, key) { var property = MutableProperty<T>(getter()) property.producer .start(next: { newValue in setter(newValue) }) return property } } extension UIView { public var rac_alpha: MutableProperty<CGFloat> { return lazyMutableProperty(self, &AssociationKey.alpha, { self.alpha = $0 }, { self.alpha }) } public var rac_hidden: MutableProperty<Bool> { return lazyMutableProperty(self, &AssociationKey.hidden, { self.hidden = $0 }, { self.hidden }) } } extension UILabel { public var rac_text: MutableProperty<String> { return lazyMutableProperty(self, &AssociationKey.text, { self.text = $0 }, { self.text ?? "" }) } } extension UITextField { public var rac_text: MutableProperty<String> { return lazyAssociatedProperty(self, &AssociationKey.text) { self.addTarget(self, action: "changed", forControlEvents: UIControlEvents.EditingChanged) var property = MutableProperty<String>(self.text ?? "") property.producer .start(next: { newValue in self.text = newValue }) return property } } func changed() { rac_text.value = self.text } }
apache-2.0
36125f771ef3d6107cf67fde27d5258d
27.094595
128
0.67292
4.09252
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Moog Ladder/AKMoogLadderPresets.swift
2
974
// // AKMoogLadderPresets.swift // AudioKit // // Created by Nicholas Arner, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation /// Preset for the AKMoogLadder public extension AKMoogLadder { /// Blurry, foggy filter public func presetFogMoogLadder() { cutoffFrequency = 515.578 resonance = 0.206 } /// Dull noise filter public func presetDullNoiseMoogLadder() { cutoffFrequency = 3088.157 resonance = 0.075 } /// Print out current values in case you want to save it as a preset public func printCurrentValuesAsPreset() { print("public func presetSomeNewMoogLadderFilter() {") print(" cutoffFrequency = \(String(format: "%0.3f", cutoffFrequency))") print(" resonance = \(String(format: "%0.3f", resonance))") print(" ramp time = \(String(format: "%0.3f", rampTime))") print("}\n") } }
mit
9d990660126d993be2cdeaf85aaa1872
26.8
82
0.624872
4.248908
false
false
false
false
aahmedae/blitz-news-ios
Blitz News/AppDelegate.swift
1
2740
// // AppDelegate.swift // Blitz News // // Created by Asad Ahmed on 5/13/17. // // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // setup app theme setupCustomAppTheme() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // Sets up the custom app theme fileprivate func setupCustomAppTheme() { // navigation bar let navigationBarAppearace = UINavigationBar.appearance() navigationBarAppearace.tintColor = UISettings.NAV_BAR_HEADER_FONT_COLOR navigationBarAppearace.barTintColor = UISettings.HEADER_BAR_COLOR navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UISettings.NAV_BAR_HEADER_FONT_COLOR, NSFontAttributeName: UISettings.NAV_BAR_HEADER_FONT] // status bar UIApplication.shared.statusBarStyle = UISettings.STATUS_BAR_STYLE } }
mit
bb83f723c220125bf035288815620bef
44.666667
285
0.739781
5.591837
false
false
false
false
whitepixelstudios/Material
Sources/iOS/Card.swift
1
7894
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit open class Card: PulseView { /// A container view for subviews. open let container = UIView() @IBInspectable open override var cornerRadiusPreset: CornerRadiusPreset { didSet { container.cornerRadiusPreset = cornerRadiusPreset } } @IBInspectable open var cornerRadius: CGFloat { get { return container.layer.cornerRadius } set(value) { container.layer.cornerRadius = value } } open override var shapePreset: ShapePreset { didSet { container.shapePreset = shapePreset } } @IBInspectable open override var backgroundColor: UIColor? { didSet { container.backgroundColor = backgroundColor } } /// A reference to the toolbar. @IBInspectable open var toolbar: Toolbar? { didSet { oldValue?.removeFromSuperview() if let v = toolbar { container.addSubview(v) } layoutSubviews() } } /// A preset wrapper around toolbarEdgeInsets. open var toolbarEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { toolbarEdgeInsets = EdgeInsetsPresetToValue(preset: toolbarEdgeInsetsPreset) } } /// A reference to toolbarEdgeInsets. @IBInspectable open var toolbarEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /// A reference to the contentView. @IBInspectable open var contentView: UIView? { didSet { oldValue?.removeFromSuperview() if let v = contentView { v.clipsToBounds = true container.addSubview(v) } layoutSubviews() } } /// A preset wrapper around contentViewEdgeInsets. open var contentViewEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { contentViewEdgeInsets = EdgeInsetsPresetToValue(preset: contentViewEdgeInsetsPreset) } } /// A reference to contentViewEdgeInsets. @IBInspectable open var contentViewEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /// A reference to the bottomBar. @IBInspectable open var bottomBar: Bar? { didSet { oldValue?.removeFromSuperview() if let v = bottomBar { container.addSubview(v) } layoutSubviews() } } /// A preset wrapper around bottomBarEdgeInsets. open var bottomBarEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { bottomBarEdgeInsets = EdgeInsetsPresetToValue(preset: bottomBarEdgeInsetsPreset) } } /// A reference to bottomBarEdgeInsets. @IBInspectable open var bottomBarEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /** An initializer that accepts a NSCoder. - Parameter coder aDecoder: A NSCoder. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** An initializer that accepts a CGRect. - Parameter frame: A CGRect. */ public override init(frame: CGRect) { super.init(frame: frame) } /// A convenience initializer. public convenience init() { self.init(frame: .zero) } /** A convenience initiazlier. - Parameter toolbar: An optional Toolbar. - Parameter contentView: An optional UIView. - Parameter bottomBar: An optional Bar. */ public convenience init?(toolbar: Toolbar?, contentView: UIView?, bottomBar: Bar?) { self.init(frame: .zero) prepareProperties(toolbar: toolbar, contentView: contentView, bottomBar: bottomBar) } open override func layoutSubviews() { super.layoutSubviews() container.frame.size.width = bounds.width reload() } /// Reloads the layout. open func reload() { var h: CGFloat = 0 if let v = toolbar { h = prepare(view: v, with: toolbarEdgeInsets, from: h) } if let v = contentView { h = prepare(view: v, with: contentViewEdgeInsets, from: h) } if let v = bottomBar { h = prepare(view: v, with: bottomBarEdgeInsets, from: h) } container.frame.size.height = h bounds.size.height = h } open override func prepare() { super.prepare() pulseAnimation = .none cornerRadiusPreset = .cornerRadius1 prepareContainer() } /** Prepare the view size from a given top position. - Parameter view: A UIView. - Parameter edge insets: An EdgeInsets. - Parameter from top: A CGFloat. - Returns: A CGFloat. */ @discardableResult open func prepare(view: UIView, with insets: EdgeInsets, from top: CGFloat) -> CGFloat { let y = insets.top + top view.frame.origin.y = y view.frame.origin.x = insets.left let w = container.bounds.width - insets.left - insets.right var h = view.bounds.height if 0 == h || nil != view as? UILabel { (view as? UILabel)?.sizeToFit() h = view.sizeThatFits(CGSize(width: w, height: .greatestFiniteMagnitude)).height } view.frame.size.width = w view.frame.size.height = h return y + h + insets.bottom } /** A preparation method that sets the base UI elements. - Parameter toolbar: An optional Toolbar. - Parameter contentView: An optional UIView. - Parameter bottomBar: An optional Bar. */ internal func prepareProperties(toolbar: Toolbar?, contentView: UIView?, bottomBar: Bar?) { self.toolbar = toolbar self.contentView = contentView self.bottomBar = bottomBar } } extension Card { /// Prepares the container. fileprivate func prepareContainer() { container.clipsToBounds = true addSubview(container) } }
bsd-3-clause
016793db714480f3546b12f839a987fd
29.129771
96
0.616418
5.070006
false
false
false
false
dboyliao/NumSwift
NumSwift/Source/FFT.swift
1
11862
// // Dear maintainer: // // When I wrote this code, only I and God // know what it was. // Now, only God knows! // // So if you are done trying to 'optimize' // this routine (and failed), // please increment the following counter // as warning to the next guy: // // var TotalHoursWastedHere = 0 // // Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered import Accelerate /** Complex-to-Complex Fast Fourier Transform. - Note: we use radix-2 fft. As a result, it may process only partial input data depending on the # of data is of power of 2 or not. - Parameters: - realp: real part of input data - imagp: imaginary part of input data - Returns: - `(realp:[Double], imagp:[Double])`: Fourier coeficients. It's a tuple with named attributes, `realp` and `imagp`. */ public func fft(_ realp:[Double], imagp: [Double]) -> (realp:[Double], imagp:[Double]) { let log2N = vDSP_Length(log2f(Float(realp.count))) let fftN = Int(1 << log2N) // buffers. var inputRealp = [Double](realp[0..<fftN]) var inputImagp = [Double](imagp[0..<fftN]) var fftCoefRealp = [Double](repeating: 0.0, count: fftN) var fftCoefImagp = [Double](repeating: 0.0, count: fftN) // setup DFT and execute. let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(fftN), vDSP_DFT_Direction.FORWARD) vDSP_DFT_ExecuteD(setup!, &inputRealp, &inputImagp, &fftCoefRealp, &fftCoefImagp) // destroy setup. vDSP_DFT_DestroySetupD(setup) return (fftCoefRealp, fftCoefImagp) } /** Complex-to-Complex Fast Fourier Transform. - Note: that we use radix-2 fft. As a result, it may process only partial input data depending on the # of data is of power of 2 or not. - Parameters: - realp: real part of input data - imagp: imaginary part of input data - Returns: `(realp:[Float], imagp:[Float])`: Fourier coeficients. It's a tuple with named attributes, `realp` and `imagp`. */ public func fft(_ realp:[Float], imagp:[Float]) -> (realp:[Float], imagp:[Float]){ let log2N = vDSP_Length(log2f(Float(realp.count))) let fftN = Int(1 << log2N) // buffers. var inputRealp = [Float](realp[0..<fftN]) var inputImagp = [Float](imagp[0..<fftN]) var fftCoefRealp = [Float](repeating: 0.0, count: fftN) var fftCoefImagp = [Float](repeating: 0.0, count: fftN) // setup DFT and execute. let setup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftN), vDSP_DFT_Direction.FORWARD) vDSP_DFT_Execute(setup!, &inputRealp, &inputImagp, &fftCoefRealp, &fftCoefImagp) // destroy setup. vDSP_DFT_DestroySetup(setup) return (fftCoefRealp, fftCoefImagp) } /** Complex-to-Complex Inverse Fast Fourier Transform. - Note: we use radix-2 Inverse Fast Fourier Transform. As a result, it may process only partial input data depending on the # of data is of power of 2 or not. - Parameters: - realp: real part of input data - imagp: imaginary part of input data - Returns: `(realp:[Double], imagp:[Double])`: Fourier coeficients. It's a tuple with named attributes, `realp` and `imagp`. */ public func ifft(_ realp:[Double], imagp:[Double]) -> (realp:[Double], imagp:[Double]){ let log2N = vDSP_Length(log2f(Float(realp.count))) let fftN = Int(1 << log2N) // buffers. var inputCoefRealp = [Double](realp[0..<fftN]) var inputCoefImagp = [Double](imagp[0..<fftN]) var outputRealp = [Double](repeating: 0.0, count: fftN) var outputImagp = [Double](repeating: 0.0, count: fftN) // setup DFT and execute. let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(fftN), vDSP_DFT_Direction.INVERSE) vDSP_DFT_ExecuteD(setup!, &inputCoefRealp, &inputCoefImagp, &outputRealp, &outputImagp) // normalization of ifft var scale = Double(fftN) var normalizedOutputRealp = [Double](repeating: 0.0, count: fftN) var normalizedOutputImagp = [Double](repeating: 0.0, count: fftN) vDSP_vsdivD(&outputRealp, 1, &scale, &normalizedOutputRealp, 1, vDSP_Length(fftN)) vDSP_vsdivD(&outputImagp, 1, &scale, &normalizedOutputImagp, 1, vDSP_Length(fftN)) // destroy setup. vDSP_DFT_DestroySetupD(setup) return (normalizedOutputRealp, normalizedOutputImagp) } /** Complex-to-Complex Inverse Fast Fourier Transform. - Note: we use radix-2 Inverse Fast Fourier Transform. As a result, it may process only partial input data depending on the # of data is of power of 2 or not. - Parameters: - realp: real part of input data - imagp: imaginary part of input data - Returns: `(realp:[Float], imagp:[Float])`: Fourier coeficients. It's a tuple with named attributes, `realp` and `imagp`. */ public func ifft(_ realp:[Float], imagp:[Float]) -> (realp:[Float], imagp:[Float]){ let log2N = vDSP_Length(log2f(Float(realp.count))) let fftN = Int(1 << log2N) // buffers. var inputCoefRealp = [Float](realp[0..<fftN]) var inputCoefImagp = [Float](imagp[0..<fftN]) var outputRealp = [Float](repeating: 0.0, count: fftN) var outputImagp = [Float](repeating: 0.0, count: fftN) // setup DFT and execute. let setup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftN), vDSP_DFT_Direction.INVERSE) defer { // destroy setup. vDSP_DFT_DestroySetup(setup) } vDSP_DFT_Execute(setup!, &inputCoefRealp, &inputCoefImagp, &outputRealp, &outputImagp) // normalization of ifft var scale = Float(fftN) var normalizedOutputRealp = [Float](repeating: 0.0, count: fftN) var normalizedOutputImagp = [Float](repeating: 0.0, count: fftN) vDSP_vsdiv(&outputRealp, 1, &scale, &normalizedOutputRealp, 1, vDSP_Length(fftN)) vDSP_vsdiv(&outputImagp, 1, &scale, &normalizedOutputImagp, 1, vDSP_Length(fftN)) return (normalizedOutputRealp, normalizedOutputImagp) } /** Convolution with Fast Fourier Transform Perform convolution by Fast Fourier Transform - Parameters: - x: input array for convolution. - y: input array for convolution. - mode: mode of the convolution. - "full": return full result (default). - "same": return result with the same length as the longest input arrays between x and y. - "valid": only return the result given for points where two arrays overlap completely. - Returns: the result of the convolution of x and y. */ public func fft_convolve(_ x:[Double], y:[Double], mode:String = "full") -> [Double] { var longArray:[Double] var shortArray:[Double] if x.count < y.count { longArray = [Double](y) shortArray = [Double](x) } else { longArray = [Double](x) shortArray = [Double](y) } let N = longArray.count let M = shortArray.count let convN = N+M-1 let convNPowTwo = leastPowerOfTwo(convN) longArray = pad(longArray, toLength:convNPowTwo, value:0.0) shortArray = pad(shortArray, toLength:convNPowTwo, value:0.0) let zeros = [Double](repeating: 0.0, count: convNPowTwo) var (coefLongArrayRealp, coefLongArrayImagp) = fft(longArray, imagp:zeros) var (coefShortArrayRealp, coefShortArrayImagp) = fft(shortArray, imagp:zeros) // setup input buffers for vDSP_zvmulD // long array: var coefLongArrayComplex = DSPDoubleSplitComplex(realp:&coefLongArrayRealp, imagp:&coefLongArrayImagp) // short array: var coefShortArrayComplex = DSPDoubleSplitComplex(realp:&coefShortArrayRealp, imagp:&coefShortArrayImagp) // setup output buffers for vDSP_zvmulD var coefConvRealp = [Double](repeating: 0.0, count: convNPowTwo) var coefConvImagp = [Double](repeating: 0.0, count: convNPowTwo) var coefConvComplex = DSPDoubleSplitComplex(realp:&coefConvRealp, imagp:&coefConvImagp) // Elementwise Complex Multiplication vDSP_zvmulD(&coefLongArrayComplex, 1, &coefShortArrayComplex, 1, &coefConvComplex, 1, vDSP_Length(convNPowTwo), Int32(1)) // ifft var (convResult, _) = ifft(coefConvRealp, imagp:coefConvImagp) // Remove padded zeros convResult = [Double](convResult[0..<convN]) // modify the result according mode before return let finalResult:[Double] switch mode { case "same": let numOfResultToBeRemoved = convN - N let toBeRemovedHalf = numOfResultToBeRemoved / 2 if numOfResultToBeRemoved % 2 == 0 { finalResult = [Double](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf)]) } else { finalResult = [Double](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf-1)]) } case "valid": finalResult = [Double](convResult[(M-1)..<(convN-M+1)]) default: finalResult = convResult } return finalResult } /** Convolution with Fast Fourier Transform Perform convolution by Fast Fourier Transform - Parameters: - x: input array for convolution. - y: input array for convolution. - mode: mode of the convolution. - "full": return full result (default). - "same": return result with the same length as the longest input array between x and y. - "valid": only return the result given for points where two arrays overlap completely. - Returns: the result of the convolution of x and y. */ public func fft_convolve(_ x:[Float], y:[Float], mode:String = "full") -> [Float] { var longArray:[Float] var shortArray:[Float] if x.count < y.count { longArray = [Float](y) shortArray = [Float](x) } else { longArray = [Float](x) shortArray = [Float](y) } let N = longArray.count let M = shortArray.count let convN = N+M-1 let convNPowTwo = leastPowerOfTwo(convN) longArray = pad(longArray, toLength:convNPowTwo, value:0.0) shortArray = pad(shortArray, toLength:convNPowTwo, value:0.0) let zeros = [Float](repeating: 0.0, count: convNPowTwo) var (coefLongArrayRealp, coefLongArrayImagp) = fft(longArray, imagp:zeros) var (coefShortArrayRealp, coefShortArrayImagp) = fft(shortArray, imagp:zeros) // setup input buffers for vDSP_zvmulD // long array: var coefLongArrayComplex = DSPSplitComplex(realp:&coefLongArrayRealp, imagp:&coefLongArrayImagp) // short array: var coefShortArrayComplex = DSPSplitComplex(realp:&coefShortArrayRealp, imagp:&coefShortArrayImagp) // setup output buffers for vDSP_zvmulD var coefConvRealp = [Float](repeating: 0.0, count: convNPowTwo) var coefConvImagp = [Float](repeating: 0.0, count: convNPowTwo) var coefConvComplex = DSPSplitComplex(realp:&coefConvRealp, imagp:&coefConvImagp) // Elementwise Complex Multiplication vDSP_zvmul(&coefLongArrayComplex, 1, &coefShortArrayComplex, 1, &coefConvComplex, 1, vDSP_Length(convNPowTwo), Int32(1)) // ifft var (convResult, _) = ifft(coefConvRealp, imagp:coefConvImagp) // Remove padded zeros convResult = [Float](convResult[0..<convN]) // modify the result according mode before return let finalResult:[Float] switch mode { case "same": let numOfResultToBeRemoved = convN - N let toBeRemovedHalf = numOfResultToBeRemoved / 2 if numOfResultToBeRemoved % 2 == 0 { finalResult = [Float](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf)]) } else { finalResult = [Float](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf-1)]) } case "valid": finalResult = [Float](convResult[(M-1)..<(convN-M+1)]) default: finalResult = convResult } return finalResult }
mit
2359baf72cb0e599cfea216193df6a41
31.146341
121
0.660007
3.652094
false
false
false
false
eTilbudsavis/native-ios-eta-sdk
Sources/CoreAPI/Models/CoreAPI_Dealer.swift
1
3843
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import UIKit extension CoreAPI { public struct Dealer: Decodable, Equatable { public typealias Identifier = GenericIdentifier<Dealer> public var id: Identifier public var name: String public var website: URL? public var description: String? public var descriptionMarkdown: String? public var logoOnWhite: URL public var logoOnBrandColor: URL public var brandColor: UIColor? public var country: Country public var favoriteCount: Int enum CodingKeys: String, CodingKey { case id case name case website case description case descriptionMarkdown = "description_markdown" case logoOnWhite = "logo" case colorStr = "color" case pageFlip = "pageflip" case country case favoriteCount = "favorite_count" enum PageFlipKeys: String, CodingKey { case logo case colorStr = "color" } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.id = try values.decode(Identifier.self, forKey: .id) self.name = try values.decode(String.self, forKey: .name) self.website = try? values.decode(URL.self, forKey: .website) self.description = try? values.decode(String.self, forKey: .description) self.descriptionMarkdown = try? values.decode(String.self, forKey: .descriptionMarkdown) self.logoOnWhite = try values.decode(URL.self, forKey: .logoOnWhite) if let colorStr = try? values.decode(String.self, forKey: .colorStr) { self.brandColor = UIColor(hex: colorStr) } let pageflipValues = try values.nestedContainer(keyedBy: CodingKeys.PageFlipKeys.self, forKey: .pageFlip) self.logoOnBrandColor = try pageflipValues.decode(URL.self, forKey: .logo) self.country = try values.decode(Country.self, forKey: .country) self.favoriteCount = try values.decode(Int.self, forKey: .favoriteCount) } } // MARK: - public struct Country: Decodable, Equatable { public typealias Identifier = GenericIdentifier<Country> public var id: Identifier public init(id: Identifier) { self.id = id } } } //{ // "id": "25f5mL", // "ern": "ern:dealer:25f5mL", // "name": "3", // "website": "http://3.dk", // "description": "3 tilbyder danskerne mobiltelefoni og mobilt bredbånd. Kombinationen af 3’s 3G-netværk og lynhurtige 4G /LTE-netværk, sikrer danskerne adgang til fremtidens netværk - i dag.", // "description_markdown": null, // "logo": "https://d3ikkoqs9ddhdl.cloudfront.net/img/logo/default/25f5mL_2gvnjz51j.png", // "color": "000000", // "pageflip": { // "logo": "https://d3ikkoqs9ddhdl.cloudfront.net/img/logo/pageflip/25f5mL_4ronjz51j.png", // "color": "000000" // }, // "category_ids": [], // "country": { // "id": "DK", // "unsubscribe_print_url": null // }, // "favorite_count": 0, // "facebook_page_id": "168499089859599", // "youtube_user_id": "3Denmark", // "twitter_handle": "3BusinessDK" //}
mit
9d48c00ffef6ef89b754e80c8ce12e21
35.188119
197
0.563064
3.787565
false
false
false
false
MessageKit/MessageKit
Sources/Views/Cells/MediaMessageCell.swift
1
3407
// MIT License // // Copyright (c) 2017-2019 MessageKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit /// A subclass of `MessageContentCell` used to display video and audio messages. open class MediaMessageCell: MessageContentCell { /// The play button view to display on video messages. open lazy var playButtonView: PlayButtonView = { let playButtonView = PlayButtonView() return playButtonView }() /// The image view display the media content. open var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill return imageView }() // MARK: - Methods /// Responsible for setting up the constraints of the cell's subviews. open func setupConstraints() { imageView.fillSuperview() playButtonView.centerInSuperview() playButtonView.constraint(equalTo: CGSize(width: 35, height: 35)) } open override func setupSubviews() { super.setupSubviews() messageContainerView.addSubview(imageView) messageContainerView.addSubview(playButtonView) setupConstraints() } open override func prepareForReuse() { super.prepareForReuse() imageView.image = nil } open override func configure( with message: MessageType, at indexPath: IndexPath, and messagesCollectionView: MessagesCollectionView) { super.configure(with: message, at: indexPath, and: messagesCollectionView) guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else { fatalError(MessageKitError.nilMessagesDisplayDelegate) } switch message.kind { case .photo(let mediaItem): imageView.image = mediaItem.image ?? mediaItem.placeholderImage playButtonView.isHidden = true case .video(let mediaItem): imageView.image = mediaItem.image ?? mediaItem.placeholderImage playButtonView.isHidden = false default: break } displayDelegate.configureMediaMessageImageView(imageView, for: message, at: indexPath, in: messagesCollectionView) } /// Handle tap gesture on contentView and its subviews. open override func handleTapGesture(_ gesture: UIGestureRecognizer) { let touchLocation = gesture.location(in: imageView) guard imageView.frame.contains(touchLocation) else { super.handleTapGesture(gesture) return } delegate?.didTapImage(in: self) } }
mit
0bd5b6064453c49e139d6c306318cc41
34.489583
118
0.742002
4.888092
false
false
false
false
ellited/Lieferando-Services
Lieferando Services/PlaceParseModel.swift
1
710
// // Place.swift // Lieferando Services // // Created by Mikhail Rudenko on 10/06/2017. // Copyright © 2017 App-Smart. All rights reserved. // import Foundation import SQLite struct PlaceParseModel { let id = Expression<Int>("id") let name = Expression<String?>("name") let imageUrl = Expression<String?>("imageUrl") let postalCode = Expression<String?>("postalCode") let city = Expression<String?>("city") let street = Expression<String?>("street") let url = Expression<String?>("url") let rating = Expression<String?>("rating") let person = Expression<String?>("person") let fax = Expression<String?>("fax") let email = Expression<String?>("email") }
apache-2.0
08b0f1c2d55c156c312712cd06646ec7
27.36
54
0.660085
4.074713
false
false
false
false
praca-japao/156
PMC156Inteligente/CategoriesTableViewController.swift
1
3262
// // CategoriesTableViewController.swift // PMC156Inteligente // // Created by Giovanni Pietrangelo on 11/29/15. // Copyright © 2015 Sigma Apps. All rights reserved. // import UIKit class CategoriesTableViewController: UITableViewController { var categorySelected: String! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) categorySelected = cell?.textLabel?.text performSegueWithIdentifier("newRequest", sender: self) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Category", forIndexPath: indexPath) cell.textLabel?.text = "Categoria" return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "newRequest" { // Date Controller let destinationViewController = segue.destinationViewController as! NewRequestViewController destinationViewController.category = categorySelected } } }
gpl-2.0
f1b880e13036f7ddef68c0fd4ae722ae
32.96875
157
0.686599
5.671304
false
false
false
false
LoopKit/LoopKit
LoopKitUI/View Controllers/ChartsManager.swift
1
7243
// // Chart.swift // Naterade // // Created by Nathan Racklyeft on 2/19/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit import LoopKit import SwiftCharts open class ChartsManager { private lazy var timeFormatter: DateFormatter = { let formatter = DateFormatter() let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)! let isAmPmTimeFormat = dateFormat.firstIndex(of: "a") != nil formatter.dateFormat = isAmPmTimeFormat ? "h a" : "H:mm" return formatter }() public init( colors: ChartColorPalette, settings: ChartSettings, axisLabelFont: UIFont = .systemFont(ofSize: 14), // caption1, but hard-coded until axis can scale with type preference charts: [ChartProviding], traitCollection: UITraitCollection ) { self.colors = colors self.chartSettings = settings self.charts = charts self.traitCollection = traitCollection self.chartsCache = Array(repeating: nil, count: charts.count) axisLabelSettings = ChartLabelSettings(font: axisLabelFont, fontColor: colors.axisLabel) guideLinesLayerSettings = ChartGuideLinesLayerSettings(linesColor: colors.grid) } // MARK: - Configuration private let colors: ChartColorPalette private let chartSettings: ChartSettings private let labelsWidthY: CGFloat = 30 public let charts: [ChartProviding] /// The amount of horizontal space reserved for fixed margins public var fixedHorizontalMargin: CGFloat { return chartSettings.leading + chartSettings.trailing + labelsWidthY + chartSettings.labelsToAxisSpacingY } private let axisLabelSettings: ChartLabelSettings private let guideLinesLayerSettings: ChartGuideLinesLayerSettings public var gestureRecognizer: UIGestureRecognizer? // MARK: - UITraitEnvironment public var traitCollection: UITraitCollection public func didReceiveMemoryWarning() { for chart in charts { chart.didReceiveMemoryWarning() } xAxisValues = nil } // MARK: - Data /// The earliest date on the X-axis public var startDate = Date() { didSet { if startDate != oldValue { xAxisValues = nil // Set a new minimum end date endDate = startDate.addingTimeInterval(.hours(3)) } } } /// The latest date on the X-axis private var endDate = Date() { didSet { if endDate != oldValue { xAxisValues = nil } } } /// The latest allowed date on the X-axis public var maxEndDate = Date.distantFuture { didSet { endDate = min(endDate, maxEndDate) } } /// Updates the endDate using a new candidate date /// /// Dates are rounded up to the next hour. /// /// - Parameter date: The new candidate date public func updateEndDate(_ date: Date) { if date > endDate { let components = DateComponents(minute: 0) endDate = min( maxEndDate, Calendar.current.nextDate( after: date, matching: components, matchingPolicy: .strict, direction: .forward ) ?? date ) } } // MARK: - State private var xAxisValues: [ChartAxisValue]? { didSet { if let xAxisValues = xAxisValues, xAxisValues.count > 1 { xAxisModel = ChartAxisModel(axisValues: xAxisValues, lineColor: colors.axisLine, labelSpaceReservationMode: .fixed(20)) } else { xAxisModel = nil } chartsCache.replaceAllElements(with: nil) } } private var xAxisModel: ChartAxisModel? private var chartsCache: [Chart?] // MARK: - Generators public func chart(atIndex index: Int, frame: CGRect) -> Chart? { if let chart = chartsCache[index], chart.frame != frame { chartsCache[index] = nil } if chartsCache[index] == nil, let xAxisModel = xAxisModel, let xAxisValues = xAxisValues { chartsCache[index] = charts[index].generate(withFrame: frame, xAxisModel: xAxisModel, xAxisValues: xAxisValues, axisLabelSettings: axisLabelSettings, guideLinesLayerSettings: guideLinesLayerSettings, colors: colors, chartSettings: chartSettings, labelsWidthY: labelsWidthY, gestureRecognizer: gestureRecognizer, traitCollection: traitCollection) } return chartsCache[index] } public func invalidateChart(atIndex index: Int) { chartsCache[index] = nil } // MARK: - Shared Axis private func generateXAxisValues() { if let endDate = charts.compactMap({ $0.endDate }).max() { updateEndDate(endDate) } let points = [ ChartPoint( x: ChartAxisValueDate(date: startDate, formatter: timeFormatter), y: ChartAxisValue(scalar: 0) ), ChartPoint( x: ChartAxisValueDate(date: endDate, formatter: timeFormatter), y: ChartAxisValue(scalar: 0) ) ] let segments = ceil(endDate.timeIntervalSince(startDate).hours) let xAxisValues = ChartAxisValuesStaticGenerator.generateXAxisValuesWithChartPoints(points, minSegmentCount: segments - 1, maxSegmentCount: segments + 1, multiple: TimeInterval(hours: 1), axisValueGenerator: { ChartAxisValueDate( date: ChartAxisValueDate.dateFromScalar($0), formatter: timeFormatter, labelSettings: self.axisLabelSettings ) }, addPaddingSegmentIfEdge: false ) xAxisValues.first?.hidden = true xAxisValues.last?.hidden = true self.xAxisValues = xAxisValues } /// Runs any necessary steps before rendering charts public func prerender() { if xAxisValues == nil { generateXAxisValues() } } } fileprivate extension Array { mutating func replaceAllElements(with element: Element) { self = Array(repeating: element, count: count) } } public protocol ChartProviding { /// Instructs the chart to clear its non-critical resources like caches func didReceiveMemoryWarning() /// The last date represented in the chart data var endDate: Date? { get } /// Creates a chart from the current data /// /// - Returns: A new chart object func generate(withFrame frame: CGRect, xAxisModel: ChartAxisModel, xAxisValues: [ChartAxisValue], axisLabelSettings: ChartLabelSettings, guideLinesLayerSettings: ChartGuideLinesLayerSettings, colors: ChartColorPalette, chartSettings: ChartSettings, labelsWidthY: CGFloat, gestureRecognizer: UIGestureRecognizer?, traitCollection: UITraitCollection ) -> Chart }
mit
2787c9722bc5c05e98d807bb703f9b3d
29.301255
357
0.619442
5.263081
false
false
false
false
asm-products/voicesrepo
Voices/Voices/RootViewController.swift
1
2519
// // ViewController.swift // Voices // // Created by Mazyad Alabduljaleel on 11/1/14. // Copyright (c) 2014 Assembly. All rights reserved. // import UIKit /** The root view controller contains the whole app, and manages the * content scroll view which contains the content view controllers */ class RootViewController: UIViewController { private let contentViewControllers: [UIViewController] @IBOutlet var contentScrollView: UIScrollView? required init(coder aDecoder: NSCoder) { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) contentViewControllers = [ "ContactsViewController", "RecordViewController", "InboxViewController" ].map { mainStoryboard.instantiateViewControllerWithIdentifier($0) as UIViewController } super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Keep calm, and assert all your assumptions assert(contentScrollView != nil, "Content scroll view must be connected in IB") let scrollView = contentScrollView! scrollView.contentSize.width = CGFloat(contentViewControllers.count) * self.view.bounds.width scrollView.contentOffset.x = self.view.bounds.width var xOffset = CGFloat(0) for viewController in contentViewControllers { viewController.view.frame.origin.x = xOffset viewController.view.frame.size = scrollView.bounds.size scrollView.addSubview(viewController.view) xOffset += self.view.bounds.width } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } } /** Subclass the Root view to draw the background gradient */ class RootView: UIView { override class func layerClass() -> AnyClass { return CAGradientLayer.self } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let gradientLayer = layer as CAGradientLayer gradientLayer.colors = [ UIColor.orangeColor().CGColor, UIColor.redColor().CGColor ] gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 1) contentMode = .Redraw } }
agpl-3.0
2e83a1f0957f3fabc8b1af72a9e9c001
27.303371
101
0.632791
5.348195
false
false
false
false
Jamol/Nutil
Xcode/NutilSampleOSX/main.swift
1
2812
// // main.swift // NutilSampleOSX // // Created by Jamol Bao on 11/3/16. // // import Foundation import Nutil #if false var tcp = TcpSocket() tcp.onConnect { print("Tcp.onConnect, err=\($0)\n") } //let ret = tcp.connect("127.0.0.1", 52328) let ret = tcp.connect("www.google.com", 80) #endif #if false var a = Acceptor() a.onAccept { (fd, ip, port) in print("onAccept, fd=\(fd), ip=\(ip), port=\(port)") } _ = a.listen("127.0.0.1", 52328) #endif #if false var udp = UdpSocket() udp.onRead { var d = [UInt8](repeating: 0, count: 4096) let len = d.count let ret = d.withUnsafeMutableBufferPointer() { return udp.read($0.baseAddress!, len) } print("Udp.onRead, ret=\(ret)") } _ = udp.bind("127.0.0.1", 52328) #endif #if false var ssl = SslSocket() ssl.onConnect { print("Ssl.onConnect, err=\($0)\n") } let ret = ssl.connect("www.google.com", 443) #endif #if false let req = NutilFactory.createRequest(version: "HTTP/1.1")! req .onData { (data: UnsafeMutableRawPointer, len: Int) in print("data received, len=\(len)") } .onHeaderComplete { print("header completed") } .onRequestComplete { print("request completed") } .onError { err in print("request error, err=\(err)") } _ = req.sendRequest("GET", "https://www.google.com") #endif #if false let server = HttpServer() _ = server.start(addr: "0.0.0.0", port: 8443) #endif #if false let ws = NutilFactory.createWebSocket() ws.onData { (data, len, isText, fin) in print("WebSocket.onData, len=\(len), fin=\(fin)") ws.close() } .onError { err in print("WebSocket.onError, err=\(err)") } let ret = ws.connect("wss://127.0.0.1:8443") { err in print("WebSocket.onConnect, err=\(err)") let buf = Array<UInt8>(repeating: 64, count: 16*1024) let ret = ws.sendData(buf, buf.count, false, true) } #endif #if true var totalBytesReceived = 0 let req = NutilFactory.createRequest(version: "HTTP/2.0")! req .onData { (data: UnsafeMutableRawPointer, len: Int) in totalBytesReceived += len print("data received, len=\(len), total=\(totalBytesReceived)") } .onHeaderComplete { print("header completed") } .onRequestComplete { print("request completed") } .onError { err in print("request error, err=\(err)") } req.addHeader("user-agent", "kuma 1.0") //_ = req.sendRequest("GET", "https://127.0.0.1:8443/testdata") //_ = req.sendRequest("GET", "https://www.google.com") _ = req.sendRequest("GET", "https://http2.golang.org/reqinfo") //_ = req.sendRequest("GET", "https://www.cloudflare.com") #endif RunLoop.main.run()
mit
1ed76cf9eaa1adc8a1a1c2270a328a31
23.452174
71
0.588193
3.235903
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/Extensions/String+Additions.swift
1
2577
import Foundation extension String { static let NON_BREAKING_LINE_SPACE = "\u{00a0}" static let SPACE = " " static func isNullOrEmpty(_ value: String?) -> Bool { return value == nil || value!.isEmpty } func existsLocalized() -> Bool { let localizedString = self.localized return localizedString != self } static func isDigitsOnly(_ number: String) -> Bool { if Regex("^[0-9]*$").test(number) { return true } else { return false } } func startsWith(_ prefix: String) -> Bool { if prefix == self { return true } let startIndex = self.range(of: prefix) if startIndex == nil || self.startIndex != startIndex?.lowerBound { return false } return true } func lastCharacters(number: Int) -> String { let trimmedString: String = (self as NSString).substring(from: max(self.count - number, 0)) return trimmedString } func indexAt(_ theInt: Int) ->String.Index { return self.index(self.startIndex, offsetBy: theInt) } func trimSpaces() -> String { var stringTrimmed = self.replacingOccurrences(of: " ", with: "") stringTrimmed = stringTrimmed.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return stringTrimmed } mutating func paramsAppend(key: String, value: String?) { if !key.isEmpty && !String.isNullOrEmpty(value) { if self.isEmpty { self = key + "=" + value! } else { self += "&" + key + "=" + value! } } } func toAttributedString(attributes: [NSAttributedString.Key: Any]? = nil) -> NSMutableAttributedString { return NSMutableAttributedString(string: self, attributes: attributes) } func getAttributedStringNewLine() -> NSMutableAttributedString { return "\n".toAttributedString() } static func getDate(_ string: String?) -> Date? { guard let dateString = string else { return nil } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" return dateFormatter.date(from: dateString) } var isNumber: Bool { return rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil } func insert(_ string: String, ind: Int) -> String { return String(self.prefix(ind)) + string + String(self.suffix(self.count - ind)) } var isNotEmpty: Bool { return !isEmpty } }
mit
cfc7fd4d9745b8e5149de0d014d7e80c
28.62069
108
0.598758
4.505245
false
false
false
false
Zerounodue/splinxsChat
splinxsChat/startViewController.swift
1
4566
// // startViewController.swift // splinxsChat // // Created by Elia Kocher on 17.05.16. // Copyright © 2016 BFH. All rights reserved. // import UIKit class startViewController: UIViewController { var isConnected = false let localIP = "http://192.168.178.36:3000" let splinxsIP = "http://147.87.116.139:3000" @IBOutlet weak var nicknameTextFiel: UITextField! @IBOutlet weak var ipSegmentedControl: UISegmentedControl! @IBOutlet weak var statusLable: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { self.statusLable.text = "Offline" socketIOcontroller.sharedInstance.isConnectionEstablished{ (isConnected) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.isConnected = isConnected self.statusLable.text = isConnected ? "Online" : "Offline" }) } } @IBAction func infoAction(sender: AnyObject) { let alertController = UIAlertController(title: "Info", message: "The local IP is: " + localIP + " consider to chang it in order to mach your PC's IP \n the Splinxs server is avaliable only if you are connected to the BFH network", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func connectAction(sender: AnyObject) { //check if it's connected to socket.io if !isConnected { let alertController = UIAlertController(title: "Attention", message: "You are not connected, maybe the server is down. \n I try to reconnect now.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } //check if the text is not empty else if nicknameTextFiel.text?.characters.count == 0 { let alertController = UIAlertController(title: "Attention", message: "You must enter a nickname", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } else { //self.nickname = nicknameTextFiel.text self.performSegueWithIdentifier("goToUsers", sender: nicknameTextFiel.text) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "goToUsers" { let usersTableVC = segue.destinationViewController as! usersTableViewController usersTableVC.nickname = nicknameTextFiel.text } } } @IBAction func ipChanged(sender: AnyObject) { isConnected = false self.statusLable.text = "Offline" let socketIP = (ipSegmentedControl.selectedSegmentIndex != 0) ? splinxsIP : localIP socketIOcontroller.sharedInstance.closeConnection() socketIOcontroller.sharedInstance.setSocketIP(socketIP) socketIOcontroller.sharedInstance.isConnectionEstablished{ (isConnected) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.isConnected = isConnected self.statusLable.text = isConnected ? "Online" : "Offline" }) } socketIOcontroller.sharedInstance.establishConnection() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
bff05a2593ab0bdcced69a27c13cc5de
39.758929
224
0.649726
5.060976
false
false
false
false
Fenrikur/ef-app_ios
Eurofurence/Modules/Map Detail/Interactor/DefaultMapDetailInteractor.swift
1
3391
import EurofurenceModel import Foundation class DefaultMapDetailInteractor: MapDetailInteractor, MapsObserver { private struct ViewModel: MapDetailViewModel { let map: Map var mapImagePNGData: Data var mapName: String { return map.location } func showContentsAtPosition(x: Float, y: Float, describingTo visitor: MapContentVisitor) { let contentHandler = ContentHandler(x: x, y: y, visitor: visitor) map.fetchContentAt(x: Int(x), y: Int(y), completionHandler: contentHandler.handle) } } private struct ContentHandler { var x: Float var y: Float var visitor: MapContentVisitor func handle(_ content: MapContent) { switch content { case .location(let altX, let altY, let name): let coordinate = MapCoordinate(x: altX, y: altY) if let name = name { let contextualInfo = MapInformationContextualContent(coordinate: coordinate, content: name) visitor.visit(contextualInfo) } visitor.visit(coordinate) case .room(let room): let coordinate = MapCoordinate(x: x, y: y) let contextualInfo = MapInformationContextualContent(coordinate: coordinate, content: room.name) visitor.visit(contextualInfo) case .dealer(let dealer): visitor.visit(dealer.identifier) case .multiple(let contents): visitor.visit(OptionsViewModel(contents: contents, handler: self)) case .none: break } } } private struct OptionsViewModel: MapContentOptionsViewModel { private let contents: [MapContent] private let handler: ContentHandler init(contents: [MapContent], handler: ContentHandler) { self.contents = contents self.handler = handler optionsHeading = .selectAnOption options = contents.compactMap { (content) -> String? in switch content { case .room(let room): return room.name case .dealer(let dealer): return dealer.preferredName case .location(_, _, let name): return name default: return nil } } } var optionsHeading: String var options: [String] func selectOption(at index: Int) { let content = contents[index] handler.handle(content) } } private let mapsService: MapsService private var maps = [Map]() init(mapsService: MapsService) { self.mapsService = mapsService mapsService.add(self) } func makeViewModelForMap(identifier: MapIdentifier, completionHandler: @escaping (MapDetailViewModel) -> Void) { guard let map = maps.first(where: { $0.identifier == identifier }) else { return } map.fetchImagePNGData { (mapGraphicData) in let viewModel = ViewModel(map: map, mapImagePNGData: mapGraphicData) completionHandler(viewModel) } } func mapsServiceDidChangeMaps(_ maps: [Map]) { self.maps = maps } }
mit
eab5b6dbea008038548f6acae1951c20
28.745614
116
0.571808
5.106928
false
false
false
false
mohssenfathi/MTLImage
Example-iOS/Example-iOS/ViewControllers/Info/InfoViewController.swift
1
1839
// // InfoViewController.swift // MTLImage // // Created by Mohssen Fathi on 4/3/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit class InfoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var metadata: [[String:Any]]! override func viewDidLoad() { super.viewDidLoad() } @IBAction func closeButtonPressed(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } // MARK: - UITableView // MARK: DataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return metadata.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let titleLabel = cell.viewWithTag(101) as! UILabel let valueLabel = cell.viewWithTag(102) as! UILabel let dict = metadata[(indexPath as NSIndexPath).row] as! [String : String] titleLabel.text = dict["title"]?.capitalized valueLabel.text = dict["value"] return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
460f3c1d037e6ab445b3237a97321d77
27.276923
106
0.649619
5.162921
false
false
false
false
SwiftOnEdge/Edge
Sources/POSIX/Socket.swift
1
1414
#if os(Linux) import Glibc let sockStream = Int32(SOCK_STREAM.rawValue) let sockDgram = Int32(SOCK_DGRAM.rawValue) let sockSeqPacket = Int32(SOCK_SEQPACKET.rawValue) let sockRaw = Int32(SOCK_RAW.rawValue) let sockRDM = Int32(SOCK_RDM.rawValue) #else import Darwin.C let sockStream = SOCK_STREAM let sockDgram = SOCK_DGRAM let sockSeqPacket = SOCK_SEQPACKET let sockRaw = SOCK_RAW let sockRDM = SOCK_RDM #endif public typealias Port = UInt16 public struct SocketType { public static let stream = SocketType(rawValue: sockStream) public static let datagram = SocketType(rawValue: sockDgram) public static let seqPacket = SocketType(rawValue: sockSeqPacket) public static let raw = SocketType(rawValue: sockRaw) public static let reliableDatagram = SocketType(rawValue: sockRDM) public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } } public struct AddressFamily { public static let unix = AddressFamily(rawValue: AF_UNIX) public static let inet = AddressFamily(rawValue: AF_INET) public static let inet6 = AddressFamily(rawValue: AF_INET6) public static let ipx = AddressFamily(rawValue: AF_IPX) public static let netlink = AddressFamily(rawValue: AF_APPLETALK) public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } }
mit
4dc89af1037df2d3c289bc6d2b71b0d2
29.73913
70
0.717115
3.750663
false
false
false
false
juheon0615/GhostHandongSwift
HandongAppSwift/MenuModel.swift
3
506
// // MenuModel.swift // HandongAppSwift // // Created by csee on 2015. 2. 5.. // Copyright (c) 2015년 GHOST. All rights reserved. // import Foundation class MenuModel { var menu: String var price: String init(menu: String?, price: String?) { if menu != nil { self.menu = menu! } else { self.menu = " " } if price != nil { self.price = price! } else { self.price = "" } } }
mit
36eb1dbe83c12043b1be93e7e6ac08c7
17.035714
51
0.474206
3.789474
false
false
false
false
nerdishbynature/OysterKit
OysterKit/OysterKitTests/stateTestBranch.swift
1
2687
// // stateTestBranch.swift // OysterKit Mac // // Created by Nigel Hughes on 03/07/2014. // Copyright (c) 2014 RED When Excited Limited. All rights reserved. // import XCTest import OysterKit class stateTestBranch: XCTestCase { let tokenizer = Tokenizer() func testBranch(){ let branch = char("x").branch(char("y").token("xy"), char("z").token("xz")) tokenizer.branch(branch, OKStandard.eot) XCTAssert(tokenizer.tokenize("xyxz") == [token("xy"),token("xz")]) } func testRepeatLoopEquivalence(){ let seperator = Characters(from: ",").token("sep") let lettersWithLoop = LoopingCharacters(from:"abcdef").token("easy") let state = Characters(from:"abcdef").token("ignore") let lettersWithRepeat = Repeat(state: state).token("easy") let space = Characters(from: " ") let bracketedWithRepeat = Delimited(open: "(", close: ")", states: lettersWithRepeat).token("bracket") let bracketedWithLoop = Delimited(open: "(", close: ")", states: lettersWithLoop).token("bracket") tokenizer.branch([ bracketedWithLoop, seperator, space ]) let underTest = Tokenizer() underTest.branch([ bracketedWithRepeat, seperator, space]) let testString = "(a),(b) (c)(e),(abc),(def) (fed)(aef)" let testTokens = underTest.tokenize(testString) let referenceTokens = tokenizer.tokenize(testString) assertTokenListsEqual(testTokens, reference: referenceTokens) } func testNestedBranch(){ let branch = Branch(states: [char("x").branch(char("y").token("xy"), char("z").token("xz"))]) tokenizer.branch(branch) XCTAssert(tokenizer.tokenize("xyxz") == [token("xy"),token("xz")]) } func testXY(){ tokenizer.sequence(char("x"),char("y").token("xy")) tokenizer.branch(OKStandard.eot) XCTAssert(tokenizer.tokenize("xy") == [token("xy")], "Chained results do not match") } func testSequence1(){ let expectedResults = [token("done",chars:"xyz")] tokenizer.branch( sequence(char("x"),char("y"),char("z").token("done")), OKStandard.eot ) XCTAssert(tokenizer.tokenize("xyz") == expectedResults) } func testSequence2(){ let expectedResults = [token("done",chars:"xyz")] tokenizer.branch( char("x").sequence(char("y"),char("z").token("done")), OKStandard.eot ) XCTAssert(tokenizer.tokenize("xyz") == expectedResults) } }
bsd-2-clause
5bafcfc922d53164e437f169832c3e68
29.885057
110
0.582434
4.27186
false
true
false
false
katzbenj/MeBoard
Keyboard/ExNumKeyboard.swift
2
6696
// // ExNumKeyboard.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/10/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // func exNumKeyboard() -> Keyboard { let exNumKeyboard = Keyboard() let shift = Key(.shift) let backspace = Key(.backspace) let offset = 0 for key in [":~", "Q1", "W2", "E3", "R4", "T5", "Y6", "U7", "I8", "O9", "P0", "({", ")}", "/\\"] { let keyModel = Key(.character) if key.characters.count == 1 { keyModel.setLetter(key) } else { let secondLetterIndex = key.index(key.startIndex, offsetBy: 1) keyModel.setLetter(String(key[key.startIndex]), secondaryLetter: String(key[secondLetterIndex])) } exNumKeyboard.addKey(keyModel, row: 0 + offset, page: 0) } let tabKey = Key(.tab) tabKey.uppercaseKeyCap = "tab" tabKey.uppercaseOutput = "\t" tabKey.lowercaseOutput = "\t" tabKey.size = 1 exNumKeyboard.addKey(tabKey, row: 1 + offset, page: 0) for key in ["A#", "S$", "D%", "F+", "G-", "H=", "J*", "K^", "L&", "!¡", "\"<", "'>"] { let keyModel = Key(.character) if key.characters.count == 1 { keyModel.setLetter(key) } else { let secondLetterIndex = key.index(key.startIndex, offsetBy: 1) keyModel.setLetter(String(key[key.startIndex]), secondaryLetter: String(key[secondLetterIndex])) } exNumKeyboard.addKey(keyModel, row: 1 + offset, page: 0) } let tab2 = Key(.tab) tab2.uppercaseKeyCap = "tab" tab2.uppercaseOutput = "\t" tab2.lowercaseOutput = "\t" //exNumKeyboard.addKey(tab2, row: 1 + offset, page: 0) exNumKeyboard.addKey(shift, row: 2 + offset, page: 0) for key in ["Z`", "X_", "C✓", "V°", "B×", "N≈", "M÷", ",;", ".•", "?¿"] { let keyModel = Key(.character) if key.characters.count == 1 { keyModel.setLetter(key) } else { let secondLetterIndex = key.index(key.startIndex, offsetBy: 1) keyModel.setLetter(String(key[key.startIndex]), secondaryLetter: String(key[secondLetterIndex])) } exNumKeyboard.addKey(keyModel, row: 2 + offset, page: 0) } //let backspace = Key(.backspace) exNumKeyboard.addKey(backspace, row: 2 + offset, page: 0) let keyModeChangeNumbers = Key(.modeChange) keyModeChangeNumbers.uppercaseKeyCap = "123" keyModeChangeNumbers.toMode = 1 exNumKeyboard.addKey(keyModeChangeNumbers, row: 3 + offset, page: 0) let keyboardChange = Key(.keyboardChange) exNumKeyboard.addKey(keyboardChange, row: 3 + offset, page: 0) //let settings = Key(.settings) //exNumKeyboard.addKey(settings, row: 3 + offset, page: 0) let space = Key(.space) space.uppercaseKeyCap = "space" space.uppercaseOutput = " " space.lowercaseOutput = " " exNumKeyboard.addKey(space, row: 3 + offset, page: 0) let keyModel = Key(.specialCharacter) keyModel.setLetter("@") exNumKeyboard.addKey(keyModel, row: 3 + offset, page: 0) let returnKey = Key(.return) returnKey.uppercaseKeyCap = "return" returnKey.uppercaseOutput = "\n" returnKey.lowercaseOutput = "\n" exNumKeyboard.addKey(returnKey, row: 3 + offset, page: 0) let atSize = 1 / exNumKeyboard.pages[0].maxRowSize() let spaceBarSize = 0.6 - atSize exNumKeyboard.pages[0].setRelativeSizes(percentArray: [0.1, 0.1, spaceBarSize, atSize, 0.2], rowNum: 3 + offset) for key in ["#", "$", "&", ":", "-", "7", "8", "9", "/", "°"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 0, page: 1) } for key in ["@", "(", ")", "=", "+", "4", "5", "6", "*", "_"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 1, page: 1) } let keyModeChangeSpecialCharacters = Key(.modeChange) keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+=" keyModeChangeSpecialCharacters.toMode = 2 exNumKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1) for key in ["'", "\"", "%", "1", "2", "3"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 2, page: 1) } exNumKeyboard.addKey(Key(backspace), row: 2, page: 1) let keyModeChangeLetters = Key(.modeChange) keyModeChangeLetters.uppercaseKeyCap = "ABC" keyModeChangeLetters.toMode = 0 exNumKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1) exNumKeyboard.addKey(Key(keyboardChange), row: 3, page: 1) //exNumKeyboard.addKey(Key(settings), row: 3, page: 1) exNumKeyboard.addKey(Key(space), row: 3, page: 1) for key in [",", "0", "."] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 3, page: 1) } exNumKeyboard.addKey(Key(returnKey), row: 3, page: 1) exNumKeyboard.pages[1].setRelativeSizes(percentArray: [0.1, 0.1, 0.3, 0.1, 0.1, 0.1, 0.2], rowNum: 3 + offset) for key in ["£", "€", "¥", "₵", "©", "®", "™", "~", "¿", "≈"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 0, page: 2) } for key in ["[", "]", "{", "}", "<", ">", "^", "¡", "×", "•"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 1, page: 2) } exNumKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2) for key in ["`", ";", "÷", "\\", "|", "✓"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 2, page: 2) } exNumKeyboard.addKey(Key(backspace), row: 2, page: 2) exNumKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2) exNumKeyboard.addKey(Key(keyboardChange), row: 3, page: 2) //exNumKeyboard.addKey(Key(settings), row: 3, page: 2) exNumKeyboard.addKey(Key(space), row: 3, page: 2) exNumKeyboard.addKey(Key(returnKey), row: 3, page: 2) exNumKeyboard.pages[2].setRelativeSizes(percentArray: [0.1, 0.1, 0.6, 0.2], rowNum: 3 + offset) return exNumKeyboard } func proportionalButtonSize(page: Page, percentage: Double)->Double { assert(percentage < 1) let maxRowSize = page.maxRowSize() return maxRowSize * percentage }
bsd-3-clause
fb6dc0cd2c16c0c262d07c6b06da8cdc
34.636364
116
0.593637
3.426221
false
false
false
false
xcs-go/swift-Learning
Control Flow.playground/Contents.swift
1
19169
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // For 循环 // swift提供了两种for循环:for--in / for //for in 循环对一个集合里面的每个元素执行一系列语句 //for 循环,用来重复执行一系列语句直到达成特定条件,一般通过在每次循环完成后增加计数器的值来实现 //for in:可以使用for-in循环来遍历一个集合里面的所有元素,例如由数字表示的区间、数组中的元素、字符串中的字符 for index in 1...5{ print("\(index) time 5 is \(index * 5)") } // 如果你不需要知道区间序列内每一项的值,你可以使用下划线“_”替代变量名来忽略对值的访问 let base = 3 let power = 10 var answer = 1 for _ in 1...power { answer *= base } print("\(base) to the power of \(power) is \(answer)") // 使用for-in 遍历一个数组所有元素 let names = ["Anna","Alex","Brian","Jack"] for name in names{ print("Hello,\(name)!") } // 可以遍历一个字典来访问它的健值对。遍历字典时,字典的每项元素会以(key,value)元组的形式返回,可以在for in循环中使用显式的常量名称来解读(key,value)元组。 let numberOfLegs = ["spider":"8","ant":"6","cat":"4"] for(animalNam,legCount) in numberOfLegs{ print("\(animalNam)s have \(legCount) legs") } // 注意:字典元素的遍历顺序和插入顺序可能不同,字典的内容在内部是无序的,所以遍历元素是不能保证顺序。 //For 循环 swift提供使用条件判断和递增方法的标准C样式for循环 for var index = 0;index<3; ++index{ print("index is \(index)") } // while循环 //while循环运行一系列语句直到条件变成false。这类循环适合使用在第一次迭代次数未知的情况下。 // while循环,每次在循环开始时计算条件是否符合,如果不符合,则跳过循环,符合条件才会执行循环里面的代码 // repeat-while循环,每次在循环结束时计算条件是否符合 // 条件语句 //if和switch;if语句he其它语言的if语句一样,只是没有了() //switch 区间匹配 case分支的模式也可以是一个值的区间。 let approximateCount = 62 let countedThings = "moons orbiting Saturn" var naturalCount:String switch approximateCount{ case 0: naturalCount = "no" case 1..<5: naturalCount = "a few" case 5..<12: naturalCount = "serveral" case 12..<100: naturalCount = "dozens of" case 100..<1000: naturalCount = "hundreds of" default: naturalCount = "many" } print("There are \(naturalCount) \(countedThings).") // 元组 ,我们可以使用元组在同一个switch语句中测试多个值,元组中的元素可以是值,也可以是区间,另外,使用下划线(_)来匹配所有可能的值 let somePoint = (1,1) print("\(somePoint.1)") // 可以利用点语法从元组中取出某个值 switch somePoint{ case(0,0): print("(0,0) is at the origin") case(_,0): print("(\(somePoint.0),0) is on the x-axis") case(0,_): print("(0,\(somePoint.1)) is on the y-axis") case(-2...2,-2...2): print("(\(somePoint.0), \(somePoint.1)) is inside the box") default: print("(\(somePoint.0), \(somePoint.1)) is outside of the box") } // 带标签的语句 // 使用标签来标记一个循环体或者switch代码块,当使用break或者continue时,带上这个标签,可以控制标签代表对象的中断或者执行 // 产生一个带标签的语句是通过在该语句的关键词的同一行前面放置一个标签,并且该标签后面还需要带着一个冒号。 //label name:while condition{ //} // 提前退出 // 像if语句一样,guard的执行取决于一个表达式的布尔值。可以使用guard语句来要求条件必须为真时,以执行guard语句后的代码。不同于if语句,一个guard语句总是有一个else分句,如果条件不为真则执行else分句中的代码 //func greet(person:[String:String]){ // guard let name = person["name"] else{ // return // } // print("hello \(name)") // // guard let location = person["location"] else { // print("I hope the weather is nice near you.") // return // } // print("I hope the weather is nice in \(location)") //} // 函数 // 1:函数的定义与调用 // 定义函数时,可以定义函数的参数和参数的类型,也可以定义函数的返回值 // 每个函数有个函数名。用来描述函数执行的任务,使用函数时,使用函数名调用函数吗并且给该函数传递相关的参数 func sayHello(person:String) -> String { let greeting = "hello, " + person + "!" return greeting } print(sayHello("lmg")) // 函数参数与返回值 //1:无参函数 func sayHelloWorld() -> String{ return"hello world" } print(sayHelloWorld()) // 2:多参数函数 // 函数可以带有多种参数,参数类型也可以不相同,这些参数被包含在函数的括号中,相互之间用逗号分隔 func sayHi(personName:String, alreadyGreeted:Bool) -> String { if alreadyGreeted { return sayHello(personName) } else { return sayHelloWorld() } } print(sayHi("Tim", true)) //3:无返回值函数 func sayGoodbye(personName: String) { print("Goodbye, \(personName)!") } sayGoodbye("Dave") // 被调用时,一个函数的返回值可以被忽略 //func printAndCount(StringToPrint:String) -> Int { // print(StringToPrint) // return StringToPrint.characters.count //} //func printWithoutCounting(stringToPrint:String) { // printAndCount(stringToPrint) // 被调用,函数的返回值被忽略 //} // //printAndCount("hello world") // 多重返回值函数 // 使用元组类型让多个值作为一个复合值从函数中返回 //func minMax(array:[Int]) -> (min:Int,max:Int) { // var currentMin = array[0] // var currentMax = array[0] // for value in array[1..<array.count]{ // if value < currentMin { // currentMin = value // }else if value > currentMax { // currentMax = value // } // } // return(currentMin,currentMax) //} //print(minMax([2,5,6,8,0,74,85])) // 可选元组返回类型 // 如果函数返回的元组类型有可能整个元组都没有值,则可以在元组的返回值的右括号中添加一个❓来表示该元组是一个可选的。 func minMax(array:[Int]) -> (min:Int,max:Int)? { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count]{ if value < currentMin { currentMin = value }else if value > currentMax { currentMax = value } } return(currentMin,currentMax) } print(minMax([2,5,6,8,0,74,85])) // 可以使用可选绑定来检查minMax:函数返回的是一个实际的元组值还是nil // 函数参数名称 // 函数参数都有有一个外部参数名和一个局部参数名,外部参数名用于在函数调用时标注传递给函数的参数,局部参数名在函数的实现内部使用 //func someFunction(firstParameterName:Int,secondParameterName:Int) { // //} // //someFunction(1, 2) // 指定外部参数名:在局部参数名前指定外部参数名,中间以空格分隔 func say(to person:String,and anotherPerson:String) -> String { return "hello \(person) and \(anotherPerson)" } print(say(to: "Bill", and: "Ted")) // 可变参数:一个可变参数可以接受零个或多个值。函数调用时, 你可以用可变参数来指定函数参数可以被传入不确定数量的输入值通过在变量名后面加入(...)的方式来定义可变参数。 // 可变参数的传入值在函数体中变为此类型的一个数组。一个函数最多只有一个可变参数 func arithmeticMean(numbers:Double...) -> Double { var total:Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } arithmeticMean(1,2,3,4,5) // 常量参数和变量参数 //func alignRight(var String:String,totalLength:Int,pad:Character) -> String { // let amountToPad = totalLength - String.characters.count // if amountToPad<1{ // return String // } // let padstring = String(pad) // for _ in 1...amoutToPad { // String = padstring + String // } // return String //} // //let originalString = "hello" //let paddedString = alignRight(originalString, 10, "-") // 输入输出参数 // 如果你想要一个函数可以修改参数的值,并且想要在这些修改在函数调用结束后仍然存在,那么就应该把这个参数定义为输入输出参数.在参数定义前加input关键字,传入参数时,需要在参数名前加&符,表示这个值可以被修改 func swapTwoInts(inout a:Int,inout b:Int){ let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt) // 函数类型 func addTwoInts(a:Int,b:Int) -> Int { return a + b } func mulitiplyTwoInts(a:Int,b:Int) -> Int { return a * b } // 使用函数类型 // 在swift中,使用函数类型就想使用其他类型一样。可以定义一个类型为函数的常量或变量,并将适当的函数赋值给它 var mathFunction:(Int,Int) -> Int = addTwoInts // 通过使用mathFunction来调用被赋值的函数 print("\(mathFunction(2,3))") // 有相同匹配类型的不同函数可以被赋值给同一个变量 mathFunction = mulitiplyTwoInts print("\(mathFunction(2,3))") // 函数类型作为参数类型 func printMathResult(mathFunction:(Int,Int) -> Int,a :Int,b:Int) -> Int { // print("\(mathFunction(a,b))") return mathFunction(a,b) } printMathResult(addTwoInts, 3, 4) // 函数类型作为返回类型 // 在返回箭头后写一个完整的函数类型 func stepForward(input:Int) -> Int { return input + 1 } func stepBackward(input:Int) -> Int { return input - 1 } func chooseStepFunction(backwards:Bool) -> (Int) ->Int { return backwards ? stepBackward : stepForward } var currentValue = 3 let moveNearerToZero = chooseStepFunction(currentValue > 0) // 嵌套函数 : 在一个函数体中定义另一个函数,叫做嵌套函数 // 默认情况下,嵌套函数是对外界不可见的,但是可以被它们的外围函数调用,一个外围函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他领域中被调用 // 闭包 // 闭包是自包含的函数代码块,可以在代码中被传递和使用。闭包可以捕获和存储其所在上下文中任意常量和变量的应用。这就是所谓的闭合并包裹着这些常量和变量,俗称闭包 // 闭包的三种形式 //1:全局函数是一个有名字但不会捕获任何值的闭包 //2:嵌套函数是一个有名字并可以捕获其封闭函数内值的闭包 //3:闭包表达式是一个利用轻量级语法所写的可以捕获其上下文中变量或常量的值的匿名闭包 //swift 的闭包表达式拥有简洁的风格,并鼓励在常见场景中进行语法优化 //1:利用上下文推断参数和返回值类型 //2:隐士返回单表达式闭包,即单表达式闭包可以省略return关键字 //3:参数名称缩写 //4:尾随闭包语法 // 闭包表达式 // sort方法:会根据提供的用于排序的闭包函数将已知类型数组中的值进行排序,排序完成后,sort方法会返回一个与原数组大小相同,包含同类型元素且元素已正确排序的新数组。 let stringNames = ["Chris","Alex","Ewa","Barry","Daniella"] //func backWards(s1:String,s2:String) -> Bool{ // return s1 > s2 //} //var reversed = stringNames.sorted(backWards) // //print("\(reversed)") // 闭包表达式语法形式: // {(parameters) -> returnType in 闭包的函数体部分由关键字in引入,该关键字表示闭包的参数和返回值类型定义已经完成,闭包函数体即将开始 // statements //} var reversed = stringNames.sorted({(s1:String,s2:String) -> Bool in return s1 > s2 }) // 根据上下文推断类型:通过内联闭包表达式构造的闭包作为参数传递给函数或方法时,都可以推断出闭包的参数和返回值类型。这意味着闭包作为函数或者方法的参数时,几乎不需要利用完整格式构造内联闭包. reversed = stringNames.sorted({s1,s2 in return s1 > s2}) print("\(reversed)") // 单表达式闭包隐士返回 // 单行表达式闭包可以通过省略return关键字来隐士返回单行表达式的结果 reversed = stringNames.sorted({s1,s2 in s1 > s2}) // 参数名称缩写 // swift自动为内联闭包提供了参数名称缩写功能,可以直接通过$0,$1,$2来顺序调用闭包的参数.如果在闭包表达式中使用参数名称缩写,您可以在闭包参数列表中省略对其的定义,并且对应参数名称缩写的类型会通过函数类型进行推断。in关键字也同样可以被省略 reversed = stringNames.sorted({$0 > $1}) // 运算符函数 //swift的string类型定义了有关“>”的字符串实现,其作为一个函数接受两个String类型的参数并返回Bool类型的值。swift可以自动推断您想使用大于号的字符串函数实现 reversed = stringNames.sorted(>) // 尾随闭包 // 如果您需要将一个很长的闭包表达式作为最后一个参数传递给函数,可以使用尾随闭包来增强函数的可读性。尾随闭包是一个书写在函数括号之后的闭包表达式,函数支持将其作为最后一个参数调用: func someFunctionThatTakesAClosure(closure:() -> Void) { // 函数体部分 } // 以下是不使用尾随闭包进行函数调用 someFunctionThatTakesAClosure({ // 闭包主体部分 }) // 一下是使用尾随闭包进行函数调用 someFunctionThatTakesAClosure(){ // 闭包主体部分 } reversed = stringNames.sorted(){(s1:String,s2:String) -> Bool in s1 > s2} print("\(reversed)") reversed = stringNames.sorted(){s1,s2 in s1 > s2} reversed = stringNames.sorted(){$0 > $1} // 如果函数只需要闭包表达式一个参数,当使用尾随闭包时,可以把()省略掉 reversed = stringNames.sorted{$0 > $1} print("\(reversed)") // Array类型的map(_:)方法,其获取一个闭包表达式作为其唯一参数,该闭包函数会为数组中的每一个元素调用一次,并且返回该元素所映射的值。具体的映射方式和返回值类型由闭包来指定 let digitNames = [ 0:"Zero",1:"One",2:"Two",3:"There",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine" ] let numbers = [16,58,510] let strings = numbers.map{(var number) -> String in var output = "" while number > 0 { output = digitNames[number % 10]! + output number /= 10 } return output } // 捕获值 // 闭包可以在其被定义的上下文中捕获常量或变量。即便定义这些常量和变量的原作用域已经不存在,闭包仍然可以在闭包函数体内引用和修改这些值 func makeIncrementor(forIncrement amout:Int) -> () -> Int { var runningTotal = 0 func incrementor() -> Int { runningTotal += amout return runningTotal } return incrementor // 函数可以作为一个返回值返回 } // 为了优化,如果一个值是不可变的,swift可能会改为捕获并保存一份对值的拷贝 let incrementByTen = makeIncrementor(forIncrement: 10) incrementByTen() incrementByTen() incrementByTen() // 如果创建了另一个incrementor,它会有属于它自己的一个全新、独立的runningTotal变量的引用;再次调用原来的incrementByTen会在原来的变量runningTotal上继续增加值,该变量和increnmentBySeven中捕获的变量没有任何联系 let incrementBySeven = makeIncrementor(forIncrement: 7) incrementBySeven() incrementByTen() // 闭包是引用类型 // 函数和闭包都是引用类型 // 无论将函数或闭包赋值给一个变量还是常量,实际上都是将变量或常量的值设置为对应函数或闭包的引用.因此,如果将闭包赋值给了两个不同的常量或变量,两个值都会指向同一个闭包 let alsoIncrementByTen = incrementByTen alsoIncrementByTen() // 非逃逸闭包 // 当一个闭包作为参数传到一个函数中,但是这个闭包在函数返回之后才被执行,我们称该闭包从函数中逃逸。当定义接受闭包作为函数的参数时,可以在参数名之前标注@noescape,用来指明之歌闭包不允许“逃逸”出这个函数. // 闭包职能在函数体中执行,不能脱离函数体执行 func someFunctionWithNoescapeCloure(@noescape cloure:() -> Void) { } var completionHandlers:[() -> Void] = [] // 定义了一个数组变量 func someFunctionWithEscapingClosure(completionHandler: () -> Void) { completionHandlers.append(completionHandler) } //print("irhjdf") class someClass { var x = 10 func dosomething() { someFunctionWithEscapingClosure { self.x = 100 } someFunctionWithNoescapeCloure({x = 200}) } } let instance = someClass() instance.dosomething() print(instance.x) completionHandlers.first?() print(instance.x) completionHandlers.last?() print(instance.x) // 自动闭包 // 自动闭包是一种自动创建的闭包,用于包装传递给函数作为参数的表达式。这种闭包不接受任何参数,当它被调用的时候,会返回被包装在其中的表达式的值。 // 自动闭包让你能够延迟求值 var customersInLine = ["Chris","Alex","Ewa","Barry","Daniella"] print(customersInLine.count) let customerProvider = {customersInLine.removeAtIndex(0)} // {}创建自动闭包 print(customersInLine.count) // 当它被调用的时候,会返回被包装在其中的表达式 print(customerProvider()) // 当它被调用的时候,会返回被包装在其中的表达式 print("Now servins \(customerProvider())!") print(customersInLine.count) // 将闭包作为参数传递给函数时,能获得同样的延时求值行为 func serveCustomer (customerProvider:() -> String) { // 说明接受的是显式的闭包 print("now serviing \(customerProvider())!") // 调用闭包 } serveCustomer(customerProvider) // serveCustomer({customerInLine.removeAtIndex(0)}) print(customersInLine.count) // @autoclosure :标记接收一个自动闭包 func serverCustomer(@autoclosure customerProvider:() -> String) { // 说明接受的是自动闭包 print("Now serving \(customerProvider())!") } serverCustomer(customerProvider()) // @autoclosure 特性暗含了@noescape特性。如果你想让这个闭包可以“逃逸”,则应该使用@autoclosure(escaping)特性 var customereProviders: [() -> String] = [] func collectCustomerProviders(@autoclosure(escaping) customerProvider: () -> String) { customereProviders.append(customerProvider) } collectCustomerProviders(customerProvider()) print("Collected \(customereProviders.count) closures.") for custo in customereProviders { print("Now serving \(customerProvider())!") } print("Collected \(customereProviders.count) closures.")
apache-2.0
bfc33a79395e031a2ec79b4bb7fdc0f4
23.164151
138
0.711095
2.747104
false
false
false
false
samodom/TestableCoreLocation
TestableCoreLocation/CLLocationManager/CLLocationManagerRequestAlwaysAuthorizationSpy.swift
1
2060
// // CLLocationManagerRequestAlwaysAuthorizationSpy.swift // TestableCoreLocation // // Created by Sam Odom on 3/6/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import CoreLocation import FoundationSwagger import TestSwagger public extension CLLocationManager { private static let requestAlwaysAuthorizationCalledKeyString = UUIDKeyString() private static let requestAlwaysAuthorizationCalledKey = ObjectAssociationKey(requestAlwaysAuthorizationCalledKeyString) private static let requestAlwaysAuthorizationCalledReference = SpyEvidenceReference(key: requestAlwaysAuthorizationCalledKey) /// Spy controller for ensuring that a location manager has had `requestAlwaysAuthorization` /// called on it. public enum RequestAlwaysAuthorizationSpyController: SpyController { public static let rootSpyableClass: AnyClass = CLLocationManager.self public static let vector = SpyVector.direct public static let coselectors = [ SpyCoselectors( methodType: .instance, original: #selector(CLLocationManager.requestAlwaysAuthorization), spy: #selector(CLLocationManager.spy_requestAlwaysAuthorization) ) ] as Set public static let evidence = [requestAlwaysAuthorizationCalledReference] as Set public static let forwardsInvocations = false } /// Spy method that replaces the true implementation of `requestAlwaysAuthorization` dynamic public func spy_requestAlwaysAuthorization() { requestAlwaysAuthorizationCalled = true } /// Indicates whether the `requestAlwaysAuthorization` method has been called on this object. public final var requestAlwaysAuthorizationCalled: Bool { get { return loadEvidence(with: CLLocationManager.requestAlwaysAuthorizationCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: CLLocationManager.requestAlwaysAuthorizationCalledReference) } } }
mit
c2aa28f9050bd19c9ee5adc0e80b6a39
35.767857
116
0.73288
6.277439
false
false
false
false
zhubofei/IGListKit
Examples/Examples-iOS/IGListKitExamples/ViewControllers/LoadMoreViewController.swift
4
3111
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class LoadMoreViewController: UIViewController, ListAdapterDataSource, UIScrollViewDelegate { lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self) }() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) lazy var items = Array(0...20) var loading = false let spinToken = "spinner" override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self adapter.scrollViewDelegate = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } // MARK: ListAdapterDataSource func objects(for listAdapter: ListAdapter) -> [ListDiffable] { var objects = items as [ListDiffable] if loading { objects.append(spinToken as ListDiffable) } return objects } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { if let obj = object as? String, obj == spinToken { return spinnerSectionController() } else { return LabelSectionController() } } func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil } // MARK: UIScrollViewDelegate func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let distance = scrollView.contentSize.height - (targetContentOffset.pointee.y + scrollView.bounds.height) if !loading && distance < 200 { loading = true adapter.performUpdates(animated: true, completion: nil) DispatchQueue.global(qos: .default).async { // fake background loading task sleep(2) DispatchQueue.main.async { self.loading = false let itemCount = self.items.count self.items.append(contentsOf: Array(itemCount..<itemCount + 5)) self.adapter.performUpdates(animated: true, completion: nil) } } } } }
mit
290e6180bc23080ab3621ce0ad9d7441
34.758621
113
0.656702
5.575269
false
false
false
false
luispadron/GradePoint
GradePoint/CustomControls/UIBlurAlert/UIBlurAlertView.swift
1
2857
// // UIBlurAlertView.swift // GradePoint // // Created by Luis Padron on 1/17/17. // Copyright © 2017 Luis Padron. All rights reserved. // import UIKit internal class UIBlurAlertView: UIView { // MARK: - Properties private var _title: NSAttributedString internal var title: NSAttributedString { get { return self._title } } private var _message: NSAttributedString? internal var message: NSAttributedString? { get { return self._message} } private lazy var titleLabel = UILabel() private lazy var messageLabel = UILabel() internal var buttons = [UIButton]() { didSet { self.updateButtons() } } // MARK: - Initializers internal required init(frame: CGRect, title: NSAttributedString, message: NSAttributedString?) { self._title = title self._message = message super.init(frame: frame) self.drawViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Helpers private func drawViews() { self.layer.cornerRadius = 5 self.clipsToBounds = true titleLabel.attributedText = _title titleLabel.textAlignment = .center messageLabel.attributedText = _message messageLabel.textAlignment = .center // Set up frames titleLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 30) messageLabel.frame = CGRect(x: 0, y: titleLabel.frame.height + 25, width: self.bounds.width, height: 30) messageLabel.resizeToFitText() self.addSubview(titleLabel) self.addSubview(messageLabel) // Add a border to view let bottomBorder = CALayer() bottomBorder.frame = CGRect(x: self.layer.frame.minX, y: titleLabel.frame.height, width: self.layer.frame.width, height: 1) bottomBorder.backgroundColor = UIColor.gray.cgColor self.layer.addSublayer(bottomBorder) } private func updateButtons() { // Loop through all the buttons and add them for (index, button) in buttons.enumerated() { // Calculate the size and positions let width = self.bounds.width / CGFloat(buttons.count) let height = self.bounds.height * 1/4 let xForButton: CGFloat = width * CGFloat(index) let yForButton: CGFloat = self.bounds.maxY - height button.frame = CGRect(x: xForButton, y: yForButton, width: width, height: height) // If already added, then just continue and dont add the button as a subview again if let _ = self.subviews.firstIndex(of: button) { continue } self.addSubview(button) } } }
apache-2.0
242f0a8bc8876cd3bc0d50aac50b16bb
31.089888
131
0.613445
4.674304
false
false
false
false
astralbodies/CleanRooms
CleanRooms/Services/RoomService.swift
1
2195
/* * Copyright (c) 2015 Razeware LLC * * 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 CoreData public class RoomService { let managedObjectContext: NSManagedObjectContext public init(managedObjectContext: NSManagedObjectContext) { self.managedObjectContext = managedObjectContext } public func getAllRooms() -> [Room] { let fetchRequest = NSFetchRequest(entityName: "Room") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "roomNumber", ascending: true)] var results: [AnyObject] do { try results = managedObjectContext.executeFetchRequest(fetchRequest) } catch { print("Error when fetching rooms: \(error)") return [Room]() } return results as! [Room] } public func getRoomByID(roomID: String) -> Room? { let fetchRequest = NSFetchRequest(entityName: "Room") fetchRequest.predicate = NSPredicate(format: "roomID == %@", roomID) var results: [AnyObject] do { try results = managedObjectContext.executeFetchRequest(fetchRequest) } catch { print("Error when fetching Room by ID: \(error)") return nil } return results.first as? Room } }
mit
0eeadf9b8abd0e26bd0d989b641dbb45
34.403226
89
0.735308
4.730603
false
false
false
false
SaberVicky/LoveStory
LoveStory/Feature/Profile/LSProfileViewController.swift
1
1438
// // LSProfileViewController.swift // LoveStory // // Created by songlong on 2017/1/19. // Copyright © 2017年 com.Saber. All rights reserved. // import UIKit class LSProfileViewController: UITableViewController { private let dataList: [[String]] = [["更改头像", "昵称", "性别", "生日"], ["解除关系"]]; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = .white tableView = UITableView(frame: UIScreen.main.bounds, style: .grouped) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "ProfileCell") } override func numberOfSections(in tableView: UITableView) -> Int { return dataList.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataList[section].count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell", for: indexPath) cell.accessoryType = .disclosureIndicator cell.textLabel?.text = dataList[indexPath.section][indexPath.row] return cell } }
mit
71a958cbebaa88cfd09cd2ba493a985f
30.977273
109
0.670931
4.971731
false
false
false
false
tkremenek/swift
test/decl/subscript/subscripting.swift
11
14524
// RUN: %target-typecheck-verify-swift struct X { } // expected-note * {{did you mean 'X'?}} // Simple examples struct X1 { var stored : Int subscript (i : Int) -> Int { get { return stored } mutating set { stored = newValue } } } struct X2 { var stored : Int subscript (i : Int) -> Int { get { return stored + i } set(v) { stored = v - i } } } struct X3 { var stored : Int subscript (_ : Int) -> Int { get { return stored } set(v) { stored = v } } } struct X4 { var stored : Int subscript (i : Int, j : Int) -> Int { get { return stored + i + j } set(v) { stored = v + i - j } } } struct X5 { static var stored : Int = 1 static subscript (i : Int) -> Int { get { return stored + i } set { stored = newValue - i } } } class X6 { static var stored : Int = 1 class subscript (i : Int) -> Int { get { return stored + i } set { stored = newValue - i } } } protocol XP1 { subscript (i : Int) -> Int { get set } static subscript (i : Int) -> Int { get set } } // Semantic errors struct Y1 { var x : X subscript(i: Int) -> Int { get { return x // expected-error{{cannot convert return expression of type 'X' to return type 'Int'}} } set { x = newValue // expected-error{{cannot assign value of type 'Int' to type 'X'}} } } } struct Y2 { subscript(idx: Int) -> TypoType { // expected-error {{cannot find type 'TypoType' in scope}} get { repeat {} while true } set {} } } class Y3 { subscript(idx: Int) -> TypoType { // expected-error {{cannot find type 'TypoType' in scope}} get { repeat {} while true } set {} } } class Y4 { var x = X() static subscript(idx: Int) -> X { get { return x } // expected-error {{instance member 'x' cannot be used on type 'Y4'}} set {} } } class Y5 { static var x = X() subscript(idx: Int) -> X { get { return x } // expected-error {{static member 'x' cannot be used on instance of type 'Y5'}} set {} } } protocol ProtocolGetSet0 { subscript(i: Int) -> Int {} // expected-error {{subscript declarations must have a getter}} } protocol ProtocolGetSet1 { subscript(i: Int) -> Int { get } } protocol ProtocolGetSet2 { subscript(i: Int) -> Int { set } // expected-error {{subscript with a setter must also have a getter}} } protocol ProtocolGetSet3 { subscript(i: Int) -> Int { get set } } protocol ProtocolGetSet4 { subscript(i: Int) -> Int { set get } } protocol ProtocolWillSetDidSet1 { subscript(i: Int) -> Int { willSet } // expected-error {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}} } protocol ProtocolWillSetDidSet2 { subscript(i: Int) -> Int { didSet } // expected-error {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}} } protocol ProtocolWillSetDidSet3 { subscript(i: Int) -> Int { willSet didSet } // expected-error 2 {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}} } protocol ProtocolWillSetDidSet4 { subscript(i: Int) -> Int { didSet willSet } // expected-error 2 {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}} } class DidSetInSubscript { subscript(_: Int) -> Int { didSet { // expected-error {{'didSet' is not allowed in subscripts}} print("eek") } get {} } } class WillSetInSubscript { subscript(_: Int) -> Int { willSet { // expected-error {{'willSet' is not allowed in subscripts}} print("eek") } get {} } } subscript(i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}} get {} } func f() { // expected-note * {{did you mean 'f'?}} subscript (i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}} get {} } } struct NoSubscript { } struct OverloadedSubscript { subscript(i: Int) -> Int { get { return i } set {} } subscript(i: Int, j: Int) -> Int { get { return i } set {} } } struct RetOverloadedSubscript { subscript(i: Int) -> Int { // expected-note {{found this candidate}} get { return i } set {} } subscript(i: Int) -> Float { // expected-note {{found this candidate}} get { return Float(i) } set {} } } struct MissingGetterSubscript1 { subscript (i : Int) -> Int { } // expected-error {{subscript must have accessors specified}} } struct MissingGetterSubscript2 { subscript (i : Int, j : Int) -> Int { set {} // expected-error{{subscript with a setter must also have a getter}} } } func test_subscript(_ x2: inout X2, i: Int, j: Int, value: inout Int, no: NoSubscript, ovl: inout OverloadedSubscript, ret: inout RetOverloadedSubscript) { no[i] = value // expected-error{{value of type 'NoSubscript' has no subscripts}} value = x2[i] x2[i] = value value = ovl[i] ovl[i] = value value = ovl[i, j] ovl[i, j] = value value = ovl[(i, j, i)] // expected-error{{cannot convert value of type '(Int, Int, Int)' to expected argument type 'Int'}} ret[i] // expected-error{{ambiguous use of 'subscript(_:)'}} value = ret[i] ret[i] = value X5[i] = value value = X5[i] } func test_proto_static<XP1Type: XP1>( i: Int, value: inout Int, existential: inout XP1, generic: inout XP1Type ) { existential[i] = value value = existential[i] type(of: existential)[i] = value value = type(of: existential)[i] generic[i] = value value = generic[i] XP1Type[i] = value value = XP1Type[i] } func subscript_rvalue_materialize(_ i: inout Int) { i = X1(stored: 0)[i] } func subscript_coerce(_ fn: ([UnicodeScalar], [UnicodeScalar]) -> Bool) {} func test_subscript_coerce() { subscript_coerce({ $0[$0.count-1] < $1[$1.count-1] }) } struct no_index { subscript () -> Int { return 42 } func test() -> Int { return self[] } } struct tuple_index { subscript (x : Int, y : Int) -> (Int, Int) { return (x, y) } func test() -> (Int, Int) { return self[123, 456] } } struct MutableComputedGetter { var value: Int subscript(index: Int) -> Int { value = 5 // expected-error{{cannot assign to property: 'self' is immutable}} return 5 } var getValue : Int { value = 5 // expected-error {{cannot assign to property: 'self' is immutable}} return 5 } } struct MutableSubscriptInGetter { var value: Int subscript(index: Int) -> Int { get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} value = 5 // expected-error{{cannot assign to property: 'self' is immutable}} return 5 } } } protocol Protocol {} protocol RefinedProtocol: Protocol {} class SuperClass {} class SubClass: SuperClass {} class SubSubClass: SubClass {} class ClassConformingToProtocol: Protocol {} class ClassConformingToRefinedProtocol: RefinedProtocol {} struct GenSubscriptFixitTest { subscript<T>(_ arg: T) -> Bool { return true } // expected-note 3 {{declared here}} // expected-note@-1 2 {{in call to 'subscript(_:)'}} } func testGenSubscriptFixit(_ s0: GenSubscriptFixitTest) { _ = s0.subscript("hello") // expected-error@-1 {{value of type 'GenSubscriptFixitTest' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{27-28=]}} } func testUnresolvedMemberSubscriptFixit(_ s0: GenSubscriptFixitTest) { _ = s0.subscript // expected-error@-1 {{value of type 'GenSubscriptFixitTest' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-19=[<#index#>]}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} s0.subscript = true // expected-error@-1 {{value of type 'GenSubscriptFixitTest' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{5-15=[<#index#>]}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} } struct SubscriptTest1 { subscript(keyword:String) -> Bool { return true } // expected-note@-1 5 {{found this candidate}} expected-note@-1 {{'subscript(_:)' produces 'Bool', not the expected contextual result type 'Int'}} subscript(keyword:String) -> String? {return nil } // expected-note@-1 5 {{found this candidate}} expected-note@-1 {{'subscript(_:)' produces 'String?', not the expected contextual result type 'Int'}} subscript(arg: SubClass) -> Bool { return true } // expected-note {{declared here}} // expected-note@-1 2 {{found this candidate}} subscript(arg: Protocol) -> Bool { return true } // expected-note 2 {{declared here}} // expected-note@-1 2 {{found this candidate}} subscript(arg: (foo: Bool, bar: (Int, baz: SubClass)), arg2: String) -> Bool { return true } // expected-note@-1 3 {{declared here}} } func testSubscript1(_ s1 : SubscriptTest1) { let _ : Int = s1["hello"] // expected-error {{no 'subscript' candidates produce the expected contextual result type 'Int'}} if s1["hello"] {} _ = s1.subscript((true, (5, SubClass())), "hello") // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{52-53=]}} _ = s1.subscript((true, (5, baz: SubSubClass())), "hello") // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{60-61=]}} _ = s1.subscript((fo: true, (5, baz: SubClass())), "hello") // expected-error@-1 {{cannot convert value of type '(fo: Bool, (Int, baz: SubClass))' to expected argument type '(foo: Bool, bar: (Int, baz: SubClass))'}} // expected-error@-2 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} _ = s1.subscript(SubSubClass()) // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{33-34=]}} _ = s1.subscript(ClassConformingToProtocol()) // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{47-48=]}} _ = s1.subscript(ClassConformingToRefinedProtocol()) // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{54-55=]}} _ = s1.subscript(true) // expected-error@-1 {{no exact matches in call to subscript}} _ = s1.subscript(SuperClass()) // expected-error@-1 {{no exact matches in call to subscript}} _ = s1.subscript("hello") // expected-error@-1 {{no exact matches in call to subscript}} _ = s1.subscript("hello" // expected-error@-1 {{no exact matches in call to subscript}} // expected-note@-2 {{to match this opening '('}} let _ = s1["hello"] // expected-error@-1 {{ambiguous use of 'subscript(_:)'}} // expected-error@-2 {{expected ')' in expression list}} } struct SubscriptTest2 { subscript(a : String, b : Int) -> Int { return 0 } // expected-note {{candidate expects value of type 'Int' for parameter #2}} // expected-note@-1 2 {{declared here}} subscript(a : String, b : String) -> Int { return 0 } // expected-note {{candidate expects value of type 'String' for parameter #2}} } func testSubscript1(_ s2 : SubscriptTest2) { _ = s2["foo"] // expected-error {{missing argument for parameter #2 in call}} let a = s2["foo", 1.0] // expected-error {{no exact matches in call to subscript}} _ = s2.subscript("hello", 6) // expected-error@-1 {{value of type 'SubscriptTest2' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{30-31=]}} let b = s2[1, "foo"] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} // rdar://problem/27449208 let v: (Int?, [Int]?) = (nil [17]) // expected-error {{cannot subscript a nil literal value}} } // sr-114 & rdar://22007370 class Foo { subscript(key: String) -> String { // expected-note {{'subscript(_:)' previously declared here}} get { a } // expected-error {{cannot find 'a' in scope}} set { b } // expected-error {{cannot find 'b' in scope}} } subscript(key: String) -> String { // expected-error {{invalid redeclaration of 'subscript(_:)'}} get { _ = 0; a } // expected-error {{cannot find 'a' in scope}} set { b } // expected-error {{cannot find 'b' in scope}} } } // <rdar://problem/23952125> QoI: Subscript in protocol with missing {}, better diagnostic please protocol r23952125 { associatedtype ItemType var count: Int { get } subscript(index: Int) -> ItemType // expected-error {{subscript in protocol must have explicit { get } or { get set } specifier}} {{36-36= { get <#set#> \}}} var c : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-14= { get <#set#> \}}} } // SR-2575 struct SR2575 { subscript() -> Int { // expected-note {{declared here}} return 1 } } SR2575().subscript() // expected-error@-1 {{value of type 'SR2575' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{20-21=]}} // SR-7890 struct InOutSubscripts { subscript(x1: inout Int) -> Int { return 0 } // expected-error@-1 {{'inout' must not be used on subscript parameters}} subscript(x2: inout Int, y2: inout Int) -> Int { return 0 } // expected-error@-1 2{{'inout' must not be used on subscript parameters}} subscript(x3: (inout Int) -> ()) -> Int { return 0 } // ok subscript(x4: (inout Int, inout Int) -> ()) -> Int { return 0 } // ok subscript(inout x5: Int) -> Int { return 0 } // expected-error@-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} // expected-error@-2 {{'inout' must not be used on subscript parameters}} }
apache-2.0
8808ce98b192c9316a84254248a24e0f
30.234409
198
0.626067
3.575579
false
true
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxDataSources/Example/Example4_DifferentSectionAndItemTypes.swift
3
4225
// // MultipleSectionModelViewController.swift // RxDataSources // // Created by Segii Shulga on 4/26/16. // Copyright © 2016 kzaher. All rights reserved. // import UIKit import RxDataSources import RxCocoa import RxSwift // the trick is to just use enum for different section types class MultipleSectionModelViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let sections: [MultipleSectionModel] = [ .ImageProvidableSection(title: "Section 1", items: [.ImageSectionItem(image: UIImage(named: "settings")!, title: "General")]), .ToggleableSection(title: "Section 2", items: [.ToggleableSectionItem(title: "On", enabled: true)]), .StepperableSection(title: "Section 3", items: [.StepperSectionItem(title: "1")]) ] let dataSource = RxTableViewSectionedReloadDataSource<MultipleSectionModel>() skinTableViewDataSource(dataSource) Observable.just(sections) .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) } func skinTableViewDataSource(_ dataSource: RxTableViewSectionedReloadDataSource<MultipleSectionModel>) { dataSource.configureCell = { (dataSource, table, idxPath, _) in switch dataSource[idxPath] { case let .ImageSectionItem(image, title): let cell: ImageTitleTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath) cell.titleLabel.text = title cell.cellImageView.image = image return cell case let .StepperSectionItem(title): let cell: TitleSteperTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath) cell.titleLabel.text = title return cell case let .ToggleableSectionItem(title, enabled): let cell: TitleSwitchTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath) cell.switchControl.isOn = enabled cell.titleLabel.text = title return cell } } dataSource.titleForHeaderInSection = { dataSource, index in let section = dataSource[index] return section.title } } } enum MultipleSectionModel { case ImageProvidableSection(title: String, items: [SectionItem]) case ToggleableSection(title: String, items: [SectionItem]) case StepperableSection(title: String, items: [SectionItem]) } enum SectionItem { case ImageSectionItem(image: UIImage, title: String) case ToggleableSectionItem(title: String, enabled: Bool) case StepperSectionItem(title: String) } extension MultipleSectionModel: SectionModelType { typealias Item = SectionItem var items: [SectionItem] { switch self { case .ImageProvidableSection(title: _, items: let items): return items.map {$0} case .StepperableSection(title: _, items: let items): return items.map {$0} case .ToggleableSection(title: _, items: let items): return items.map {$0} } } init(original: MultipleSectionModel, items: [Item]) { switch original { case let .ImageProvidableSection(title: title, items: _): self = .ImageProvidableSection(title: title, items: items) case let .StepperableSection(title, _): self = .StepperableSection(title: title, items: items) case let .ToggleableSection(title, _): self = .ToggleableSection(title: title, items: items) } } } extension MultipleSectionModel { var title: String { switch self { case .ImageProvidableSection(title: let title, items: _): return title case .StepperableSection(title: let title, items: _): return title case .ToggleableSection(title: let title, items: _): return title } } }
mit
761e6096aa0a71dda60373aa36d6013d
33.909091
108
0.621922
5.12
false
false
false
false
ioscodigo/ICTabFragment
ICTabFragment/ICTabCollectionViewCell.swift
2
2349
// // ICTabCollectionViewCell.swift // ICTabFragment // // Created by Digital Khrisna on 6/1/17. // Copyright © 2017 codigo. All rights reserved. // import UIKit class ICTabCollectionViewCell: UICollectionViewCell { var tabNameLabel: UILabel = { let label = UILabel() label.textColor = UIColor.black label.font = UIFont.systemFont(ofSize: 12) label.numberOfLines = 0 label.text = "Label" label.sizeToFit() return label }() var indicatorView: UIView = { let view = UIView() return view }() private var indicatorTopSpaceConstraint: NSLayoutConstraint! private var indicatorHeightConstraint: NSLayoutConstraint! var indicatorTopSpace: CGFloat = 0 { didSet { indicatorTopSpaceConstraint.constant = indicatorTopSpace } } var indicatorHeight: CGFloat = 5 { didSet { indicatorHeightConstraint.constant = indicatorHeight } } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(tabNameLabel) tabNameLabel.translatesAutoresizingMaskIntoConstraints = false tabNameLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true tabNameLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0).isActive = true self.addSubview(indicatorView) indicatorView.translatesAutoresizingMaskIntoConstraints = false indicatorView.widthAnchor.constraint(equalTo: tabNameLabel.widthAnchor, multiplier: 0.8).isActive = true indicatorTopSpaceConstraint = indicatorView.topAnchor.constraint(equalTo: tabNameLabel.bottomAnchor, constant: indicatorTopSpace) indicatorTopSpaceConstraint.isActive = true indicatorView.centerXAnchor.constraint(equalTo: tabNameLabel.centerXAnchor, constant: 0).isActive = true indicatorHeightConstraint = indicatorView.heightAnchor.constraint(equalToConstant: indicatorHeight) indicatorHeightConstraint.isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var reuseIdentifier: String? { return "ictabcollectionviewcell" } }
mit
27de542b0b8ff2d08c116a5faa4abc0e
32.542857
137
0.681857
5.435185
false
false
false
false
joerocca/GitHawk
Pods/Tabman/Sources/Tabman/TabmanBar/TabmanBar.swift
1
13153
// // TabmanBar.swift // Tabman // // Created by Merrick Sapsford on 17/02/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit import PureLayout import Pageboy public protocol TabmanBarDelegate: class { /// Whether a bar should select an item at an index. /// /// - Parameters: /// - index: The proposed selection index. /// - Returns: Whether the index should be selected. func bar(shouldSelectItemAt index: Int) -> Bool } /// A bar that displays the current page status of a TabmanViewController. open class TabmanBar: UIView, TabmanBarLifecycle { // MARK: Types /// The height for the bar. /// /// - auto: Autosize the bar according to its contents. /// - explicit: Explicit value for the bar height. public enum Height { case auto case explicit(value: CGFloat) } // MARK: Properties /// The items that are displayed in the bar. internal var items: [TabmanBar.Item]? { didSet { self.isHidden = (items?.count ?? 0) == 0 } } internal private(set) var currentPosition: CGFloat = 0.0 internal weak var transitionStore: TabmanBarTransitionStore? internal lazy var behaviorEngine = BarBehaviorEngine(for: self) /// The object that acts as a responder to the bar. internal weak var responder: TabmanBarResponder? /// The object that acts as a data source to the bar. public weak var dataSource: TabmanBarDataSource? { didSet { self.reloadData() } } /// Appearance configuration for the bar. public var appearance: Appearance = .defaultAppearance { didSet { self.updateCore(forAppearance: appearance) } } /// The height for the bar. Default: .auto public var height: Height = .auto { didSet { switch height { case let .explicit(value) where value == 0: removeAllSubviews() default: break } self.invalidateIntrinsicContentSize() self.superview?.setNeedsLayout() self.superview?.layoutIfNeeded() } } open override var intrinsicContentSize: CGSize { var autoSize = super.intrinsicContentSize switch self.height { case .explicit(let height): autoSize.height = height return autoSize default: return autoSize } } /// Background view of the bar. public private(set) var backgroundView: BackgroundView = BackgroundView(forAutoLayout: ()) /// The content view for the bar. public private(set) var contentView = UIView(forAutoLayout: ()) /// The bottom separator view for the bar. internal private(set) var bottomSeparator = SeparatorView() /// Indicator for the bar. public internal(set) var indicator: TabmanIndicator? { didSet { indicator?.delegate = self self.clear(indicator: oldValue) } } /// Mask view used for indicator. internal var indicatorMaskView: UIView = { let maskView = UIView() maskView.backgroundColor = .black return maskView }() internal var indicatorLeftMargin: NSLayoutConstraint? internal var indicatorWidth: NSLayoutConstraint? internal var indicatorIsProgressive: Bool = TabmanBar.Appearance.defaultAppearance.indicator.isProgressive ?? false { didSet { guard indicatorIsProgressive != oldValue else { return } UIView.animate(withDuration: 0.3, animations: { self.updateForCurrentPosition() }) } } internal var indicatorBounces: Bool = TabmanBar.Appearance.defaultAppearance.indicator.bounces ?? false internal var indicatorCompresses: Bool = TabmanBar.Appearance.defaultAppearance.indicator.compresses ?? false /// Preferred style for the indicator. /// Bar conforms at own discretion via usePreferredIndicatorStyle() public var preferredIndicatorStyle: TabmanIndicator.Style? { didSet { self.updateIndicator(forPreferredStyle: preferredIndicatorStyle) } } /// The limit that the bar has for the number of items it can display. public var itemCountLimit: Int? { return nil } // MARK: Init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initTabBar(coder: aDecoder) } public override init(frame: CGRect) { super.init(frame: frame) initTabBar(coder: nil) } private func initTabBar(coder aDecoder: NSCoder?) { self.addSubview(backgroundView) backgroundView.autoPinEdgesToSuperviewEdges() bottomSeparator.addAsSubview(to: self) self.addSubview(contentView) if #available(iOS 11, *) { contentView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor), contentView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor), contentView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor) ]) } else { contentView.autoPinEdgesToSuperviewEdges() } self.indicator = self.create(indicatorForStyle: self.defaultIndicatorStyle()) } // MARK: Lifecycle open override func layoutSubviews() { super.layoutSubviews() // refresh intrinsic size for indicator self.indicator?.invalidateIntrinsicContentSize() } open override func addSubview(_ view: UIView) { if view !== self.backgroundView && view !== self.contentView && view !== self.bottomSeparator { fatalError("Please add subviews to the contentView rather than directly onto the TabmanBar") } super.addSubview(view) } /// The default indicator style for the bar. /// /// - Returns: The default indicator style. open func defaultIndicatorStyle() -> TabmanIndicator.Style { print("indicatorStyle() returning default. This should be overridden in subclass") return .clear } /// Whether the bar should use preferredIndicatorStyle if available /// /// - Returns: Whether to use preferredIndicatorStyle open func usePreferredIndicatorStyle() -> Bool { return true } /// The type of transition to use for the indicator (Internal use only). /// /// - Returns: The transition type. internal func indicatorTransitionType() -> TabmanIndicatorTransition.Type? { return nil } // MARK: Data /// Reload and reconstruct the contents of the bar. public func reloadData() { self.items = self.dataSource?.items(for: self) self.clearAndConstructBar() } // MARK: Updating internal func updatePosition(_ position: CGFloat, direction: PageboyViewController.NavigationDirection, bounds: CGRect? = nil) { guard let items = self.items else { return } let bounds = bounds ?? self.bounds self.layoutIfNeeded() self.currentPosition = position self.update(forPosition: position, direction: direction, indexRange: 0 ..< items.count - 1, bounds: bounds) } internal func updateForCurrentPosition(bounds: CGRect? = nil) { self.updatePosition(self.currentPosition, direction: .neutral, bounds: bounds) } // MARK: TabmanBarLifecycle open func construct(in contentView: UIView, for items: [TabmanBar.Item]) { } open func add(indicator: TabmanIndicator, to contentView: UIView) { } open func update(forPosition position: CGFloat, direction: PageboyViewController.NavigationDirection, indexRange: Range<Int>, bounds: CGRect) { guard self.indicator != nil else { return } let indicatorTransition = self.transitionStore?.indicatorTransition(forBar: self) indicatorTransition?.transition(withPosition: position, direction: direction, indexRange: indexRange, bounds: bounds) let itemTransition = self.transitionStore?.itemTransition(forBar: self, indicator: self.indicator!) itemTransition?.transition(withPosition: position, direction: direction, indexRange: indexRange, bounds: bounds) } /// Appearance updates that are core to TabmanBar and must always be evaluated /// /// - Parameter appearance: The appearance config internal func updateCore(forAppearance appearance: Appearance) { let defaultAppearance = Appearance.defaultAppearance self.preferredIndicatorStyle = appearance.indicator.preferredStyle let backgroundStyle = appearance.style.background ?? defaultAppearance.style.background! self.backgroundView.style = backgroundStyle let height: Height let hideWhenSingleItem = appearance.state.shouldHideWhenSingleItem ?? defaultAppearance.state.shouldHideWhenSingleItem! if hideWhenSingleItem && items?.count ?? 0 <= 1 { height = .explicit(value: 0) } else { height = appearance.layout.height ?? .auto } self.height = height let bottomSeparatorColor = appearance.style.bottomSeparatorColor ?? defaultAppearance.style.bottomSeparatorColor! self.bottomSeparator.color = bottomSeparatorColor let bottomSeparatorEdgeInsets = appearance.layout.bottomSeparatorEdgeInsets ?? defaultAppearance.layout.bottomSeparatorEdgeInsets! self.bottomSeparator.edgeInsets = bottomSeparatorEdgeInsets self.update(forAppearance: appearance, defaultAppearance: defaultAppearance) } open func update(forAppearance appearance: Appearance, defaultAppearance: Appearance) { let indicatorIsProgressive = appearance.indicator.isProgressive ?? defaultAppearance.indicator.isProgressive! self.indicatorIsProgressive = indicatorIsProgressive ? self.indicator?.isProgressiveCapable ?? false : false let indicatorBounces = appearance.indicator.bounces ?? defaultAppearance.indicator.bounces! self.indicatorBounces = indicatorBounces let indicatorCompresses = appearance.indicator.compresses ?? defaultAppearance.indicator.compresses! self.indicatorCompresses = indicatorBounces ? false : indicatorCompresses // only allow compression if bouncing disabled let indicatorColor = appearance.indicator.color self.indicator?.tintColor = indicatorColor ?? defaultAppearance.indicator.color! let indicatorUsesRoundedCorners = appearance.indicator.useRoundedCorners let lineIndicator = self.indicator as? TabmanLineIndicator lineIndicator?.useRoundedCorners = indicatorUsesRoundedCorners ?? defaultAppearance.indicator.useRoundedCorners! let indicatorWeight = appearance.indicator.lineWeight ?? defaultAppearance.indicator.lineWeight! if let lineIndicator = self.indicator as? TabmanLineIndicator { lineIndicator.weight = indicatorWeight } } // MARK: Actions /// Inform the TabmanViewController that an item in the bar was selected. /// /// - Parameter index: The index of the selected item. open func itemSelected(at index: Int) { responder?.bar(self, didSelectItemAt: index) } } extension TabmanBar: TabmanIndicatorDelegate { func indicator(requiresLayoutInvalidation indicator: TabmanIndicator) { self.invalidateIntrinsicContentSize() self.setNeedsLayout() self.layoutIfNeeded() } } internal extension TabmanIndicator.Style { var rawType: TabmanIndicator.Type? { switch self { case .line: return TabmanLineIndicator.self case .dot: return TabmanDotIndicator.self case .chevron: return TabmanChevronIndicator.self case .custom(let type): return type case .clear: return TabmanClearIndicator.self } } }
mit
0254859d0c083904f8e9b4ec9a789568
34.642276
138
0.626293
5.58946
false
false
false
false
aschwaighofer/swift
stdlib/public/Windows/WinSDK.swift
1
6333
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import WinSDK // Clang module // WinBase.h public let HANDLE_FLAG_INHERIT: DWORD = 0x00000001 // WinBase.h public let STARTF_USESTDHANDLES: DWORD = 0x00000100 // WinBase.h public let INFINITE: DWORD = DWORD(bitPattern: -1) // WinBase.h public let WAIT_OBJECT_0: DWORD = 0 // WinBase.h public let STD_INPUT_HANDLE: DWORD = DWORD(bitPattern: -10) public let STD_OUTPUT_HANDLE: DWORD = DWORD(bitPattern: -11) public let STD_ERROR_HANDLE: DWORD = DWORD(bitPattern: -12) // handleapi.h public let INVALID_HANDLE_VALUE: HANDLE = HANDLE(bitPattern: -1)! // shellapi.h public let FOF_NO_UI: FILEOP_FLAGS = FILEOP_FLAGS(FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR) // winioctl.h public let FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4 public let FSCTL_GET_REPARSE_POINT: DWORD = 0x900a8 public let FSCTL_DELETE_REPARSE_POINT: DWORD = 0x900ac // WinSock2.h public let INVALID_SOCKET: SOCKET = SOCKET(bitPattern: -1) public let FIONBIO: Int32 = Int32(bitPattern: 0x8004667e) // WinUser.h public let CW_USEDEFAULT: Int32 = Int32(truncatingIfNeeded: 2147483648) public let WS_OVERLAPPEDWINDOW: UINT = UINT(WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX) public let WS_POPUPWINDOW: UINT = UINT(Int32(WS_POPUP) | WS_BORDER | WS_SYSMENU) // fileapi.h public let INVALID_FILE_ATTRIBUTES: DWORD = DWORD(bitPattern: -1) // CommCtrl.h public let WC_BUTTONW: [WCHAR] = Array<WCHAR>("Button".utf16) public let WC_COMBOBOXW: [WCHAR] = Array<WCHAR>("ComboBox".utf16) public let WC_EDITW: [WCHAR] = Array<WCHAR>("Edit".utf16) public let WC_HEADERW: [WCHAR] = Array<WCHAR>("SysHeader32".utf16) public let WC_LISTBOXW: [WCHAR] = Array<WCHAR>("ListBox".utf16) public let WC_LISTVIEWW: [WCHAR] = Array<WCHAR>("SysListView32".utf16) public let WC_SCROLLBARW: [WCHAR] = Array<WCHAR>("ScrollBar".utf16) public let WC_STATICW: [WCHAR] = Array<WCHAR>("Static".utf16) public let WC_TABCONTROLW: [WCHAR] = Array<WCHAR>("SysTabControl32".utf16) public let WC_TREEVIEWW: [WCHAR] = Array<WCHAR>("SysTreeView32".utf16) public let ANIMATE_CLASSW: [WCHAR] = Array<WCHAR>("SysAnimate32".utf16) public let HOTKEY_CLASSW: [WCHAR] = Array<WCHAR>("msctls_hotkey32".utf16) public let PROGRESS_CLASSW: [WCHAR] = Array<WCHAR>("msctls_progress32".utf16) public let STATUSCLASSNAMEW: [WCHAR] = Array<WCHAR>("msctls_statusbar32".utf16) public let TOOLBARW_CLASSW: [WCHAR] = Array<WCHAR>("ToolbarWindow32".utf16) public let TRACKBAR_CLASSW: [WCHAR] = Array<WCHAR>("msctls_trackbar32".utf16) public let UPDOWN_CLASSW: [WCHAR] = Array<WCHAR>("msctls_updown32".utf16) // consoleapi.h public let PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: DWORD_PTR = 0x00020016 // windef.h public let DPI_AWARENESS_CONTEXT_UNAWARE: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(bitPattern: -1)! public let DPI_AWARENESS_CONTEXT_SYSTEM_AWARE: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(bitPattern: -2)! public let DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(bitPattern: -3)! public let DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(bitPattern: -4)! public let DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(bitPattern: -5)! // winreg.h public let HKEY_CLASSES_ROOT: HKEY = HKEY(bitPattern: 0x80000000)! public let HKEY_CURRENT_USER: HKEY = HKEY(bitPattern: 0x80000001)! public let HKEY_LOCAL_MACHINE: HKEY = HKEY(bitPattern: 0x80000002)! public let HKEY_USERS: HKEY = HKEY(bitPattern: 0x80000003)! public let HKEY_PERFORMANCE_DATA: HKEY = HKEY(bitPattern: 0x80000004)! public let HKEY_PERFORMANCE_TEXT: HKEY = HKEY(bitPattern: 0x80000050)! public let HKEY_PERFORMANCE_NLSTEXT: HKEY = HKEY(bitPattern: 0x80000060)! public let HKEY_CURRENT_CONFIG: HKEY = HKEY(bitPattern: 0x80000005)! public let HKEY_DYN_DATA: HKEY = HKEY(bitPattern: 0x80000006)! public let HKEY_CURRENT_USER_LOCAL_SETTINGS: HKEY = HKEY(bitPattern: 0x80000007)! // Swift Convenience public extension FILETIME { var time_t: time_t { let NTTime: Int64 = Int64(self.dwLowDateTime) | (Int64(self.dwHighDateTime) << 32) return (NTTime - 116444736000000000) / 10000000 } init(from time: time_t) { let UNIXTime: Int64 = ((time * 10000000) + 116444736000000000) self = FILETIME(dwLowDateTime: DWORD(UNIXTime & 0xffffffff), dwHighDateTime: DWORD((UNIXTime >> 32) & 0xffffffff)) } } // WindowsBool /// The `BOOL` type declared in WinDefs.h and used throughout WinSDK /// /// The C type is a typedef for `int`. @frozen public struct WindowsBool : ExpressibleByBooleanLiteral { @usableFromInline var _value: Int32 /// The value of `self`, expressed as a `Bool`. @_transparent public var boolValue: Bool { return !(_value == 0) } @_transparent public init(booleanLiteral value: Bool) { self.init(value) } /// Create an instance initialized to `value`. @_transparent public init(_ value: Bool) { self._value = value ? 1 : 0 } } extension WindowsBool : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: boolValue) } } extension WindowsBool : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self.boolValue.description } } extension WindowsBool : Equatable { @_transparent public static func ==(lhs: WindowsBool, rhs: WindowsBool) -> Bool { return lhs.boolValue == rhs.boolValue } } @_transparent public // COMPILER_INTRINSIC func _convertBoolToWindowsBool(_ b: Bool) -> WindowsBool { return WindowsBool(b) } @_transparent public // COMPILER_INTRINSIC func _convertWindowsBoolToBool(_ b: WindowsBool) -> Bool { return b.boolValue }
apache-2.0
a05bbb9843648715973da59fdd3816f3
34.379888
99
0.714038
3.203338
false
false
false
false
NileshJarad/shopping_cart_ios_swift
ShoppingCartTests/Login/LoginPresenterTest.swift
1
1856
// // LoginPresenterTest.swift // ShoppingCart // // Created by Nilesh Jarad on 15/09/16. // Copyright © 2016 Nilesh Jarad. All rights reserved. // import XCTest @testable import ShoppingCart class LoginPresenterTest: XCTestCase { var loginViewMocked : LoginViewMocked! var loginPresenter : LoginPresenter! override func setUp() { super.setUp() loginViewMocked = LoginViewMocked() loginPresenter = LoginPresenter(loginView: loginViewMocked) // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testUserNamePasswordWrong() { loginPresenter.doValidation("N@J", pasword: "J@N") XCTAssertTrue(loginViewMocked.showErrorMessageCalled) } // func testUserNamePasswordCorrect() { loginPresenter.doValidation("N@J", pasword: "N@J") XCTAssertTrue(loginViewMocked.showSuccessMessageCalled) } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } /* # Mocked View classes */ class LoginViewMocked : LoginView{ var showErrorMessageCalled :Bool = false var showSuccessMessageCalled :Bool = false func showErrorMessage(errorMessage: String){ self.showErrorMessageCalled = true } func showSuccessMessage(success: String){ self.showSuccessMessageCalled = true } func intializeViewAndDelegate(){ } } }
lgpl-3.0
5eecd882637754e45df6e173cdafb41a
27.106061
111
0.632884
5.040761
false
true
false
false
Mobilette/MobiletteDashboardiOS
MobiletteDashboardIOS/Classes/Modules/Root/RootWireframe.swift
1
1042
// // RootWireframe.swift // MobiletteDashboardIOS // // Created by Issouf M'sa Benaly on 9/15/15. // Copyright (c) 2015 Mobilette. All rights reserved. // import UIKit class RootWireframe { // MARK: - Presentation func presentRootViewController(fromWindow window: UIWindow) { // self.present<# Root module name #>ViewController(fromWindow: window) } /* private func present<# Root module name #>ViewController(fromWindow window: UIWindow) { let presenter = <# Root module name #>Presenter() let interactor = <# Root module name #>Interactor() // let networkController = <# Root module name #>NetworkController() let wireframe = <# Root module name #>Wireframe() // interactor.networkController = networkController interactor.output = presenter presenter.interactor = interactor presenter.wireframe = wireframe wireframe.presenter = presenter wireframe.presentInterface(fromWindow: window) } */ }
mit
cae5bde8e991f417c348ceffca4cb3b8
27.944444
89
0.65643
4.651786
false
false
false
false
xivol/MCS-V3-Mobile
examples/networking/firebase-test/FireAuthWrapper.swift
1
3227
// // FireAuthWrapper.swift // firebase-test // // Created by Илья Лошкарёв on 14.11.2017. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import Firebase import FirebaseAuthUI import FirebaseGoogleAuthUI protocol FireAuthWrapperDelegate: class { func didChangeAuth(_ auth: FireAuthWrapper, forUser user: User?) func failed(withError error: Error, onAction action: FireAuthWrapper.Action) } class FireAuthWrapper: NSObject, FUIAuthDelegate { private var didChangeAuthHandle: AuthStateDidChangeListenerHandle! public weak var delegate: FireAuthWrapperDelegate? { didSet { guard let delegate = delegate else { auth.removeStateDidChangeListener(didChangeAuthHandle) return } didChangeAuthHandle = auth.addStateDidChangeListener { (auth, user) in delegate.didChangeAuth(self, forUser: user) } } } private let auth = Auth.auth() public let ui = FUIAuth.defaultAuthUI()! public var signInController: UIViewController { let authVC = ui.authViewController() // remove cancel button authVC.navigationBar.items?[0].leftBarButtonItems = nil return authVC } public var currentUser: User? { return auth.currentUser } public var isSignedIn: Bool { return currentUser != nil } public override init() { super.init() ui.providers = [FUIGoogleAuth()] } deinit { if delegate != nil { auth.removeStateDidChangeListener(didChangeAuthHandle) } } public enum Action: String { case register, signIn, signOut, passwordReset } public func register(withEmail email: String, password: String) { auth.createUser(withEmail: email, password: password) { [weak self] (usr, error) in guard let error = error else {return} self?.delegate?.failed(withError: error, onAction: .register) } } public func signIn(withEmail email: String, password: String) { auth.signIn(withEmail: email, password: password) { [weak self] (usr, error) in guard let error = error else {return} self?.delegate?.failed(withError: error, onAction: .signIn) } } public func signOut() { print("signing out") do { try auth.signOut() } catch let error as NSError { delegate?.failed(withError: error, onAction: .signOut) } } public func passwordReset(forEmail email: String) { auth.sendPasswordReset(withEmail: email) { [weak self] (error) in guard let error = error else {return} self?.delegate?.failed(withError: error, onAction: .passwordReset) } } func authUI(_ authUI: FUIAuth, didSignInWith user: User?, error: Error?) { guard let _ = user else { delegate?.failed(withError: error!, onAction: .signIn) return } //delegate?.didChangeAuth(self, forUser: user) } }
mit
3cd6d725d41b9261eb3afff2704cf9a5
28.109091
80
0.602436
4.764881
false
false
false
false
jwolkovitzs/AMScrollingNavbar
Source/ScrollingNavbar+Sizes.swift
1
2161
import UIKit import WebKit /** Implements the main functions providing constants values and computed ones */ extension ScrollingNavigationController { // MARK: - View sizing var fullNavbarHeight: CGFloat { return navbarHeight + statusBarHeight } var navbarHeight: CGFloat { return navigationBar.frame.size.height } var statusBarHeight: CGFloat { var statusBarHeight = UIApplication.shared.statusBarFrame.size.height if #available(iOS 11.0, *) { // Account for the notch when the status bar is hidden statusBarHeight = max(UIApplication.shared.statusBarFrame.size.height, UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0) } return max(statusBarHeight - extendedStatusBarDifference, 0) } // Extended status call changes the bounds of the presented view var extendedStatusBarDifference: CGFloat { return abs(view.bounds.height - (UIApplication.shared.delegate?.window??.frame.size.height ?? UIScreen.main.bounds.height)) } var tabBarOffset: CGFloat { // Only account for the tab bar if a tab bar controller is present and the bar is not translucent if let tabBarController = tabBarController, !(topViewController?.hidesBottomBarWhenPushed ?? false) { return tabBarController.tabBar.isTranslucent ? 0 : tabBarController.tabBar.frame.height } return 0 } func scrollView() -> UIScrollView? { if let webView = self.scrollableView as? UIWebView { return webView.scrollView } else if let wkWebView = self.scrollableView as? WKWebView { return wkWebView.scrollView } else { return scrollableView as? UIScrollView } } var contentOffset: CGPoint { return scrollView()?.contentOffset ?? CGPoint.zero } var contentSize: CGSize { guard let scrollView = scrollView() else { return CGSize.zero } let verticalInset = scrollView.contentInset.top + scrollView.contentInset.bottom return CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + verticalInset) } var navbarFullHeight: CGFloat { return navbarHeight - statusBarHeight } }
mit
6a817e43b47cdc960c63f3a0f37f4fd9
31.253731
141
0.722351
4.979263
false
false
false
false
BLVudu/SkyFloatingLabelTextField
SkyFloatingLabelTextField/SkyFloatingLabelTextFieldExample/Example4/IconTextField.swift
1
3277
// Copyright 2016 Skyscanner 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 UIKit @IBDesignable public class IconTextField: SkyFloatingLabelTextField { public var iconLabel:UILabel! public var iconWidth:CGFloat = 25.0 @IBInspectable public var icon:String? { didSet { self.iconLabel?.text = icon } } // MARK: Initializers override public init(frame: CGRect) { super.init(frame: frame) self.createIconLabel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.createIconLabel() } // MARK: Creating the icon label func createIconLabel() { let iconLabel = UILabel() iconLabel.backgroundColor = UIColor.clearColor() iconLabel.textAlignment = .Center iconLabel.autoresizingMask = [.FlexibleTopMargin, .FlexibleRightMargin] self.iconLabel = iconLabel self.addSubview(iconLabel) self.updateIconLabelColor() } // MARK: Handling the icon color override public func updateColors() { super.updateColors() self.updateIconLabelColor() } private func updateIconLabelColor() { if self.hasErrorMessage { self.iconLabel?.textColor = self.errorColor } else { self.iconLabel?.textColor = self.editing ? self.selectedLineColor : self.lineColor } } // MARK: Custom layout overrides override public func textRectForBounds(bounds: CGRect) -> CGRect { var rect = super.textRectForBounds(bounds) if (isLTRLanguage) { rect.origin.x += iconWidth } else { rect.origin.x = 0 } rect.size.width -= iconWidth return rect } override public func editingRectForBounds(bounds: CGRect) -> CGRect { var rect = super.textRectForBounds(bounds) rect.origin.x += iconWidth - iconWidth rect.size.width -= iconWidth return rect } override public func placeholderRectForBounds(bounds: CGRect) -> CGRect { var rect = super.placeholderRectForBounds(bounds) rect.origin.x += iconWidth rect.size.width -= iconWidth return rect } override public func layoutSubviews() { super.layoutSubviews() let textHeight = self.textHeight() let textWidth:CGFloat = self.bounds.size.width if (isLTRLanguage) { self.iconLabel.frame = CGRectMake(0, self.bounds.size.height - textHeight, iconWidth, textHeight) } else { self.iconLabel.frame = CGRectMake(textWidth - iconWidth, self.bounds.size.height - textHeight, iconWidth, textHeight) } } }
apache-2.0
69e0182992862f1cec1bbe1d94112c80
31.127451
309
0.644797
4.913043
false
false
false
false
victorpimentel/SwiftLint
Source/SwiftLintFramework/Rules/ProtocolPropertyAccessorsOrderRule.swift
2
2523
// // ProtocolPropertyAccessorsOrderRule.swift // SwiftLint // // Created by Marcelo Fabri on 15/05/17. // Copyright © 2017 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct ProtocolPropertyAccessorsOrderRule: ConfigurationProviderRule, CorrectableRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "protocol_property_accessors_order", name: "Protocol Property Accessors Order", description: "When declaring properties in protocols, the order of accessors should be `get set`.", nonTriggeringExamples: [ "protocol Foo {\n var bar: String { get set }\n }", "protocol Foo {\n var bar: String { get }\n }", "protocol Foo {\n var bar: String { set }\n }" ], triggeringExamples: [ "protocol Foo {\n var bar: String { ↓set get }\n }" ], corrections: [ "protocol Foo {\n var bar: String { ↓set get }\n }": "protocol Foo {\n var bar: String { get set }\n }" ] ) public func validate(file: File) -> [StyleViolation] { return violationRanges(file: file).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } private func violationRanges(file: File) -> [NSRange] { return file.match(pattern: "\\bset\\s*get\\b", with: [.keyword, .keyword]) } public func correct(file: File) -> [Correction] { let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(file: file), for: self) var correctedContents = file.contents var adjustedLocations = [Int]() for violatingRange in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents .replacingCharacters(in: indexRange, with: "get set") adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } }
mit
70f85786249bf11f78aab5c397883596
36.029412
107
0.615171
4.759924
false
true
false
false
githubError/KaraNotes
KaraNotes/KaraNotes/MyArticle/Model/CPFMyArticleModel.swift
1
2726
// // CPFMyArticleModel.swift // KaraNotes // // Created by 崔鹏飞 on 2017/4/19. // Copyright © 2017年 崔鹏飞. All rights reserved. // import Foundation struct CPFMyArticleModel { var abstract_content:String var article_attachment:String var article_create_time:TimeInterval var article_id:String var article_show_img:String var article_title:String var article_update_time:UInt16 var classify_id:String var collect_num:Int var comment_num:Int var praise_num:Int var user_id:String var article_create_formatTime:String { return timestampToString(timestamp: article_create_time) } var article_show_img_URL:URL { return URL(string: article_show_img)! } } extension CPFMyArticleModel { static func parse(json: JSONDictionary) -> CPFMyArticleModel { guard let abstract_content = json["abstract_content"] as? String else {fatalError("解析CPFMyArticleModel出错")} guard let article_attachment = json["article_attachment"] as? String else {fatalError("解析CPFMyArticleModel出错")} guard let article_create_time = json["article_create_time"] as? TimeInterval else {fatalError("解析CPFMyArticleModel出错")} guard let article_id = json["article_id"] as? String else {fatalError("解析CPFMyArticleModel出错")} guard let article_show_img = json["article_show_img"] as? String else {fatalError("解析CPFMyArticleModel出错")} guard let article_title = json["article_title"] as? String else {fatalError("解析CPFMyArticleModel出错")} guard let article_update_time = json["article_update_time"] as? UInt16 else {fatalError("解析CPFMyArticleModel出错")} guard let classify_id = json["classify_id"] as? String else {fatalError("解析CPFMyArticleModel出错")} guard let collect_num = json["collect_num"] as? Int else {fatalError("解析CPFMyArticleModel出错")} guard let comment_num = json["comment_num"] as? Int else {fatalError("解析CPFMyArticleModel出错")} guard let praise_num = json["praise_num"] as? Int else {fatalError("解析CPFMyArticleModel出错")} guard let user_id = json["user_id"] as? String else {fatalError("解析CPFMyArticleModel出错")} return CPFMyArticleModel(abstract_content: abstract_content, article_attachment: article_attachment, article_create_time: article_create_time, article_id: article_id, article_show_img: article_show_img, article_title: article_title, article_update_time: article_update_time, classify_id: classify_id, collect_num: collect_num, comment_num: comment_num, praise_num: praise_num, user_id: user_id) } }
apache-2.0
33dd3b3abda46bd7acce3fd1fffd538a
46.545455
402
0.707075
3.823099
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/System/3DTouch/WP3DTouchShortcutCreator.swift
1
7164
import UIKit public class WP3DTouchShortcutCreator: NSObject { enum LoggedIn3DTouchShortcutIndex: Int { case Notifications = 0, Stats, NewPhotoPost, NewPost } var application: UIApplication! var mainContext: NSManagedObjectContext! var blogService: BlogService! private let logInShortcutIconImageName = "icon-shortcut-signin" private let notificationsShortcutIconImageName = "icon-shortcut-notifications" private let statsShortcutIconImageName = "icon-shortcut-stats" private let newPhotoPostShortcutIconImageName = "icon-shortcut-new-photo" private let newPostShortcutIconImageName = "icon-shortcut-new-post" override public init() { super.init() application = UIApplication.sharedApplication() mainContext = ContextManager.sharedInstance().mainContext blogService = BlogService(managedObjectContext: mainContext) } public func createShortcutsIf3DTouchAvailable(loggedIn: Bool) { if !is3DTouchAvailable() { return } if loggedIn { if hasBlog() { createLoggedInShortcuts() } else { clearShortcuts() } } else { createLoggedOutShortcuts() } } private func loggedOutShortcutArray() -> [UIApplicationShortcutItem] { let logInShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.LogIn.type, localizedTitle: NSLocalizedString("Sign In", comment: "Sign In 3D Touch Shortcut"), localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: logInShortcutIconImageName), userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.LogIn.rawValue]) return [logInShortcut] } private func loggedInShortcutArray() -> [UIApplicationShortcutItem] { var defaultBlogName: String? if blogService.blogCountForAllAccounts() > 1 { defaultBlogName = blogService.lastUsedOrFirstBlog()?.settings?.name } let notificationsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.type, localizedTitle: NSLocalizedString("Notifications", comment: "Notifications 3D Touch Shortcut"), localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: notificationsShortcutIconImageName), userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.rawValue]) let statsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Stats.type, localizedTitle: NSLocalizedString("Stats", comment: "Stats 3D Touch Shortcut"), localizedSubtitle: defaultBlogName, icon: UIApplicationShortcutIcon(templateImageName: statsShortcutIconImageName), userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.Stats.rawValue]) let newPhotoPostShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPhotoPost.type, localizedTitle: NSLocalizedString("New Photo Post", comment: "New Photo Post 3D Touch Shortcut"), localizedSubtitle: defaultBlogName, icon: UIApplicationShortcutIcon(templateImageName: newPhotoPostShortcutIconImageName), userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPhotoPost.rawValue]) let newPostShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPost.type, localizedTitle: NSLocalizedString("New Post", comment: "New Post 3D Touch Shortcut"), localizedSubtitle: defaultBlogName, icon: UIApplicationShortcutIcon(templateImageName: newPostShortcutIconImageName), userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPost.rawValue]) return [notificationsShortcut, statsShortcut, newPhotoPostShortcut, newPostShortcut] } private func createLoggedInShortcuts() { var entireShortcutArray = loggedInShortcutArray() var visibleShortcutArray = [UIApplicationShortcutItem]() if hasWordPressComAccount() { visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.Notifications.rawValue]) } if doesCurrentBlogSupportStats() { visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.Stats.rawValue]) } visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.NewPhotoPost.rawValue]) visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.NewPost.rawValue]) application.shortcutItems = visibleShortcutArray } private func clearShortcuts() { application.shortcutItems = nil } private func createLoggedOutShortcuts() { application.shortcutItems = loggedOutShortcutArray() } private func is3DTouchAvailable() -> Bool { let window = UIApplication.sharedApplication().keyWindow return window?.traitCollection.forceTouchCapability == .Available } private func hasWordPressComAccount() -> Bool { let accountService = AccountService(managedObjectContext: mainContext) return accountService.defaultWordPressComAccount() != nil } private func doesCurrentBlogSupportStats() -> Bool { guard let currentBlog = blogService.lastUsedOrFirstBlog() else { return false } return hasWordPressComAccount() && currentBlog.supports(BlogFeature.Stats) } private func hasBlog() -> Bool { return blogService.blogCountForAllAccounts() > 0 } }
gpl-2.0
b70fded4924b386ea19c19b7a4c21bc1
51.291971
205
0.621161
7.446985
false
false
false
false
kickstarter/ios-oss
KsApi/models/graphql/adapters/Project.Country+CountryFragment.swift
1
1045
import Prelude extension Project.Country { static func country(from countryFragment: GraphAPI.CountryFragment, minPledge: Int, maxPledge: Int, currency: GraphAPI.CurrencyCode) -> Project.Country? { guard let countryWithCurrencyDefault = Project.Country.all .first(where: { $0.countryCode == countryFragment.code.rawValue }) else { return nil } var updatedCountryWithProjectCurrency = countryWithCurrencyDefault |> Project.Country.lens.minPledge .~ minPledge |> Project.Country.lens.maxPledge .~ maxPledge |> Project.Country.lens.currencyCode .~ currency.rawValue if let matchingCurrencySymbol = Project.Country.all .first(where: { $0.currencyCode.lowercased() == currency.rawValue.lowercased() })?.currencySymbol { updatedCountryWithProjectCurrency = updatedCountryWithProjectCurrency |> Project.Country.lens.currencySymbol .~ matchingCurrencySymbol } return updatedCountryWithProjectCurrency } }
apache-2.0
891ac6b122c8e25667285203911d3f1b
39.192308
105
0.698565
4.952607
false
false
false
false
euajudo/ios
euajudo/View/CampaignCell.swift
1
2529
// // CampaignCell.swift // euajudo // // Created by Rafael Kellermann Streit on 4/11/15. // Copyright (c) 2015 euajudo. All rights reserved. // import UIKit class CampaignCell: UICollectionViewCell { var campaign: Campaign? var progressView: CampaignGoalView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var labelDescription: UILabel! @IBOutlet weak var playImage: UIImageView! @IBOutlet weak var userName: UILabel! override func drawRect(rect: CGRect) { super.drawRect(rect) progressView = NSBundle.mainBundle().loadNibNamed("CampaignGoalView", owner: self, options: nil)[0] as! CampaignGoalView self.containerView.addSubview(progressView) self.containerView.bringSubviewToFront(progressView.progress) let frameSize = progressView.frame progressView.frame = CGRectMake(progressView.frame.origin.x, self.frame.size.height - frameSize.height, self.frame.size.width, frameSize.height) progressView.setNeedsLayout() progressView.layoutIfNeeded() progressView.layoutSubviews() progressView?.campaign = campaign self.applyCardPattern() } override func layoutSubviews() { super.layoutSubviews() self.applyCardPattern() switch self.campaign!.mainMedia.type { case .Image: self.playImage.alpha = 0.0 case .Video: self.playImage.alpha = 1.0 } } func applyCardPattern() { let shadowPath = UIBezierPath(rect: self.containerView.bounds) self.layer.masksToBounds = false; self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowOffset = CGSizeMake(1.0, 1.0); self.layer.shadowOpacity = 0.2; self.layer.shadowPath = shadowPath.CGPath; self.layer.cornerRadius = 3.0; self.contentView.layer.cornerRadius = 1.5 self.contentView.clipsToBounds = true } func updateInformations() { labelTitle.text = campaign?.name labelDescription.text = campaign?.description userName.text = campaign?.user["name"]! unowned let weakSelf = self campaign?.mainMedia.image({ (image) -> Void in weakSelf.imageView.image = image }) progressView?.campaign = campaign } }
mit
38e976c99921916948c6a4d26195f895
30.222222
152
0.639779
4.817143
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Renderers/LineChartRenderer.swift
6
25219
// // LineChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIFont @objc public protocol LineChartRendererDelegate { func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData!; func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!; func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter; func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter!; func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Float; func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Float; func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Float; func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Float; func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int; } public class LineChartRenderer: ChartDataRendererBase { public weak var delegate: LineChartRendererDelegate?; public init(delegate: LineChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler); self.delegate = delegate; } public override func drawData(#context: CGContext) { var lineData = delegate!.lineChartRendererData(self); if (lineData === nil) { return; } for (var i = 0; i < lineData.dataSetCount; i++) { var set = lineData.getDataSetByIndex(i); if (set !== nil && set!.isVisible) { drawDataSet(context: context, dataSet: set as! LineChartDataSet); } } } internal struct CGCPoint { internal var x: CGFloat = 0.0; internal var y: CGFloat = 0.0; /// x-axis distance internal var dx: CGFloat = 0.0; /// y-axis distance internal var dy: CGFloat = 0.0; internal init(x: CGFloat, y: CGFloat) { self.x = x; self.y = y; } } internal func drawDataSet(#context: CGContext, dataSet: LineChartDataSet) { var lineData = delegate!.lineChartRendererData(self); var entries = dataSet.yVals; if (entries.count < 1) { return; } CGContextSaveGState(context); CGContextSetLineWidth(context, dataSet.lineWidth); if (dataSet.lineDashLengths != nil) { CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths, dataSet.lineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } // if drawing cubic lines is enabled if (dataSet.isDrawCubicEnabled) { drawCubic(context: context, dataSet: dataSet, entries: entries); } else { // draw normal (straight) lines drawLinear(context: context, dataSet: dataSet, entries: entries); } CGContextRestoreGState(context); } internal func drawCubic(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry]) { var trans = delegate?.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency); var entryFrom = dataSet.entryForXIndex(_minX); var entryTo = dataSet.entryForXIndex(_maxX); var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0); var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count); var phaseX = _animator.phaseX; var phaseY = _animator.phaseY; // get the color that is specified for this position from the DataSet var drawingColor = dataSet.colors.first!; var intensity = dataSet.cubicIntensity; // the path for the cubic-spline var cubicPath = CGPathCreateMutable(); var valueToPixelMatrix = trans!.valueToPixelMatrix; var size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); if (size - minx >= 2) { var prevDx: CGFloat = 0.0; var prevDy: CGFloat = 0.0; var curDx: CGFloat = 0.0; var curDy: CGFloat = 0.0; var prevPrev = entries[minx]; var prev = entries[minx]; var cur = entries[minx]; var next = entries[minx + 1]; // let the spline start CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY); prevDx = CGFloat(cur.xIndex - prev.xIndex) * intensity; prevDy = CGFloat(cur.value - prev.value) * intensity; curDx = CGFloat(next.xIndex - cur.xIndex) * intensity; curDy = CGFloat(next.value - cur.value) * intensity; // the first cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY); for (var j = minx + 1, count = min(size, entries.count - 1); j < count; j++) { prevPrev = entries[j == 1 ? 0 : j - 2]; prev = entries[j - 1]; cur = entries[j]; next = entries[j + 1]; prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity; prevDy = CGFloat(cur.value - prevPrev.value) * intensity; curDx = CGFloat(next.xIndex - prev.xIndex) * intensity; curDy = CGFloat(next.value - prev.value) * intensity; CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY); } if (size > entries.count - 1) { prevPrev = entries[entries.count - (entries.count >= 3 ? 3 : 2)]; prev = entries[entries.count - 2]; cur = entries[entries.count - 1]; next = cur; prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity; prevDy = CGFloat(cur.value - prevPrev.value) * intensity; curDx = CGFloat(next.xIndex - prev.xIndex) * intensity; curDy = CGFloat(next.value - prev.value) * intensity; // the last cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY); } } CGContextSaveGState(context); if (dataSet.isDrawFilledEnabled) { drawCubicFill(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix, from: minx, to: size); } CGContextBeginPath(context); CGContextAddPath(context, cubicPath); CGContextSetStrokeColorWithColor(context, drawingColor.CGColor); CGContextStrokePath(context); CGContextRestoreGState(context); } internal func drawCubicFill(#context: CGContext, dataSet: LineChartDataSet, spline: CGMutablePath, var matrix: CGAffineTransform, from: Int, to: Int) { CGContextSaveGState(context); var fillMin = delegate!.lineChartRendererFillFormatter(self).getFillLinePosition( dataSet: dataSet, data: delegate!.lineChartRendererData(self), chartMaxY: delegate!.lineChartRendererChartYMax(self), chartMinY: delegate!.lineChartRendererChartYMin(self)); var pt1 = CGPoint(x: CGFloat(to - 1), y: fillMin); var pt2 = CGPoint(x: CGFloat(from), y: fillMin); pt1 = CGPointApplyAffineTransform(pt1, matrix); pt2 = CGPointApplyAffineTransform(pt2, matrix); CGContextBeginPath(context); CGContextAddPath(context, spline); CGContextAddLineToPoint(context, pt1.x, pt1.y); CGContextAddLineToPoint(context, pt2.x, pt2.y); CGContextClosePath(context); CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor); CGContextSetAlpha(context, dataSet.fillAlpha); CGContextFillPath(context); CGContextRestoreGState(context); } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()); internal func drawLinear(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry]) { var lineData = delegate!.lineChartRendererData(self); var dataSetIndex = lineData.indexOfDataSet(dataSet); var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency); var valueToPixelMatrix = trans.valueToPixelMatrix; var phaseX = _animator.phaseX; var phaseY = _animator.phaseY; var pointBuffer = CGPoint(); CGContextSaveGState(context); var entryFrom = dataSet.entryForXIndex(_minX); var entryTo = dataSet.entryForXIndex(_maxX); var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0); var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count); // more than 1 color if (dataSet.colors.count > 1) { if (_lineSegments.count != 2) { _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()); } for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { if (count > 1 && j == count - 1) { // Last point, we have already drawn a line to this point break; } var e = entries[j]; _lineSegments[0].x = CGFloat(e.xIndex); _lineSegments[0].y = CGFloat(e.value) * phaseY; _lineSegments[0] = CGPointApplyAffineTransform(_lineSegments[0], valueToPixelMatrix); if (j + 1 < count) { e = entries[j + 1]; _lineSegments[1].x = CGFloat(e.xIndex); _lineSegments[1].y = CGFloat(e.value) * phaseY; _lineSegments[1] = CGPointApplyAffineTransform(_lineSegments[1], valueToPixelMatrix); } else { _lineSegments[1] = _lineSegments[0]; } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break; } // make sure the lines don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))) { continue; } // get the color that is set for this line-segment CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor); CGContextStrokeLineSegments(context, _lineSegments, 2); } } else { // only one color per dataset var e1: ChartDataEntry!; var e2: ChartDataEntry!; if (_lineSegments.count != max((entries.count - 1) * 2, 2)) { _lineSegments = [CGPoint](count: max((entries.count - 1) * 2, 2), repeatedValue: CGPoint()); } e1 = entries[minx]; var count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); for (var x = count > 1 ? minx + 1 : minx, j = 0; x < count; x++) { e1 = entries[x == 0 ? 0 : (x - 1)]; e2 = entries[x]; _lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY), valueToPixelMatrix); _lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY), valueToPixelMatrix); } var size = max((count - minx - 1) * 2, 2) CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor); CGContextStrokeLineSegments(context, _lineSegments, size); } CGContextRestoreGState(context); // if drawing filled is enabled if (dataSet.isDrawFilledEnabled && entries.count > 0) { drawLinearFill(context: context, dataSet: dataSet, entries: entries, minx: minx, maxx: maxx, trans: trans); } } internal func drawLinearFill(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry], minx: Int, maxx: Int, trans: ChartTransformer) { CGContextSaveGState(context); CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor); // filled is usually drawn with less alpha CGContextSetAlpha(context, dataSet.fillAlpha); var filled = generateFilledPath( entries, fillMin: delegate!.lineChartRendererFillFormatter(self).getFillLinePosition( dataSet: dataSet, data: delegate!.lineChartRendererData(self), chartMaxY: delegate!.lineChartRendererChartYMax(self), chartMinY: delegate!.lineChartRendererChartYMin(self)), from: minx, to: maxx, matrix: trans.valueToPixelMatrix); CGContextBeginPath(context); CGContextAddPath(context, filled); CGContextFillPath(context); CGContextRestoreGState(context); } /// Generates the path that is used for filled drawing. private func generateFilledPath(entries: [ChartDataEntry], fillMin: CGFloat, from: Int, to: Int, var matrix: CGAffineTransform) -> CGPath { var point = CGPoint(); var phaseX = _animator.phaseX; var phaseY = _animator.phaseY; var filled = CGPathCreateMutable(); CGPathMoveToPoint(filled, &matrix, CGFloat(entries[from].xIndex), fillMin); CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[from].xIndex), CGFloat(entries[from].value) * phaseY); // create a new path for (var x = from + 1, count = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))); x < count; x++) { var e = entries[x]; CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY); } // close up CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, entries.count - 1), 0)].xIndex), fillMin); CGPathCloseSubpath(filled); return filled; } public override func drawValues(#context: CGContext) { var lineData = delegate!.lineChartRendererData(self); if (lineData === nil) { return; } var defaultValueFormatter = delegate!.lineChartDefaultRendererValueFormatter(self); if (CGFloat(lineData.yValCount) < CGFloat(delegate!.lineChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX) { var dataSets = lineData.dataSets; for (var i = 0; i < dataSets.count; i++) { var dataSet = dataSets[i] as! LineChartDataSet; if (!dataSet.isDrawValuesEnabled) { continue; } var valueFont = dataSet.valueFont; var valueTextColor = dataSet.valueTextColor; var formatter = dataSet.valueFormatter; if (formatter === nil) { formatter = defaultValueFormatter; } var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency); // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75); if (!dataSet.isDrawCirclesEnabled) { valOffset = valOffset / 2; } var entries = dataSet.yVals; var entryFrom = dataSet.entryForXIndex(_minX); var entryTo = dataSet.entryForXIndex(_maxX); var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0); var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count); var positions = trans.generateTransformedValuesLine( entries, phaseX: _animator.phaseX, phaseY: _animator.phaseY, from: minx, to: maxx); for (var j = 0, count = positions.count; j < count; j++) { if (!viewPortHandler.isInBoundsRight(positions[j].x)) { break; } if (!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y)) { continue; } var val = entries[j + minx].value; ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: positions[j].x, y: positions[j].y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]); } } } } public override func drawExtras(#context: CGContext) { drawCircles(context: context); } private func drawCircles(#context: CGContext) { var phaseX = _animator.phaseX; var phaseY = _animator.phaseY; var lineData = delegate!.lineChartRendererData(self); var dataSets = lineData.dataSets; var pt = CGPoint(); var rect = CGRect(); CGContextSaveGState(context); for (var i = 0, count = dataSets.count; i < count; i++) { var dataSet = lineData.getDataSetByIndex(i) as! LineChartDataSet!; if (!dataSet.isVisible || !dataSet.isDrawCirclesEnabled) { continue; } var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency); var valueToPixelMatrix = trans.valueToPixelMatrix; var entries = dataSet.yVals; var circleRadius = dataSet.circleRadius; var circleDiameter = circleRadius * 2.0; var circleHoleDiameter = circleRadius; var circleHoleRadius = circleHoleDiameter / 2.0; var isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled; var entryFrom = dataSet.entryForXIndex(_minX); var entryTo = dataSet.entryForXIndex(_maxX); var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0); var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count); for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { var e = entries[j]; pt.x = CGFloat(e.xIndex); pt.y = CGFloat(e.value) * phaseY; pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix); if (!viewPortHandler.isInBoundsRight(pt.x)) { break; } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue; } CGContextSetFillColorWithColor(context, dataSet.getCircleColor(j)!.CGColor); rect.origin.x = pt.x - circleRadius; rect.origin.y = pt.y - circleRadius; rect.size.width = circleDiameter; rect.size.height = circleDiameter; CGContextFillEllipseInRect(context, rect); if (isDrawCircleHoleEnabled) { CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor); rect.origin.x = pt.x - circleHoleRadius; rect.origin.y = pt.y - circleHoleRadius; rect.size.width = circleHoleDiameter; rect.size.height = circleHoleDiameter; CGContextFillEllipseInRect(context, rect); } } } CGContextRestoreGState(context); } var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint()); public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { var lineData = delegate!.lineChartRendererData(self); var chartXMax = delegate!.lineChartRendererChartXMax(self); var chartYMax = delegate!.lineChartRendererChartYMax(self); var chartYMin = delegate!.lineChartRendererChartYMin(self); CGContextSaveGState(context); for (var i = 0; i < indices.count; i++) { var set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as! LineChartDataSet!; if (set === nil) { continue; } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor); CGContextSetLineWidth(context, set.highlightLineWidth); if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX) { continue; } var y = CGFloat(set.yValForXIndex(xIndex)) * _animator.phaseY; // get the y-position _highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMax)); _highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMin)); _highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.lineChartRendererChartXMin(self)), y: y); _highlightPtsBuffer[3] = CGPoint(x: CGFloat(chartXMax), y: y); var trans = delegate!.lineChartRenderer(self, transformerForAxis: set.axisDependency); trans.pointValuesToPixel(&_highlightPtsBuffer); // draw the highlight lines CGContextStrokeLineSegments(context, _highlightPtsBuffer, 4); } CGContextRestoreGState(context); } }
gpl-2.0
f2345cdca13ea8c5cb1b4c2c4194b006
38.968304
307
0.55256
5.509941
false
false
false
false
piars777/TheMovieDatabaseSwiftWrapper
Sources/Models/Discover/DiscoverTV.swift
1
6826
// // DiscoverTV.swift // TheMovieDBWrapperSwift // // Created by George on 2016-02-05. // Copyright © 2016 GeorgeKye. All rights reserved. // import Foundation public enum TVGenres: String{ case Action_Adventure = "10759"; case Animation = "16"; case Comedy = "35"; case Documentary = "99"; case Drama = "18"; case Education = "10761"; case Family = "10751"; case Kids = "10762"; case Mystery = "9648"; case News = "10763"; case Reality = "10764"; case ScifiFantasy = "10765"; case Soap = "10766"; case Talk = "10767"; case WarPolitics = "10768"; case Western = "37"; } public class DiscoverTVMDB: DiscoverMDB { // ///DiscoverTV query. Language must be an ISO 639-1 code. Page must be greater than one. sort_by expected values can be found in DiscoverSortBy() and DiscoverSortByTV class variables. ALL parameters are optional public class func discoverTV(api_key: String, language: String?, sort_by: String?, page: Double?, completionHandler: (clientReturn: ClientReturn, data: [TVMDB]?) -> ()) -> (){ Client.discover(api_key, baseURL: "tv", sort_by: sort_by, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: nil, air_date_lte: nil, first_air_date_gte: nil, first_air_date_lte: nil, first_air_date_year: nil, language: language, page: page, timezone: nil, vote_average_gte: nil, vote_average_lte: nil, vote_count_gte: nil, vote_count_lte: nil, with_genres: nil, with_cast: nil, with_crew: nil, with_companies: nil, with_keywords: nil, with_people: nil, with_networks: nil, year: nil, certification_gte: nil){ apiReturn in var data: [TVMDB]? if(apiReturn.error == nil){ data = TVMDB.initialize(json: apiReturn.json!["results"]) } completionHandler(clientReturn: apiReturn, data: data) } } ///lte = The minimum. gte = maximum. Expected date format is YYYY-MM-DD. Excpected year format is (####) ie.2010. ALL parameters are optional public class func discoverTV(api_key: String, first_air_date_year: String?, first_air_date_gte: String?, first_air_date_lte: String?, air_date_gte: String?, air_date_lte: String?, language: String?, sort_by: String?, page: Double?, timezone: String?, completionHandler: (clientReturn: ClientReturn, data: [TVMDB]?) -> ()) -> (){ Client.discover(api_key, baseURL: "tv", sort_by: sort_by, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: air_date_gte, air_date_lte: air_date_lte, first_air_date_gte: first_air_date_gte, first_air_date_lte: first_air_date_lte, first_air_date_year: first_air_date_year, language: language, page: page, timezone: timezone, vote_average_gte: nil, vote_average_lte: nil, vote_count_gte: nil, vote_count_lte: nil, with_genres: nil, with_cast: nil, with_crew: nil, with_companies: nil, with_keywords: nil, with_people: nil, with_networks: nil, year: nil, certification_gte: nil){ apiReturn in var data: [TVMDB]? if(apiReturn.error == nil){ data = TVMDB.initialize(json: apiReturn.json!["results"]) } completionHandler(clientReturn: apiReturn, data: data) } } ////DiscoverTV query. Language must be an ISO 639-1 code. Page must be greater than one. sort_by expected values can be found in DiscoverSortBy() and DiscoverSortByTV class variables. lte = The minimum. gte = maximum. Expected date format is YYYY-MM-DD. Excpected year format is (####) ie.2010. ALL parameters are optional public class func discoverTV(api_key: String, language: String?, sort_by: String?, page: Double?, first_air_date_year: String?, first_air_date_gte: String?, first_air_date_lte: String?, air_date_gte: String?, air_date_lte: String?, timezone: String?, vote_average_gte: Double?, vote_count_gte: Double?, with_genres: String?, with_networks: String?, completionHandler: (clientReturn: ClientReturn, data: [TVMDB]?) -> ()) -> (){ Client.discover(api_key, baseURL: "tv", sort_by: sort_by, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: air_date_gte, air_date_lte: air_date_lte, first_air_date_gte: first_air_date_gte, first_air_date_lte: first_air_date_lte, first_air_date_year: first_air_date_year, language: language, page: page, timezone: timezone, vote_average_gte: vote_average_gte, vote_average_lte: nil, vote_count_gte: vote_count_gte, vote_count_lte: nil, with_genres: with_genres, with_cast: nil, with_crew: nil, with_companies: nil, with_keywords: nil, with_people: nil, with_networks: with_networks, year: nil, certification_gte: nil){ apiReturn in var data: [TVMDB]? if(apiReturn.error == nil){ data = TVMDB.initialize(json: apiReturn.json!["results"]) } completionHandler(clientReturn: apiReturn, data: data) } } //Discover tv shows with public class func discoverTVWith(api_key: String, with_genres: String?, with_networks: String?, sort_by: String?, language: String?, page: Double?, completionHandler: (clientReturn: ClientReturn, data: [TVMDB]?) -> ()) -> (){ Client.discover(api_key, baseURL: "tv", sort_by: sort_by, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: nil, air_date_lte: nil, first_air_date_gte: nil, first_air_date_lte: nil, first_air_date_year: nil, language: language, page: page, timezone: nil, vote_average_gte: nil, vote_average_lte: nil, vote_count_gte: nil, vote_count_lte: nil, with_genres: with_genres, with_cast: nil, with_crew: nil, with_companies: nil, with_keywords: nil, with_people: nil, with_networks: with_networks, year: nil, certification_gte: nil){ apiReturn in var data: [TVMDB]? if(apiReturn.error == nil){ data = TVMDB.initialize(json: apiReturn.json!["results"]) } completionHandler(clientReturn: apiReturn, data: data) } } }
mit
b8985aaa86260887d58d95ba740533ec
78.372093
837
0.673993
3.521672
false
false
false
false
glorybird/KeepReading2
kr/kr/ui/ViewController.swift
1
1486
// // ViewController.swift // kr // // Created by FanFamily on 16/1/20. // Copyright © 2016年 glorybird. All rights reserved. // import UIKit class ViewController: UIViewController, SideMenuBuilderDelegate { var readListVC:ReadListViewController? var builder:SideMenuBuilder? override func viewDidLoad() { super.viewDidLoad() let menuVC:MenuViewController = MenuViewController() readListVC = ReadListViewController() let menuButton:UIButton = UIButton(type: UIButtonType.System) menuButton.frame = CGRectMake(0, 0, 50, 50) menuButton.setTitle("...", forState: UIControlState.Normal) builder = SideMenuBuilder(containVC: self, leftVC: menuVC, rightVC: readListVC!, menuButton:menuButton) builder!.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() builder!.build() } func willChangeLeftSpace(space: CGFloat) { if space == 0 { self.readListVC!.collectionView.frame.size.width = self.readListVC!.view.frame.width } } func didChangeLeftSpace(space: CGFloat) { if space > 0 { self.readListVC!.collectionView.frame.size.width = self.readListVC!.view.frame.width - space } } }
apache-2.0
e0af661ccb89b994733146b42d612cde
27.519231
111
0.652057
4.783871
false
false
false
false
pixel-ink/PIRipple
PIRipple/PIRipple.swift
1
6836
//--------------------------------------- // https://github.com/pixel-ink/PIRipple //--------------------------------------- import UIKit public extension UIView { public func rippleBorder(location:CGPoint, color:UIColor) { rippleBorder(location, color: color){} } public func rippleBorder(location:CGPoint, color:UIColor, then: ()->() ) { Ripple.border(self, locationInView: location, color: color, then: then) } public func rippleFill(location:CGPoint, color:UIColor) { rippleFill(location, color: color){} } public func rippleFill(location:CGPoint, color:UIColor, then: ()->() ) { Ripple.fill(self, locationInView: location, color: color, then: then) } public func rippleStop() { Ripple.stop(self) } } public class Ripple { private static var targetLayer: CALayer? public struct Option { public var borderWidth = CGFloat(5.0) public var radius = CGFloat(30.0) public var duration = CFTimeInterval(0.4) public var borderColor = UIColor.whiteColor() public var fillColor = UIColor.clearColor() public var scale = CGFloat(3.0) public var isRunSuperView = true } public class func option () -> Option { return Option() } public class func run(view:UIView, locationInView:CGPoint, option:Ripple.Option) { run(view, locationInView: locationInView, option: option){} } public class func run(view:UIView, locationInView:CGPoint, option:Ripple.Option, then: ()->() ) { prePreform(view, point: locationInView, option: option, isLocationInView: true, then: then) } public class func run(view:UIView, absolutePosition:CGPoint, option:Ripple.Option) { run(view, absolutePosition: absolutePosition, option: option){} } public class func run(view:UIView, absolutePosition:CGPoint, option:Ripple.Option, then: ()->() ) { prePreform(view, point: absolutePosition, option: option, isLocationInView: false, then: then) } public class func border(view:UIView, locationInView:CGPoint, color:UIColor) { border(view, locationInView: locationInView, color: color){} } public class func border(view:UIView, locationInView:CGPoint, color:UIColor, then: ()->() ) { var opt = Ripple.Option() opt.borderColor = color prePreform(view, point: locationInView, option: opt, isLocationInView: true, then: then) } public class func border(view:UIView, absolutePosition:CGPoint, color:UIColor) { border(view, absolutePosition: absolutePosition, color: color){} } public class func border(view:UIView, absolutePosition:CGPoint, color:UIColor, then: ()->() ) { var opt = Ripple.Option() opt.borderColor = color prePreform(view, point: absolutePosition, option: opt, isLocationInView: false, then: then) } public class func fill(view:UIView, locationInView:CGPoint, color:UIColor) { fill(view, locationInView: locationInView, color: color){} } public class func fill(view:UIView, locationInView:CGPoint, color:UIColor, then: ()->() ) { var opt = Ripple.Option() opt.borderColor = color opt.fillColor = color prePreform(view, point: locationInView, option: opt, isLocationInView: true, then: then) } public class func fill(view:UIView, absolutePosition:CGPoint, color:UIColor) { fill(view, absolutePosition: absolutePosition, color: color){} } public class func fill(view:UIView, absolutePosition:CGPoint, color:UIColor, then: ()->() ) { var opt = Ripple.Option() opt.borderColor = color opt.fillColor = color prePreform(view, point: absolutePosition, option: opt, isLocationInView: false, then: then) } private class func prePreform(view:UIView, point:CGPoint, option: Ripple.Option, isLocationInView:Bool, then: ()->() ) { let p = isLocationInView ? CGPointMake(point.x + view.frame.origin.x, point.y + view.frame.origin.y) : point if option.isRunSuperView, let superview = view.superview { prePreform( superview, point: p, option: option, isLocationInView: isLocationInView, then: then ) } else { perform( view, point:p, option:option, then: then ) } } private class func perform(view:UIView, point:CGPoint, option: Ripple.Option, then: ()->() ) { UIGraphicsBeginImageContextWithOptions ( CGSizeMake((option.radius + option.borderWidth) * 2, (option.radius + option.borderWidth) * 2), false, 3.0) let path = UIBezierPath( roundedRect: CGRectMake(option.borderWidth, option.borderWidth, option.radius * 2, option.radius * 2), cornerRadius: option.radius) option.fillColor.setFill() path.fill() option.borderColor.setStroke() path.lineWidth = option.borderWidth path.stroke() let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let opacity = CABasicAnimation(keyPath: "opacity") opacity.autoreverses = false opacity.fillMode = kCAFillModeForwards opacity.removedOnCompletion = false opacity.duration = option.duration opacity.fromValue = 1.0 opacity.toValue = 0.0 let transform = CABasicAnimation(keyPath: "transform") transform.autoreverses = false transform.fillMode = kCAFillModeForwards transform.removedOnCompletion = false transform.duration = option.duration transform.fromValue = NSValue(CATransform3D: CATransform3DMakeScale(1.0 / option.scale, 1.0 / option.scale, 1.0)) transform.toValue = NSValue(CATransform3D: CATransform3DMakeScale(option.scale, option.scale, 1.0)) var rippleLayer:CALayer? = targetLayer if rippleLayer == nil { rippleLayer = CALayer() view.layer.addSublayer(rippleLayer!) targetLayer = rippleLayer targetLayer?.addSublayer(CALayer())//Temporary, CALayer.sublayers is Implicitly Unwrapped Optional } dispatch_async(dispatch_get_main_queue()) { [weak rippleLayer] in if let target = rippleLayer { let layer = CALayer() layer.contents = img.CGImage layer.frame = CGRectMake(point.x - option.radius, point.y - option.radius, option.radius * 2, option.radius * 2) target.addSublayer(layer) CATransaction.begin() CATransaction.setAnimationDuration(option.duration) CATransaction.setCompletionBlock { layer.contents = nil layer.removeAllAnimations() layer.removeFromSuperlayer() then() } layer.addAnimation(opacity, forKey:nil) layer.addAnimation(transform, forKey:nil) CATransaction.commit() } } } public class func stop(view:UIView) { guard let sublayers = targetLayer?.sublayers else { return } for layer in sublayers { layer.removeAllAnimations() } } }
mit
9296dc0709ee293597595114cd40c46a
33.185
122
0.677004
4.348601
false
false
false
false
bourdakos1/Visual-Recognition-Tool
iOS/Visual Recognition/SnapperViewController.swift
1
4228
// // SnapperViewController.swift // Visual Recognition // // Created by Nicholas Bourdakos on 7/14/17. // Copyright © 2017 Nicholas Bourdakos. All rights reserved. // import UIKit import AVFoundation import Photos class SnapperViewController: CameraViewController { var classifier = PendingClassifier() var pendingClass = PendingClass() @IBOutlet var thumbnail: UIView! @IBOutlet var thumbnailImage: UIImageView! @IBOutlet weak var width: NSLayoutConstraint! @IBOutlet weak var height: NSLayoutConstraint! // MARK: View Controller Life Cycle override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // load the thumbnail of images. // This needs to happen in view did appear so it loads in the right spot. let border = UIView() let frame = CGRect(x: self.thumbnailImage.frame.origin.x - 1.0, y: self.thumbnailImage.frame.origin.y - 1.0, width: self.thumbnailImage.frame.size.height + 2.0, height: self.thumbnailImage.frame.size.height + 2.0) border.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.25) border.frame = frame border.layer.cornerRadius = 7.0 self.view.insertSubview(border, belowSubview: self.thumbnailImage) } override func viewDidLoad() { super.viewDidLoad() self.thumbnailImage.layer.cornerRadius = 5.0 grabPhoto() } func grabPhoto() { let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! do { // Get the directory contents urls (including subfolders urls) let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl.appendingPathComponent(classifier.id!).appendingPathComponent(pendingClass.name!), includingPropertiesForKeys: nil, options: []) // if you want to filter the directory contents you can do like this: let jpgFile = directoryContents.filter{ $0.pathExtension == "jpg" } .map { url -> (URL, TimeInterval) in var lastModified = try? url.resourceValues(forKeys: [URLResourceKey.contentModificationDateKey]) return (url, lastModified?.contentModificationDate?.timeIntervalSinceReferenceDate ?? 0) } .sorted(by: { $0.1 > $1.1 }) // sort descending modification dates .map{ $0.0 }.first! thumbnailImage.image = UIImage(contentsOfFile: jpgFile.path)! } catch { print(error.localizedDescription) } } override func captured(image: UIImage) { DispatchQueue.main.async { [unowned self] in self.width.constant = 5 self.height.constant = 5 self.thumbnailImage.image = image self.view.layoutIfNeeded() self.width.constant = 60 self.height.constant = 60 UIView.animate(withDuration: 0.3, delay: 0.0, options: [.curveEaseOut], animations: { () -> Void in self.thumbnailImage.alpha = 1.0 }, completion: nil) UIView.animate(withDuration: 0.3, delay: 0.0, options: [.curveEaseOut], animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) } let reducedImage = image.resized(toWidth: 300)! let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let path = documentsUrl.appendingPathComponent(self.classifier.id!).appendingPathComponent(self.pendingClass.name!) do { try FileManager.default.createDirectory(atPath: path.path, withIntermediateDirectories: true, attributes: nil) } catch { print(error.localizedDescription) } let filename = path.appendingPathComponent("\(NSUUID().uuidString).jpg") do { try UIImageJPEGRepresentation(reducedImage, 0.4)!.write(to: filename) } catch { print(error.localizedDescription) } } }
mit
86d0861b528c03035447aded8d85d80a
39.257143
225
0.623137
4.892361
false
false
false
false
xedin/swift
stdlib/public/core/Zip.swift
1
5527
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// Creates a sequence of pairs built out of two underlying sequences. /// /// In the `Zip2Sequence` instance returned by this function, the elements of /// the *i*th pair are the *i*th elements of each underlying sequence. The /// following example uses the `zip(_:_:)` function to iterate over an array /// of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// If the two sequences passed to `zip(_:_:)` are different lengths, the /// resulting sequence is the same length as the shorter sequence. In this /// example, the resulting array is the same length as `words`: /// /// let naturalNumbers = 1...Int.max /// let zipped = Array(zip(words, naturalNumbers)) /// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] /// /// - Parameters: /// - sequence1: The first sequence or collection to zip. /// - sequence2: The second sequence or collection to zip. /// - Returns: A sequence of tuple pairs, where the elements of each pair are /// corresponding elements of `sequence1` and `sequence2`. @inlinable // generic-performance public func zip<Sequence1, Sequence2>( _ sequence1: Sequence1, _ sequence2: Sequence2 ) -> Zip2Sequence<Sequence1, Sequence2> { return Zip2Sequence(sequence1, sequence2) } /// A sequence of pairs built out of two underlying sequences. /// /// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th /// elements of each underlying sequence. To create a `Zip2Sequence` instance, /// use the `zip(_:_:)` function. /// /// The following example uses the `zip(_:_:)` function to iterate over an /// array of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" @frozen // generic-performance public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> { @usableFromInline // generic-performance internal let _sequence1: Sequence1 @usableFromInline // generic-performance internal let _sequence2: Sequence2 /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. @inlinable // generic-performance internal init(_ sequence1: Sequence1, _ sequence2: Sequence2) { (_sequence1, _sequence2) = (sequence1, sequence2) } } extension Zip2Sequence { /// An iterator for `Zip2Sequence`. @frozen // generic-performance public struct Iterator { @usableFromInline // generic-performance internal var _baseStream1: Sequence1.Iterator @usableFromInline // generic-performance internal var _baseStream2: Sequence2.Iterator @usableFromInline // generic-performance internal var _reachedEnd: Bool = false /// Creates an instance around a pair of underlying iterators. @inlinable // generic-performance internal init( _ iterator1: Sequence1.Iterator, _ iterator2: Sequence2.Iterator ) { (_baseStream1, _baseStream2) = (iterator1, iterator2) } } } extension Zip2Sequence.Iterator: IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (Sequence1.Element, Sequence2.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 // generic-performance public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next() else { _reachedEnd = true return nil } return (element1, element2) } } extension Zip2Sequence: Sequence { public typealias Element = (Sequence1.Element, Sequence2.Element) /// Returns an iterator over the elements of this sequence. @inlinable // generic-performance public __consuming func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator()) } @inlinable // generic-performance public var underestimatedCount: Int { return Swift.min( _sequence1.underestimatedCount, _sequence2.underestimatedCount ) } }
apache-2.0
189d9403180ebe53cdc84b8591260c0b
34.658065
80
0.648453
4.149399
false
false
false
false
SwiftGen/SwiftGen
Sources/SwiftGenKit/Parsers/Strings/StringsEntry.swift
1
1037
// // SwiftGenKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import PathKit extension Strings { struct Entry { var comment: String? let key: String let translation: String let types: [PlaceholderType] let keyStructure: [String] init(key: String, translation: String, types: [PlaceholderType], keyStructureSeparator: String) { self.key = key self.translation = translation self.types = types self.keyStructure = Self.split(key: key, separator: keyStructureSeparator) } init(key: String, translation: String, keyStructureSeparator: String) throws { let types = try PlaceholderType.placeholderTypes(fromFormat: translation) self.init(key: key, translation: translation, types: types, keyStructureSeparator: keyStructureSeparator) } // MARK: - Structured keys private static func split(key: String, separator: String) -> [String] { key .components(separatedBy: separator) .filter { !$0.isEmpty } } } }
mit
35876bd4eedc14683184e85201e93c0e
26.263158
111
0.684363
4.316667
false
false
false
false
VirgilSecurity/virgil-sdk-keys-x
Source/Cards/CardManager/CardManager+Queries.swift
2
12540
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation import VirgilCrypto // MARK: - Extension for primary operations extension CardManager { /// Makes CallbackOperation<Card> for getting verified Virgil Card /// from the Virgil Cards Service with given ID, if exists /// /// - Parameter cardId: identifier of Virgil Card to find /// - Returns: CallbackOperation<GetCardResponse> for getting `GetCardResponse` with verified Virgil Card open func getCard(withId cardId: String) -> GenericOperation<Card> { return CallbackOperation { _, completion in do { let responseModel = try self.cardClient.getCard(withId: cardId) let card = try self.parseCard(from: responseModel.rawCard) card.isOutdated = responseModel.isOutdated guard card.identifier == cardId else { throw CardManagerError.gotWrongCard } guard self.cardVerifier.verifyCard(card) else { throw CardManagerError.cardIsNotVerified } completion(card, nil) } catch { completion(nil, error) } } } /// Generates self signed RawSignedModel /// /// - Parameters: /// - privateKey: VirgilPrivateKey to self sign with /// - publicKey: Public Key instance /// - identity: Card's identity /// - previousCardId: Identifier of Virgil Card with same identity this Card will replace /// - extraFields: Dictionary with extra data to sign with model. Should be JSON-compatible /// - Returns: Self signed RawSignedModel /// - Throws: Rethrows from `VirgilCrypto`, `JSONEncoder`, `JSONSerialization`, `ModelSigner` @objc open func generateRawCard(privateKey: VirgilPrivateKey, publicKey: VirgilPublicKey, identity: String, previousCardId: String? = nil, extraFields: [String: String]? = nil) throws -> RawSignedModel { return try CardManager.generateRawCard(crypto: self.crypto, modelSigner: self.modelSigner, privateKey: privateKey, publicKey: publicKey, identity: identity, previousCardId: previousCardId, extraFields: extraFields) } /// Generates self signed RawSignedModel /// /// - Parameters: /// - crypto: VirgilCrypto implementation /// - modelSigner: ModelSigner implementation /// - privateKey: VirgilPrivateKey to self sign with /// - publicKey: Public Key instance /// - identity: Card's identity /// - previousCardId: Identifier of Virgil Card with same identity this Card will replace /// - extraFields: Dictionary with extra data to sign with model. Should be JSON-compatible /// - Returns: Self signed RawSignedModel /// - Throws: Rethrows from `VirgilCrypto`, `JSONEncoder`, `JSONSerialization`, `ModelSigner` @objc open class func generateRawCard(crypto: VirgilCrypto, modelSigner: ModelSigner, privateKey: VirgilPrivateKey, publicKey: VirgilPublicKey, identity: String, previousCardId: String? = nil, extraFields: [String: String]? = nil) throws -> RawSignedModel { let exportedPubKey = try crypto.exportPublicKey(publicKey) let cardContent = RawCardContent(identity: identity, publicKey: exportedPubKey, previousCardId: previousCardId, createdAt: Date()) let snapshot = try JSONEncoder().encode(cardContent) let rawCard = RawSignedModel(contentSnapshot: snapshot) var data: Data? if extraFields != nil { data = try JSONSerialization.data(withJSONObject: extraFields as Any, options: []) } else { data = nil } try modelSigner.selfSign(model: rawCard, privateKey: privateKey, additionalData: data) return rawCard } /// Makes CallbackOperation<Card> for creating Virgil Card instance /// on the Virgil Cards Service and associates it with unique identifier /// /// - Parameter rawCard: RawSignedModel of Card to create /// - Returns: CallbackOperation<Card> for creating Virgil Card instance open func publishCard(rawCard: RawSignedModel) -> GenericOperation<Card> { return CallbackOperation { _, completion in do { let signedRawCard = try CallbackOperation<RawSignedModel> { _, completion in if let signCallback = self.signCallback { signCallback(rawCard) { rawCard, error in completion(rawCard, error) } } else { completion(rawCard, nil) } }.startSync().get() let responseModel = try self.cardClient.publishCard(model: signedRawCard) guard responseModel.contentSnapshot == rawCard.contentSnapshot, let selfSignature = rawCard.signatures .first(where: { $0.signer == ModelSigner.selfSignerIdentifier }), let responseSelfSignature = responseModel.signatures .first(where: { $0.signer == ModelSigner.selfSignerIdentifier }), selfSignature.snapshot == responseSelfSignature.snapshot else { throw CardManagerError.gotWrongCard } let card = try self.parseCard(from: responseModel) guard self.cardVerifier.verifyCard(card) else { throw CardManagerError.cardIsNotVerified } completion(card, nil) } catch { completion(nil, error) } } } /// Makes CallbackOperation<Card> for generating self signed RawSignedModel and /// creating Virgil Card instance on the Virgil Cards Service /// /// - Parameters: /// - privateKey: VirgilPrivateKey to self sign with /// - publicKey: Public Key instance /// - identity: Card's identity /// - previousCardId: Identifier of Virgil Card with same identity this Card will replace /// - extraFields: Dictionary with extra data to sign with model. Should be JSON-compatible /// - Returns: CallbackOperation<Card> for generating self signed RawSignedModel and /// creating Virgil Card instance on the Virgil Cards Service open func publishCard(privateKey: VirgilPrivateKey, publicKey: VirgilPublicKey, identity: String, previousCardId: String? = nil, extraFields: [String: String]? = nil) -> GenericOperation<Card> { return CallbackOperation { _, completion in do { let rawCard = try self.generateRawCard(privateKey: privateKey, publicKey: publicKey, identity: identity, previousCardId: previousCardId, extraFields: extraFields) let card = try self.publishCard(rawCard: rawCard).startSync().get() completion(card, nil) } catch { completion(nil, error) } } } /// Makes CallbackOperation<[Card]> for performing search of Virgil Cards /// on the Virgil Cards Service using identities /// /// - Note: Resulting array will contain only actual cards. /// Older cards (that were replaced) can be accessed using previousCard property of new cards. /// /// - Parameter identities: identities of cards to search /// - Returns: CallbackOperation<[Card]> for performing search of Virgil Cards open func searchCards(identities: [String]) -> GenericOperation<[Card]> { return CallbackOperation { _, completion in do { let cards = try self.cardClient.searchCards(identities: identities) .map { rawSignedModel -> Card in try self.parseCard(from: rawSignedModel) } let result = try cards .compactMap { card -> Card? in guard identities.contains(card.identity) else { throw CardManagerError.gotWrongCard } if let nextCard = cards.first(where: { $0.previousCardId == card.identifier }) { nextCard.previousCard = card card.isOutdated = true return nil } return card } guard result.allSatisfy({ self.cardVerifier.verifyCard($0) }) else { throw CardManagerError.cardIsNotVerified } completion(result, nil) } catch { completion(nil, error) } } } /// Returns list of cards that were replaced with newer ones /// /// - Parameter cardIds: card ids to check /// - Returns: GenericOperation<[String]> open func getOutdated(cardIds: [String]) -> GenericOperation<[String]> { return CallbackOperation { _, completion in do { let cardIds = try self.cardClient.getOutdated(cardIds: cardIds) completion(cardIds, nil) } catch { completion(nil, error) } } } /// Makes CallbackOperation<Void> for performing revokation of Virgil Card /// /// Revoked card gets isOutdated flag to be set to true. /// Also, such cards could be obtained using get query, but will be absent in search query result. /// /// - Parameter cardId: identifier of card to revoke /// - Returns: CallbackOperation<Void> open func revokeCard(withId cardId: String) -> GenericOperation<Void> { return CallbackOperation { _, completion in do { try self.cardClient.revokeCard(withId: cardId) completion(Void(), nil) } catch { completion(nil, error) } } } }
bsd-3-clause
5ef59fea8a4e43d6055b52934762fd8f
42.69338
109
0.578389
5.466434
false
false
false
false
practicalswift/swift
stdlib/public/core/StringUTF8Validation.swift
2
8136
private func _isUTF8MultiByteLeading(_ x: UInt8) -> Bool { return (0xC2...0xF4).contains(x) } private func _isNotOverlong_F0(_ x: UInt8) -> Bool { return (0x90...0xBF).contains(x) } private func _isNotOverlong_F4(_ x: UInt8) -> Bool { return _isContinuation(x) && x <= 0x8F } private func _isNotOverlong_E0(_ x: UInt8) -> Bool { return (0xA0...0xBF).contains(x) } private func _isNotOverlong_ED(_ x: UInt8) -> Bool { return _isContinuation(x) && x <= 0x9F } private func _isASCII_cmp(_ x: UInt8) -> Bool { return x <= 0x7F } internal struct UTF8ExtraInfo: Equatable { public var isASCII: Bool } internal enum UTF8ValidationResult { case success(UTF8ExtraInfo) case error(toBeReplaced: Range<Int>) } extension UTF8ValidationResult: Equatable {} private struct UTF8ValidationError: Error {} internal func validateUTF8(_ buf: UnsafeBufferPointer<UInt8>) -> UTF8ValidationResult { if _allASCII(buf) { return .success(UTF8ExtraInfo(isASCII: true)) } var iter = buf.makeIterator() var lastValidIndex = buf.startIndex @inline(__always) func guaranteeIn(_ f: (UInt8) -> Bool) throws { guard let cu = iter.next() else { throw UTF8ValidationError() } guard f(cu) else { throw UTF8ValidationError() } } @inline(__always) func guaranteeContinuation() throws { try guaranteeIn(_isContinuation) } func _legacyInvalidLengthCalculation(_ _buffer: (_storage: UInt32, ())) -> Int { // function body copied from UTF8.ForwardParser._invalidLength if _buffer._storage & 0b0__1100_0000__1111_0000 == 0b0__1000_0000__1110_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111 if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 } } else if _buffer._storage & 0b0__1100_0000__1111_1000 == 0b0__1000_0000__1111_0000 { // Prefix of 4-byte sequence. The top 5 bits of the decoded result // must be nonzero and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 { return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000 == 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2 } } return 1 } func _legacyNarrowIllegalRange(buf: Slice<UnsafeBufferPointer<UInt8>>) -> Range<Int> { var reversePacked: UInt32 = 0 if let third = buf.dropFirst(2).first { reversePacked |= UInt32(third) reversePacked <<= 8 } if let second = buf.dropFirst().first { reversePacked |= UInt32(second) reversePacked <<= 8 } reversePacked |= UInt32(buf.first!) let _buffer: (_storage: UInt32, x: ()) = (reversePacked, ()) let invalids = _legacyInvalidLengthCalculation(_buffer) return buf.startIndex ..< buf.startIndex + invalids } func findInvalidRange(_ buf: Slice<UnsafeBufferPointer<UInt8>>) -> Range<Int> { var endIndex = buf.startIndex var iter = buf.makeIterator() _ = iter.next() while let cu = iter.next(), !_isASCII(cu) && !_isUTF8MultiByteLeading(cu) { endIndex += 1 } let illegalRange = Range(buf.startIndex...endIndex) _internalInvariant(illegalRange.clamped(to: (buf.startIndex..<buf.endIndex)) == illegalRange, "illegal range out of full range") // FIXME: Remove the call to `_legacyNarrowIllegalRange` and return `illegalRange` directly return _legacyNarrowIllegalRange(buf: buf[illegalRange]) } do { var isASCII = true while let cu = iter.next() { if _isASCII(cu) { lastValidIndex &+= 1; continue } isASCII = false if _slowPath(!_isUTF8MultiByteLeading(cu)) { throw UTF8ValidationError() } switch cu { case 0xC2...0xDF: try guaranteeContinuation() lastValidIndex &+= 2 case 0xE0: try guaranteeIn(_isNotOverlong_E0) try guaranteeContinuation() lastValidIndex &+= 3 case 0xE1...0xEC: try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 3 case 0xED: try guaranteeIn(_isNotOverlong_ED) try guaranteeContinuation() lastValidIndex &+= 3 case 0xEE...0xEF: try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 3 case 0xF0: try guaranteeIn(_isNotOverlong_F0) try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 4 case 0xF1...0xF3: try guaranteeContinuation() try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 4 case 0xF4: try guaranteeIn(_isNotOverlong_F4) try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 4 default: Builtin.unreachable() } } return .success(UTF8ExtraInfo(isASCII: isASCII)) } catch { return .error(toBeReplaced: findInvalidRange(buf[lastValidIndex...])) } } internal func repairUTF8(_ input: UnsafeBufferPointer<UInt8>, firstKnownBrokenRange: Range<Int>) -> String { _internalInvariant(input.count > 0, "empty input doesn't need to be repaired") _internalInvariant(firstKnownBrokenRange.clamped(to: input.indices) == firstKnownBrokenRange) // During this process, `remainingInput` contains the remaining bytes to process. It's split into three // non-overlapping sub-regions: // // 1. `goodChunk` (may be empty) containing bytes that are known good UTF-8 and can be copied into the output String // 2. `brokenRange` (never empty) the next range of broken bytes, // 3. the remainder (implicit, will become the next `remainingInput`) // // At the beginning of the process, the `goodChunk` starts at the beginning and extends to just before the first // known broken byte. The known broken bytes are covered in the `brokenRange` and everything following that is // the remainder. // We then copy the `goodChunk` into the target buffer and append a UTF8 replacement character. `brokenRange` is // skipped (replaced by the replacement character) and we restart the same process. This time, `goodChunk` extends // from the byte after the previous `brokenRange` to the next `brokenRange`. var result = _StringGuts() let replacementCharacterCount = Unicode.Scalar._replacementCharacter.withUTF8CodeUnits { $0.count } result.reserveCapacity(input.count + 5 * replacementCharacterCount) // extra space for some replacement characters var brokenRange: Range<Int> = firstKnownBrokenRange var remainingInput = input repeat { _internalInvariant(brokenRange.count > 0, "broken range empty") _internalInvariant(remainingInput.count > 0, "empty remaining input doesn't need to be repaired") let goodChunk = remainingInput[..<brokenRange.startIndex] // very likely this capacity reservation does not actually do anything because we reserved space for the entire // input plus up to five replacement characters up front result.reserveCapacity(result.count + remainingInput.count + replacementCharacterCount) // we can now safely append the next known good bytes and a replacement character result.appendInPlace(UnsafeBufferPointer(rebasing: goodChunk), isASCII: false /* appending replacement character anyway, so let's not bother */) Unicode.Scalar._replacementCharacter.withUTF8CodeUnits { result.appendInPlace($0, isASCII: false) } remainingInput = UnsafeBufferPointer(rebasing: remainingInput[brokenRange.endIndex...]) switch validateUTF8(remainingInput) { case .success: result.appendInPlace(remainingInput, isASCII: false) return String(result) case .error(let newBrokenRange): brokenRange = newBrokenRange } } while remainingInput.count > 0 return String(result) }
apache-2.0
9c10de1d1b94d95157cd2feba4e9ad17
38.115385
119
0.671952
4.080241
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/EnterAmount/AccountAuxiliaryView/AccountAuxiliaryView.swift
1
4839
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import PlatformUIKit import RxCocoa import RxSwift import ToolKit import UIKit final class AccountAuxiliaryView: UIView { // MARK: - Public Properties var presenter: AccountAuxiliaryViewPresenter! { willSet { disposeBag = DisposeBag() } didSet { presenter .titleLabel .drive(titleLabel.rx.content) .disposed(by: disposeBag) // If there is a badge to be displayed, we hide the subtitle. // We do this as this views height is hard coded in the // `EnterAmountViewController`. Driver.combineLatest( presenter .subtitleLabel, presenter .badgeViewVisiblity ) .map { $0.1.isHidden ? $0.0 : .empty } .drive(subtitleLabel.rx.content) .disposed(by: disposeBag) presenter .badgeViewVisiblity .map { $0.isHidden ? 0.0 : 24.0 } .drive(badgeView.rx.rx_heightAnchor) .disposed(by: disposeBag) presenter .badgeViewModel .drive(badgeView.rx.badgeViewModel) .disposed(by: disposeBag) presenter .badgeViewVisiblity .map(\.inverted) .drive(subtitleLabel.rx.visibility) .disposed(by: disposeBag) presenter .badgeImageViewModel .drive(badgeImageView.rx.viewModel) .disposed(by: disposeBag) presenter .buttonEnabled .drive(button.rx.isEnabled) .disposed(by: disposeBag) presenter.buttonEnabled .map(Visibility.init(boolValue:)) .drive(disclosureImageView.rx.visibility) .disposed(by: disposeBag) button.rx .controlEvent(.touchUpInside) .bindAndCatch(to: presenter.tapRelay) .disposed(by: disposeBag) } } // MARK: - Private Properties private let button = UIButton() private let titleLabel = UILabel() private let badgeView = BadgeView() private let subtitleLabel = UILabel() private let stackView = UIStackView() private let separatorView = UIView() private let disclosureImageView = UIImageView() private let tapGestureRecognizer = UITapGestureRecognizer() private let badgeImageView = BadgeImageView() private var disposeBag = DisposeBag() init() { super.init(frame: UIScreen.main.bounds) layer.cornerRadius = 16 layer.masksToBounds = true layer.borderColor = UIColor(Color.semantic.light).cgColor layer.borderWidth = 1 addSubview(stackView) stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(subtitleLabel) stackView.addArrangedSubview(badgeView) addSubview(badgeImageView) addSubview(separatorView) addSubview(disclosureImageView) addSubview(button) button.fillSuperview() badgeImageView.layoutToSuperview(.centerY) badgeImageView.layout(size: .init(edge: Sizing.badge)) badgeImageView.layoutToSuperview(.leading, offset: Spacing.inner) disclosureImageView.layoutToSuperview(.trailing, offset: -Spacing.inner) disclosureImageView.layoutToSuperview(.centerY) disclosureImageView.layout(size: CGSize(width: 14, height: 24)) disclosureImageView.contentMode = .scaleAspectFit disclosureImageView.image = Icon.chevronRight.uiImage stackView.layoutToSuperview(.centerY) stackView.layout( edge: .leading, to: .trailing, of: badgeImageView, offset: Spacing.inner ) stackView.layout( edge: .trailing, to: .leading, of: disclosureImageView, offset: -Spacing.inner ) stackView.axis = .vertical stackView.spacing = 4.0 separatorView.backgroundColor = .lightBorder separatorView.layoutToSuperview(.leading, .trailing, .top) separatorView.layout(dimension: .height, to: 1) button.addTargetForTouchDown(self, selector: #selector(touchDown)) button.addTargetForTouchUp(self, selector: #selector(touchUp)) } required init?(coder: NSCoder) { unimplemented() } // MARK: - Private Functions @objc private func touchDown() { backgroundColor = .hightlightedBackground } @objc private func touchUp() { backgroundColor = .white } }
lgpl-3.0
42d33de9e3805046bce9431802f5d9ae
30.012821
80
0.599215
5.363636
false
false
false
false
biohazardlover/ROer
DataImporter/MonsterSpawn.swift
1
4166
import Foundation import CoreData /// <map name>,<x>,<y>,<xs>,<ys>%TAB%monster%TAB%<monster name>%TAB%<mob id>,<amount>,<delay1>,<delay2>,<event> /// /// Map name is the name of the map the monsters will spawn on. x,y are the /// coordinates where the mob should spawn. If xs and ys are non-zero, they /// specify the diameters of a spawn-rectangle area who's center is x,y. /// Putting zeros instead of these coordinates will spawn the monsters randomly. /// Note this is only the initial spawn zone, as mobs random-walk, they are free /// to move away from their specified spawn region. /// /// Monster name is the name the monsters will have on screen, and has no relation /// whatsoever to their names anywhere else. It's the mob id that counts, which /// identifies monster record in 'mob_db.txt' database of monsters. If the mob name /// is given as "--ja--", the 'japanese name' field from the monster database is /// used, (which, in eAthena, actually contains an english name) if it's "--en--", /// it's the 'english name' from the monster database (which contains an uppercase /// name used to summon the monster with a GM command). /// /// If you add 20000 to the monster ID, the monster will be spawned in a 'big /// version', (monster size class will increase) and if you add 10000, the 'tiny /// version' of the monster will be created. However, this method is deprecated /// and not recommended, as the values to add can change at a later time (20000 /// and 10000 actually stand for 2*MAX_MOB_DB and MAX_MOB_DB respectively, which /// is defined on mob.h, and can change in the future as more mobs are created). /// The recommended way to change a mob's size is to use the event-field (see /// below). /// /// Amount is the amount of monsters that will be spawned when this command is /// executed, it is affected by spawn rates in 'battle_athena.conf'. /// /// Delay1 and delay2 are the monster respawn delays - the first one counts the time /// since a monster defined in this spawn was last respawned and the second one /// counts the time since the monster of this spawn was last killed. Whichever turns /// out to be higher will be used. If the resulting number is smaller than a random /// value between 5 and 10 seconds, this value will be used instead. (Which is /// normally the case if both delay values are zero.) The times are given in /// 1/1000ths of a second. /// /// You can specify a custom level to use for the mob different from the one of /// the database by adjoining the level after the name with a comma. eg: /// "Poring,50" for a name will spawn a monster with name Poring and level 50. /// /// Event is a script event to be executed when the mob is killed. The event must /// be in the form "NPCName::OnEventName" to execute, and the event name label /// should start with "On". As with all events, if the NPC is an on-touch npc, the /// player who triggers the script must be within 'trigger' range for the event to /// work. class MonsterSpawn: NSManagedObject { @NSManaged var mapName: String? @NSManaged var x: NSNumber? @NSManaged var y: NSNumber? @NSManaged var xs: NSNumber? @NSManaged var ys: NSNumber? @NSManaged var monsterName: String? @NSManaged var monsterID: NSNumber? @NSManaged var amount: NSNumber? @NSManaged var delay1: NSNumber? @NSManaged var delay2: NSNumber? @NSManaged var event: NSNumber? } extension MonsterSpawn { var map: Map? { guard let mapName = mapName else { return nil } let fetchRequest = NSFetchRequest<Map>(entityName: "Map") fetchRequest.predicate = NSPredicate(format: "mapName == %@", mapName) let maps = try? managedObjectContext?.fetch(fetchRequest) return maps??.first } var monster: Monster? { guard let monsterID = monsterID else { return nil } let fetchRequest = NSFetchRequest<Monster>(entityName: "Monster") fetchRequest.predicate = NSPredicate(format: "id == %@", monsterID) let monsters = try? managedObjectContext?.fetch(fetchRequest) return monsters??.first } }
mit
612e7f2ab3b852f37667ff6c3f3e0db2
45.808989
111
0.698032
4.068359
false
false
false
false
biohazardlover/ROer
Roer/StatusCalculatorCheckboxInputElementCell.swift
1
928
import UIKit class StatusCalculatorCheckboxInputElementCell: UICollectionViewCell { fileprivate var checkboxInputElement: StatusCalculator.CheckboxInputElement! @IBOutlet var elementDescriptionLabel: UILabel! @IBOutlet var checkbox: UIButton! @IBAction func checkboxSelected(_ sender: AnyObject) { checkbox.isSelected = !checkbox.isSelected checkboxInputElement.checked = checkbox.isSelected } } extension StatusCalculatorCheckboxInputElementCell: StatusCalculatorElementCell { func configureWithElement(_ element: AnyObject) { guard let checkboxInputElement = element as? StatusCalculator.CheckboxInputElement else { return } self.checkboxInputElement = checkboxInputElement elementDescriptionLabel.text = checkboxInputElement.description checkbox.isSelected = checkboxInputElement.checked } }
mit
be477822e259c4a1ee67f706b57ea9b8
31
97
0.737069
5.987097
false
false
false
false
cwaffles/Soulcast
Soulcast/HistoryDataSource.swift
1
5385
// // HistoryDataSource.swift // Soulcast // // Created by June Kim on 2016-11-19. // Copyright © 2016 Soulcast-team. All rights reserved. // import Foundation import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. 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 } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } protocol HistoryDataSourceDelegate: class { func willFetch() func didFetch(_ success:Bool) func didUpdate(_ soulCount:Int) func didFinishUpdating(_ soulCount:Int) func didRequestBlock(_ soul: Soul) } class HistoryDataSource: NSObject, SoulCatcherDelegate { fileprivate var souls = [Soul]() fileprivate var soulCatchers = Set<SoulCatcher>() weak var delegate: HistoryDataSourceDelegate? var updateTimer: Timer = Timer() func fetch() { //TODO: delegate?.willFetch() ServerFacade.getHistory({ souls in self.catchSouls(souls) self.delegate?.didFetch(true) }, failure: { failureCode in self.delegate?.didFetch(false) }) } func startTimer() { updateTimer.invalidate() updateTimer = Timer.scheduledTimer( timeInterval: 0.25, target: self, selector: #selector(timerExpired), userInfo: nil, repeats: false) } func timerExpired() { updateTimer.invalidate() // assertSorted() delegate?.didFinishUpdating(souls.count) print("HistoryDataSource timerExpired!!") } func assertSorted() { for soulIndex in 0...(souls.count-1) { assert(souls[soulIndex].epoch > souls[soulIndex + 1].epoch) } } func soul(forIndex index:Int) -> Soul? { guard index < souls.count else { return nil } return souls[index] } func indexPath(forSoul soul:Soul) -> IndexPath { if let index = souls.index(of: soul) { return IndexPath(row: index, section: 0) } return IndexPath() } func catchSouls(_ souls:[Soul]) { soulCatchers.removeAll(keepingCapacity: true) self.souls.removeAll(keepingCapacity: true) for eachSoul in souls { let catcher = SoulCatcher(soul: eachSoul) catcher.delegate = self soulCatchers.insert(catcher) } } func remove(_ soul:Soul) { if let index = souls.index(of: soul) { souls.remove(at: index) delegate?.didUpdate(souls.count) } } func insertByEpoch(_ soul: Soul) { var insertionIndex = 0 for eachSoul in souls { if eachSoul.epoch > soul.epoch { insertionIndex = indexPath(forSoul: eachSoul).row + 1 } } souls.insert(soul, at: insertionIndex) delegate?.didUpdate(souls.count) } func debugEpoch() { for eachSoul in souls { print(eachSoul.epoch!) } print(" ") } //SoulCatcherDelegate func soulDidStartToDownload(_ catcher: SoulCatcher, soul: Soul) { // } func soulIsDownloading(_ catcher: SoulCatcher, progress: Float) { // } func soulDidFinishDownloading(_ catcher: SoulCatcher, soul: Soul) { insertByEpoch(soul) soulCatchers.remove(catcher) startTimer() } func soulDidFailToDownload(_ catcher: SoulCatcher) { // soulCatchers.remove(catcher) } func soulCount() -> Int { return souls.count } } extension HistoryDataSource: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return souls.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Recent Souls" } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return "" } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: if let blockingSoul = soul(forIndex: indexPath.row) { delegate?.didRequestBlock(blockingSoul) } case .insert: break case .none: break } } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: String(describing: UITableViewCell())) if let thisSoul = soul(forIndex: indexPath.row), let epoch = thisSoul.epoch, let radius = thisSoul.radius { cell.textLabel?.text = timeAgo(epoch: epoch) cell.detailTextLabel?.text = String(round(radius*10)/10) + "km away" cell.detailTextLabel?.textColor = UIColor.gray cell.accessoryType = .disclosureIndicator } return cell } }
mit
219b965c095bb51b5078b85416f556aa
26.055276
125
0.665862
4.066465
false
false
false
false
MaddTheSane/WWDC
WWDC/SlidesDownloader.swift
1
2118
// // SlidesDownloader.swift // WWDC // // Created by Guilherme Rambo on 10/3/15. // Copyright © 2015 Guilherme Rambo. All rights reserved. // import Cocoa import Alamofire class SlidesDownloader { private let maxPDFLength = 16*1024*1024 typealias ProgressHandler = (downloaded: Double, total: Double) -> Void typealias CompletionHandler = (success: Bool, data: NSData?) -> Void var session: Session init(session: Session) { self.session = session } func downloadSlides(completionHandler: CompletionHandler, progressHandler: ProgressHandler?) { guard session.slidesURL != "" else { return completionHandler(success: false, data: nil) } guard let slidesURL = NSURL(string: session.slidesURL) else { return completionHandler(success: false, data: nil) } Alamofire.download(Method.GET, slidesURL.absoluteString) { tempURL, response in if let data = NSData(contentsOfURL: tempURL) { mainQ { // this operation can fail if the PDF file is too big, Realm currently supports blobs of up to 16MB if data.length < self.maxPDFLength { WWDCDatabase.sharedDatabase.doChanges { self.session.slidesPDFData = data } } else { print("Error saving slides data to database, the file is too big to be saved") } completionHandler(success: true, data: data) } } else { completionHandler(success: false, data: nil) } do { try NSFileManager.defaultManager().removeItemAtURL(tempURL) } catch { print("Error removing temporary PDF file") } return tempURL }.progress { _, totalBytesRead, totalBytesExpected in mainQ { progressHandler?(downloaded: Double(totalBytesRead), total: Double(totalBytesExpected)) } } } }
bsd-2-clause
0cb7b9881d7b562fad203e8f75cdbf49
34.898305
123
0.57487
5.332494
false
false
false
false
Eonil/Monolith.Swift
Text/Sources/Parsing/Stepping.swift
2
8690
// // Parsing.swift // EDXC // // Created by Hoon H. on 10/14/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation extension Parsing { /// Represents parsing state. /// /// Parsing state is represneted node-list. /// Node-list can be empty by a result of successful parsing. (in case /// of repetition rule) /// /// If parsing is unsuccessful, the node-list will be `nil`. contain one or more /// error-node. Upper rule can decide what to do with errors. /// If parsing is successful, the resulting node list can be empty or /// If node-list is empty (`count == 0`), it means parser couldn't find /// any matching, and the composition is ignored to try next pattern. /// This is a normal pattern matching procedure, and the parser will /// continue parsing. /// /// If node-list is non-empty and contains any error-node, it just means /// *error* state. Error-node must be placed at the end of the node-list. /// Parser will stop parsing ASAP. /// /// If node-list is non-empty and contains no error-node, it means *ready* /// state. Parser found propr matching pattern, and continues parsing. /// /// If node-list is non-empty and contains some mark-node, it means one /// or more marker has been found at proper position, and that means /// current syntax pattern must be satisfied. Parser will force to find /// current pattern, and will emit an error if current pattern cannot be /// completed. This marking-effect will be applied only to current rule /// composition, and disappear when parser switches to another rule. public struct Stepping : Printable { public let status:Status public let location:Cursor public let nodes:NodeList init(status:Status, location:Cursor, nodes:NodeList) { assert(status != Status.Match || nodes.count == 0 || nodes.last!.endCursor <= location) self.status = status self.location = location self.nodes = nodes } init(status:Status, location:Cursor, nodes:[Node]) { self.init(status: status, location: location, nodes: NodeList(nodes)) } var match:Bool { get { return status == Status.Match } } /// Mismatch means the pattern does not fit to the source. var mismatch:Bool { get { return status == Status.Mismatch } } /// Error is defined only when there's some node result. var error:Bool { get { assert(status != Status.Error || nodes.hasAnyError()) return status == Status.Error } } var marking:Bool { get { return nodes.hasAnyMarkingAtCurrentLevel() } } func reoriginate(rule r1:Rule) -> Stepping { precondition(match) func reoriginateAll(n:Stepping.Node) -> Stepping.Node { return n.reorigination(rule: r1) } let ns2 = nodes.map(reoriginateAll) return Stepping(status: status, location: location, nodes: ns2) } func remark(m:Node.Mark) -> Stepping { assert(match) let ns1 = self.nodes let ns2 = ns1.map({ n in return n.remark(m) }) as NodeList return Stepping.match(location: self.location, nodes: ns2) } static func mismatch(location l1:Cursor) -> Stepping { return Stepping(status: Status.Mismatch, location: l1, nodes: NodeList()) } static func match(location l1:Cursor, nodes ns1:NodeList) -> Stepping { assert(ns1.count == 0 || l1 >= ns1.last!.endCursor) assert(ns1.hasAnyError() == false) return Stepping(status: Status.Match, location: l1, nodes: ns1) } /// Error status should return some parsed node to provide debugging information to users. static func error(location l1:Cursor, nodes ns1:NodeList, message m1:String) -> Stepping { assert(ns1.count == 0 || l1 >= ns1.last!.endCursor) // assert(ns1.hasAnyError() == false) // Discovered return Stepping(status: Status.Error, location: l1, nodes: ns1 + NodeList([Node(location: l1, error: m1)])) } // static func discover(location l1:Cursor, nodes ns1:NodeList) -> Stepping { // assert(ns1.count == 0 || l1 >= ns1.last!.endCursor) // // if ns1.hasAnyError() { // return Parsing.error(location: l1, nodes: ns1, message m1:String) // } else { // return Parsing.match(location: l1, nodes: ns1) // } // } public enum Status { case Mismatch ///< No match with no error. Parser will return no result and this status can be ignored safely. case Match ///< Exact match found. Good result. Parser will return fully established tree. case Error ///< No match with some error. Parser quit immediately and will return some result containing error information in tree. } public struct NodeList : Printable { init() { _items = [] } init(_ ns1:[Node]) { _items = ns1 } public var count:Int { get { return _items.count } } public var first:Node? { get { return _items.first } } public var last:Node? { get { return _items.last } } public var description:String { get { return "\(_items)" } } public subscript(index:Int) -> Node { get { return _items[index] } } public func map(t:Node->Node) -> NodeList { return NodeList(map(t)) } public func map<U>(t:Node->U) -> [U] { return _items.map(t) } public func reduce<U>(v:U, combine c:(U,Node)->U) -> U { return _items.reduce(v, combine: c) } public func filter(f:Node->Bool) -> NodeList { return NodeList(_items.filter(f)) } //// private let _items:[Node] private func hasAnyError() -> Bool { /// TODO: Optimisation. return _items.reduce(false, combine: { u, n in return u || n.hasAnyError() }) } private func hasAnyMarkingAtCurrentLevel() -> Bool { /// TODO: Optimisation. return _items.reduce(false, combine: { u, n in return u || (n.marking != nil) }) } } public struct Node { var startCursor:Cursor var endCursor:Cursor var origin:Rule? var marking:Mark? var subnodes:NodeList = NodeList() let error:String? // Read-only for easier optimization. Once error-node will be eternally an error. init(start:Cursor, end:Cursor, origin:Rule?, subnodes:NodeList) { self.init(start: start, end: end, origin: origin, marking: nil, subnodes: subnodes, error: nil) } // init(start:Cursor, end:Cursor) { // self.init(start: start, end: end, origin: nil, marking: nil, subnodes: NodeList()) // } init(start:Cursor, end:Cursor) { self.init(start: start, end: end, origin: nil, subnodes: NodeList([])) } init(location:Cursor, error:String) { self.init(start: location, end: location, origin: nil, marking: nil, subnodes: NodeList(), error: error) } var content:String { get { return startCursor.content(to: endCursor) } } func reorigination(rule r1:Rule) -> Node { var n2 = self n2.origin = r1 return n2 } func remark(m:Mark) -> Node { var n2 = self n2.marking = m return n2 } /// Rule name will be reported if `expectation` is `nil`. struct Mark { let expectation: String? init(expectation: String?) { self.expectation = expectation } } // enum Mark { // case None // case Flag(expectation:String) // // private var none:Bool { // get { // switch self { // case let None: return true // default: return false // } // } // } // private var expectation:String? { // get { // switch self { // case let Flag(state): return state.expectation // default: return nil // } // } // } // } //// private var _cache_any_error = false private init(start:Cursor, end:Cursor, origin:Rule?, marking:Mark?, subnodes:NodeList, error:String?) { assert(start <= end) self.startCursor = start self.endCursor = end self.origin = origin self.marking = marking self.subnodes = subnodes self.error = error } private func hasAnyError() -> Bool { return (error != nil) || subnodes.hasAnyError() } } // struct Error { // let message:String // } } } extension Parsing.Stepping { public var description:String { get { return "Parsing(status: \(status), location: \(location), nodes: \(nodes))" } } } func + (left:Parsing.Stepping.NodeList, right:Parsing.Stepping.NodeList) -> Parsing.Stepping.NodeList { return Parsing.Stepping.NodeList(left._items + right._items) } func += (inout left:Parsing.Stepping.NodeList, right:Parsing.Stepping.NodeList) { left = left + right } extension Parsing.Stepping.NodeList { var marking:Bool { get { return hasAnyMarkingAtCurrentLevel() } } }
mit
289159b5534111b79c1c07daaca727ab
24.043228
136
0.638665
3.10025
false
false
false
false
ishkawa/APIKit
Demo.playground/Contents.swift
2
1721
import PlaygroundSupport import Foundation import APIKit PlaygroundPage.current.needsIndefiniteExecution = true //: Step 1: Define request protocol protocol GitHubRequest: Request { } extension GitHubRequest { var baseURL: URL { return URL(string: "https://api.github.com")! } } //: Step 2: Create model object struct RateLimit { let count: Int let resetDate: Date init?(dictionary: [String: AnyObject]) { guard let count = dictionary["rate"]?["limit"] as? Int else { return nil } guard let resetDateString = dictionary["rate"]?["reset"] as? TimeInterval else { return nil } self.count = count self.resetDate = Date(timeIntervalSince1970: resetDateString) } } //: Step 3: Define request type conforming to created request protocol // https://developer.github.com/v3/rate_limit/ struct GetRateLimitRequest: GitHubRequest { typealias Response = RateLimit var method: HTTPMethod { return .get } var path: String { return "/rate_limit" } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { guard let dictionary = object as? [String: AnyObject], let rateLimit = RateLimit(dictionary: dictionary) else { throw ResponseError.unexpectedObject(object) } return rateLimit } } //: Step 4: Send request let request = GetRateLimitRequest() Session.send(request) { result in switch result { case .success(let rateLimit): print("count: \(rateLimit.count)") print("reset: \(rateLimit.resetDate)") case .failure(let error): print("error: \(error)") } }
mit
78969ed81ca60ef6b8f4c41f38267079
22.902778
88
0.643812
4.505236
false
false
false
false
leonardo-ferreira07/OnTheMap
OnTheMap/OnTheMap/API/Clients/StudentLocationClient.swift
1
2797
// // StudentLocationClient.swift // OnTheMap // // Created by Leonardo Vinicius Kaminski Ferreira on 10/10/17. // Copyright © 2017 Leonardo Ferreira. All rights reserved. // import Foundation import CoreLocation struct StudentLocationClient { static fileprivate let headers: [String: String] = ["X-Parse-Application-Id": "QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", "X-Parse-REST-API-Key": "QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY"] static func getStudentsLocations(_ completion: @escaping (_ success: Bool) -> Void) { let url = APIClient.buildURL(["limit": "100", "order": "-updatedAt"] as [String: AnyObject], withHost: Constants.apiHostParseClasses, withPathExtension: Constants.apiPathUdacityParseStudentLocations) _ = APIClient.performRequest(url, headerValues: headers, completion: { (dict, error) in guard let dict = dict else { completion(false) return } if let array = dict[StudentLocationKeys.results.rawValue] as? [[String: AnyObject]] { MemoryStorage.shared.studentsLocations.removeAll() for object in array { MemoryStorage.shared.studentsLocations.append(StudentLocation(withDictionary: object)) } completion(true) } else { completion(false) } }) { } } static func postStudentLocation(mapString: String, mediaURL: String, coordinate: CLLocationCoordinate2D, completion: @escaping (_ success: Bool) -> Void) { guard let id = MemoryStorage.shared.session?.account.id, let firstName = MemoryStorage.shared.user?.user.firstName, let lastName = MemoryStorage.shared.user?.user.lastName else { completion(false) return } let url = APIClient.buildURL(withHost: Constants.apiHostParseClasses, withPathExtension: Constants.apiPathUdacityParseStudentLocations) let jsonBody = ["uniqueKey": id, "firstName": firstName, "lastName": lastName, "mapString": mapString, "mediaURL": mediaURL, "latitude": coordinate.latitude, "longitude": coordinate.longitude] as [String: AnyObject] _ = APIClient.performRequest(url, method: .POST, jsonBody: jsonBody, headerValues: headers, completion: { (dict, error) in guard dict != nil else { completion(false) return } completion(true) }) { } } }
mit
2a158684482e62e2fe93265ab04e89f8
37.833333
207
0.579399
4.939929
false
false
false
false
DarthRumata/EventsTree
EventsTreeiOSExample/Sources/IOSExample/Main/TreeNodeView.swift
1
5380
// // TreeNodeView.swift // EventNodeExample // // Created by Rumata on 6/22/17. // Copyright © 2017 DarthRumata. All rights reserved. // import Foundation import UIKit import EventsTree import AMPopTip extension TreeNodeView { enum Events { struct NodeSelected: Event { let view: TreeNodeView? } struct EventImitationStarted: Event { let sharedTime: SharedTime } struct UserGeneratedEventRaised: Event {} } class SharedTime { var startTime: DispatchTime = .now() } } @IBDesignable class TreeNodeView: UIView { @IBInspectable var title: String = "" { didSet { self.titleLabel.text = title } } var eventNode: EventNode! { didSet { addInitialHandlers() } } @IBOutlet fileprivate weak var titleLabel: UILabel! @IBOutlet fileprivate weak var eventDirectionMarker: UIImageView! fileprivate var selectedState: SelectedState = .normal { didSet { updateBackground() } } fileprivate var highlightedState: HighlightedState = .none { didSet { updateIcon() } } fileprivate let popTip = PopTip() // MARK: Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let nib = UINib(nibName: String(describing: TreeNodeView.self), bundle: nil) let content = nib.instantiate(withOwner: self, options: nil)[0] as! UIView addSubview(content) content.frame = bounds } override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 5 layer.masksToBounds = true } // MARK: Actions @IBAction func didTapOnView() { let event = Events.NodeSelected(view: self) eventNode.raise(event: event) } } fileprivate extension TreeNodeView { /// TODO: Can be optimized by merging to states in OptionSet enum SelectedState { case normal, selected var color: UIColor { switch self { case .normal: return .lightGray case .selected: return .green } } } enum HighlightedState { case onPropagate, onRaise, none var icon: UIImage? { switch self { case .onPropagate: return UIImage(named: "arrowDown") case .onRaise: return UIImage(named: "arrowUp") case .none: return nil } } } func addInitialHandlers() { eventNode.addHandler { [weak self] (event: Events.NodeSelected) in guard let strongSelf = self else { return } let newState: SelectedState = event.view == strongSelf ? .selected : .normal if strongSelf.selectedState != newState { strongSelf.selectedState = newState } } eventNode.addHandler { [weak self] (event: MainViewController.Events.AddHandler) in guard let strongSelf = self else { return } guard strongSelf.selectedState == .selected else { return } let handlerInfo = event.info strongSelf.eventNode.addHandler(handlerInfo.handlerMode) { (event: Events.UserGeneratedEventRaised) in strongSelf.popTip.show( text: handlerInfo.tipText, direction: .down, maxWidth: 150, in: strongSelf.superview!, from: strongSelf.frame, duration: 2 ) } } eventNode.addHandler { [weak self] (event: MainViewController.Events.SendTestEvent) in guard let strongSelf = self else { return } guard strongSelf.selectedState == .selected else { return } let flowImitationEvent = Events.EventImitationStarted(sharedTime: SharedTime()) strongSelf.eventNode.raise(event: flowImitationEvent) let userEvent = Events.UserGeneratedEventRaised() strongSelf.eventNode.raise(event: userEvent) } eventNode.addHandler { [weak self] (event: MainViewController.Events.RemoveHandler) in guard let strongSelf = self else { return } guard strongSelf.selectedState == .selected else { return } strongSelf.eventNode.removeHandlers(for: Events.UserGeneratedEventRaised.self) } eventNode.addHandler(.onPropagate) { [weak self] (event: Events.EventImitationStarted) in guard let strongSelf = self else { return } /// TODO: Need to provide more convient implimentation via separate serial queue let sharedTime = event.sharedTime let scheduledTime = sharedTime.startTime sharedTime.startTime = sharedTime.startTime + 1 DispatchQueue.main.asyncAfter(deadline: scheduledTime) { strongSelf.highlightedState = .onPropagate DispatchQueue.main.asyncAfter(deadline: scheduledTime + 1) { strongSelf.highlightedState = .none } } } eventNode.addHandler(.onRaise) { [weak self] (event: Events.EventImitationStarted) in guard let strongSelf = self else { return } let sharedTime = event.sharedTime let scheduledTime = sharedTime.startTime sharedTime.startTime = sharedTime.startTime + 1 DispatchQueue.main.asyncAfter(deadline: scheduledTime) { strongSelf.highlightedState = .onRaise DispatchQueue.main.asyncAfter(deadline: scheduledTime + 1) { if strongSelf.highlightedState == .onRaise { strongSelf.highlightedState = .none } } } } } func updateBackground() { backgroundColor = selectedState.color } func updateIcon() { eventDirectionMarker.image = highlightedState.icon } }
mit
783f6f2806a03451b9472193481a169b
25.11165
108
0.668712
4.412633
false
false
false
false
scotlandyard/expocity
expocity/View/Chat/DisplayAnnotations/VChatDisplayAnnotations.swift
1
9649
import UIKit class VChatDisplayAnnotations:UIView { weak var controller:CChatDisplayAnnotations! weak var shadeTop:VChatDisplayAnnotationsShade! weak var shadeBottom:VChatDisplayAnnotationsShade! weak var list:VChatDisplayAnnotationsList! weak var tutorial:VChatDisplayAnnotationsTutorial! weak var placer:VChatDisplayAnnotationsPlacer! weak var editText:VChatDisplayAnnoationsEdit! weak var layoutShadeTopHeight:NSLayoutConstraint! weak var layoutShadeBottomHeight:NSLayoutConstraint! weak var layoutPlacerTop:NSLayoutConstraint! weak var layoutPlacerHeight:NSLayoutConstraint! weak var layoutEditTextBottom:NSLayoutConstraint! private let kEditTextHeight:CGFloat = 45 private let kAnimationDuration:TimeInterval = 0.3 private let kWaitingTime:TimeInterval = 0.1 convenience init(controller:CChatDisplayAnnotations) { self.init() clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let shadeTop:VChatDisplayAnnotationsShade = VChatDisplayAnnotationsShade(borderTop:false, borderBottom:true) self.shadeTop = shadeTop let shadeBottom:VChatDisplayAnnotationsShade = VChatDisplayAnnotationsShade(borderTop:true, borderBottom:false) self.shadeBottom = shadeBottom let list:VChatDisplayAnnotationsList = VChatDisplayAnnotationsList(controller:controller) self.list = list let tutorial:VChatDisplayAnnotationsTutorial = VChatDisplayAnnotationsTutorial(controller:controller) self.tutorial = tutorial let placer:VChatDisplayAnnotationsPlacer = VChatDisplayAnnotationsPlacer(controller:controller) self.placer = placer let editText:VChatDisplayAnnoationsEdit = VChatDisplayAnnoationsEdit(controller:controller) self.editText = editText shadeTop.addSubview(list) shadeTop.addSubview(tutorial) addSubview(shadeTop) addSubview(shadeBottom) addSubview(placer) addSubview(editText) let views:[String:UIView] = [ "shadeTop":shadeTop, "shadeBottom":shadeBottom, "list":list, "tutorial":tutorial, "placer":placer, "editText":editText] let metrics:[String:CGFloat] = [ "editTextHeight":kEditTextHeight] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[placer]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[shadeTop]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[shadeBottom]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[list]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[tutorial]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[editText]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[shadeTop]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:[shadeBottom]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[list]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[tutorial]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:[editText(editTextHeight)]", options:[], metrics:metrics, views:views)) layoutShadeTopHeight = NSLayoutConstraint( item:shadeTop, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:1, constant:0) layoutShadeBottomHeight = NSLayoutConstraint( item:shadeBottom, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:1, constant:0) layoutPlacerTop = NSLayoutConstraint( item:placer, attribute:NSLayoutAttribute.top, relatedBy:NSLayoutRelation.equal, toItem:self, attribute:NSLayoutAttribute.top, multiplier:1, constant:0) layoutPlacerHeight = NSLayoutConstraint( item:placer, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:1, constant:0) layoutEditTextBottom = NSLayoutConstraint( item:editText, attribute:NSLayoutAttribute.bottom, relatedBy:NSLayoutRelation.equal, toItem:self, attribute:NSLayoutAttribute.bottom, multiplier:1, constant:0) addConstraint(layoutShadeTopHeight) addConstraint(layoutShadeBottomHeight) addConstraint(layoutPlacerTop) addConstraint(layoutPlacerHeight) addConstraint(layoutEditTextBottom) layoutShades() NotificationCenter.default.addObserver( self, selector:#selector(notifiedKeyboardChanged(sender:)), name:NSNotification.Name.UIKeyboardWillChangeFrame, object:nil) } deinit { NotificationCenter.default.removeObserver(self) } override func layoutSubviews() { let delayLayout:TimeInterval = kWaitingTime DispatchQueue.main.async { [weak self] in self?.shadeTop.alpha = 0 self?.shadeBottom.alpha = 0 DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + delayLayout) { [weak self] in self?.layoutShades() self?.animateShades() } } super.layoutSubviews() } //MARK: notified func notifiedKeyboardChanged(sender notification:Notification) { let userInfo:[AnyHashable:Any] = notification.userInfo! let keyboardFrameValue:NSValue = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue let keyRect:CGRect = keyboardFrameValue.cgRectValue let yOrigin = keyRect.origin.y let screenHeight:CGFloat = UIScreen.main.bounds.size.height let keyboardHeight:CGFloat if yOrigin < screenHeight { keyboardHeight = screenHeight - yOrigin } else { keyboardHeight = 0 } layoutEditTextBottom.constant = -keyboardHeight UIView.animate(withDuration:kAnimationDuration) { [weak self] in self?.layoutIfNeeded() } } //MARK: private private func layoutShades() { let imageRect:CGRect = controller.controllerChat.displayImageRect() let screenRect:CGRect = UIScreen.main.bounds let topHeight:CGFloat = imageRect.minY let bottomHeight:CGFloat = screenRect.maxY - imageRect.maxY layoutShadeTopHeight.constant = topHeight layoutShadeBottomHeight.constant = bottomHeight layoutPlacerTop.constant = topHeight layoutPlacerHeight.constant = imageRect.size.height } private func modelAtIndex(index:IndexPath) -> MChatDisplayAnnotationsItem { let item:MChatDisplayAnnotationsItem = controller.controllerChat.model.annotations.items[index.item] return item } //MARK: public func animateShades() { UIView.animate(withDuration:kAnimationDuration) { [weak self] in self?.shadeTop.alpha = 1 self?.shadeBottom.alpha = 1 } } func addAnnotation() { list.alpha = 0 tutorial.tutorialPlaceMark() placer.addAnnotation() } func cancelAnnotation() { list.alpha = 1 tutorial.closeTutorial() placer.cancelAnnotation() } func confirmAnnotation() { tutorial.tutorialText() editText.beginEditingText() placer.reloadItems() } func confirmTextAnnotation() { list.alpha = 1 list.collectionView.reloadData() tutorial.closeTutorial() placer.reloadItems() } }
mit
52fc61c4a8c93a7fae9318a3551d016a
31.819728
119
0.610633
5.485503
false
false
false
false
jsslai/Action
UIButton+Rx.swift
1
3170
import UIKit import RxSwift import RxCocoa import ObjectiveC public extension UIButton { /// Binds enabled state of action to button, and subscribes to rx_tap to execute action. /// These subscriptions are managed in a private, inaccessible dispose bag. To cancel /// them, set the rx_action to nil or another action. public var rx_action: CocoaAction? { get { var action: CocoaAction? doLocked { action = objc_getAssociatedObject(self, &AssociatedKeys.Action) as? Action } return action } set { doLocked { // Store new value. objc_setAssociatedObject(self, &AssociatedKeys.Action, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) // This effectively disposes of any existing subscriptions. self.resetActionDisposeBag() // Set up new bindings, if applicable. if let action = newValue { action .enabled .bindTo(self.rx.isEnabled) .addDisposableTo(self.actionDisposeBag) // Technically, this file is only included on tv/iOS platforms, // so this optional will never be nil. But let's be safe 😉 let lookupControlEvent: ControlEvent<Void>? #if os(tvOS) lookupControlEvent = self.rx.primaryAction #elseif os(iOS) lookupControlEvent = self.rx.tap #endif guard let controlEvent = lookupControlEvent else { return } controlEvent .subscribe(onNext: { _ in _ = action.execute()}) .addDisposableTo(self.actionDisposeBag) } } } } } // Note: Actions performed in this extension are _not_ locked // So be careful! internal extension NSObject { internal struct AssociatedKeys { static var Action = "rx_action" static var DisposeBag = "rx_disposeBag" } // A dispose bag to be used exclusively for the instance's rx_action. internal var actionDisposeBag: DisposeBag { var disposeBag: DisposeBag if let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag { disposeBag = lookup } else { disposeBag = DisposeBag() objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, disposeBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return disposeBag } // Resets the actionDisposeBag to nil, disposeing of any subscriptions within it. internal func resetActionDisposeBag() { objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } // Uses objc_sync on self to perform a locked operation. internal func doLocked(_ closure: () -> Void) { objc_sync_enter(self); defer { objc_sync_exit(self) } closure() } }
mit
0dea0debb166de1434ad22cc3857bf0b
34.188889
118
0.575308
5.432247
false
false
false
false
advantys/workflowgen-templates
integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/ios/JWT.swift
1
5420
import Foundation import CommonCrypto @objc(JWT) class JWT : NSObject, RCTBridgeModule { static func moduleName() -> String! { return "JWT" } static func requiresMainQueueSetup() -> Bool { return false } @objc(decode:resolve:reject:) func decode(args: NSDictionary!, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { guard let header = args["header"] as? String, let payload = args["payload"] as? String else { reject( "jwt_decode_error", "You must specify the header and the payload.", NSError(domain: "JWT", code: 1, userInfo: nil) ) return } let decodePart = { (part: String) throws -> NSDictionary in try JSONSerialization.jsonObject( with: NSData(base64UrlEncodedString: part)! as Data, options: [] ) as! NSDictionary } let decodedHeader: NSDictionary let decodedPayload: NSDictionary do { decodedHeader = try decodePart(header) decodedPayload = try decodePart(payload) } catch { reject( "jwt_decode_error", "Could not decode the header or the payload.", NSError(domain: "JWT", code: 2, userInfo: nil) ) return } resolve([decodedHeader, decodedPayload]) } @objc(verify:resolve:reject:) func verify(args: NSDictionary!, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { guard let header = args["header"] as? String, let payload = args["payload"] as? String, let signature = args["signature"] as? String, var publicKeyArr = args["publicKey"] as? [String] else { reject( "jwt_verify_error", "You must specify the header, payload, signature and public key.", NSError(domain: "JWT", code: 1, userInfo: nil) ) return } // Convert PEM format to DER publicKeyArr.removeFirst() // Remove BEGIN header publicKeyArr.removeLast(2) // Remove END footer and newline let publicKey = publicKeyArr.joined(separator: "") let publicKeyDataBase64 = Data(base64Encoded: publicKey)! let signedPart = [header, payload].joined(separator: ".") let signatureData = NSData(base64UrlEncodedString: signature)! as Data let signingInput = signedPart.data(using: .ascii)! // Represent the certificate with Apple Security Framework guard let cert = SecCertificateCreateWithData(nil, publicKeyDataBase64 as CFData) else { reject( "jwt_verify_error", "Could not create the Apple Security Framework representation of the PEM certificate.", NSError(domain: "jwt", code: 3, userInfo: nil) ) return } // Get the public key guard let key = SecCertificateCopyKey(cert) else { reject( "jwt_verify_error", "Could not retrieve the key (SecKey) from the certificate representation.", NSError(domain: "jwt", code: 4, userInfo: nil) ) return } var error: Unmanaged<CFError>? // Verify the signature of the token let result = SecKeyVerifySignature( key, .rsaSignatureMessagePKCS1v15SHA256, signingInput as CFData, signatureData as CFData, &error ) if let errorPointer = error { let cfError = errorPointer.takeUnretainedValue() let description = CFErrorCopyDescription(cfError) let domain = CFErrorGetDomain(cfError) let code = CFErrorGetCode(cfError) let userInfo = CFErrorCopyUserInfo(cfError) reject( "jwt_verify_error", description as String? ?? "An error occured when verifying the token's signature.", NSError( domain: domain as String? ?? "jwt", code: code, userInfo: userInfo as? [String:Any] ) ) errorPointer.release() return } resolve(result) } @objc(verifyAtHash:accessToken:resolve:reject:) func verifyAtHash( value atHash: String, accessToken components: NSArray!, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock ) { let accessToken = components.componentsJoined(by: ".") let accessTokenData = accessToken.data(using: .ascii)! var buffer = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) accessTokenData.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in _ = CC_SHA256(bytes.baseAddress, CC_LONG(accessTokenData.count), &buffer) } buffer.removeLast(buffer.count / 2) let accessTokenFirstHalfBase64 = (Data(buffer) as NSData).base64UrlEncodedString() resolve(accessTokenFirstHalfBase64 == atHash) } }
mit
7adfa189a8db4ce748725164ad709006
36.123288
103
0.557011
5.257032
false
false
false
false
bag-umbala/music-umbala
Music-Umbala/Music-Umbala/Controller/PlaylistViewController.swift
1
4215
// // PlaylistViewController.swift // Music-Umbala // // Created by Nam Nguyen on 5/19/17. // Copyright © 2017 Nam Vo. All rights reserved. // import UIKit class PlaylistViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating { // MARK: *** Data model var modelPlaylist : [Playlist]? var modelPlaylistSearchResults : [Playlist]? var searchController: UISearchController = UISearchController(searchResultsController: nil) // MARK: *** UI Elements @IBOutlet weak var tableView: UITableView! // MARK: *** UI events // MARK: *** Local variables let didSelectIdPlaylist : Int32 = -1 var didSelectPlaylist : Playlist? // MARK: *** UIViewController override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() DB.createDBOrGetDBExist() modelPlaylist = PlaylistManager.all() NotificationCenter.default.addObserver(self, selector: #selector(loadPlaylistTables), name: NSNotification.Name(rawValue: "loadPlaylistTables"), object: nil) self.tableView.delegate = self self.tableView.dataSource = self searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.scopeButtonTitles = ["Name"] //, "ID" searchController.searchBar.delegate = self tableView?.tableHeaderView = searchController.searchBar // definesPresentationContext = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let speciesDetailVC = segue.destination as? PlaylistDetailViewController { speciesDetailVC.playlist = didSelectPlaylist // let indexPath = self.searchDisplayController?.searchResultsTableView.indexPathForSelectedRow // if indexPath != nil { // speciesDetailVC.playlist = // } } } func loadPlaylistTables() { modelPlaylist = PlaylistManager.all() self.tableView.reloadData() // Cập nhật giao diện } // MARK: Search func filterContentForSearchText(searchText: String, scope: Int) { // Filter the array using the filter method if self.modelPlaylist == nil { self.modelPlaylistSearchResults = nil return } self.modelPlaylistSearchResults = self.modelPlaylist!.filter({( aPlaylist: Playlist) -> Bool in var fieldToSearch: String? switch (scope) { case (0): fieldToSearch = aPlaylist.name // case (1): // fieldToSearch = "\(aPlaylist.id)" default: fieldToSearch = nil } if fieldToSearch == nil { self.modelPlaylistSearchResults = nil return false } return fieldToSearch!.lowercased().range(of: searchText.lowercased()) != nil }) } func updateSearchResults(for searchController: UISearchController) { let selectedIndex = searchController.searchBar.selectedScopeButtonIndex let searchString = searchController.searchBar.text ?? "" filterContentForSearchText(searchText: searchString, scope: selectedIndex) tableView?.reloadData() } func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { let selectedIndex = searchBar.selectedScopeButtonIndex let searchString = searchBar.text ?? "" filterContentForSearchText(searchText: searchString, scope: selectedIndex) tableView?.reloadData() } }
mit
4f782e16293c693607a73de401c511e3
33.211382
165
0.639734
5.588313
false
false
false
false
suosuopuo/SwiftyAlgorithm
SwiftyAlgorithm/Queue.swift
1
2177
// // Queue.swift // SwiftyAlgorithm // // Created by suosuopuo on 24/10/2017. // Copyright © 2017 shellpanic. All rights reserved. // import Foundation public struct Queue<T> { private var array = [T?]() private var head = 0 public var isEmpty: Bool { return count == 0 } public var count: Int { return array.count - head } public mutating func enqueue(_ element: T) { array.append(element) } public mutating func dequeue() -> T? { guard head < array.count, let element = array[head] else { return nil } array[head] = nil head += 1 let percentage = Double(head)/Double(array.count) if array.count > 50 && percentage > 0.25 { array.removeFirst(head) head = 0 } return element } public var front: T? { if isEmpty { return nil } else { return array[head] } } } public struct LinkedQueue<T> { fileprivate var list = List<T>() public var count: Int { return list.count } public var isEmpty: Bool { return list.isEmpty } public mutating func enqueue(_ element: T) { list.append(element) } public mutating func dequeue() -> T? { return list.removeFirst() } public var front: T? { return list.first?.value } } public struct LinkedDeque<T> { private var list = List<T>() public var isEmpty: Bool { return list.isEmpty } public var count: Int { return list.count } public mutating func enqueue(_ element: T) { list.append(element) } public mutating func enqueueFront(_ element: T) { list.prepend(element) } public mutating func dequeue() -> T? { return list.removeFirst() } public mutating func dequeueBack() -> T? { return list.removeLast() } public var front: T? { return list.first?.value } public var back: T? { return list.last?.value } }
mit
1cd2ff1f6a57455535f7fb84723830a0
18.963303
79
0.532629
4.283465
false
false
false
false
tbkka/swift-protobuf
Sources/SwiftProtobuf/ExtensibleMessage.swift
3
3484
// Sources/SwiftProtobuf/ExtensibleMessage.swift - Extension support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Additional capabilities needed by messages that allow extensions. /// // ----------------------------------------------------------------------------- // Messages that support extensions implement this protocol public protocol ExtensibleMessage: Message { var _protobuf_extensionFieldValues: ExtensionFieldValueSet { get set } } extension ExtensibleMessage { public mutating func setExtensionValue<F: ExtensionField>(ext: MessageExtension<F, Self>, value: F.ValueType) { _protobuf_extensionFieldValues[ext.fieldNumber] = F(protobufExtension: ext, value: value) } public func getExtensionValue<F: ExtensionField>(ext: MessageExtension<F, Self>) -> F.ValueType? { if let fieldValue = _protobuf_extensionFieldValues[ext.fieldNumber] as? F { return fieldValue.value } return nil } public func hasExtensionValue<F: ExtensionField>(ext: MessageExtension<F, Self>) -> Bool { return _protobuf_extensionFieldValues[ext.fieldNumber] is F } public mutating func clearExtensionValue<F: ExtensionField>(ext: MessageExtension<F, Self>) { _protobuf_extensionFieldValues[ext.fieldNumber] = nil } } // Additional specializations for the different types of repeated fields so // setting them to an empty array clears them from the map. extension ExtensibleMessage { public mutating func setExtensionValue<T>(ext: MessageExtension<RepeatedExtensionField<T>, Self>, value: [T.BaseType]) { _protobuf_extensionFieldValues[ext.fieldNumber] = value.isEmpty ? nil : RepeatedExtensionField<T>(protobufExtension: ext, value: value) } public mutating func setExtensionValue<T>(ext: MessageExtension<PackedExtensionField<T>, Self>, value: [T.BaseType]) { _protobuf_extensionFieldValues[ext.fieldNumber] = value.isEmpty ? nil : PackedExtensionField<T>(protobufExtension: ext, value: value) } public mutating func setExtensionValue<E>(ext: MessageExtension<RepeatedEnumExtensionField<E>, Self>, value: [E]) { _protobuf_extensionFieldValues[ext.fieldNumber] = value.isEmpty ? nil : RepeatedEnumExtensionField<E>(protobufExtension: ext, value: value) } public mutating func setExtensionValue<E>(ext: MessageExtension<PackedEnumExtensionField<E>, Self>, value: [E]) { _protobuf_extensionFieldValues[ext.fieldNumber] = value.isEmpty ? nil : PackedEnumExtensionField<E>(protobufExtension: ext, value: value) } public mutating func setExtensionValue<M>(ext: MessageExtension<RepeatedMessageExtensionField<M>, Self>, value: [M]) { _protobuf_extensionFieldValues[ext.fieldNumber] = value.isEmpty ? nil : RepeatedMessageExtensionField<M>(protobufExtension: ext, value: value) } public mutating func setExtensionValue<M>(ext: MessageExtension<RepeatedGroupExtensionField<M>, Self>, value: [M]) { _protobuf_extensionFieldValues[ext.fieldNumber] = value.isEmpty ? nil : RepeatedGroupExtensionField<M>(protobufExtension: ext, value: value) } }
apache-2.0
2de5749926dd9561199122c2c474054e
46.726027
124
0.693456
4.872727
false
false
false
false
dclelland/RefreshableViewController
Sources/RefreshableState.swift
1
1360
// // RefreshableState.swift // RefreshableViewController // // Created by Daniel Clelland on 30/08/17. // Copyright © 2017 Daniel Clelland. All rights reserved. // import Foundation import PromiseKit // MARK: Refreshable state public enum RefreshableState<Value> { case ready case loading case success(Value) case failure(Error) // MARK: Mutable properties public var value: Value? { set { guard let value = newValue else { if case .success = self { self = .ready } return } self = .success(value) } get { guard case .success(let response) = self else { return nil } return response } } public var error: Error? { set { guard let error = newValue else { if case .failure = self { self = .ready } return } self = .failure(error) } get { guard case .failure(let error) = self else { return nil } return error } } }
mit
a2b4802d96869361808887ab227abba0
18.985294
59
0.428992
5.479839
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/Class/ThirdVC/BKBK/NUKController/GroupListViewController.swift
1
3585
// // GroupListViewController.swift // NUK // // Created by NUK on 16/8/13. // Copyright © 2016年 NUK. All rights reserved. // import UIKit class GroupListViewController: NUKBaseViewController,ZKDownloaderDelegate { var id:String! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func downloaderData() { //http://picaman.picacomic.com/api/categories/1/page/1/comics let urlString = String(format: "http://picaman.picacomic.com/api/categories/%@/page/%d/comics", self.id,self.curPage) let download = ZKDownloader() download.getWithUrl(urlString) download.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension GroupListViewController{ func downloader(_ downloader: ZKDownloader, didFailWithError error: NSError) { ZKTools.showAlert(error.localizedDescription, onViewController: self) } func downloader(_ download: ZKDownloader, didFinishWithData data: Data?) { let jsonData = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) if (jsonData as AnyObject).isKind(of: NSArray.self){ if self.curPage == 1 { self.dataArray.removeAllObjects() } let array = jsonData as! NSArray for arr in array{ let dict = arr as! Dictionary<String,AnyObject> let model = GroupListModel() model.setValuesForKeys(dict) self.dataArray.add(model) } DispatchQueue.main.async(execute: { self.tbView?.reloadData() self.tbView?.headerView?.endRefreshing() self.tbView?.footerView?.endRefreshing() }) } } } extension GroupListViewController{ override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellId = "groupListCellId" var cell = tableView.dequeueReusableCell(withIdentifier: cellId)as? GroupListCell if cell == nil { cell = Bundle.main.loadNibNamed("GroupListCell", owner: nil, options: nil)?.last as? GroupListCell } let model = self.dataArray[(indexPath as NSIndexPath).row]as! GroupListModel cell?.config(model) return cell! } func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) { let detailCtrl = DetailViewController() let model = self.dataArray[(indexPath as NSIndexPath).row]as! GroupListModel detailCtrl.id = "\((model.id)!)" self.navigationController?.pushViewController(detailCtrl, animated: true) } }
mit
9bf72db14e01deb0ade3438894fba0ef
31.27027
125
0.643216
5.023843
false
false
false
false
hooman/swift
test/AutoDiff/stdlib/simd.swift
1
9186
// RUN: %target-run-simple-swift(-Xfrontend -requirement-machine=off) // REQUIRES: executable_test // Would fail due to unavailability of swift_autoDiffCreateLinearMapContext. // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime import _Differentiation import StdlibUnittest var SIMDTests = TestSuite("SIMD") SIMDTests.test("init(repeating:)") { let g = SIMD4<Float>(1, 1, 1, 1) func foo1(x: Float) -> SIMD4<Float> { return SIMD4<Float>(repeating: 2 * x) } let (val1, pb1) = valueWithPullback(at: 5, of: foo1) expectEqual(SIMD4<Float>(10, 10, 10, 10), val1) expectEqual(8, pb1(g)) } // FIXME(TF-1103): Derivative registration does not yet support // `@_alwaysEmitIntoClient` original functions. /* SIMDTests.test("Sum") { let a = SIMD4<Float>(1, 2, 3, 4) func foo1(x: SIMD4<Float>) -> Float { return x.sum() } let (val1, pb1) = valueWithPullback(at: a, of: foo1) expectEqual(10, val1) expectEqual(SIMD4<Float>(3, 3, 3, 3), pb1(3)) } */ SIMDTests.test("Identity") { let a = SIMD4<Float>(1, 2, 3, 4) let g = SIMD4<Float>(1, 1, 1, 1) func foo1(x: SIMD4<Float>) -> SIMD4<Float> { return x } let (val1, pb1) = valueWithPullback(at: a, of: foo1) expectEqual(a, val1) expectEqual(g, pb1(g)) } SIMDTests.test("Negate") { let a = SIMD4<Float>(1, 2, 3, 4) let g = SIMD4<Float>(1, 1, 1, 1) func foo1(x: SIMD4<Float>) -> SIMD4<Float> { return -x } let (val1, pb1) = valueWithPullback(at: a, of: foo1) expectEqual(-a, val1) expectEqual(-g, pb1(g)) } SIMDTests.test("Subscript") { let a = SIMD4<Float>(1, 2, 3, 4) func foo1(x: SIMD4<Float>) -> Float { return x[3] } let (val1, pb1) = valueWithPullback(at: a, of: foo1) expectEqual(4, val1) expectEqual(SIMD4<Float>(0, 0, 0, 7), pb1(7)) } SIMDTests.test("SubscriptSetter") { let a = SIMD4<Float>(1, 2, 3, 4) let ones = SIMD4<Float>(1, 1, 1, 1) // A wrapper around `subscript(_: Int).set`. func subscriptSet( _ simd: SIMD4<Float>, index: Int, newScalar: Float ) -> SIMD4<Float> { var result = simd result[index] = newScalar return result } let (val1, pb1) = valueWithPullback(at: a, 5, of: { subscriptSet($0, index: 2, newScalar: $1) }) expectEqual(SIMD4<Float>(1, 2, 5, 4), val1) expectEqual((SIMD4<Float>(1, 1, 0, 1), 1), pb1(ones)) func doubled(_ x: SIMD4<Float>) -> SIMD4<Float> { var result = x for i in withoutDerivative(at: x.indices) { result[i] = x[i] * 2 } return result } let (val2, pb2) = valueWithPullback(at: a, of: doubled) expectEqual(SIMD4<Float>(2, 4, 6, 8), val2) expectEqual(SIMD4<Float>(2, 2, 2, 2), pb2(ones)) } SIMDTests.test("Addition") { let a = SIMD4<Float>(1, 2, 3, 4) let g = SIMD4<Float>(1, 1, 1, 1) // SIMD + SIMD func foo1(x: SIMD4<Float>, y: SIMD4<Float>) -> SIMD4<Float> { return x + y } let (val1, pb1) = valueWithPullback(at: a, a, of: foo1) expectEqual(SIMD4<Float>(2, 4, 6, 8), val1) expectEqual((g, g), pb1(g)) // SIMD + Scalar func foo2(x: SIMD4<Float>, y: Float) -> SIMD4<Float> { return x + y } let (val2, pb2) = valueWithPullback(at: a, 5, of: foo2) expectEqual(SIMD4<Float>(6, 7, 8, 9), val2) expectEqual((g, 4), pb2(g)) // Scalar + SIMD func foo3(x: SIMD4<Float>, y: Float) -> SIMD4<Float> { return y + x } let (val3, pb3) = valueWithPullback(at: a, 5, of: foo3) expectEqual(SIMD4<Float>(6, 7, 8, 9), val3) expectEqual((g, 4), pb3(g)) } SIMDTests.test("Subtraction") { let a = SIMD4<Float>(1, 2, 3, 4) let g = SIMD4<Float>(1, 1, 1, 1) // SIMD - SIMD func foo1(x: SIMD4<Float>, y: SIMD4<Float>) -> SIMD4<Float> { return x - y } let (val1, pb1) = valueWithPullback(at: a, a, of: foo1) expectEqual(SIMD4<Float>(0, 0, 0, 0), val1) expectEqual((g, -g), pb1(g)) // SIMD - Scalar func foo2(x: SIMD4<Float>, y: Float) -> SIMD4<Float> { return x - y } let (val2, pb2) = valueWithPullback(at: a, 5, of: foo2) expectEqual(SIMD4<Float>(-4, -3, -2, -1), val2) expectEqual((g, -4), pb2(g)) // Scalar - SIMD func foo3(x: SIMD4<Float>, y: Float) -> SIMD4<Float> { return y - x } let (val3, pb3) = valueWithPullback(at: a, 5, of: foo3) expectEqual(SIMD4<Float>(4, 3, 2, 1), val3) expectEqual((-g, 4), pb3(g)) } SIMDTests.test("Multiplication") { let a = SIMD4<Float>(1, 2, 3, 4) let g = SIMD4<Float>(1, 1, 1, 1) // SIMD * SIMD func foo1(x: SIMD4<Float>, y: SIMD4<Float>) -> SIMD4<Float> { return x * y } let (val1, pb1) = valueWithPullback(at: a, a, of: foo1) expectEqual(a * a, val1) expectEqual((a, a), pb1(g)) // SIMD * Scalar func foo2(x: SIMD4<Float>, y: Float) -> SIMD4<Float> { return x * y } let (val2, pb2) = valueWithPullback(at: a, 5, of: foo2) expectEqual(a * 5, val2) expectEqual((SIMD4<Float>(5, 5, 5, 5), 10), pb2(g)) // Scalar * SIMD func foo3(x: SIMD4<Float>, y: Float) -> SIMD4<Float> { return y * x } let (val3, pb3) = valueWithPullback(at: a, 5, of: foo3) expectEqual(a * 5, val3) expectEqual((SIMD4<Float>(5, 5, 5, 5), 10), pb3(g)) } SIMDTests.test("Division") { let a = SIMD4<Float>(1, 2, 3, 4) let g = SIMD4<Float>(1, 1, 1, 1) // SIMD / SIMD func foo1(x: SIMD4<Float>, y: SIMD4<Float>) -> SIMD4<Float> { return x / y } let dlhs1 = g / a let drhs1 = -1 / a let (val1, pb1) = valueWithPullback(at: a, a, of: foo1) expectEqual(a / a, val1) expectEqual((dlhs1, drhs1), pb1(g)) // SIMD / Scalar func foo2(x: SIMD4<Float>, y: Float) -> SIMD4<Float> { return x / y } let dlhs2 = g / 5 let drhs2 = (-a / 25 * g).sum() let (val2, pb2) = valueWithPullback(at: a, 5, of: foo2) expectEqual(a / 5, val2) expectEqual((dlhs2, drhs2), pb2(g)) // Scalar / SIMD func foo3(x: Float, y: SIMD4<Float>) -> SIMD4<Float> { return x / y } let dlhs3 = (g / a).sum() let drhs3 = -5 / (a*a) * g let (val3, pb3) = valueWithPullback(at: 5, a, of: foo3) expectEqual(5 / a, val3) expectEqual((dlhs3, drhs3), pb3(g)) } SIMDTests.test("Generics") { let a = SIMD3<Double>(1, 2, 3) let g = SIMD3<Double>(1, 1, 1) func testInit<Scalar, SIMDType: SIMD>(x: Scalar) -> SIMDType where SIMDType.Scalar == Scalar, SIMDType : Differentiable, Scalar : BinaryFloatingPoint & Differentiable, SIMDType.TangentVector == SIMDType, Scalar.TangentVector == Scalar { return SIMDType.init(repeating: x) } func simd3Init(x: Double) -> SIMD3<Double> { testInit(x: x) } let (val1, pb1) = valueWithPullback(at: 10, of: simd3Init) expectEqual(SIMD3<Double>(10, 10, 10), val1) expectEqual(3, pb1(g)) // SIMDType + SIMDType func testAddition<Scalar, SIMDType: SIMD>(lhs: SIMDType, rhs: SIMDType) -> SIMDType where SIMDType.Scalar == Scalar, SIMDType : Differentiable, SIMDType.TangentVector : SIMD, Scalar : BinaryFloatingPoint, SIMDType.TangentVector.Scalar : BinaryFloatingPoint { return lhs + rhs } func simd3Add(lhs: SIMD3<Double>, rhs: SIMD3<Double>) -> SIMD3<Double> { return testAddition(lhs: lhs, rhs: rhs) } let (val2, pb2) = valueWithPullback(at: a, a, of: simd3Add) expectEqual(SIMD3<Double>(2, 4, 6), val2) expectEqual((g, g), pb2(g)) // Scalar - SIMDType func testSubtraction<Scalar, SIMDType: SIMD>(lhs: Scalar, rhs: SIMDType) -> SIMDType where SIMDType.Scalar == Scalar, SIMDType : Differentiable, Scalar : BinaryFloatingPoint & Differentiable, SIMDType.TangentVector == SIMDType, Scalar.TangentVector == Scalar { return lhs - rhs } func simd3Subtract(lhs: Double, rhs: SIMD3<Double>) -> SIMD3<Double> { return testSubtraction(lhs: lhs, rhs: rhs) } let (val3, pb3) = valueWithPullback(at: 5, a, of: simd3Subtract) expectEqual(SIMD3<Double>(4, 3, 2), val3) expectEqual((3, SIMD3<Double>(-1, -1, -1)), pb3(g)) // SIMDType * Scalar func testMultiplication<Scalar, SIMDType: SIMD>(lhs: SIMDType, rhs: Scalar) -> SIMDType where SIMDType.Scalar == Scalar, SIMDType : Differentiable, Scalar : BinaryFloatingPoint & Differentiable, SIMDType.TangentVector == SIMDType, Scalar.TangentVector == Scalar { return lhs * rhs } func simd3Multiply(lhs: SIMD3<Double>, rhs: Double) -> SIMD3<Double> { return testMultiplication(lhs: lhs, rhs: rhs) } let (val4, pb4) = valueWithPullback(at: a, 5, of: simd3Multiply) expectEqual(SIMD3<Double>(5, 10, 15), val4) expectEqual((SIMD3<Double>(5, 5, 5), 6), pb4(g)) // FIXME(TF-1103): Derivative registration does not yet support // `@_alwaysEmitIntoClient` original functions like `SIMD.sum()`. /* func testSum<Scalar, SIMDType: SIMD>(x: SIMDType) -> Scalar where SIMDType.Scalar == Scalar, SIMDType : Differentiable, Scalar : BinaryFloatingPoint & Differentiable, Scalar.TangentVector : BinaryFloatingPoint, SIMDType.TangentVector == SIMDType { return x.sum() } func simd3Sum(x: SIMD3<Double>) -> Double { testSum(x: x) } let (val5, pb5) = valueWithPullback(at: a, of: simd3Sum) expectEqual(6, val5) expectEqual(SIMD3<Double>(7, 7, 7), pb5(7)) */ } runAllTests()
apache-2.0
17cdea6f713d0e8687e5d3c2ae1b399e
28.442308
98
0.620183
2.966096
false
true
false
false
iamcam/Sinker
Sinker/ViewController.swift
1
5150
// // ViewController.swift // Hook Line and Sinker // // Created by Cameron Perry on 12/16/14. // Copyright (c) 2014 Cameron Perry. All rights reserved. // import UIKit class ViewController: UIViewController, SettingsDelegate { let kClientAccessIdentifier = CommonSettings().clientAccessIdentifier var manager: AFOAuth2Manager? var widgets: NSArray? var client_id: String { get { return CommonSettings().client_id } } var client_secret: String { get { return CommonSettings().client_secret } } var baseURL: NSURL? { get { return NSURL(string: CommonSettings().hostURL) } } @IBOutlet var pullButton: UIView! @IBAction func showSettings(sender: UIButton) { var settings = SettingsViewController(nibName:"SettingsViewController", bundle:nil) settings.delegate = self presentViewController(settings, animated: true, completion: nil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) manager = AFOAuth2Manager(baseURL: self.baseURL, clientID: self.client_id, secret: self.client_secret) } @IBAction func pushedButton(sender: AnyObject) { authenticateApp({ (credential) -> () in println("👍 Credential found: \(credential!)") }, failure: { (error) -> () in println("💩 \(error)") }) } @IBAction func logOut(sender: AnyObject) { if( true == AFOAuthCredential.deleteCredentialWithIdentifier(kClientAccessIdentifier) ){ println("'Logged out'") } else { println("Could not delete credential") } } @IBAction func fetchWidgets(sender: AnyObject) { if( credentialIsCurrent()) { retrieveWidgets() } else { authenticateApp({ (credential) -> () in self.retrieveWidgets() }, failure: { (error) -> () in // handle the error }) } } func authenticateApp(success: ((AFOAuthCredential?)->()), failure:((NSError)->())) { if ( credentialIsCurrent() ) { success(AFOAuthCredential.retrieveCredentialWithIdentifier(kClientAccessIdentifier)) } else { manager?.authenticateUsingOAuthWithURLString("/oauth/token", scope: "public", success: { (credential) -> Void in println("Good job! \(credential)" ) var didSave = AFOAuthCredential.storeCredential(credential, withIdentifier: self.kClientAccessIdentifier) success(credential); }, failure: { (error) -> Void in failure(error) }) } } func credentialIsCurrent() -> Bool{ var isValid = false if let credential = AFOAuthCredential.retrieveCredentialWithIdentifier(kClientAccessIdentifier){ println("Found credential: \(credential)") if (credential.expired) { println("Credential expired") AFOAuthCredential.deleteCredentialWithIdentifier(kClientAccessIdentifier) isValid = false } else { isValid = true } } else { isValid = false } return isValid } func retrieveWidgets(){ if let credential = AFOAuthCredential.retrieveCredentialWithIdentifier(kClientAccessIdentifier){ manager?.requestSerializer.setAuthorizationHeaderFieldWithCredential(credential) manager?.GET("api/v1/widgets.json", parameters: nil, success: { (theOperation, responseObject) -> Void in println("Working") self.widgets = responseObject as? NSArray if (self.widgets != nil && self.widgets!.count > 0){ if let d = self.widgets![0] as? NSDictionary { println("First Widget: \(d)") if let uuid = d["uuid"] as? String { println("UUID is \(uuid)"); } } } else { println("No Widgets Found") } }, failure: { (theOperation, error) -> Void in println("Error \(error)") }) } else { authenticateApp({ (credential) -> () in self.retrieveWidgets() }, failure: { (error) -> () in println("Failed authentication. Maybe something is wrong with the client id and secret") }) } } //MARK: - Settings Delegate methods func apiSettingsChanged() { println("baseURL: \(self.baseURL), clientID: \(self.client_id), secret: \(self.client_secret)") manager = AFOAuth2Manager(baseURL: self.baseURL, clientID: self.client_id, secret: self.client_secret) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ac82658ec9383f77dbf598bfbb59d365
30.753086
124
0.562986
5.138861
false
false
false
false
romainPellerin/SilverCalc
SilverCalc-iOS/RootViewController.swift
2
3914
import UIKit @IBObject class RootViewController : UIViewController { var buttons : [UIButton] = [] var calc : Calculator = Calculator() var tf : UITextField! @IBOutlet var tf_numb : UITextField! var NUMBER_ACTION = 0 var OPERATOR_ACTION = 1 var DOT_ACTION = 2 var EQUAL_ACTION = 3 var lastAction = NUMBER_ACTION public override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupButtons() } func alert(s:String){ let alert = UIAlertView() alert.title = "Calc alert" alert.message = s alert.addButtonWithTitle("Ok") alert.show() } func setupButtons(){ // discover buttons from view in Main.storyboard // instead of duplicate buttons declarations for bt in self.view.subviews { if bt is UIButton { // set buttons style bt.layer.cornerRadius = 5.0; bt.layer.borderColor = UIColor(red: 191.0/255, green: 188.0/255, blue: 188.0/255, alpha: 1.0).CGColor bt.layer.borderWidth = 0.5 // bind target methods to buttons if bt.titleLabel.text == "x" { bt.addTarget(self, action: "multiply:", forControlEvents: UIControlEvents.TouchUpInside) } else if bt.titleLabel.text == "/" { bt.addTarget(self, action: "divide:", forControlEvents: UIControlEvents.TouchUpInside) } else if bt.titleLabel.text == "-" { bt.addTarget(self, action: "minus:", forControlEvents: UIControlEvents.TouchUpInside) } else if bt.titleLabel.text == "+" { bt.addTarget(self, action: "add:", forControlEvents: UIControlEvents.TouchUpInside) } else if bt.titleLabel.text == "C" { bt.addTarget(self, action: "clear:", forControlEvents: UIControlEvents.TouchUpInside) } else if bt.titleLabel.text == "+/-" { bt.addTarget(self, action: "invert:", forControlEvents: UIControlEvents.TouchUpInside) } else if bt.titleLabel.text == "=" { bt.addTarget(self, action: "equal:", forControlEvents: UIControlEvents.TouchUpInside) } else if bt.titleLabel.text == "," { bt.addTarget(self, action: "dot:", forControlEvents: UIControlEvents.TouchUpInside) } else { bt.addTarget(self, action: "numberPressed:", forControlEvents: UIControlEvents.TouchUpInside) } } else if bt is UITextField { tf = bt tf.text = "0.0" tf.enabled = NO tf.textAlignment = .Right } buttons.append(bt) } } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); // Dispose of any resources that can be recreated. } func numberPressed(sender:UIButton!) { lastAction = NUMBER_ACTION var nb:String = sender.titleLabel.text var c : Int32 = nb[0]-48 // calc will compose number with new int part calc.composeNumber(c) tf.text = calc.getStringValue() } func multiply(sender:UIButton!) { lastAction = OPERATOR_ACTION calc.multiply() tf.text = calc.getStringValue() } func divide(sender:UIButton!) { lastAction = OPERATOR_ACTION calc.divide() tf.text = calc.getStringValue() } func minus(sender:UIButton!) { lastAction = OPERATOR_ACTION calc.minus() tf.text = calc.getStringValue() } func add(sender:UIButton!) { lastAction = OPERATOR_ACTION calc.add() tf.text = calc.getStringValue() } func equal(sender:UIButton!) { lastAction = EQUAL_ACTION calc.process() tf.text = calc.getStringValue() } func clear(sender:UIButton!) { lastAction = OPERATOR_ACTION calc.clearNumber() tf.text = calc.getStringValue() } func invert(sender:UIButton!) { lastAction = OPERATOR_ACTION calc.invert() tf.text = calc.getStringValue() } func dot(sender:UIButton!) { lastAction = OPERATOR_ACTION calc.afterdot = true } }
apache-2.0
aa5739bcfef9bdb08fc7838b2f030ea1
22.616352
106
0.64545
3.471162
false
false
false
false
turekj/ReactiveTODO
ReactiveTODOTests/Classes/ViewModels/Factories/Impl/TODONoteListViewModelFactorySpec.swift
1
1166
@testable import ReactiveTODOFramework import Nimble import Quick import RealmSwift class TODONoteListViewModelFactorySpec: QuickSpec { override func spec() { describe("TODONoteListViewModelFactory") { let dao = TODONoteDataAccessObjectMock() let sut = TODONoteListViewModelFactory(todoNoteDAO: dao) beforeEach { let realm = try! Realm() let firstTodo = TODONote() firstTodo.guid = "1st" let secondTodo = TODONote() secondTodo.guid = "2nd" try! realm.write { realm.add(firstTodo) realm.add(secondTodo) } } context("When creating a view model") { it("Should fetch all current notes from dao") { dao.targetGuid = "1st" let viewModel = sut.createViewModel() let notes = viewModel.notes.collection expect(notes.count).to(equal(1)) expect(notes[0].guid).to(equal("1st")) } } } } }
mit
7e6c71608e55265ca458765c31039a13
26.761905
68
0.509434
5.159292
false
false
false
false
frootloops/swift
test/NameBinding/Dependencies/private-typealias.swift
2
838
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps private struct Wrapper { static func test() -> InterestingType { fatalError() } } // CHECK-OLD: sil_global @_T04main1x{{[^ ]+}} : $Int // CHECK-NEW: sil_global @_T04main1x{{[^ ]+}} : $Double public var x = Wrapper.test() + 0 // CHECK-DEPS-LABEL: depends-top-level: // CHECK-DEPS: - "InterestingType"
apache-2.0
ea842293113432c1d6bb40fc320bc295
51.375
203
0.710024
3.162264
false
true
false
false
ta2yak/MaterialKit
Source/MKImageView.swift
1
3470
// // MKImageView.swift // MaterialKit // // Created by Le Van Nghia on 11/29/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit @IBDesignable public class MKImageView: UIImageView { @IBInspectable public var maskEnabled: Bool = true { didSet { mkLayer.enableMask(enable: maskEnabled) } } @IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation { didSet { mkLayer.rippleLocation = rippleLocation } } @IBInspectable public var rippleAniDuration: Float = 0.75 @IBInspectable public var backgroundAniDuration: Float = 1.0 @IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear @IBInspectable public var backgroundAniTimingFunction: MKTimingFunction = .Linear @IBInspectable public var backgroundAniEnabled: Bool = true { didSet { if !backgroundAniEnabled { mkLayer.enableOnlyCircleLayer() } } } @IBInspectable public var ripplePercent: Float = 0.9 { didSet { mkLayer.ripplePercent = ripplePercent } } @IBInspectable public var cornerRadius: CGFloat = 2.5 { didSet { layer.cornerRadius = cornerRadius mkLayer.setMaskLayerCornerRadius(cornerRadius) } } // color @IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) { didSet { mkLayer.setCircleLayerColor(rippleLayerColor) } } @IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) { didSet { mkLayer.setBackgroundLayerColor(backgroundLayerColor) } } override public var bounds: CGRect { didSet { mkLayer.superLayerDidResize() } } private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer) required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override public init(frame: CGRect) { super.init(frame: frame) setup() } override public init(image: UIImage!) { super.init(image: image) setup() } override public init(image: UIImage!, highlightedImage: UIImage?) { super.init(image: image, highlightedImage: highlightedImage) setup() } private func setup() { mkLayer.setCircleLayerColor(rippleLayerColor) mkLayer.setBackgroundLayerColor(backgroundLayerColor) mkLayer.setMaskLayerCornerRadius(cornerRadius) } public func animateRipple(location: CGPoint? = nil) { if let point = location { mkLayer.didChangeTapLocation(point) } else if rippleLocation == .TapLocation { rippleLocation = .Center } mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(self.rippleAniDuration)) mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(self.backgroundAniDuration)) } override public func touchesBegan(touches: NSSet, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) if let firstTouch = touches.anyObject() as? UITouch { let location = firstTouch.locationInView(self) animateRipple(location: location) } } }
mit
7b0838cf0e82408244c161f251449fb2
30.834862
153
0.651585
5.087977
false
false
false
false
victorlin/ReactiveCocoa
ReactiveCocoa/Swift/Atomic.swift
1
4249
// // Atomic.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-06-10. // Copyright (c) 2014 GitHub. All rights reserved. // import Foundation final class PosixThreadMutex: NSLocking { private var mutex = pthread_mutex_t() init() { let result = pthread_mutex_init(&mutex, nil) precondition(result == 0, "Failed to initialize mutex with error \(result).") } deinit { let result = pthread_mutex_destroy(&mutex) precondition(result == 0, "Failed to destroy mutex with error \(result).") } func lock() { let result = pthread_mutex_lock(&mutex) precondition(result == 0, "Failed to lock \(self) with error \(result).") } func unlock() { let result = pthread_mutex_unlock(&mutex) precondition(result == 0, "Failed to unlock \(self) with error \(result).") } } /// An atomic variable. public final class Atomic<Value>: AtomicProtocol { private let lock: PosixThreadMutex private var _value: Value /// Initialize the variable with the given initial value. /// /// - parameters: /// - value: Initial value for `self`. public init(_ value: Value) { _value = value lock = PosixThreadMutex() } /// Atomically modifies the variable. /// /// - parameters: /// - action: A closure that takes the current value. /// /// - returns: The result of the action. @discardableResult public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result { lock.lock() defer { lock.unlock() } return try action(&_value) } /// Atomically perform an arbitrary action using the current value of the /// variable. /// /// - parameters: /// - action: A closure that takes the current value. /// /// - returns: The result of the action. @discardableResult public func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result { lock.lock() defer { lock.unlock() } return try action(_value) } } /// An atomic variable which uses a recursive lock. internal final class RecursiveAtomic<Value>: AtomicProtocol { private let lock: NSRecursiveLock private var _value: Value private let didSetObserver: ((Value) -> Void)? /// Initialize the variable with the given initial value. /// /// - parameters: /// - value: Initial value for `self`. /// - name: An optional name used to create the recursive lock. /// - action: An optional closure which would be invoked every time the /// value of `self` is mutated. internal init(_ value: Value, name: StaticString? = nil, didSet action: ((Value) -> Void)? = nil) { _value = value lock = NSRecursiveLock() lock.name = name.map(String.init(describing:)) didSetObserver = action } /// Atomically modifies the variable. /// /// - parameters: /// - action: A closure that takes the current value. /// /// - returns: The result of the action. @discardableResult func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result { lock.lock() defer { didSetObserver?(_value) lock.unlock() } return try action(&_value) } /// Atomically perform an arbitrary action using the current value of the /// variable. /// /// - parameters: /// - action: A closure that takes the current value. /// /// - returns: The result of the action. @discardableResult func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result { lock.lock() defer { lock.unlock() } return try action(_value) } } public protocol AtomicProtocol: class { associatedtype Value @discardableResult func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result @discardableResult func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result } extension AtomicProtocol { /// Atomically get or set the value of the variable. public var value: Value { get { return withValue { $0 } } set(newValue) { swap(newValue) } } /// Atomically replace the contents of the variable. /// /// - parameters: /// - newValue: A new value for the variable. /// /// - returns: The old value. @discardableResult public func swap(_ newValue: Value) -> Value { return modify { (value: inout Value) in let oldValue = value value = newValue return oldValue } } }
mit
0f90b4b36a3b608070e907f51c4330ef
24.142012
100
0.667922
3.591716
false
false
false
false
Kijjakarn/Crease-Pattern-Analyzer
CreasePatternAnalyzer/Utilities/Axioms.swift
1
7914
// // Axioms.swift // CreasePatternAnalyzer // // Created by Kijjakarn Praditukrit on 11/22/16. // Copyright © 2016-2017 Kijjakarn Praditukrit. All rights reserved. // import Darwin /*---------------------------------------------------------------------------- Huzita-Justin Axioms Implementations - All points and lines passed to these functions must be distinct -----------------------------------------------------------------------------*/ // Axiom 1: Given two points p1 and p2, we can fold a line connecting them func axiom1(_ p1: PointVector, _ p2: PointVector) -> Line? { let fold = Line(p1, p2) return main.paper.contains(line: fold) ? fold : nil } // Axiom 2: Given two points p1 and p2, we can fold p1 onto p2 func axiom2(_ p1: PointVector, _ p2: PointVector) -> Line? { let unitNormal = ((p1 - p2)/2).normalized() let midPoint = (p1 + p2)/2 let fold = Line(point: midPoint, unitNormal: unitNormal) return main.paper.contains(line: fold) ? fold : nil } // Axiom 3: Given two lines line1 and line2, we can fold line1 onto line2 // - If lines are parallel, return one solution // - Otherwise, return line(s) contained in main.paper func axiom3(_ line1: Line, _ line2: Line) -> [Line] { guard let p = intersection(line1, line2) else { return [Line(distance: (line1.distance + line2.distance)/2, unitNormal: line1.unitNormal)] } let direction = (line1.unitNormal + line2.unitNormal).normalized() let fold1 = Line(point: p, unitNormal: direction) let fold2 = Line(point: p, unitNormal: direction.rotatedBy90()) var folds = [Line]() if main.paper.contains(line: fold1) { folds.append(fold1) } if main.paper.contains(line: fold2) { folds.append(fold2) } return folds } // Axiom 4: Given a point p and a line, we can make a fold perpendicular to the // line passing through the point p func axiom4(point: PointVector, line: Line) -> Line? { if main.paper.encloses(point: line.projection(ofPoint: point)) { let fold = Line(point: point, unitNormal: line.unitNormal.rotatedBy90()) return main.paper.contains(line: fold) ? fold : nil } return nil } // Axiom 5: Given two points p1 and p2 and a line, we can make a fold that // places p1 onto the line and passes through p2 // - This is the same as finding lines that go through p2 and the intersection // between the circle centered at p2 with radius |p2 - p1| func axiom5(bring p1: PointVector, to line: Line, through p2: PointVector) -> [Line] { let radius = (p1 - p2).magnitude let centerToLine = line.unitNormal*(line.distance - line.unitNormal.dot(p2)) // If the line does not intersect the circle if radius < centerToLine.magnitude { return [] } let addVector = line.unitNormal.rotatedBy90() * sqrt(radius*radius - centerToLine.magnitudeSquared()) let point1 = centerToLine + p2 + addVector let point2 = centerToLine + p2 - addVector var folds = [Line]() if main.paper.encloses(point: point1) { let p11 = (p1 + point1)/2 if p2 != p11 { folds.append(Line(p2, p11)) } } if main.paper.encloses(point: point2) { let p12 = (p1 + point2)/2 if p2 != p12 { folds.append(Line(p2, p12)) } } return folds } // Axiom 6: Given two points p1 and p2 and two lines line1 and line2, we can // make a fold that places p1 onto line1 and places p2 onto line2 // - First transform the coordinate system by aligning line1 with the x-axis by // - shifting and rotating, then put p1 on the y-axis by shifting func axiom6(bring p1: PointVector, to line1: Line, and p2: PointVector, on line2: Line) -> [Line] { let u1 = line1.unitNormal let u2 = line2.unitNormal let u1P = u1.rotatedBy90()*(-1) let v1 = p1 - u1*line1.distance let v2 = p2 - u1*line1.distance let x1 = v1.dot(u1P) let x2 = v2.dot(u1P) - x1 let y1 = v1.dot(u1) let y2 = v2.dot(u1) let u2x = u2.dot(u1P) let u2y = u2.dot(u1) let d2 = line2.distance - u2.dot(u1*line1.distance) - u2x*x1 let yy = 2*y2 - y1 let z = d2 - u2x*x2 - u2y*y2 // Coefficients of the cubic equation let a = u2x let b = -(2*u2x*x2 + u2y*y1 + z) let c = y1*(2*u2y*x2 + u2x*yy) let d = -y1*y1*(u2y*yy + z) // Solve the equation and get the folded line let roots = solveCubic(a, b, c, d) var folds = [Line]() for root in roots { let p1Folded = u1*line1.distance + u1P*(root + x1) // If fold goes through p1 or main.paper doesn't enclose reflected point if p1 == p1Folded || !main.paper.encloses(point: p1Folded) { continue } let fold = Line(point: (p1 + p1Folded)/2, normal: (p1 - p1Folded)) // If main.paper doesn't contain the fold or p1 and p2 aren't on the // same side of main.paper if !main.paper.contains(line: fold) || (line1.distance - p1.dot(u1))*(line1.distance - p1.dot(u2)) < 0 { continue } let p2Folded = fold.reflection(ofPoint: p2) // If fold doesn't enclose the reflected p2 if !main.paper.encloses(point: p2Folded) { continue } folds.append(fold) } return folds } // Solve cubic equation of the form ax^3 + bx^2 + cx + d = 0 // - Use Cardano's formula // - Return real solutions only // - See https://proofwiki.org/wiki/Cardano%27s_Formula/Real_Coefficients func solveCubic(_ a: Double , _ b: Double, _ c: Double, _ d: Double) -> [Double] { // The equation is not cubic if abs(a) < main.ε { if abs(b) < main.ε { // The equation is wrong or trivial if abs(c) < main.ε { return [] } // The equation is linear return [-d/c] } // The equation is quadratic let discriminant = c*c - 4*b*d if discriminant < 0 { return [] } if discriminant < main.ε { return [-c/(2*b)] } let sqrtOfDiscriminant = sqrt(discriminant) let x1 = (-c + sqrtOfDiscriminant)/(2*b) let x2 = (-c - sqrtOfDiscriminant)/(2*b) return [x1, x2] } // The equation is cubic let q = (3*a*c - b*b)/(9*a*a) let r = (9*a*b*c - 27*a*a*d - 2*b^^3)/(54*a^^3) let discriminant = q^^3 + r^^2 // All roots are real and distinct if discriminant < 0 { let θ = acos(r/sqrt(-q^^3))/3 let e = 2*sqrt(-q) let f = b/(3*a) let x1 = e*cos(θ) - f let x2 = e*cos(θ + 2*π/3) - f let x3 = e*cos(θ + 4*π/3) - f return [x1, x2, x3] } // All roots are real and at least two are equal if discriminant < main.ε { // There is only one real root if r == 0 { return [-b/(3*a)] } let e = cbrt(r) let f = b/(3*a) let x1 = 2*e - f let x2 = -e - f return [x1, x2] } // There is one real root and the other two are complex conjugates let sqrtOfDiscriminant = sqrt(discriminant) let x1 = cbrt(r + sqrtOfDiscriminant) + cbrt(r - sqrtOfDiscriminant) - b/(3*a) return [x1] } // Axiom 7: Given a point p and two lines line1 and line2, we can make a fold // perpendicular to line2 that places p onto line1 func axiom7(bring p: PointVector, to line1: Line, along line2: Line) -> Line? { let u1 = line1.unitNormal let u2 = line2.unitNormal let u2P = u2.rotatedBy90() let foldDistance = (line1.distance - p.dot(u1)) / (2*u2P.dot(u1)) + p.dot(u2P) let fold = Line(distance: foldDistance, unitNormal: u2P) if (main.paper.encloses(point: fold.reflection(ofPoint: p)) && main.paper.contains(line: fold)) { return fold } return nil }
gpl-3.0
dc63151659ca21566e399e8c68d99ef2
35.414747
80
0.583776
3.167134
false
false
false
false
bingoogolapple/SwiftNote-PartOne
swift2048/swift2048/MainViewController.swift
2
2451
// // MainViewController.swift // swift2048 // // Created by bingoogol on 14-6-18. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class MainViewController:UIViewController { // 游戏方格维度 var dimension:Int = 4 // 游戏过关最大值 var maxNumber:Int = 2048 //数字格子的宽度 var width:CGFloat = 50 //格子与格子的间距 var padding:CGFloat = 6 var backgrounds:Array<UIView> init() { self.backgrounds = Array<UIView>() super.init(nibName:nil,bundle:nil) } override func viewDidLoad() { super.viewDidLoad() setupBackground() getNumber() } func setupBackground() { var x:CGFloat = 30 var y:CGFloat = 150 for col in 0 .. dimension { y = 150 for row in 0 .. dimension { var background = UIView(frame:CGRectMake(x,y,width,width)) background.backgroundColor = UIColor.darkGrayColor() self.view.addSubview(background) backgrounds += background y += padding + width } x += padding + width } } func getNumber() { let randv = Int(arc4random_uniform(10)) println(randv) var seed:Int = 2 if(randv == 1) { seed = 4 } let col = Int(arc4random_uniform(UInt32(dimension))) let row = Int(arc4random_uniform(UInt32(dimension))) insertTitle((row,col),value:seed); } func insertTitle(pos:(Int,Int),value:Int) { let (row,col) = pos let x = 30 + CGFloat(col) * (width + padding) let y = 150 + CGFloat(row) * (width + padding) let tile = TileView(pos:CGPointMake(x,y),width:width,value:value) self.view.addSubview(tile) self.view.bringSubviewToFront(tile) UIView.animateWithDuration(0.3,delay:0.1,options: UIViewAnimationOptions.TransitionNone,animations:{ ()->Void in tile.layer.setAffineTransform(CGAffineTransformMakeScale(1,1)) },completion: { (finished:Bool)->Void in UIView.animateWithDuration(0.08,animations:{ ()->Void in tile.layer.setAffineTransform(CGAffineTransformIdentity) }) }) } }
apache-2.0
ed12af9ff21bb796d4689fe420931982
27.5
78
0.546594
4.406998
false
false
false
false
StanZabroda/Hydra
Hydra/HRFooterProgress.swift
1
1650
// // HRFooterProgress.swift // Hydra // // Created by Evgeny Evgrafov on 9/22/15. // Copyright © 2015 Evgeny Evgrafov. All rights reserved. // import UIKit class HRFooterProgress: UIView { var progressActivity : UIActivityIndicatorView! var infoTitle : UILabel! override init(frame: CGRect) { let customFrame = CGRectMake(0, 0, screenSizeWidth, 80) super.init(frame: customFrame) self.progressActivity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) self.progressActivity.frame = CGRectMake(screenSizeWidth/2-5, 60, 10, 10) self.infoTitle = UILabel() self.infoTitle.frame = CGRectMake(0, 5, screenSizeWidth, 50) self.infoTitle.textColor = UIColor.grayColor() self.infoTitle.font = UIFont(name: "HelveticaNeue-Thin", size: 11) self.infoTitle.textAlignment = NSTextAlignment.Center self.infoTitle.numberOfLines = 0 self.addSubview(self.progressActivity) self.addSubview(self.infoTitle) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func startProgress() { self.progressActivity.startAnimating() } func stopProgress() { self.progressActivity.stopAnimating() self.hideTitle() } func titleText(text:String) { self.infoTitle.text = text self.showTitle() } func showTitle() { self.infoTitle.hidden = false } func hideTitle() { self.infoTitle.hidden = true } }
mit
8f6b51f205df697ff84a9d10fc024caa
25.596774
114
0.63675
4.385638
false
false
false
false
brennanMKE/StravaKit
Sources/StravaAthlete.swift
2
7345
// // StravaAthlete.swift // StravaKit // // Created by Brennan Stehling on 8/21/16. // Copyright © 2016 SmallSharpTools LLC. All rights reserved. // import Foundation public enum AthleteResourcePath: String { case Athlete = "/api/v3/athlete" case Athletes = "/api/v3/athletes/:id" case Friends = "/api/v3/athlete/friends" case Zones = "/api/v3/athlete/zones" case Stats = "/api/v3/athletes/:id/stats" } public extension Strava { /** Gets profile for current athlete. ```swift Strava.getAthlete { (athlete, error) in } ``` Docs: http://strava.github.io/api/v3/athlete/#get-details */ @discardableResult public static func getAthlete(_ completionHandler: ((_ athlete: Athlete?, _ error: NSError?) -> ())?) -> URLSessionTask? { let path = AthleteResourcePath.Athlete.rawValue return request(.GET, authenticated: true, path: path, params: nil) { (response, error) in if let error = error { DispatchQueue.main.async { completionHandler?(nil, error) } return } handleAthleteResponse(response, completionHandler: completionHandler) } } /** Gets profile for athlete by ID. ```swift Strava.getAthlete(athleteId) { (athlete, error) in } ``` Docs: http://strava.github.io/api/v3/athlete/#get-another-details */ @discardableResult public static func getAthlete(_ athleteId: Int, completionHandler: ((_ athlete: Athlete?, _ error: NSError?) -> ())?) -> URLSessionTask? { let path = replaceId(id: athleteId, in: AthleteResourcePath.Athletes.rawValue) return request(.GET, authenticated: true, path: path, params: nil) { (response, error) in if let error = error { DispatchQueue.main.async { completionHandler?(nil, error) } return } handleAthleteResponse(response, completionHandler: completionHandler) } } /** Gets friends of current athlete. ```swift Strava.getAthleteFriends { (athletes, error) in } ``` Docs: http://strava.github.io/api/v3/follow/#friends */ @discardableResult public static func getAthleteFriends(_ page: Page? = nil, completionHandler: ((_ athletes: [Athlete]?, _ error: NSError?) -> ())?) -> URLSessionTask? { let path = AthleteResourcePath.Friends.rawValue var params: ParamsDictionary? = nil if let page = page { params = [ PageKey: page.page, PerPageKey: page.perPage ] } return request(.GET, authenticated: true, path: path, params: params) { (response, error) in if let error = error { DispatchQueue.main.async { completionHandler?(nil, error) } return } handleAthleteFriendsResponse(response, completionHandler: completionHandler) } } /** Gets zones of current athlete. ```swift Strava.getAthleteZones { (zones, error) in } ``` Docs: http://strava.github.io/api/v3/athlete/#zones */ @discardableResult public static func getAthleteZones(_ page: Page? = nil, completionHandler: ((_ zones: Zones?, _ error: NSError?) -> ())?) -> URLSessionTask? { let path = AthleteResourcePath.Zones.rawValue var params: ParamsDictionary? = nil if let page = page { params = [ PageKey: page.page, PerPageKey: page.perPage ] } return request(.GET, authenticated: true, path: path, params: params) { (response, error) in if let error = error { DispatchQueue.main.async { completionHandler?(nil, error) } return } handleAthleteZonesResponse(response, completionHandler: completionHandler) } } /** Gets stats for athlete by ID. ```swift Strava.getStats(athleteId, completionHandler: { (stats, error) in } ``` Docs: http://strava.github.io/api/v3/athlete/#stats */ @discardableResult public static func getStats(_ athleteId: Int, completionHandler: ((_ stats: Stats?, _ error: NSError?) -> ())?) -> URLSessionTask? { let path = replaceId(id: athleteId, in: AthleteResourcePath.Stats.rawValue) return request(.GET, authenticated: true, path: path, params: nil) { (response, error) in if let error = error { DispatchQueue.main.async { completionHandler?(nil, error) } return } handleStatsResponse(athleteId, response: response, completionHandler: completionHandler) } } // MARK: - Internal Functions - internal static func handleAthleteResponse(_ response: Any?, completionHandler: ((_ athlete: Athlete?, _ error: NSError?) -> ())?) { if let dictionary = response as? JSONDictionary, let athlete = Athlete(dictionary: dictionary) { DispatchQueue.main.async { completionHandler?(athlete, nil) } } else { let error = Strava.error(.invalidResponse, reason: "Invalid Response") DispatchQueue.main.async { completionHandler?(nil, error) } } } internal static func handleAthleteFriendsResponse(_ response: Any?, completionHandler: ((_ athletes: [Athlete]?, _ error: NSError?) -> ())?) { if let dictionaries = response as? JSONArray { let athletes = Athlete.athletes(dictionaries) DispatchQueue.main.async { completionHandler?(athletes, nil) } } else { let error = Strava.error(.invalidResponse, reason: "Invalid Response") DispatchQueue.main.async { completionHandler?(nil, error) } } } internal static func handleAthleteZonesResponse(_ response: Any?, completionHandler: ((_ zones: Zones?, _ error: NSError?) -> ())?) { if let dictionary = response as? JSONDictionary, let zones = Zones(dictionary: dictionary) { DispatchQueue.main.async { completionHandler?(zones, nil) } } else { let error = Strava.error(.invalidResponse, reason: "Invalid Response") DispatchQueue.main.async { completionHandler?(nil, error) } } } internal static func handleStatsResponse(_ athleteId: Int, response: Any?, completionHandler: ((_ stats: Stats?, _ error: NSError?) -> ())?) { if let dictionary = response as? JSONDictionary, let stats = Stats(athleteId: athleteId, dictionary: dictionary) { DispatchQueue.main.async { completionHandler?(stats, nil) } } else { let error = Strava.error(.invalidResponse, reason: "Invalid Response") DispatchQueue.main.async { completionHandler?(nil, error) } } } }
mit
3490b47798af4d32a0f2a6a9ab7cd098
31.64
155
0.569444
4.73501
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/NoImageModeHelper.swift
1
1390
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Shared struct NoImageModePrefsKey { static let NoImageModeStatus = PrefsKeys.KeyNoImageModeStatus } class NoImageModeHelper: TabContentScript { fileprivate weak var tab: Tab? required init(tab: Tab) { self.tab = tab } static func name() -> String { return "NoImageMode" } func scriptMessageHandlerName() -> String? { return "NoImageMode" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { // Do nothing. } static func isActivated(_ prefs: Prefs) -> Bool { return prefs.boolForKey(NoImageModePrefsKey.NoImageModeStatus) ?? false } static func toggle(isEnabled: Bool, profile: Profile, tabManager: TabManager) { if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let bvc = appDelegate.browserViewController { bvc.navigationToolbar.hideImagesBadge(visible: isEnabled) } profile.prefs.setBool(isEnabled, forKey: PrefsKeys.KeyNoImageModeStatus) tabManager.tabs.forEach { $0.noImageMode = isEnabled } } }
mpl-2.0
7b744d2d204783521ca77cbee80dc284
30.590909
132
0.702158
4.793103
false
false
false
false
safx/IIJMioKit
IIJMioKitSample/PacketLogCell.swift
1
1229
// // PacketLogCell.swift // IIJMioKit // // Created by Safx Developer on 2015/05/16. // Copyright (c) 2015年 Safx Developers. All rights reserved. // import UIKit import IIJMioKit class PacketLogCell: UITableViewCell { @IBOutlet weak var date: UILabel! @IBOutlet weak var withCoupon: UILabel! @IBOutlet weak var withoutCoupon: UILabel! private let dateFormatter = NSDateFormatter() var model: MIOPacketLog? { didSet { modelDidSet() } } private func modelDidSet() { dateFormatter.dateFormat = "YYYY-MM-dd" date!.text = dateFormatter.stringFromDate(model!.date) let f = NSByteCountFormatter() f.allowsNonnumericFormatting = false f.allowedUnits = [.UseMB, .UseGB] withCoupon!.text = f.stringFromByteCount(Int64(model!.withCoupon * 1000 * 1000)) withoutCoupon!.text = f.stringFromByteCount(Int64(model!.withoutCoupon * 1000 * 1000)) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
95314a97a1864da43fc003f080fbe3be
26.266667
94
0.667482
4.245675
false
false
false
false
tkester/swift-algorithm-club
Ordered Set/AppleOrderedSet.swift
2
1965
public class AppleOrderedSet<T: Hashable> { private var objects: [T] = [] private var indexOfKey: [T: Int] = [:] public init() {} // O(1) public func add(_ object: T) { guard indexOfKey[object] == nil else { return } objects.append(object) indexOfKey[object] = objects.count - 1 } // O(n) public func insert(_ object: T, at index: Int) { assert(index < objects.count, "Index should be smaller than object count") assert(index >= 0, "Index should be bigger than 0") guard indexOfKey[object] == nil else { return } objects.insert(object, at: index) indexOfKey[object] = index for i in index+1..<objects.count { indexOfKey[objects[i]] = i } } // O(1) public func object(at index: Int) -> T { assert(index < objects.count, "Index should be smaller than object count") assert(index >= 0, "Index should be bigger than 0") return objects[index] } // O(1) public func set(_ object: T, at index: Int) { assert(index < objects.count, "Index should be smaller than object count") assert(index >= 0, "Index should be bigger than 0") guard indexOfKey[object] == nil else { return } indexOfKey.removeValue(forKey: objects[index]) indexOfKey[object] = index objects[index] = object } // O(1) public func indexOf(_ object: T) -> Int { return indexOfKey[object] ?? -1 } // O(n) public func remove(_ object: T) { guard let index = indexOfKey[object] else { return } indexOfKey.removeValue(forKey: object) objects.remove(at: index) for i in index..<objects.count { indexOfKey[objects[i]] = i } } }
mit
faaabf64e517fb110017b42a8fd9a796
26.291667
82
0.526209
4.180851
false
false
false
false
DerekYuYi/Ant
MyPlayground.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift
1
1529
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) /// 使用 stride 进行周期性的运算 //: 从 from 开始,以间距 by 为单位到 to 但小于 to for tickMark in stride(from: 0, to: 60, by: 5) { print(tickMark) } let hours = 12 let hourInterval = 3 //: 从 from 开始,以间距 by 为单位到 through 但不超过 for tickMark in stride(from: 3, through: hours, by: hourInterval) { print("----\(tickMark)") } // Tuples let somePoint = (1, 1) switch somePoint { case (0, 0): print("\(somePoint) is at the origin") case (_, 0): print("\(somePoint) is on the x-axis") case (0, _): print("\(somePoint) is on the y-axis") case (-2...2, -2...2): print("\(somePoint) is inside the box") default: print("\(somePoint) is outside of the box") } // Value Bindings let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): print("on the x-axis with an x value of \(x)") case (0, let y): print("on the y-axis with a y value of \(y)") case let (x, y): print("somewhere else at (\(x), \(y)") } // Where let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: print("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y: print("(\(x), \(y)) is on the line x == -y") case let (x, y): print("(\(x), \(y)) is just some arbitrary point") } ///: 使用 `fallthrough` 来实现 switch 中 case 的贯穿 ///: Checking API Availability if #available(iOS 11, macOS 10.12, *) { }
mit
e364ae23a297fad477468ed45adf328a
21.390625
67
0.597348
2.960744
false
false
false
false
AvdLee/ALDataRequestView
Source/ALDataRequestView.swift
1
10541
// // ALDataRequestView.swift // Pods // // Created by Antoine van der Lee on 28/02/16. // // import UIKit import PureLayout import ReachabilitySwift public typealias RetryAction = (() -> Void) public enum RequestState { case possible case loading case failed case success case empty } public enum ReloadReason { case generalError case noInternetConnection } public struct ReloadType { public var reason: ReloadReason public var error: Error? } public protocol Emptyable { var isEmpty:Bool { get } } public protocol ALDataReloadType { var retryButton:UIButton? { get set } func setup(for reloadType:ReloadType) } // Make methods optional with default implementations public extension ALDataReloadType { func setup(for reloadType:ReloadType){ } } public protocol ALDataRequestViewDataSource : class { func loadingView(for dataRequestView: ALDataRequestView) -> UIView? func reloadViewController(for dataRequestView: ALDataRequestView) -> ALDataReloadType? func emptyView(for dataRequestView: ALDataRequestView) -> UIView? func hideAnimationDuration(for dataRequestView: ALDataRequestView) -> Double func showAnimationDuration(for dataRequestView: ALDataRequestView) -> Double } // Make methods optional with default implementations public extension ALDataRequestViewDataSource { func loadingView(for dataRequestView: ALDataRequestView) -> UIView? { return nil } func reloadViewController(for dataRequestView: ALDataRequestView) -> ALDataReloadType? { return nil } func emptyView(for dataRequestView: ALDataRequestView) -> UIView? { return nil } func hideAnimationDuration(for dataRequestView: ALDataRequestView) -> Double { return 0 } func showAnimationDuration(for dataRequestView: ALDataRequestView) -> Double { return 0 } } public class ALDataRequestView: UIView { // Public properties public weak var dataSource:ALDataRequestViewDataSource? /// Action for retrying a failed situation /// Will be triggered by the retry button, on foreground or when reachability changed to connected public var retryAction:RetryAction? /// If failed earlier, the retryAction will be triggered on foreground public var automaticallyRetryOnForeground:Bool = true /// If failed earlier, the retryAction will be triggered when reachability changed to reachable public var automaticallyRetryWhenReachable:Bool = true /// Set to true for debugging purposes public var loggingEnabled:Bool = false // Internal properties internal var state:RequestState = .possible // Private properties private var loadingView:UIView? private var reloadView:UIView? private var emptyView:UIView? fileprivate var reachability:Reachability? override public func awakeFromNib() { super.awakeFromNib() setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal func setup(){ // Hide by default isHidden = true // Background color is not needed backgroundColor = UIColor.clear // Setup for automatic retrying initOnForegroundObserver() initReachabilityMonitoring() debugLog(logString: "Init DataRequestView") } deinit { NotificationCenter.default.removeObserver(self) debugLog(logString: "Deinit DataRequestView") } // MARK: Public Methods public func changeRequestState(state:RequestState, error: Error? = nil){ guard state != self.state else { return } layer.removeAllAnimations() self.state = state resetToPossibleState(completion: { [weak self] (completed) in () guard let state = self?.state else { return } switch state { case .loading: self?.showLoadingView() break case .failed: self?.showReloadView(error: error) break case .empty: self?.showEmptyView() break default: break } }) } // MARK: Private Methods /// This will remove all views added private func resetToPossibleState(completion: ((Bool) -> Void)?){ UIView.animate(withDuration: dataSource?.hideAnimationDuration(for: self) ?? 0, animations: { [weak self] in () self?.loadingView?.alpha = 0 self?.emptyView?.alpha = 0 self?.reloadView?.alpha = 0 }) { [weak self] (completed) in self?.resetViews(views: [self?.loadingView, self?.emptyView, self?.reloadView]) self?.isHidden = true completion?(completed) } } private func resetViews(views: [UIView?]) { views.forEach { (view) in view?.alpha = 1 view?.removeFromSuperview() } } /// This will show the loading view internal func showLoadingView(){ guard let dataSourceLoadingView = dataSource?.loadingView(for: self) else { debugLog(logString: "No loading view provided!") return } isHidden = false loadingView = dataSourceLoadingView // Only add if not yet added if loadingView?.superview == nil { addSubview(loadingView!) loadingView?.autoPinEdgesToSuperviewEdges() layoutIfNeeded() } dataSourceLoadingView.showWithDuration(duration: dataSource?.showAnimationDuration(for: self)) } /// This will show the reload view internal func showReloadView(error: Error? = nil){ guard let dataSourceReloadType = dataSource?.reloadViewController(for: self) else { debugLog(logString: "No reload view provided!") return } if let dataSourceReloadView = dataSourceReloadType as? UIView { reloadView = dataSourceReloadView } else if let dataSourceReloadViewController = dataSourceReloadType as? UIViewController { reloadView = dataSourceReloadViewController.view } guard let reloadView = reloadView else { debugLog(logString: "Could not determine reloadView") return } var reloadReason: ReloadReason = .generalError if let error = error as NSError?, error.isNetworkConnectionError() || reachability?.isReachable == false { reloadReason = .noInternetConnection } isHidden = false addSubview(reloadView) reloadView.autoPinEdgesToSuperviewEdges() dataSourceReloadType.setup(for: ReloadType(reason: reloadReason, error: error)) #if os(tvOS) if #available(iOS 9.0, *) { dataSourceReloadType.retryButton?.addTarget(self, action: #selector(ALDataRequestView.retryButtonTapped), for: UIControlEvents.primaryActionTriggered) } #else dataSourceReloadType.retryButton?.addTarget(self, action: #selector(ALDataRequestView.retryButtonTapped), for: UIControlEvents.touchUpInside) #endif reloadView.showWithDuration(duration: dataSource?.showAnimationDuration(for: self)) } /// This will show the empty view internal func showEmptyView(){ guard let dataSourceEmptyView = dataSource?.emptyView(for: self) else { debugLog(logString: "No empty view provided!") // Hide as we don't have anything to show from the empty view isHidden = true return } isHidden = false emptyView = dataSourceEmptyView addSubview(emptyView!) emptyView?.autoPinEdgesToSuperviewEdges() dataSourceEmptyView.showWithDuration(duration: dataSource?.showAnimationDuration(for: self)) } /// IBAction for the retry button @objc private func retryButtonTapped(button:UIButton){ retryIfRetryable() } /// This will trigger the retryAction if current state is failed fileprivate func retryIfRetryable(){ guard state == RequestState.failed else { return } guard let retryAction = retryAction else { debugLog(logString: "No retry action provided") return } retryAction() } } /// On foreground Observer methods. private extension ALDataRequestView { func initOnForegroundObserver(){ NotificationCenter.default.addObserver(self, selector: #selector(ALDataRequestView.onForeground), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } @objc private func onForeground(notification:NSNotification){ guard automaticallyRetryOnForeground == true else { return } retryIfRetryable() } } /// Reachability methods private extension ALDataRequestView { func initReachabilityMonitoring() { reachability = Reachability() reachability?.whenReachable = { [weak self] reachability in guard self?.automaticallyRetryWhenReachable == true else { return } self?.retryIfRetryable() } do { try reachability?.startNotifier() } catch { debugLog(logString: "Unable to start notifier") } } } /// Logging purposes private extension ALDataRequestView { func debugLog(logString:String){ guard loggingEnabled else { return } print("ALDataRequestView: \(logString)") } } /// NSError extension private extension NSError { func isNetworkConnectionError() -> Bool { let networkErrors = [NSURLErrorNetworkConnectionLost, NSURLErrorNotConnectedToInternet] if domain == NSURLErrorDomain && networkErrors.contains(code) { return true } return false } } /// UIView extension private extension UIView { func showWithDuration(duration: Double?) { guard let duration = duration else { alpha = 1 return } alpha = 0 UIView.animate(withDuration: duration, animations: { self.alpha = 1 }) } }
mit
9f86ce016ba143835a0a9f1a7e9fcbed
30.465672
174
0.63789
5.358922
false
false
false
false
CPRTeam/CCIP-iOS
OPass/Class+addition/OPassAPI/EventScenario.swift
1
11297
// // EventScenario.swift // OPass // // Created by 腹黒い茶 on 2019/6/17. // 2019 OPass. // import Foundation import SwiftyJSON struct ScenarioAttribute: OPassData { var _data: JSON init(_ data: JSON) { self._data = data } subscript(_ member: String) -> Any { return self._data[member].object } } struct Scenario: OPassData, Equatable { static func == (lhs: Scenario, rhs: Scenario) -> Bool { return lhs.Id == rhs.Id } var _data: JSON var Id: String var Used: Int? var Disabled: String? var Attributes: ScenarioAttribute var Countdown: Int? var ExpireTime: Int? var AvailableTime: Int? var DisplayText: String? { if let longLangUI = Constants.longLangUI { return self._data["display_text"][longLangUI].string ?? "" } return "" } var Order: Int var Message: String? init(_ data: JSON) { self._data = data self.Id = self._data["id"].stringValue self.Used = self._data["used"].int self.Disabled = self._data["disabled"].string self.Attributes = ScenarioAttribute(self._data["attr"]) self.Countdown = self._data["countdown"].int self.ExpireTime = self._data["expire_time"].int self.AvailableTime = self._data["available_time"].int self.Order = self._data["order"].intValue self.Message = self._data["message"].string } } struct ScenarioStatus: OPassData { var _data: JSON var _id: String { return self._data["_id"].dictionaryValue["$oid"]!.stringValue } var EventId: String var Token: String var UserId: String var Attributes: ScenarioAttribute var FirstUse: Int64 var Role: String var Scenarios: [Scenario] init(_ data: JSON) { self._data = data self.EventId = self._data["event_id"].stringValue self.Token = self._data["token"].stringValue self.UserId = self._data["user_id"].stringValue self.Attributes = ScenarioAttribute(self._data["attr"]) self.FirstUse = self._data["first_use"].int64Value self.Role = self._data["role"].stringValue self.Scenarios = self._data["scenarios"].arrayValue.map { obj -> Scenario in return Scenario(obj) } } subscript(_ member: String) -> String { return self._data[member].stringValue } } extension OPassAPI { static func RedeemCode(_ event: String, _ token: String, _ completion: OPassCompletionCallback) { var event = event if event == "" { event = OPassAPI.currentEvent } let token = token.trim() let allowedCharacters = NSMutableCharacterSet.init(charactersIn: "-_") allowedCharacters.formUnion(with: NSCharacterSet.alphanumerics) let nonAllowedCharacters = allowedCharacters.inverted if (token.count != 0 && token.rangeOfCharacter(from: nonAllowedCharacters) == nil) { OPassAPI.isLoginSession = false Constants.accessToken = "" OPassAPI.InitializeRequest(Constants.URL_STATUS(token: token)) { _, _, error, _ in completion?(false, nil, error) }.then { (obj: Any?) -> Void in if let o = obj { if obj != nil { switch String(describing: type(of: o)) { case OPassNonSuccessDataResponse.className: OPassAPI.duringLoginFromLink = false if let opec = UIApplication.getMostTopPresentedViewController() as? OPassEventsController { opec.performSegue(withIdentifier: "OPassTabView", sender: OPassAPI.eventInfo) } if let sr = o as? OPassNonSuccessDataResponse { if let response = sr.Response { switch response.statusCode { case 400: completion?(false, sr, NSError(domain: "OPass Redeem Code Invalid", code: 4, userInfo: nil)) break default: completion?(false, sr, NSError(domain: "OPass Redeem Code Invalid", code: 4, userInfo: nil)) } } } break default: let status = ScenarioStatus(JSON(o)) Constants.accessToken = token OPassAPI.userInfo = status OPassAPI.isLoginSession = true if OPassAPI.duringLoginFromLink { if let opec = UIApplication.getMostTopPresentedViewController() as? OPassEventsController { opec.performSegue(withIdentifier: "OPassTabView", sender: OPassAPI.eventInfo) } if OPassAPI.isLoginSession { AppDelegate.delegateInstance.displayGreetingsForLogin() } } OPassAPI.duringLoginFromLink = false AppDelegate.delegateInstance.checkinView?.reloadCard() completion?(true, status, OPassSuccessError) } } else { completion?(false, RawOPassData(o), NSError(domain: "OPass Redeem Code Invalid", code: 2, userInfo: nil)) } } } } else { completion?(false, nil, NSError(domain: "OPass Redeem Code Invalid", code: 1, userInfo: nil)) } } static func GetCurrentStatus(_ completion: OPassCompletionCallback) { let event = OPassAPI.currentEvent guard let token = Constants.accessToken else { completion?(false, nil, NSError(domain: "Not a Valid Token", code: -1, userInfo: nil)) return } if event.count > 0 && token.count > 0 { OPassAPI.InitializeRequest(Constants.URL_STATUS(token: token)) { _, _, error, _ in completion?(false, nil, error) }.then { (obj: Any?) -> Void in if let o = obj { if obj != nil { switch String(describing: type(of: o)) { case OPassNonSuccessDataResponse.className: if let sr = obj as? OPassNonSuccessDataResponse { if let response = sr.Response { switch response.statusCode { case 200: completion?(false, sr, NSError(domain: "OPass Data not valid", code: 5, userInfo: nil)) default: completion?(false, sr, NSError(domain: "OPass Current Not in Event or Not a Valid Token", code: 4, userInfo: nil)) } } } default: let status = ScenarioStatus(JSON(o)) completion?(true, status, OPassSuccessError) } } else { completion?(false, RawOPassData(o), NSError(domain: "OPass Current Not in Event or Not a Valid Token", code: 2, userInfo: nil)) } } } } else { completion?(false, nil, NSError(domain: "OPass Current Not in Event or Not a Valid Token", code: 1, userInfo: nil)) } } static func UseScenario(_ event: String, _ token: String, _ scenario: String, _ completion: OPassCompletionCallback) { if event.count > 0 { OPassAPI.InitializeRequest(Constants.URL_USE(token: token, scenario: scenario)) { _, _, error, _ in completion?(false, nil, error) }.then { (obj: Any?) -> Void in if let o = obj { if obj != nil { switch String(describing: type(of: o)) { case OPassNonSuccessDataResponse.className: if let sr = obj as? OPassNonSuccessDataResponse { completion?(false, sr, NSError(domain: "OPass Scenario can not use because current is Not in Event or Not a Valid Token", code: 3, userInfo: nil)) } default: let used = ScenarioStatus(JSON(o)) completion?(true, used, OPassSuccessError) } } else { completion?(false, RawOPassData(o), NSError(domain: "OPass Scenario can not use by return unexcepted response", code: 2, userInfo: nil)) } } } } else { completion?(false, nil, NSError(domain: "OPass Scenario can not use, because event was not set", code: 1, userInfo: nil)) } } static func ParseScenarioType(_ id: String) -> Dictionary<String, Any> { let id_pattern = "^(day(\\d+))?(\\w+)$" guard let id_regex = try? NSRegularExpression.init(pattern: id_pattern, options: .caseInsensitive) else { return [:] } let id_matches = id_regex.matches(in: id, options: .withTransparentBounds, range: NSRangeFromString(id)) guard let did_range = id_matches.first?.range(at: 2) else { return [ "scenarioType": id, "did": "" ] } let did = String(id[String.Index(utf16Offset: did_range.location, in: id)..<String.Index(utf16Offset: did_range.length, in: id)]) guard let scenarioRange = id_matches.first?.range(at: 3) else { return [ "scenarioType": id, "did": did ] } let scenarioType = String(id[String.Index(utf16Offset: scenarioRange.location, in: id)..<String.Index(utf16Offset: scenarioRange.length, in: id)]) return [ "scenarioType": scenarioType, "did": did ] } static func ParseScenarioRange(_ scenario: Scenario) -> Array<String> { let formatter = DateFormatter.init() formatter.dateFormat = Constants.appConfig.DisplayDateTimeFormat as? String formatter.timeZone = NSTimeZone.default let availDate = Date.init(timeIntervalSince1970: TimeInterval(scenario.AvailableTime ?? 0)) let expireDate = Date.init(timeIntervalSince1970: TimeInterval(scenario.ExpireTime ?? 0)) let availString = formatter.string(from: availDate) let expireString = formatter.string(from: expireDate) return [ availString, expireString ] } }
gpl-3.0
05c5c98c4effdcbc7f6217fd6d93f5bc
44.520161
182
0.515192
5.026269
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/General/Views/ImagePicker/ImagePickerCollectionViewCell.swift
1
5025
// // ImagePickerCollectionViewCell.swift // HiPDA // // Created by leizh007 on 2017/6/18. // Copyright © 2017年 HiPDA. All rights reserved. // import UIKit class ImagePickerCollectionViewCell: UICollectionViewCell { var imageView: UIImageView! var stateIndicator: ImageSelectorStateIndicator! var asset: ImageAsset? { didSet { if let oldAsset = oldValue { unsubscribeToDownloadProgressNotification(oldAsset) } guard let asset = self.asset else { return } subscribeToDownloadProgressNotification(asset) asset.getThumbImage(for: CGSize(width: contentView.bounds.size.width * C.UI.screenScale, height: contentView.bounds.size.height * C.UI.screenScale)) { [weak self] result in switch result { case let .success(image): self?.imageView.image = image default: break } } } } var assetsCollection: ImageAssetsCollection? { didSet { if let oldCollection = oldValue { unsubscribeToAssetsCollectionDidChange(oldCollection) } guard let assetsCollection = assetsCollection else { return } subscribeToAssetsCollectionDidChange(assetsCollection) } } func updateState() { guard let asset = asset, let assetsCollection = assetsCollection else { stateIndicator.clearState() return } stateIndicator.isDownloading = asset.isDownloading stateIndicator.downloadProgress = asset.downloadPercent if let index = assetsCollection.index(of: asset) { stateIndicator.selectionNumber = index + 1 } else { stateIndicator.selectionNumber = 0 } } override init(frame: CGRect) { imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true stateIndicator = ImageSelectorStateIndicator(frame: .zero) super.init(frame: frame) contentView.addSubview(imageView) contentView.addSubview(stateIndicator) contentView.backgroundColor = .white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() imageView.frame = contentView.bounds stateIndicator.frame = contentView.bounds } override func prepareForReuse() { super.prepareForReuse() asset?.cancelDownloading() if let asset = asset { unsubscribeToDownloadProgressNotification(asset) } if let collection = assetsCollection { unsubscribeToAssetsCollectionDidChange(collection) } stateIndicator.clearState() } deinit { asset?.cancelDownloading() if let asset = asset { unsubscribeToDownloadProgressNotification(asset) } if let collection = assetsCollection { unsubscribeToAssetsCollectionDidChange(collection) } } fileprivate func subscribeToDownloadProgressNotification(_ asset: ImageAsset) { NotificationCenter.default.addObserver(self, selector: #selector(didReceiveDownloadProgressNotification(_:)), name: .ImageAssetDownloadProgress, object: asset) } fileprivate func unsubscribeToDownloadProgressNotification(_ asset: ImageAsset) { NotificationCenter.default.removeObserver(self, name: .ImageAssetDownloadProgress, object: asset) } func didReceiveDownloadProgressNotification(_ notification: Notification) { guard let asset = asset else { return } let isDownloading = asset.isDownloading let progress = asset.downloadPercent let isSelected = stateIndicator.isSelected if (!isSelected) { stateIndicator.downloadProgress = progress stateIndicator.isDownloading = isDownloading } } fileprivate func subscribeToAssetsCollectionDidChange(_ assetsCollection: ImageAssetsCollection) { NotificationCenter.default.addObserver(self, selector: #selector(didReceivedAssetsCollectionChangedNotification(_:)), name: .ImageAssetsCollectionDidChange, object: assetsCollection) } fileprivate func unsubscribeToAssetsCollectionDidChange(_ assetsCollection: ImageAssetsCollection) { NotificationCenter.default.removeObserver(self, name: .ImageAssetsCollectionDidChange, object: assetsCollection) } func didReceivedAssetsCollectionChangedNotification(_ notification: Notification) { guard let asset = asset, !asset.isDownloading else { return } if let index = assetsCollection?.index(of: asset) { stateIndicator.selectionNumber = index + 1 } else { stateIndicator.selectionNumber = 0 } } }
mit
9164e882161be254b9f1f6c730480a0b
35.926471
190
0.655914
5.745995
false
false
false
false
quickthyme/PUTcat
PUTcat/Presentation/Service/ViewModel/ServiceViewDataBuilder.swift
1
1858
import UIKit class ServiceViewDataBuilder { typealias CellID = ServiceViewDataItem.CellID typealias SegueID = ServiceViewDataItem.SegueID typealias Icon = ServiceViewDataItem.Icon typealias StaticRefID = ServiceViewDataItem.StaticRefID static func update(viewData: ServiceViewData, withEnvironment environment: PCEnvironment?) -> ServiceViewData { var viewData = viewData viewData.section[0] = constructProjectSettingsSection(environment) return viewData } static func constructProjectSettingsSection(_ environment: PCEnvironment?) -> ServiceViewDataSection { return ServiceViewDataSection( title: "Project Settings", item: [ ServiceViewDataItem( refID: StaticRefID.Environment, cellID: CellID.TitleValueCell, title: "Environment", detail: environment?.name, segue: nil, icon: nil ) ] ) } static func constructViewData(serviceList: PCList<PCService>) -> ServiceViewData { let services = serviceList.list return ServiceViewData( section: [ constructProjectSettingsSection(nil), ServiceViewDataSection( title: "Services", item: services.map { ServiceViewDataItem( refID: $0.id, cellID: CellID.BasicCell, title: $0.name, detail: nil, segue: SegueID.Transaction, icon: UIImage(named: Icon.Service) ) } ) ] ) } }
apache-2.0
789704bc795865db0d20a05d5edc04eb
33.407407
115
0.525296
6.012945
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift
31
17543
// // Observable+Multiple.swift // RxSwift // // Created by Krunoslav Zaher on 3/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // // MARK: combineLatest extension Observable { /** Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - parameter resultSelector: Function to invoke whenever any of the sources produces an element. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ public static func combineLatest<C: Collection>(_ collection: C, _ resultSelector: @escaping ([C.Iterator.Element.E]) throws -> Element) -> Observable<Element> where C.Iterator.Element: ObservableType { return CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) } /** Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ public static func combineLatest<C: Collection>(_ collection: C) -> Observable<[Element]> where C.Iterator.Element: ObservableType, C.Iterator.Element.E == Element { return CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) } } // MARK: zip extension Observable { /** Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ public static func zip<C: Collection>(_ collection: C, _ resultSelector: @escaping ([C.Iterator.Element.E]) throws -> Element) -> Observable<Element> where C.Iterator.Element: ObservableType { return ZipCollectionType(sources: collection, resultSelector: resultSelector) } /** Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index. - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ public static func zip<C: Collection>(_ collection: C) -> Observable<[Element]> where C.Iterator.Element: ObservableType, C.Iterator.Element.E == Element { return ZipCollectionType(sources: collection, resultSelector: { $0 }) } } // MARK: switch extension ObservableType where E : ObservableConvertibleType { /** Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. Each time a new inner observable sequence is received, unsubscribe from the previous inner observable sequence. - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ public func switchLatest() -> Observable<E.E> { return Switch(source: asObservable()) } } // switchIfEmpty extension ObservableType { /** Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter switchTo: Observable sequence being returned when source sequence is empty. - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. */ public func ifEmpty(switchTo other: Observable<E>) -> Observable<E> { return SwitchIfEmpty(source: asObservable(), ifEmpty: other) } } // MARK: concat extension ObservableType { /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func concat<O: ObservableConvertibleType>(_ second: O) -> Observable<E> where O.E == E { return Observable.concat([self.asObservable(), second.asObservable()]) } } extension Observable { /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<S: Sequence >(_ sequence: S) -> Observable<Element> where S.Iterator.Element == Observable<Element> { return Concat(sources: sequence, count: nil) } /** Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<S: Collection >(_ collection: S) -> Observable<Element> where S.Iterator.Element == Observable<Element> { return Concat(sources: collection, count: collection.count.toIntMax()) } /** Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat(_ sources: Observable<Element> ...) -> Observable<Element> { return Concat(sources: sources, count: sources.count.toIntMax()) } } extension ObservableType where E : ObservableConvertibleType { /** Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ public func concat() -> Observable<E.E> { return merge(maxConcurrent: 1) } } // MARK: merge extension Observable { /** Merges elements from all observable sequences from collection into a single observable sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Collection of observable sequences to merge. - returns: The observable sequence that merges the elements of the observable sequences. */ public static func merge<C: Collection>(_ sources: C) -> Observable<E> where C.Iterator.Element == Observable<E> { return MergeArray(sources: Array(sources)) } /** Merges elements from all observable sequences from array into a single observable sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Array of observable sequences to merge. - returns: The observable sequence that merges the elements of the observable sequences. */ public static func merge(_ sources: [Observable<E>]) -> Observable<E> { return MergeArray(sources: sources) } /** Merges elements from all observable sequences into a single observable sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Collection of observable sequences to merge. - returns: The observable sequence that merges the elements of the observable sequences. */ public static func merge(_ sources: Observable<E>...) -> Observable<E> { return MergeArray(sources: sources) } } extension ObservableType where E : ObservableConvertibleType { /** Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - returns: The observable sequence that merges the elements of the observable sequences. */ public func merge() -> Observable<E.E> { return Merge(source: asObservable()) } /** Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. - returns: The observable sequence that merges the elements of the inner sequences. */ public func merge(maxConcurrent: Int) -> Observable<E.E> { return MergeLimited(source: asObservable(), maxConcurrent: maxConcurrent) } } // MARK: catch extension ObservableType { /** Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - parameter handler: Error handler function, producing another observable sequence. - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. */ public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable<E>) -> Observable<E> { return Catch(source: asObservable(), handler: handler) } /** Continues an observable sequence that is terminated by an error with a single element. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - parameter element: Last element in an observable sequence in case error occurs. - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. */ public func catchErrorJustReturn(_ element: E) -> Observable<E> { return Catch(source: asObservable(), handler: { _ in Observable.just(element) }) } } extension Observable { /** Continues an observable sequence that is terminated by an error with the next observable sequence. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ public static func catchError<S: Sequence>(_ sequence: S) -> Observable<Element> where S.Iterator.Element == Observable<Element> { return CatchSequence(sources: sequence) } } // MARK: takeUntil extension ObservableType { /** Returns the elements from the source observable sequence until the other observable sequence produces an element. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter other: Observable sequence that terminates propagation of elements of the source sequence. - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ public func takeUntil<O: ObservableType>(_ other: O) -> Observable<E> { return TakeUntil(source: asObservable(), other: other.asObservable()) } } // MARK: skipUntil extension ObservableType { /** Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) - parameter other: Observable sequence that starts propagation of elements of the source sequence. - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. */ public func skipUntil<O: ObservableType>(_ other: O) -> Observable<E> { return SkipUntil(source: asObservable(), other: other.asObservable()) } } // MARK: amb extension ObservableType { /** Propagates the observable sequence that reacts first. - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) - parameter right: Second observable sequence. - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. */ public func amb<O2: ObservableType> (_ right: O2) -> Observable<E> where O2.E == E { return Amb(left: asObservable(), right: right.asObservable()) } } extension Observable { /** Propagates the observable sequence that reacts first. - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. */ public static func amb<S: Sequence>(_ sequence: S) -> Observable<Element> where S.Iterator.Element == Observable<Element> { return sequence.reduce(Observable<S.Iterator.Element.E>.never()) { a, o in return a.amb(o.asObservable()) } } } // withLatestFrom extension ObservableType { /** Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - parameter second: Second observable source. - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. */ public func withLatestFrom<SecondO: ObservableConvertibleType, ResultType>(_ second: SecondO, resultSelector: @escaping (E, SecondO.E) throws -> ResultType) -> Observable<ResultType> { return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: resultSelector) } /** Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emitts an element. - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - parameter second: Second observable source. - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. */ public func withLatestFrom<SecondO: ObservableConvertibleType>(_ second: SecondO) -> Observable<SecondO.E> { return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: { $1 }) } }
mit
95c9e959ea8f7a7d72d0ad90979b57b7
42.636816
200
0.724547
5.022044
false
true
false
false
programus/this-month
src/This Month/Widget/TodayViewController.swift
1
1543
// // TodayViewController.swift // Widget // // Created by 王 元 on 15-02-01. // Copyright (c) 2015年 programus. All rights reserved. // import Cocoa import NotificationCenter class TodayViewController: NSViewController, NCWidgetProviding { @IBOutlet weak var datePickerCell: NSDatePickerCell! override var nibName: String? { return "TodayViewController" } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { // Update your data and prepare for a snapshot. Call completion handler when you are done // with NoData if nothing has changed or NewData if there is new data since the last // time we called you var now = NSDate() var needRefresh = true if let cal = NSCalendar(calendarIdentifier: NSGregorianCalendar) { var nowComp = cal.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: now) var dispComp = cal.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: self.datePickerCell.dateValue) if nowComp == dispComp { needRefresh = nowComp.year != dispComp.year || nowComp.month != dispComp.month || nowComp.day != dispComp.day } if needRefresh { self.datePickerCell.dateValue = now } } completionHandler(needRefresh ? .NewData : .NoData) } }
apache-2.0
5b374269164ab8f523e719e571977a64
38.410256
183
0.680547
4.958065
false
false
false
false
k-thorat/Dotzu
Framework/Dotzu/Dotzu/LoggerFormat.swift
1
2167
// // LoggerFormat.swift // exampleWindow // // Created by Remi Robert on 23/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit class LoggerFormat { static func formatDate(date: Date) -> String { let formatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter.string(from: date) } static func format(log: Log) -> (str: String, attr: NSMutableAttributedString) { var startIndex = 0 var lenghtDate: Int? let stringContent = NSMutableString() stringContent.append("\(log.level.logColorConsole) ") if let date = log.date, LogsSettings.shared.date { stringContent.append("[\(formatDate(date: date))] ") lenghtDate = stringContent.length startIndex = stringContent.length } if let fileInfoString = log.fileInfo, LogsSettings.shared.fileInfo { stringContent.append("\(fileInfoString) : \(log.content)") } else { stringContent.append("\(log.content)") } let attstr = NSMutableAttributedString(string: stringContent as String) attstr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range: NSMakeRange(0, stringContent.length)) if let dateLenght = lenghtDate { let range = NSMakeRange(0, dateLenght) attstr.addAttribute(NSAttributedString.Key.foregroundColor, value: Color.mainGreen, range: range) attstr.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 12), range: range) } if let fileInfoString = log.fileInfo, LogsSettings.shared.fileInfo { let range = NSMakeRange(startIndex, fileInfoString.count) attstr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.gray, range: range) attstr.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 12), range: range) } return (stringContent as String, attstr) } }
mit
fafb9338f53f4b714206ee712795f54f
39.867925
116
0.647738
4.698482
false
false
false
false
uasys/swift
test/refactoring/ExtractFunction/throw_errors.swift
5
1041
func foo1() throws -> Int { return 0 } enum MyError : Error { case E1 case E2 } func foo2() throws { try foo1() try! foo1() do { try foo1() } catch {} do { try foo1() } catch MyError.E1 { } catch MyError.E2 { } } // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %refactor -extract-function -source-filename %s -pos=8:1 -end-pos=8:13 >> %t.result/L8-8.swift // RUN: diff -u %S/Outputs/throw_errors/L8-8.swift.expected %t.result/L8-8.swift // RUN: %refactor -extract-function -source-filename %s -pos=9:1 -end-pos=9:14 >> %t.result/L9-9.swift // RUN: diff -u %S/Outputs/throw_errors/L9-9.swift.expected %t.result/L9-9.swift // RUN: %refactor -extract-function -source-filename %s -pos=10:1 -end-pos=12:13 >> %t.result/L10-12.swift // RUN: diff -u %S/Outputs/throw_errors/L10-12.swift.expected %t.result/L10-12.swift // RUN: %refactor -extract-function -source-filename %s -pos=13:1 -end-pos=17:4 >> %t.result/L13-17.swift // RUN: diff -u %S/Outputs/throw_errors/L13-17.swift.expected %t.result/L13-17.swift
apache-2.0
27fedc7e1de7fe62e9da658d1a57e375
36.178571
106
0.658021
2.508434
false
false
false
false
tjw/swift
test/attr/attr_iboutlet.swift
2
8609
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation @IBOutlet // expected-error {{only instance properties can be declared @IBOutlet}} {{1-11=}} var iboutlet_global: Int @IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}} class IBOutletClassTy {} @IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}} struct IBStructTy {} @IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}} func IBFunction() -> () {} @objc class IBOutletWrapperTy { @IBOutlet var value : IBOutletWrapperTy! = IBOutletWrapperTy() // no-warning @IBOutlet class var staticValue: IBOutletWrapperTy = 52 // expected-error {{cannot convert value of type 'Int' to specified type 'IBOutletWrapperTy'}} // expected-error@-2 {{only instance properties can be declared @IBOutlet}} {{3-12=}} // expected-error@-2 {{class stored properties not supported}} @IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{3-13=}} func click() -> () {} @IBOutlet // expected-error {{@IBOutlet attribute requires property to be mutable}} {{3-13=}} let immutable: IBOutletWrapperTy? = nil @IBOutlet // expected-error {{@IBOutlet attribute requires property to be mutable}} {{3-13=}} var computedImmutable: IBOutletWrapperTy? { return nil } } struct S { } enum E { } protocol P1 { } protocol P2 { } protocol CP1 : class { } protocol CP2 : class { } @objc protocol OP1 { } @objc protocol OP2 { } class NonObjC {} // Check where @IBOutlet can occur @objc class X { // Class type @IBOutlet var outlet2: X? @IBOutlet var outlet3: X! @IBOutlet var outlet1a: NonObjC // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}} @IBOutlet var outlet2a: NonObjC? // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}} @IBOutlet var outlet3a: NonObjC! // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}} // AnyObject @IBOutlet var outlet5: AnyObject? @IBOutlet var outlet6: AnyObject! // Any @IBOutlet var outlet5a: Any? @IBOutlet var outlet6a: Any! // Protocol types @IBOutlet var outlet7: P1 // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type 'P1'}} {{3-13=}} @IBOutlet var outlet8: CP1 // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type 'CP1'}} {{3-13=}} @IBOutlet var outlet10: P1? // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}} @IBOutlet var outlet11: CP1? // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}} @IBOutlet var outlet12: OP1? @IBOutlet var outlet13: P1! // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}} @IBOutlet var outlet14: CP1! // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}} @IBOutlet var outlet15: OP1! // Class metatype @IBOutlet var outlet15b: X.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet16: X.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet17: X.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} // AnyClass @IBOutlet var outlet18: AnyClass // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet19: AnyClass? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet20: AnyClass! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} // Protocol types @IBOutlet var outlet21: P1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet22: CP1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet23: OP1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet24: P1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet25: CP1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet26: OP1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet27: P1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet28: CP1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet29: OP1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} // weak/unowned @IBOutlet weak var outlet30: X? @IBOutlet weak var outlet31: X! // String @IBOutlet var outlet33: String? @IBOutlet var outlet34: String! // Other bad cases @IBOutlet var outlet35: S // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet36: E // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet37: (X, X) // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet38: Int // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var collection1b: [AnyObject]? @IBOutlet var collection1c: [AnyObject]! @IBOutlet var collection2b: [X]? @IBOutlet var collection2c: [X]! @IBOutlet var collection3b: [OP1]? @IBOutlet var collection3c: [OP1]! @IBOutlet var collection4a: [CP1] // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}} @IBOutlet var collection4b: ([CP1])? // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}} @IBOutlet var collection4c: ([CP1])! // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}} @IBOutlet var collection5b: ([String])? @IBOutlet var collection5c: ([String])! @IBOutlet var collection6a: [NonObjC] // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}} @IBOutlet var collection6b: ([NonObjC])? // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}} @IBOutlet var collection6c: ([NonObjC])! // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}} init() { } } @objc class Infer { @IBOutlet var outlet1: Infer! @IBOutlet weak var outlet2: Infer! func testOptionalNess() { _ = outlet1! _ = outlet2! } func testUnchecked() { _ = outlet1 _ = outlet2 } // This outlet is strong and optional. @IBOutlet var outlet4: AnyObject? func testStrong() { if outlet4 != nil {} } } @objc class C { } @objc protocol Proto { } class SwiftGizmo { @IBOutlet var a : C! @IBOutlet var b1 : [C] @IBOutlet var b2 : [C]! @IBOutlet var c : String! @IBOutlet var d : [String]! @IBOutlet var e : Proto! @IBOutlet var f : C? @IBOutlet var g : C! @IBOutlet weak var h : C? @IBOutlet weak var i : C! @IBOutlet unowned var j : C // expected-error{{@IBOutlet property has non-optional type 'C'}} // expected-note @-1{{add '?' to form the optional type 'C?'}}{{30-30=?}} // expected-note @-2{{add '!' to form an implicitly unwrapped optional}}{{30-30=!}} @IBOutlet unowned(unsafe) var k : C // expected-error{{@IBOutlet property has non-optional type 'C'}} // expected-note @-1{{add '?' to form the optional type 'C?'}}{{38-38=?}} // expected-note @-2{{add '!' to form an implicitly unwrapped optional}}{{38-38=!}} @IBOutlet var bad1 : Int // expected-error {{@IBOutlet property cannot have non-object type 'Int'}} {{3-13=}} @IBOutlet var dup: C! // expected-note{{'dup' previously declared here}} @IBOutlet var dup: C! // expected-error{{invalid redeclaration of 'dup'}} init() {} } class MissingOptional { @IBOutlet var a: C // expected-error{{@IBOutlet property has non-optional type 'C'}} // expected-note @-1{{add '?' to form the optional type 'C?'}}{{21-21=?}} // expected-note @-2{{add '!' to form an implicitly unwrapped optional}}{{21-21=!}} @IBOutlet weak var b: C // expected-error{{@IBOutlet property has non-optional type 'C'}} // expected-note @-1{{add '!' to form an implicitly unwrapped optional}} {{26-26=!}} // expected-note @-2{{add '?' to form the optional type 'C?'}} {{26-26=?}} init() {} }
apache-2.0
d8d585c6d7a505af4fc8ddcbe3b38f64
40.589372
143
0.679405
3.734924
false
false
false
false
smartystreets/smartystreets-ios-sdk
Sources/SmartyStreets/InternationalStreet/InternationalStreetChanges.swift
1
1667
import Foundation @objcMembers public class InternationalStreetChanges: NSObject, Codable { public var organization:String? public var address1:String? public var address2:String? public var address3:String? public var address4:String? public var address5:String? public var address6:String? public var address7:String? public var address8:String? public var address9:String? public var address10:String? public var address11:String? public var address12:String? public var components:InternationalStreetComponents? init(dictionary: NSDictionary) { self.organization = dictionary["organization"] as? String self.address1 = dictionary["address1"] as? String self.address2 = dictionary["address2"] as? String self.address3 = dictionary["address3"] as? String self.address4 = dictionary["address4"] as? String self.address5 = dictionary["address5"] as? String self.address6 = dictionary["address6"] as? String self.address7 = dictionary["address7"] as? String self.address8 = dictionary["address8"] as? String self.address9 = dictionary["address9"] as? String self.address10 = dictionary["address10"] as? String self.address11 = dictionary["address11"] as? String self.address12 = dictionary["address12"] as? String if let components = dictionary["components"] { self.components = InternationalStreetComponents(dictionary: components as! NSDictionary) } else { self.components = InternationalStreetComponents(dictionary: NSDictionary()) } } }
apache-2.0
f0af97d5f3676d4576b8e3f4daca19a7
40.675
100
0.688662
4.554645
false
false
false
false
ashfurrow/Nimble
Tests/Nimble/AsynchronousTest.swift
22
7550
import Foundation import XCTest import Nimble // These tests require the ObjC runtimes do not currently have the GCD and run loop facilities // required for working with Nimble's async matchers #if _runtime(_ObjC) class AsyncTest: XCTestCase, XCTestCaseProvider { var allTests: [(String, () throws -> Void)] { return [ ("testToEventuallyPositiveMatches", testToEventuallyPositiveMatches), ("testToEventuallyNegativeMatches", testToEventuallyNegativeMatches), ("testWaitUntilPositiveMatches", testWaitUntilPositiveMatches), ("testToEventuallyWithCustomDefaultTimeout", testToEventuallyWithCustomDefaultTimeout), ("testWaitUntilTimesOutIfNotCalled", testWaitUntilTimesOutIfNotCalled), ("testWaitUntilTimesOutWhenExceedingItsTime", testWaitUntilTimesOutWhenExceedingItsTime), ("testWaitUntilNegativeMatches", testWaitUntilNegativeMatches), ("testWaitUntilDetectsStalledMainThreadActivity", testWaitUntilDetectsStalledMainThreadActivity), ("testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed", testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed), ("testWaitUntilErrorsIfDoneIsCalledMultipleTimes", testWaitUntilErrorsIfDoneIsCalledMultipleTimes), ("testWaitUntilMustBeInMainThread", testWaitUntilMustBeInMainThread), ("testToEventuallyMustBeInMainThread", testToEventuallyMustBeInMainThread), ] } let errorToThrow = NSError(domain: NSInternalInconsistencyException, code: 42, userInfo: nil) private func doThrowError() throws -> Int { throw errorToThrow } func testToEventuallyPositiveMatches() { var value = 0 deferToMainQueue { value = 1 } expect { value }.toEventually(equal(1)) deferToMainQueue { value = 0 } expect { value }.toEventuallyNot(equal(1)) } func testToEventuallyNegativeMatches() { let value = 0 failsWithErrorMessage("expected to eventually not equal <0>, got <0>") { expect { value }.toEventuallyNot(equal(0)) } failsWithErrorMessage("expected to eventually equal <1>, got <0>") { expect { value }.toEventually(equal(1)) } failsWithErrorMessage("expected to eventually equal <1>, got an unexpected error thrown: <\(errorToThrow)>") { expect { try self.doThrowError() }.toEventually(equal(1)) } failsWithErrorMessage("expected to eventually not equal <0>, got an unexpected error thrown: <\(errorToThrow)>") { expect { try self.doThrowError() }.toEventuallyNot(equal(0)) } } func testToEventuallyWithCustomDefaultTimeout() { AsyncDefaults.Timeout = 2 defer { AsyncDefaults.Timeout = 1 } var value = 0 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { NSThread.sleepForTimeInterval(1.1) value = 1 } expect { value }.toEventually(equal(1)) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { NSThread.sleepForTimeInterval(1.1) value = 0 } expect { value }.toEventuallyNot(equal(1)) } func testWaitUntilPositiveMatches() { waitUntil { done in done() } waitUntil { done in deferToMainQueue { done() } } } func testWaitUntilTimesOutIfNotCalled() { failsWithErrorMessage("Waited more than 1.0 second") { waitUntil(timeout: 1) { done in return } } } func testWaitUntilTimesOutWhenExceedingItsTime() { var waiting = true failsWithErrorMessage("Waited more than 0.01 seconds") { waitUntil(timeout: 0.01) { done in dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { NSThread.sleepForTimeInterval(0.1) done() waiting = false } } } // "clear" runloop to ensure this test doesn't poison other tests repeat { NSRunLoop.mainRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(0.2)) } while(waiting) } func testWaitUntilNegativeMatches() { failsWithErrorMessage("expected to equal <2>, got <1>") { waitUntil { done in NSThread.sleepForTimeInterval(0.1) expect(1).to(equal(2)) done() } } } func testWaitUntilDetectsStalledMainThreadActivity() { let msg = "-waitUntil() timed out but was unable to run the timeout handler because the main thread is unresponsive (0.5 seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run." failsWithErrorMessage(msg) { waitUntil(timeout: 1) { done in NSThread.sleepForTimeInterval(5.0) done() } } } func testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed() { // Currently we are unable to catch Objective-C exceptions when built by the Swift Package Manager #if !SWIFT_PACKAGE let referenceLine = #line + 9 var msg = "Unexpected exception raised: Nested async expectations are not allowed " msg += "to avoid creating flaky tests." msg += "\n\n" msg += "The call to\n\t" msg += "expect(...).toEventually(...) at \(#file):\(referenceLine + 7)\n" msg += "triggered this exception because\n\t" msg += "waitUntil(...) at \(#file):\(referenceLine + 1)\n" msg += "is currently managing the main run loop." failsWithErrorMessage(msg) { // reference line waitUntil(timeout: 2.0) { done in var protected: Int = 0 dispatch_async(dispatch_get_main_queue()) { protected = 1 } expect(protected).toEventually(equal(1)) done() } } #endif } func testWaitUntilErrorsIfDoneIsCalledMultipleTimes() { #if !SWIFT_PACKAGE waitUntil { done in deferToMainQueue { done() expect { done() }.to(raiseException(named: "InvalidNimbleAPIUsage")) } } #endif } func testWaitUntilMustBeInMainThread() { #if !SWIFT_PACKAGE var executedAsyncBlock: Bool = false dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { expect { waitUntil { done in done() } }.to(raiseException(named: "InvalidNimbleAPIUsage")) executedAsyncBlock = true } expect(executedAsyncBlock).toEventually(beTruthy()) #endif } func testToEventuallyMustBeInMainThread() { #if !SWIFT_PACKAGE var executedAsyncBlock: Bool = false dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { expect { expect(1).toEventually(equal(2)) }.to(raiseException(named: "InvalidNimbleAPIUsage")) executedAsyncBlock = true } expect(executedAsyncBlock).toEventually(beTruthy()) #endif } } #endif
apache-2.0
d0fb6890d224de880549b8000e11b595
36.75
385
0.621589
5.21049
false
true
false
false