repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
jhurray/SQLiteModel-Example-Project
iOS+SQLiteModel/Blogz4Dayz/BlogListViewController.swift
1
3338
// // BlogListViewController.swift // Blogz4Dayz // // Created by Jeff Hurray on 4/9/16. // Copyright © 2016 jhurray. All rights reserved. // import UIKit class BlogListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout()) var blogz: [BlogModel]? = [] override func viewDidLoad() { super.viewDidLoad() self.title = "Blogs4Dayz" let composeButton = UIBarButtonItem(barButtonSystemItem: .Compose, target: self, action: "newBlog:") navigationItem.rightBarButtonItem = composeButton let layout = UICollectionViewFlowLayout() let spacing: CGFloat = 24.0 let width: CGFloat = view.bounds.size.width / 2 - 2 * spacing let ratio: CGFloat = 16.0 / 12.0 layout.itemSize = CGSize.init(width: width, height: width * ratio) layout.scrollDirection = .Vertical layout.sectionInset = UIEdgeInsets.init(top: spacing, left: spacing, bottom: spacing, right: spacing) collectionView.registerClass(BlogListCell.self, forCellWithReuseIdentifier: "cell") collectionView.collectionViewLayout = layout collectionView.delegate = self collectionView.dataSource = self collectionView.frame = view.bounds collectionView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.9) view.addSubview(collectionView) } override func viewDidAppear(animated: Bool) { super.viewWillAppear(animated) self.reloadData() } func newBlog(sender: AnyObject?) { let controller = BlogComposeViewController() controller.blog = try! BlogModel.new([]) controller.title = "New Blog" let navController = UINavigationController(rootViewController: controller) presentViewController(navController, animated: true, completion: nil) } func reloadData() { BlogModel.fetchAllInBackground { (blogs, error) -> Void in self.blogz = blogs self.collectionView.reloadData() } } //MARK: UICollectionViewDelegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let controller = BlogComposeViewController() let blog = self.blogz![indexPath.row] controller.blog = blog controller.title = "Edit Blog" self.navigationController?.pushViewController(controller, animated: true) } //MARK: UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let count = self.blogz?.count else { return 0 } return count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! BlogListCell cell.backgroundColor = UIColor.whiteColor() if let blog = blogz?[indexPath.row] { cell.reloadWithBlogModel(blog) } return cell } }
mit
eb8d3528e1ffc23af19a38452ffa81f3
36.494382
130
0.673959
5.390953
false
false
false
false
semonchan/LearningSwift
Project/Project - 14 - BasicGesture/Project - 14 - BasicGesture/ViewController.swift
1
1647
// // ViewController.swift // Project - 14 - BasicGesture // // Created by 程超 on 2017/12/24. // Copyright © 2017年 程超. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let imageView = UIImageView(frame: view.bounds) imageView.contentMode = UIViewContentMode.scaleAspectFill imageView.image = UIImage(named: "Middle") imageView.clipsToBounds = true view.addSubview(imageView) let leftGes = UISwipeGestureRecognizer(target: self, action: #selector(middleToTop(_ :))) leftGes.direction = UISwipeGestureRecognizerDirection.left imageView.isUserInteractionEnabled = true imageView.addGestureRecognizer(leftGes) let rightGes = UISwipeGestureRecognizer(target: self, action: #selector(middleToBottom(_ :))) rightGes.direction = UISwipeGestureRecognizerDirection.right imageView.isUserInteractionEnabled = true imageView.addGestureRecognizer(rightGes) } @objc fileprivate func middleToTop(_ gesture: UISwipeGestureRecognizer) { let delegate = UIApplication.shared.delegate let vc = delegate?.window??.rootViewController delegate?.window??.rootViewController = TopViewController() vc?.removeFromParentViewController() delegate?.window??.makeKeyAndVisible() self.view = nil } @objc fileprivate func middleToBottom(_ gesture: UISwipeGestureRecognizer) { present(BottomViewController(), animated: true, completion: nil) } }
mit
bc76b5706adb18d7e2f410fe88ea93e4
33.808511
101
0.685819
5.508418
false
false
false
false
nbkhope/swift
swift2/tour_02.swift
1
2385
/** * Swift Tour 02 * These statements should be used in a playground */ // Optionals var optionalInt: Int? print(optionalInt) // printing the var gives nil print(optionalInt == nil) if optionalInt == nil { print("The variable is nil") } else { print("The variable (optional) has a value and it is not nil") } optionalInt = 43 if optionalInt == nil { print("The variable is nil") } else { print("The variable (optional) has a value and it is not nil") } optionalInt = nil if optionalInt == nil { print("The variable is nil") } else { print("The variable (optional) has a value and it is not nil") } // Compare with non-optional var myInt: Int //print(myInt) // The above gives an error: // error: variable 'myInt' used before being initialized //print(myInt == nil) // we get an error because myInt is not an optional // Using let and nil var optionalName: String? = "John Appleseed" var greeting = "Hello!" // if optionalName is nil, the condition is false: // -> skip to the else clause // if optionalName is not nil, the condition is true: // -> assign value of optionalName to constant "name" // -> execute statements within the if clause if let name = optionalName { greeting = "Hello, \(name)" } else { print("Oops, optionalName is nil") //print(name) -- doesn't exist } // Switches // -> support any kind of data and a wide variety of comparison ops // -> aren't limited to Ints and tests for equality let veggie = "red pepper" // note: no break required, you must have a default clause switch veggie { case "celery": print("We've got some celery here") case "cucumber": print("How about that Japanese cucumber salad?") case "broccoli", "cauliflower": print("Broccoli or cauliflower is okay") case let x where x.hasSuffix("pepper"): print("Some kind of pepper, uh? Is it a spicy \(x)?") default: print("We got some veggies here") } // While loops var n = 2 while n < 100 { n = n * 2; } print(n) // repeat while loop (aka do-while) var m = 2 repeat { m = m * 2 } while m < 100 print(m) // traditional for-loop var sum = 0 for var i = 1; i <= 10; i++ { sum += i } print(sum) // using for-in loop and ..< operator (exclusive) sum = 0 // 0, 1, 2, 3 for i in 0 ..< 4 { sum += i } print(sum) // you can use ... to include the upper bound (there is no < here) sum = 0 // 0, 1, 2, 3, 4 for i in 0 ... 4 { sum += i } print(sum)
gpl-2.0
5f28da70224af1f0ef5cc6d48881e0b3
18.54918
67
0.662055
3.121728
false
false
false
false
hq7781/MoneyBook
MoneyBook/Controller/History/HistoryMasterViewController.swift
1
7584
// // HistoryMasterViewController.swift // MoneyBook // // Created by HongQuan on 2017/04/30. // Copyright © 2017年 Roan.Hong. All rights reserved. // import UIKit class HistoryMasterViewController: UITableViewController { var calendarButton: TextImageButton! override func viewDidLoad() { super.viewDidLoad() self.title = "Event History" self.view.backgroundColor = UIColor.enixOrange() // UIColor.white //self.view.backgroundColor = UIColor.white setupUI() } /// - Parameter animated: If true, the disappearance of the view is being animated. override func viewWillAppear(_ animated: Bool) { self.setEditing(false, animated: animated) super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: get event /// - Get the event at index path. /// - Parameter indexPath: An index path locating a row in tableView. /// - Returns: Event data. fileprivate func eventAtIndexPath(indexPath: IndexPath) -> Event { let eventService = self.eventService() let userName = eventService.userList[indexPath.section] let events = eventService.eventsByUser[userName] return events![indexPath.row] } /// - Get the event data /// - Returns: Instance of the event Service. func eventService() -> EventService { let app = UIApplication.shared.delegate as! AppDelegate return app.appDatabaseManager.eventService } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func setupUI() { self.navigationItem.leftBarButtonItem = self.editButtonItem //let addButton = UIBarButtonItem() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. //self.navigationItem.rightBarButtonItem = self.editButtonItem() //showCalendarViewUI() } func showCalendarViewUI() { calendarButton = TextImageButton(frame: CGRect.CGRectMake(40, 300, 80, 44)) calendarButton.setTitle("Calendar", for: .normal) calendarButton.titleLabel?.font = theme.appNaviItemFont calendarButton.setTitleColor(UIColor.black, for: UIControlState.normal) calendarButton.setImage(UIImage(named:"home_down"), for: .normal) calendarButton.addTarget(self, action: #selector(onClickPushCalendarView), for:UIControlEvents.touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: calendarButton) } func onClickPushCalendarView() { let calendarViewVC = CalendarViewController() let nav = MainNavigationController(rootViewController: calendarViewVC) present(nav, animated: true, completion: nil) } } //MARK: - ========== UITableViewDelegate, UITableViewDataSource ========== extension HistoryMasterViewController { // MARK: - Table view data source /// Asks the data source to return the number of sections in the table view. override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections let event = self.eventService() return event.userList.count } /// Tells the data source to return the number of rows in a given section of a table view. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows let eventService = self.eventService() let userName = eventService.userList[section] let events = eventService.eventsByUser[userName] return (events?.count)! } /// Asks the data source for the title of the header of the specified section of the table view. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let eventService = self.eventService() return eventService.userList[section] } /// Asks the data source for a cell to insert in a particular location of the table view. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "HistoryEventCell", for: indexPath) // Configure the cell... let typeLabel = cell.viewWithTag(0) as! UILabel let titleLabel = cell.viewWithTag(1) as! UILabel let paymentLabel = cell.viewWithTag(2) as! UILabel let dateLabel = cell.viewWithTag(3) as! UILabel let event = self.eventAtIndexPath(indexPath: indexPath) typeLabel.text = event.eventType ? "InCome":"Expend" titleLabel.text = event.eventMemo paymentLabel.text = String("¥¥: \(event.eventPayment)") let formatter = DateFormatter() let jaLocale = Locale(identifier: "ja_JP") formatter.locale = jaLocale formatter.dateFormat = "yyyy年MM月dd日 HH時mm分" dateLabel.text = formatter.string(for: event.recodedDate) return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) let eventService = self.eventService() let event = self.eventAtIndexPath(indexPath: indexPath) if eventService.remove(event: event) { self.tableView.reloadData() } } 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 tableView.insertRows(at: [indexPath], with: .fade) let eventService = self.eventService() let event = self.eventAtIndexPath(indexPath: indexPath) if eventService.add(event: event) { self.tableView.reloadData() } } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ }
mit
91bde7503f783a73ea3d127df78842be
39.693548
136
0.66191
5.131525
false
false
false
false
Noobish1/KeyedMapper
KeyedMapperTests/Supporting Files/Extensions/MapperError.swift
1
2125
import Foundation import KeyedMapper // swiftlint:disable cyclomatic_complexity extension MapperError: Equatable { public static func == (lhs: MapperError, rhs: MapperError) -> Bool { switch lhs { case .custom(field: let lhsField, message: let lhsMessage): switch rhs { case .custom(field: let rhsField, message: let rhsMessage): return lhsField == rhsField && lhsMessage == rhsMessage default: return false } case .invalidRawValue(rawValue: _, rawValueType: let lhsRawValueType): switch rhs { case .invalidRawValue(rawValue: _, rawValueType: let rhsRawValueType): return lhsRawValueType == rhsRawValueType default: return false } case .missingField(field: let lhsField, forType: let lhsType): switch rhs { case .missingField(field: let rhsField, forType: let rhsType): return lhsField == rhsField && lhsType == rhsType default: return false } case .typeMismatch(field: let lhsField, forType: let lhsType, value: _, expectedType: let lhsExpectedType): switch rhs { case .typeMismatch(field: let rhsField, forType: let rhsType, value: _, expectedType: let rhsExpectedType): return lhsField == rhsField && lhsType == rhsType && lhsExpectedType == rhsExpectedType default: return false } case .convertible(value: _, expectedType: let lhsExpectedType): switch rhs { case .convertible(value: _, expectedType: let rhsExpectedType): return lhsExpectedType == rhsExpectedType default: return false } } } } // swiftlint:enable cyclomatic_complexity
mit
6f26bcaad607002bce34f51f53630470
45.195652
127
0.523765
5.821918
false
false
false
false
imfree-jdcastro/Evrythng-iOS-SDK
Evrythng-iOS/User.swift
1
1688
// // User.swift // Evrythng-iOS // // Created by JD Castro on 26/04/2017. // Copyright © 2017 ImFree. All rights reserved. // import UIKit import SwiftyJSON import ObjectMapper public final class User: AbstractUser { public var email: String? public var password: String? public var firstName: String? public var lastName: String? public private(set) var activationCode: String? public private(set) var status: String? required public init?(jsonData: JSON) { super.init(jsonData: jsonData) self.email = jsonData["email"].stringValue self.password = jsonData["password"].stringValue self.firstName = jsonData["firstName"].stringValue self.lastName = jsonData["lastName"].stringValue self.activationCode = jsonData["activationCode"].stringValue self.status = jsonData["status"].stringValue } private func toJSON() -> JSON { var jsonData: [String: Any] = [:] if let email = self.email { jsonData["email"] = email } if let password = self.password { jsonData["password"] = password } if let firstName = self.firstName { jsonData["firstName"] = firstName } if let lastName = self.lastName { jsonData["lastName"] = lastName } if let activationCode = self.activationCode { jsonData["activationCode"] = activationCode } if let status = self.status { jsonData["status"] = status } return JSON(jsonData: jsonData) } }
apache-2.0
1d368616584351870ce91fe5256e6d78
25.777778
68
0.582098
4.889855
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/PXTheme/PXDefaultMLStyleSheet.swift
1
2433
import Foundation import MLUI class PXDefaultMLStyleSheet: NSObject, MLStyleSheetProtocol { var primaryColor: UIColor var lightPrimaryColor: UIColor var secondaryColor: UIColor var secondaryColorPressed: UIColor var secondaryColorDisabled: UIColor var modalBackgroundColor: UIColor var modalTintColor: UIColor var successColor: UIColor = MLStyleSheetDefault().successColor var warningColor: UIColor = MLStyleSheetDefault().warningColor var errorColor: UIColor = MLStyleSheetDefault().errorColor var blackColor: UIColor = MLStyleSheetDefault().blackColor var darkGreyColor: UIColor = MLStyleSheetDefault().darkGreyColor var greyColor: UIColor = MLStyleSheetDefault().greyColor var midGreyColor: UIColor = MLStyleSheetDefault().midGreyColor var lightGreyColor: UIColor = MLStyleSheetDefault().lightGreyColor var whiteColor: UIColor = MLStyleSheetDefault().whiteColor public init(withPrimaryColor: UIColor) { primaryColor = withPrimaryColor lightPrimaryColor = withPrimaryColor secondaryColor = withPrimaryColor secondaryColorPressed = withPrimaryColor secondaryColorDisabled = lightGreyColor modalBackgroundColor = withPrimaryColor modalTintColor = .white } func regularSystemFont(ofSize fontSize: CGFloat) -> UIFont { return MLStyleSheetDefault().regularSystemFont(ofSize: fontSize) } func boldSystemFont(ofSize fontSize: CGFloat) -> UIFont { return MLStyleSheetDefault().boldSystemFont(ofSize: fontSize) } func thinSystemFont(ofSize fontSize: CGFloat) -> UIFont { return MLStyleSheetDefault().thinSystemFont(ofSize: fontSize) } func lightSystemFont(ofSize fontSize: CGFloat) -> UIFont { return MLStyleSheetDefault().lightSystemFont(ofSize: fontSize) } func mediumSystemFont(ofSize fontSize: CGFloat) -> UIFont { return MLStyleSheetDefault().mediumSystemFont(ofSize: fontSize) } func semiboldSystemFont(ofSize fontSize: CGFloat) -> UIFont { return MLStyleSheetDefault().semiboldSystemFont(ofSize: fontSize) } func extraboldSystemFont(ofSize fontSize: CGFloat) -> UIFont { return MLStyleSheetDefault().extraboldSystemFont(ofSize: fontSize) } func blackSystemFont(ofSize fontSize: CGFloat) -> UIFont { return MLStyleSheetDefault().blackSystemFont(ofSize: fontSize) } }
mit
ef8c9bfff4b3758c5251c1127b715401
37.015625
74
0.74106
5.430804
false
false
false
false
jyxia/CrowdFood-iOS
CrowdFood/MapViewController.swift
1
6593
// // MapViewController.swift // CrowdFood // // Created by Jinyue Xia on 10/10/15. // Copyright © 2015 Jinyue Xia. All rights reserved. // import UIKit import MapKit import Alamofire class MapViewController: UIViewController { let locationManager = CLLocationManager() var restaurantPoints = [RestaurantPointAnnotation]() var crowdImage: UIImage! @IBOutlet weak var cfMapView: MKMapView! { didSet { cfMapView.delegate = self } } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.setNavigationBarHidden(true, animated: true) self.navigationController?.setToolbarHidden(false, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.initLocationManager() self.retrieveRestaurants() } override func prefersStatusBarHidden() -> Bool { return true } @IBAction func addReport(sender: UIBarButtonItem) { let alertController = UIAlertController(title: "Estimated Time", message: nil, preferredStyle: .ActionSheet) let levelOne = UIAlertAction(title: "5 minute", style: .Default, handler: { (action) -> Void in self.addTimeReport("5") }) let levelTwo = UIAlertAction(title: "10 minute", style: .Default, handler: { (action) -> Void in self.addTimeReport("10") }) let levelThree = UIAlertAction(title: "15 minute", style: .Default, handler: { (action) -> Void in self.addTimeReport("15") }) let delete = UIAlertAction(title: "Add a photo", style: .Destructive) { (action) -> Void in self.openCamera() } let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in }) alertController.addAction(levelOne) alertController.addAction(levelTwo) alertController.addAction(levelThree) alertController.addAction(cancel) alertController.addAction(delete) presentViewController(alertController, animated: true, completion: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "AddReportSegue" { self.navigationController?.setToolbarHidden(true, animated: true) self.navigationController?.setNavigationBarHidden(false, animated: true) } if segue.identifier == "MapToReports" { self.navigationController?.setToolbarHidden(true, animated: true) self.navigationController?.setNavigationBarHidden(false, animated: true) if let destVC = segue.destinationViewController as? ReportsTableViewController { if let annotationView = sender as? MKAnnotationView { if let annotation = annotationView.annotation as? RestaurantPointAnnotation { destVC.restaurantId = annotation.id destVC.restaurantTitle = annotation.title destVC.navigationController?.navigationItem.title = annotation.title } } } } if segue.identifier == "MapToPhoto" { self.navigationController?.setToolbarHidden(true, animated: true) self.navigationController?.setNavigationBarHidden(false, animated: true) if let destVC = segue.destinationViewController as? AddPhotoReportViewController { destVC.photo = crowdImage } } } @IBAction func tapRefresh(sender: UIBarButtonItem) { self.retrieveRestaurants() } @IBAction func tapCurrentLocation(sender: UIBarButtonItem) { self.locationManager.startUpdatingLocation() } func initLocationManager() { self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestAlwaysAuthorization() self.locationManager.startUpdatingLocation() } // MARK: // @todo should move all API calls into one place and pass a completion closure callback to the function // func retrieveRestaurants() { let apiURL = API.sharedInstance.getListRestaurantsAPI() Alamofire.request(.GET, apiURL) .responseJSON { response in if let json = response.result.value { let data = json["data"] as! NSArray for restaurant in data { let newRestaurant = RestaurantPointAnnotation() let id = restaurant["_id"] as! String newRestaurant.id = id let attributes = restaurant["attribute"] as! NSDictionary newRestaurant.title = attributes["name"] as? String newRestaurant.waiting = attributes["waiting"] as! Int newRestaurant.subtitle = "\(newRestaurant.waiting) min waiting" let location = attributes["loc"] as! NSDictionary let coordinates = location["coordinates"] as! NSArray let latitude = coordinates[0] as! Double let longitude = coordinates[1] as! Double let geoLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) newRestaurant.coordinate = geoLocation self.restaurantPoints.append(newRestaurant) } self.cfMapView.removeAnnotations(self.cfMapView.annotations) self.cfMapView.addAnnotations(self.restaurantPoints) self.cfMapView.showAnnotations(self.restaurantPoints, animated: true) } } } // MARK: - Pick from camera or gallary // func openCamera() { let picker:UIImagePickerController = UIImagePickerController() picker.delegate = self if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) { picker.sourceType = UIImagePickerControllerSourceType.Camera self.presentViewController(picker, animated: true, completion: nil) } else { openGallary(picker) } } func openGallary(picker: UIImagePickerController!) { picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary if UIDevice.currentDevice().userInterfaceIdiom == .Phone { self.presentViewController(picker, animated: true, completion: nil) } } func addTimeReport(reportTime: String) { let currentLocationId = "5619f748e4b0789ae18730d1" let apiURL = API.sharedInstance.postRestaurantReportAPI(currentLocationId) let parameters = [ "userId": "Jinyue", "waiting": reportTime ] Alamofire.request(.POST, apiURL, parameters: parameters, encoding: .JSON) .responseJSON { response in if let json = response.result.value { print(json) } } } }
mit
315004e23707023fcc5215629d69d0ed
33.694737
112
0.689169
4.956391
false
false
false
false
BoxJeon/funjcam-ios
Application/Application/Search/SearchState.swift
1
412
import Entity struct SearchState { var provider: SearchProvider var query: String = "김연아" var searchAnimatedGIF: Bool = false var images: [SearchImage] = [] var next: Int? var hasMore: Bool { return self.next != nil } init(provider: SearchProvider) { self.provider = provider } } enum SearchEvent { case loading(Bool) case errorSearch(Error) case errorSearchMore(Error) }
mit
d46bdc83211105d616a5f6584c3b7fa5
18.333333
47
0.692118
3.530435
false
false
false
false
Shaquu/SwiftProjectsPub
PickAFruit/PickAFruit/ViewController.swift
1
2477
// // ViewController.swift // PickAFruit // // Created by Tadeusz Wyrzykowski on 03.11.2016. // Copyright © 2016 Tadeusz Wyrzykowski. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate { var fruits = ["Pick a fruit", "Apples", "Oranges", "Lemons", "Limes", "Blueberries"] @IBOutlet var imageView: UIImageView! @IBOutlet var infoLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imageView.image = #imageLiteral(resourceName: "fruits") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return fruits.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return fruits[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let fruitSelected = fruits[row] switch fruitSelected { case "Apples": imageView.image = #imageLiteral(resourceName: "apples") infoLabel.text = "These Apples are red" infoLabel.textColor = UIColor.red case "Oranges": imageView.image = #imageLiteral(resourceName: "oranges") infoLabel.text = "These Oranges are orange" infoLabel.textColor = UIColor.orange case "Lemons": imageView.image = #imageLiteral(resourceName: "lemons") infoLabel.text = "These Lemons are yellow" infoLabel.textColor = UIColor.orange case "Limes": imageView.image = #imageLiteral(resourceName: "limes") infoLabel.text = "These Limes are green" infoLabel.textColor = UIColor.green case "Blueberries": imageView.image = #imageLiteral(resourceName: "blueberries") infoLabel.text = "These Blueberries are blue" infoLabel.textColor = UIColor.blue default: imageView.image = #imageLiteral(resourceName: "fruits") infoLabel.text = "" } } }
gpl-3.0
19f070490e18253de9f81e541a97d91b
32.459459
111
0.628433
4.932271
false
false
false
false
SoneeJohn/WWDC
ConfCore/ScheduleResponseAdapter.swift
1
2290
// // ScheduleResponseAdapter.swift // WWDC // // Created by Guilherme Rambo on 21/02/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Foundation import SwiftyJSON private enum ContentKeys: String, JSONSubscriptType { case response, rooms, tracks, sessions, events, contents var jsonKey: JSONKey { return JSONKey.key(rawValue) } } final class ContentsResponseAdapter: Adapter { typealias InputType = JSON typealias OutputType = ContentsResponse func adapt(_ input: JSON) -> Result<ContentsResponse, AdapterError> { guard let eventsJson = input[ContentKeys.events].array else { return .error(.missingKey(ContentKeys.events)) } guard case .success(let events) = EventsJSONAdapter().adapt(eventsJson) else { return .error(.invalidData) } guard let roomsJson = input[ContentKeys.rooms].array else { return .error(.missingKey(ContentKeys.rooms)) } guard case .success(let rooms) = RoomsJSONAdapter().adapt(roomsJson) else { return .error(.invalidData) } guard let tracksJson = input[ContentKeys.tracks].array else { return .error(.missingKey(ContentKeys.rooms)) } guard case .success(let tracks) = TracksJSONAdapter().adapt(tracksJson) else { return .error(.missingKey(ContentKeys.tracks)) } guard let sessionsJson = input[ContentKeys.contents].array else { return .error(.missingKey(ContentKeys.contents)) } guard case .success(var sessions) = SessionsJSONAdapter().adapt(sessionsJson) else { return .error(.invalidData) } guard case .success(let instances) = SessionInstancesJSONAdapter().adapt(sessionsJson) else { return .error(.invalidData) } // remove duplicated sessions instances.forEach { instance in guard let index = sessions.index(where: { $0.identifier == instance.session?.identifier }) else { return } sessions.remove(at: index) } let response = ContentsResponse(events: events, rooms: rooms, tracks: tracks, instances: instances, sessions: sessions) return .success(response) } }
bsd-2-clause
7e5a24ba1b86c6ead22636046ba4c852
29.932432
127
0.647444
4.605634
false
false
false
false
alexktchen/ExchangeRate
ExchangeRate/MainViewController.swift
1
7961
// // ViewController.swift // ExchangeRate // // Created by Alex Chen on 2015/9/14. // Copyright (c) 2015 Alex Chen. All rights reserved. // import UIKit import Core class MainViewController: UITableViewController { @IBOutlet weak var titleView: UIView! var pathCover: XHPathCover? var tableViewHeader: KTTableViewHeader? var pieChart: CircleProgressView? let pieChartWidth: CGFloat = 30 let refresh: UIRefreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView() self.tableView.dataSource = self self.tableView.delegate = self self.tableView.registerNib(UINib(nibName: "MainTableViewCell", bundle: nil), forCellReuseIdentifier: "MainTableViewCell") refresh.backgroundColor = UIColor.clearColor() refresh.tintColor = UIColor.clearColor() let x = (self.view.frame.size.width / 2) - (pieChartWidth / 2) pieChart = CircleProgressView(frame: CGRectMake(x , 10, pieChartWidth, pieChartWidth)) pieChart?.backgroundColor = UIColor.clearColor() refresh.addSubview(pieChart!) self.tableView.addSubview(refresh) let filteredDefault = LoadCountryDataService.sharedInstance.allCurrencys.filter { $0.isAddToMainDefault == true && $0.isAddToMainDefault == true } /* pathCover = XHPathCover(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 140)) pathCover!.setBackgroundImage(UIImage(named: "IntroductionBackground")) pathCover!.setInfo([XHUserNameKey: "123" , XHBirthdayKey: "13123123123"]) pathCover!.isZoomingEffect = false */ tableViewHeader = KTTableViewHeader(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 140)) tableViewHeader!.setBackgroundImage(UIImage(named: "IntroductionBackground")!) if filteredDefault.count > 0 { self.selectItem(filteredDefault[0]) self.tableView.setEditing(false, animated: true) self.tableView.tableHeaderView = self.tableViewHeader } } override func viewWillAppear(animated: Bool) { //self.tableView.reloadData() } override func viewDidLayoutSubviews() { //stretchableTableHeaderView.resizeView() // stretchableTableHeaderView1.resizeView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // pragma mark - scroll delegate override func scrollViewDidScroll(scrollView: UIScrollView) { tableViewHeader!.scrollViewDidScroll(scrollView) let systemVersionDouble: Double? = Double(UIDevice.currentDevice().systemVersion) var fixAdaptorPadding = CGFloat(0) if systemVersionDouble >= 7.0 { fixAdaptorPadding = 64 } var offsetY = scrollView.contentOffset.y * 1.5 offsetY += fixAdaptorPadding let percent = (-offsetY / (200 * 1)) if -offsetY > 0 && !isAnimating{ print(percent) if percent >= 1 { self.isAnimating = true } self.pieChart?.progress = Double(percent) } } var isAnimating = false override func scrollViewDidEndDecelerating(scrollView: UIScrollView) { tableViewHeader!.scrollViewDidEndDecelerating(scrollView) //pathCover!.scrollViewDidEndDecelerating(scrollView) if refresh.refreshing { // if !isAnimating { // doSomething() // animateRefreshStep1() //} } else { isAnimating = false } } override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if refresh.refreshing { // if !isAnimating { // doSomething() // animateRefreshStep1() //} } else { isAnimating = false } } override func scrollViewWillBeginDecelerating(scrollView: UIScrollView) { //pathCover!.scrollViewWillBeginDragging(scrollView) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let filtered = LoadCountryDataService.sharedInstance.allCurrencys.filter {$0.isAddToMain == true} return filtered.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let filtered = LoadCountryDataService.sharedInstance.allCurrencys.filter {$0.isAddToMain == true} let cell: MainTableViewCell = tableView.dequeueReusableCellWithIdentifier("MainTableViewCell", forIndexPath: indexPath) as! MainTableViewCell cell.displayNameLabel.text = filtered[indexPath.row].displayName cell.currencyLabel.text = filtered[indexPath.row].currencyCode cell.symbolLabel.text = filtered[indexPath.row].symbol cell.flagImage.image = filtered[indexPath.row].flagImage cell.backgroundColor = UIColor(rgba: "#F5F5F5") cell.priceLabel.text = String(1 * filtered[indexPath.row].rate) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true // Yes, the table view can be reordered } override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { // update the item in my data source by first removing at the from index, then inserting at the to index. let filtered = LoadCountryDataService.sharedInstance.allCurrencys.filter {$0.isAddToMain == true} let item = filtered[fromIndexPath.row] LoadCountryDataService.sharedInstance.allCurrencys.removeAtIndex(fromIndexPath.row) LoadCountryDataService.sharedInstance.allCurrencys.insert(item, atIndex: toIndexPath.row) } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { var filtered = LoadCountryDataService.sharedInstance.allCurrencys.filter {$0.isAddToMain == true} let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "cell_delete".localized) { action, index in filtered[index.row].isAddToMain = false LoadCountryDataService.sharedInstance.saveMainCountry() self.tableView.beginUpdates() self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) self.tableView.endUpdates() } let set = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "cell_default".localized) { action, index in var filteredDefault = LoadCountryDataService.sharedInstance.allCurrencys.filter { $0.isAddToMainDefault == true && $0.isAddToMainDefault == true } if filteredDefault.count > 0 { filteredDefault[0].isAddToMainDefault = false } filtered[index.row].isAddToMainDefault = true self.selectItem(filtered[indexPath.row]) LoadCountryDataService.sharedInstance.saveMainCountry() self.tableView.setEditing(false, animated: true) } set.backgroundColor = CustomColors.lightRedColor return [set,delete] } func selectItem(item: Currency) { UIView.animateWithDuration(0.3, animations: { self.tableViewHeader!.setAvatarImage(UIImage(named: item.largeFlagImageName!)!) }) } }
mit
888551b63bef0184f96e32955767455c
36.551887
149
0.677176
5.169481
false
false
false
false
argon/mas
MasKitTests/Formatters/SearchResultFormatterSpec.swift
1
3048
// // SearchResultFormatterSpec.swift // MasKitTests // // Created by Ben Chatelain on 1/14/19. // Copyright © 2019 mas-cli. All rights reserved. // @testable import MasKit import Nimble import Quick class SearchResultsFormatterSpec: QuickSpec { override func spec() { // static func reference let format = SearchResultFormatter.format(results:includePrice:) var results: [SearchResult] = [] describe("search results formatter") { beforeEach { results = [] } it("formats nothing as empty string") { let output = format(results, false) expect(output) == "" } it("can format a single result") { results = [SearchResult( price: 9.87, trackId: 12345, trackName: "Awesome App", version: "19.2.1" )] let output = format(results, false) expect(output) == " 12345 Awesome App (19.2.1)" } it("can format a single result with price") { results = [SearchResult( price: 9.87, trackId: 12345, trackName: "Awesome App", version: "19.2.1" )] let output = format(results, true) expect(output) == " 12345 Awesome App $ 9.87 (19.2.1)" } it("can format a two results") { results = [ SearchResult( price: 9.87, trackId: 12345, trackName: "Awesome App", version: "19.2.1" ), SearchResult( price: 0.01, trackId: 67890, trackName: "Even Better App", version: "1.2.0" ) ] let output = format(results, false) expect(output) == " 12345 Awesome App (19.2.1)\n 67890 Even Better App (1.2.0)" } it("can format a two results with prices") { results = [ SearchResult( price: 9.87, trackId: 12345, trackName: "Awesome App", version: "19.2.1" ), SearchResult( price: 0.01, trackId: 67890, trackName: "Even Better App", version: "1.2.0" ) ] let output = format(results, true) expect(output) == " 12345 Awesome App $ 9.87 (19.2.1)\n 67890 Even Better App $ 0.01 (1.2.0)" } } } }
mit
b33d90214aa4de015edad21ecf5bd249
34.022989
113
0.398096
5.028053
false
false
false
false
argon/mas
MasKit/AppStore/SSPurchase.swift
1
1674
// // SSPurchase.swift // mas-cli // // Created by Andrew Naylor on 25/08/2015. // Copyright (c) 2015 Andrew Naylor. All rights reserved. // import CommerceKit import StoreFoundation typealias SSPurchaseCompletion = (_ purchase: SSPurchase?, _ completed: Bool, _ error: Error?, _ response: SSPurchaseResponse?) -> Void extension SSPurchase { convenience init(adamId: UInt64, account: ISStoreAccount, purchase: Bool = false) { self.init() var parameters: [String: Any] = [ "productType": "C", "price": 0, "salableAdamId": adamId, "pg": "default", "appExtVrsId": 0 ] if purchase { parameters["macappinstalledconfirmed"] = 1 parameters["pricingParameters"] = "STDQ" } else { // is redownload, use existing functionality parameters["pricingParameters"] = "STDRDL" } buyParameters = parameters.map { key, value in return "\(key)=\(value)" }.joined(separator: "&") itemIdentifier = adamId accountIdentifier = account.dsID appleID = account.identifier // Not sure if this is needed, but lets use it here. if purchase { isRedownload = false } let downloadMetadata = SSDownloadMetadata() downloadMetadata.kind = "software" downloadMetadata.itemIdentifier = adamId self.downloadMetadata = downloadMetadata } func perform(_ completion: @escaping SSPurchaseCompletion) { CKPurchaseController.shared().perform(self, withOptions: 0, completionHandler: completion) } }
mit
0f3afd1da0e00ab750e9999193dca0f0
27.372881
106
0.607527
4.405263
false
false
false
false
romankisil/eqMac2
native/app/Source/EventInterceptor.swift
1
1717
// // EventInterceptor.swift // eqMac // // Created by Roman Kisil on 18/01/2019. // Copyright © 2019 Roman Kisil. All rights reserved. // import Foundation import Cocoa @objc(EventInterceptor) class EventInterceptor: NSApplication { override func sendEvent (_ event: NSEvent) { if (event.type == .systemDefined && event.subtype.rawValue == 8) { let keyCode = ((event.data1 & 0xFFFF0000) >> 16) let keyFlags = (event.data1 & 0x0000FFFF) // Get the key state. 0xA is KeyDown, OxB is KeyUp let keyDown = (((keyFlags & 0xFF00) >> 8)) == 0xA if (keyDown) { switch Int32(keyCode) { case NX_KEYTYPE_SOUND_UP: Application.volumeChangeButtonPressed(direction: .UP, quarterStep: shiftPressed(event: event) && optionPressed(event: event)) return case NX_KEYTYPE_SOUND_DOWN: Application.volumeChangeButtonPressed(direction: .DOWN, quarterStep: shiftPressed(event: event) && optionPressed(event: event)) return case NX_KEYTYPE_MUTE: Application.muteButtonPressed() return default: break } } } if (event.type == .keyDown) { switch (event.characters) { case "w": if (commandPressed(event: event)) { UI.close() } break default: break } } super.sendEvent(event) } func shiftPressed (event: NSEvent) -> Bool { return event.modifierFlags.contains(.shift) } func optionPressed (event: NSEvent) -> Bool { return event.modifierFlags.contains(.option) } func commandPressed (event: NSEvent) -> Bool { return event.modifierFlags.contains(.command) } }
mit
04abd95b883c16a4c7ce9efeb0a977f5
25.8125
137
0.617133
3.926773
false
false
false
false
OrielBelzer/StepCoin
Models/Store.swift
1
2182
// // Store.swift // StepCoin // // Created by Oriel Belzer on 12/24/16. // import ObjectMapper import CoreLocation import Haneke class Store: NSObject, NSCoding, Mappable { var id: Int? var city: String? var name: String? var businessUserId: Int? var locationId: Int? var logoURL: String? required init?(map: Map) { } func mapping(map: Map) { id <- map["id"] city <- map["city"] name <- map["name"] businessUserId <- map["business_user_id"] locationId <- map["location_id"] logoURL <- map["logo"] } override func isEqual(_ object: Any?) -> Bool { return self.id == (object as? Store)?.id } static func ==(left: Store, right: Store) -> Bool { return left.id == right.id } //MARK: NSCoding required init(coder aDecoder: NSCoder) { self.id = aDecoder.decodeObject(forKey: "id") as? Int self.city = aDecoder.decodeObject(forKey: "city") as? String self.name = aDecoder.decodeObject(forKey: "name") as? String self.businessUserId = aDecoder.decodeObject(forKey: "businessUserId") as? Int self.locationId = aDecoder.decodeObject(forKey: "locationId") as? Int self.logoURL = aDecoder.decodeObject(forKey: "logoURL") as? String } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(city, forKey: "city") aCoder.encode(name, forKey: "name") aCoder.encode(businessUserId, forKey: "businessUserId") aCoder.encode(locationId, forKey: "locationId") aCoder.encode(logoURL, forKey: "logoURL") } } extension Store : DataConvertible, DataRepresentable { public typealias Result = Store public class func convertFromData(_ data:Data) -> Result? { return NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? Store } public func asData() -> Data! { return (NSKeyedArchiver.archivedData(withRootObject: self) as NSData!) as Data! } }
mit
e2afe54082ffd24ec5b5da703bccf9a3
28.093333
87
0.586159
4.245136
false
false
false
false
REXLabsInc/AMScrollingNavbar
Demo/ScrollingNavbarDemoTests/ScrollingNavbarDemoTests.swift
10
3172
import UIKit import Quick import Nimble import Nimble_Snapshots import AMScrollingNavbar extension UIViewController { func preloadView() { let _ = self.view } } class TableController: UITableViewController, ScrollingNavigationControllerDelegate { var called = false var status = NavigationBarState.Expanded func scrollingNavigationController(controller: ScrollingNavigationController, didChangeState state: NavigationBarState) { called = true status = state } } class DataSource: NSObject, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? UITableViewCell { cell.textLabel?.text = "Row \(indexPath.row)" if indexPath.row % 2 == 0 { cell.backgroundColor = UIColor(white: 0.8, alpha: 1) } else { cell.backgroundColor = UIColor(white: 0.9, alpha: 1) } return cell } return UITableViewCell() } } class ScrollingNavbarDemoTests: QuickSpec { override func spec() { var subject: ScrollingNavigationController! let dataSource = DataSource() var tableController: TableController? beforeEach { tableController = TableController(style: .Plain) tableController?.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") tableController?.tableView.dataSource = dataSource subject = ScrollingNavigationController(rootViewController: tableController!) subject.scrollingNavbarDelegate = tableController UIApplication.sharedApplication().keyWindow!.rootViewController = subject subject.preloadView() tableController?.tableView.reloadData() subject.followScrollView(tableController!.tableView, delay: 0) } describe("hideNavbar") { it("should hide the navigation bar") { subject.hideNavbar(animated: false) expect(subject.view).to(haveValidSnapshot()) } } describe("showNavbar") { it("should show the navigation bar") { subject.hideNavbar(animated: false) subject.showNavbar(animated: false) expect(subject.view).toEventually(haveValidSnapshot(), timeout: 2, pollInterval: 1) } } describe("ScrollingNavigationControllerDelegate") { it("should call the delegate with the new state of scroll") { subject.hideNavbar(animated: false) expect(tableController?.called).to(beTrue()) expect(tableController?.status).to(equal(NavigationBarState.Scrolling)) expect(tableController?.status).toEventually(equal(NavigationBarState.Collapsed), timeout: 2, pollInterval: 1) } } } }
mit
31b37e4a33c895022a198d9adf3e7066
35.045455
126
0.649433
5.684588
false
false
false
false
MaxHasADHD/TraktKit
Tests/TraktKitTests/RecommendationsTests.swift
1
3506
// // RecommendationsTests.swift // TraktKitTests // // Created by Maximilian Litteral on 3/29/18. // Copyright © 2018 Maximilian Litteral. All rights reserved. // import XCTest @testable import TraktKit class RecommendationsTests: XCTestCase { let session = MockURLSession() lazy var traktManager = TestTraktManager(session: session) override func tearDown() { super.tearDown() session.nextData = nil session.nextStatusCode = StatusCodes.Success session.nextError = nil } // MARK: - Movies func test_get_movie_recommendations() { session.nextData = jsonData(named: "test_get_movie_recommendations") let expectation = XCTestExpectation(description: "Get movie recommendations") traktManager.getRecommendedMovies { result in if case .success(let movies) = result { XCTAssertEqual(movies.count, 10) expectation.fulfill() } } let result = XCTWaiter().wait(for: [expectation], timeout: 1) XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/recommendations/movies") switch result { case .timedOut: XCTFail("Something isn't working") default: break } } // MARK: - Hide Movie func test_hide_movie_recommendation() { session.nextStatusCode = StatusCodes.SuccessNoContentToReturn let expectation = XCTestExpectation(description: "Hide movie recommendation") traktManager.hideRecommendedMovie(movieID: 922) { result in if case .success = result { expectation.fulfill() } } let result = XCTWaiter().wait(for: [expectation], timeout: 1) XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/recommendations/movies/922") switch result { case .timedOut: XCTFail("Something isn't working") default: break } } // MARK: - Shows func test_get_show_recommendations() { session.nextData = jsonData(named: "test_get_show_recommendations") let expectation = XCTestExpectation(description: "Get show recommendations") traktManager.getRecommendedShows { result in if case .success(let shows) = result { XCTAssertEqual(shows.count, 10) expectation.fulfill() } } let result = XCTWaiter().wait(for: [expectation], timeout: 1) XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/recommendations/shows") switch result { case .timedOut: XCTFail("Something isn't working") default: break } } // MARK: - Hide Show func test_hide_show_recommendation() { session.nextStatusCode = StatusCodes.SuccessNoContentToReturn let expectation = XCTestExpectation(description: "Hide show recommendation") traktManager.hideRecommendedShow(showID: 922) { result in if case .success = result { expectation.fulfill() } } let result = XCTWaiter().wait(for: [expectation], timeout: 1) XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/recommendations/shows/922") switch result { case .timedOut: XCTFail("Something isn't working") default: break } } }
mit
b6f3aa3ad6b383591acf4ea0117e5a41
30.017699
106
0.614836
4.888424
false
true
false
false
kzaher/RxFeedback
Examples/Support/UIAlertController+Prompt.swift
1
2414
// // UIAlertController+Prompt.swift // RxFeedback // // Created by Krunoslav Zaher on 5/11/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import UIKit import RxSwift public protocol ActionConvertible: CustomStringConvertible { var style: UIAlertAction.Style { get } } extension UIAlertController { public static func prompt<T: ActionConvertible>( message: String, title: String?, actions: [T], parent: UIViewController, type: UIAlertController.Style = .alert, configure: @escaping (UIAlertController) -> () = { _ in } ) -> Observable<(UIAlertController, T)> { return Observable.create { observer in let promptController = UIAlertController(title: title, message: message, preferredStyle: type) for action in actions { let action = UIAlertAction(title: action.description, style: action.style, handler: { [weak promptController] alertAction -> Void in guard let controller = promptController else { return } observer.on(.next((controller, action))) observer.on(.completed) }) promptController.addAction(action) } configure(promptController) parent.present(promptController, animated: true, completion: nil) return Disposables.create() } } } public enum AlertAction { case ok case cancel case delete case confirm } extension AlertAction : ActionConvertible { public var description: String { switch self { case .ok: return NSLocalizedString("OK", comment: "Ok action for the alert controller") case .cancel: return NSLocalizedString("Cancel", comment: "Cancel action for the alert controller") case .delete: return NSLocalizedString("Delete", comment: "Delete action for the alert controller") case .confirm: return NSLocalizedString("Confirm", comment: "Confirm action for the alert controller") } } public var style: UIAlertAction.Style { switch self { case .ok: return .`default` case .cancel: return .cancel case .delete: return .destructive case .confirm: return .`default` } } }
mit
51755508582816521caf1234e6d52a7a
29.1625
148
0.606714
5.134043
false
false
false
false
OSzhou/MyTestDemo
17_SwiftTestCode/TestCode/OtherPro/WBImageTitleDetailAlertView.swift
1
7121
// // WBImageTitleDetailAlertView.swift // ACN_Wallet // // Created by Zhouheng on 2020/6/19. // Copyright © 2020 TTC. All rights reserved. // import UIKit class WBImageTitleDetailAlertView: UIView { var closeClick:(() -> ())? /// 确定 var confirmClick:(() -> ())? /// 此刻弹框是否正在展示中 static private(set) var showing: Bool = false init(frame: CGRect = UIScreen.main.bounds, image: UIImage?, title: String?, detail: String?, confirmTitle: String?, cancelTitle: String?) { super.init(frame: frame) self.backgroundColor = UIColor.black.withAlphaComponent(0.5) addSubview(contentView) if let img = image { contentView.addSubview(icon) icon.image = image icon.snp.makeConstraints { (make) in make.top.equalTo(contentView) make.centerX.equalTo(contentView) make.width.equalTo(img.size.width) make.height.equalTo(img.size.height) } midLabelLayout(title, detail: detail, markView: icon, offset: 12) } else { let placeholder = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth - 105, height: 1)) contentView.addSubview(placeholder) midLabelLayout(title, detail: detail, markView: placeholder, offset: 30) } contentView.addSubview(confirmButton) var confirmW: CGFloat = screenWidth - 105 if let confirmT = confirmTitle { confirmButton.setTitle(confirmT, for: .normal) } var markView = contentView if let _ = detail { markView = detailLabel } else if let _ = title { markView = titleLabel } if let cancelT = cancelTitle { confirmW = (screenWidth - 105) / 2.0 contentView.addSubview(cancelButton) cancelButton.setTitle(cancelT, for: .normal) cancelButton.snp.makeConstraints { (make) in make.top.equalTo(confirmButton) make.left.bottom.equalTo(0) make.width.equalTo(confirmW) make.height.equalTo(50) } } confirmButton.snp.makeConstraints { (make) in make.top.equalTo(markView.snp.bottom).offset(30) make.right.equalTo(0) make.width.equalTo(confirmW) make.height.equalTo(50) make.bottom.equalTo(0) } contentView.snp.makeConstraints { (make) in make.width.equalTo(screenWidth - 105) make.center.equalTo(self) } } private func midLabelLayout(_ title: String?, detail: String?, markView: UIView, offset: CGFloat) { if let t = title { contentView.addSubview(titleLabel) titleLabel.text = t titleLabel.snp.makeConstraints { (make) in make.left.equalTo(30) make.right.equalTo(-30) make.top.equalTo(markView.snp.bottom).offset(offset) } if let d = detail { contentView.addSubview(detailLabel) detailLabel.text = d detailLabel.snp.makeConstraints { (make) in make.left.right.equalTo(titleLabel) make.top.equalTo(titleLabel.snp.bottom).offset(4) } } } else { if let d = detail { contentView.addSubview(detailLabel) detailLabel.text = d detailLabel.snp.makeConstraints { (make) in make.left.equalTo(30) make.right.equalTo(-30) make.top.equalTo(markView.snp.bottom).offset(offset) } } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// MARK: --- action @objc func buttonClick(_ sender: UIButton) { dismiss(completion: { self.confirmClick?() }) } @objc private func cancelButtonClick(_ sender: UIButton) { dismiss(completion: { self.cancel() }) } func cancel() { self.closeClick?() } @discardableResult func show(_ superview: UIView? = nil) -> Bool { guard !WBImageTitleDetailAlertView.showing else { return false } guard let superView = superview ?? UIApplication.shared.windows.first else { return false } alpha = 0 superView.addSubview(self) WBImageTitleDetailAlertView.showing = true UIView.animate(withDuration: 0.25) { self.alpha = 1 } return true } func dismiss(animated: Bool = true, completion: (() -> Void)? = nil) { let finish = { [weak self] (finish: Bool) in self?.removeFromSuperview() WBImageTitleDetailAlertView.showing = false completion?() } if animated { UIView.animate(withDuration: 0.25, animations: { self.alpha = 0 }, completion: finish) } else { finish(true) } } /// MARK: --- lazy loading lazy var contentView: UIView = { let view = UIView() view.backgroundColor = UIColor.white view.layer.cornerRadius = 16 view.clipsToBounds = true return view }() private lazy var icon: UIImageView = { let view = UIImageView() return view }() lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 15) label.textColor = UIColor.black label.numberOfLines = 0 label.textAlignment = .center return label }() lazy var detailLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 14) label.textColor = UIColor.black label.numberOfLines = 0 label.textAlignment = .center return label }() lazy var confirmButton: UIButton = { let button = UIButton(type: .custom) button.backgroundColor = .gray button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.setTitle("确认", for: .normal) button.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside) return button }() lazy var cancelButton: UIButton = { let button = UIButton(type: .custom) button.backgroundColor = .gray button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.setTitle("取消", for: .normal) button.addTarget(self, action: #selector(cancelButtonClick(_:)), for: .touchUpInside) return button }() }
apache-2.0
91a2ca32098b0a575305a1fe015b3ca4
30.775785
143
0.548123
4.791075
false
false
false
false
cplaverty/KeitaiWaniKani
WaniKaniKit/Model/Vocabulary.swift
1
3923
// // Vocabulary.swift // WaniKaniKit // // Copyright © 2017 Chris Laverty. All rights reserved. // public struct Vocabulary: ResourceCollectionItemData, Equatable { public let createdAt: Date public let level: Int public let slug: String public let hiddenAt: Date? public let documentURL: URL public let characters: String public let meanings: [Meaning] public let auxiliaryMeanings: [AuxiliaryMeaning] public let readings: [Reading] public let partsOfSpeech: [String] public let componentSubjectIDs: [Int] public let meaningMnemonic: String public let readingMnemonic: String public let contextSentences: [ContextSentence] public let pronunciationAudios: [PronunciationAudio] public let lessonPosition: Int public var normalisedPartsOfSpeech: [String] { return partsOfSpeech.map({ normalisePartOfSpeech($0).capitalized }) } private enum CodingKeys: String, CodingKey { case createdAt = "created_at" case level case slug case hiddenAt = "hidden_at" case documentURL = "document_url" case characters case meanings case auxiliaryMeanings = "auxiliary_meanings" case readings case partsOfSpeech = "parts_of_speech" case componentSubjectIDs = "component_subject_ids" case meaningMnemonic = "meaning_mnemonic" case readingMnemonic = "reading_mnemonic" case contextSentences = "context_sentences" case pronunciationAudios = "pronunciation_audios" case lessonPosition = "lesson_position" } private func normalisePartOfSpeech(_ str: String) -> String { switch str { case "godan_verb": return "godan verb" case "i_adjective": return "い adjective" case "ichidan_verb": return "ichidan verb" case "intransitive_verb": return "intransitive verb" case "na_adjective": return "な adjective" case "no_adjective": return "の adjective" case "proper_noun": return "proper noun" case "suru_verb": return "する verb" case "transitive_verb": return "transitive verb" default: return str } } } extension Vocabulary: Subject { public var subjectType: SubjectType { return .vocabulary } } extension Vocabulary { public struct ContextSentence: Codable, Equatable { public let english: String public let japanese: String private enum CodingKeys: String, CodingKey { case english = "en" case japanese = "ja" } } } extension Vocabulary { public var allReadings: String { return readings.lazy .map({ $0.reading }) .joined(separator: ", ") } } extension Vocabulary { public struct PronunciationAudio: Codable, Equatable { public let url: URL public let metadata: Metadata public let contentType: String private enum CodingKeys: String, CodingKey { case url case metadata case contentType = "content_type" } } } extension Vocabulary.PronunciationAudio { public struct Metadata: Codable, Equatable { public let gender: String public let sourceID: Int public let pronunciation: String public let voiceActorID: Int public let voiceActorName: String public let voiceDescription: String enum CodingKeys: String, CodingKey { case gender case sourceID = "source_id" case pronunciation case voiceActorID = "voice_actor_id" case voiceActorName = "voice_actor_name" case voiceDescription = "voice_description" } } }
mit
bdce865746ad19a55df2794ccc85d4b3
28.413534
75
0.61682
4.841584
false
false
false
false
eonil/BTree
Sources/BTreeNode.swift
1
22116
// // BTreeNode.swift // BTree // // Created by Károly Lőrentey on 2016-01-13. // Copyright © 2015–2017 Károly Lőrentey. // // `bTreeNodeSize` is the maximum size (in bytes) of the keys in a single, fully loaded B-tree node. // This is related to the order of the B-tree, i.e., the maximum number of children of an internal node. // // Common sense indicates (and benchmarking verifies) that the fastest B-tree order depends on `strideof(key)`: // doubling the size of the key roughly halves the optimal order. So there is a certain optimal overall node size that // is independent of the key; this value is supposed to be that size. // // Obviously, the optimal node size depends on the hardware we're running on. // Benchmarks performed on various systems (Apple A5X, A8X, A9; Intel Core i5 Sandy Bridge, Core i7 Ivy Bridge) // indicate that 16KiB is a good overall choice. // (This may be related to the size of the L1 cache, which is frequently 16kiB or 32kiB.) // // It is not a good idea to use powers of two as the B-tree order, as that would lead to Array reallocations just before // a node is split. A node size that's just below 2^n seems like a good choice. internal let bTreeNodeSize = 16383 //MARK: BTreeNode definition /// A node in an in-memory B-tree data structure, efficiently mapping `Comparable` keys to arbitrary values. /// Iterating over the elements in a B-tree returns them in ascending order of their keys. internal final class BTreeNode<Key: Comparable, Value> { typealias Iterator = BTreeIterator<Key, Value> typealias Element = Iterator.Element typealias Node = BTreeNode<Key, Value> /// FIXME: Allocate keys/values/children in a single buffer /// The elements stored in this node, sorted by key. internal var elements: Array<Element> /// An empty array (when this is a leaf), or `elements.count + 1` child nodes (when this is an internal node). internal var children: Array<BTreeNode> /// The number of elements in this B-tree. internal var count: Int /// The order of this B-tree. An internal node will have at most this many children. internal let _order: Int32 /// The depth of this B-tree. internal let _depth: Int32 internal var depth: Int { return numericCast(_depth) } internal var order: Int { return numericCast(_order) } internal init(order: Int, elements: Array<Element>, children: Array<BTreeNode>, count: Int) { assert(children.count == 0 || elements.count == children.count - 1) self._order = numericCast(order) self.elements = elements self.children = children self.count = count self._depth = (children.count == 0 ? 0 : children[0]._depth + 1) assert(children.firstIndex { $0._depth + (1 as Int32) != self._depth } == nil) } } //MARK: Convenience initializers extension BTreeNode { static var defaultOrder: Int { return Swift.max(bTreeNodeSize / MemoryLayout<Element>.stride, 8) } convenience init(order: Int = Node.defaultOrder) { self.init(order: order, elements: [], children: [], count: 0) } internal convenience init(left: Node, separator: (Key, Value), right: Node) { assert(left.order == right.order) assert(left.depth == right.depth) self.init( order: left.order, elements: [separator], children: [left, right], count: left.count + 1 + right.count) } internal convenience init(node: BTreeNode, slotRange: CountableRange<Int>) { if node.isLeaf { let elements = Array(node.elements[slotRange]) self.init(order: node.order, elements: elements, children: [], count: elements.count) } else if slotRange.count == 0 { let n = node.children[slotRange.lowerBound] self.init(order: n.order, elements: n.elements, children: n.children, count: n.count) } else { let elements = Array(node.elements[slotRange]) let children = Array(node.children[slotRange.lowerBound ... slotRange.upperBound]) let count = children.reduce(elements.count) { $0 + $1.count } self.init(order: node.order, elements: elements, children: children, count: count) } } } //MARK: Uniqueness extension BTreeNode { @discardableResult func makeChildUnique(_ index: Int) -> BTreeNode { guard !isKnownUniquelyReferenced(&children[index]) else { return children[index] } let clone = children[index].clone() children[index] = clone return clone } func clone() -> BTreeNode { return BTreeNode(order: order, elements: elements, children: children, count: count) } } //MARK: Basic limits and properties extension BTreeNode { internal var maxChildren: Int { return order } internal var minChildren: Int { return (maxChildren + 1) / 2 } internal var maxKeys: Int { return maxChildren - 1 } internal var minKeys: Int { return minChildren - 1 } internal var isLeaf: Bool { return depth == 0 } internal var isTooSmall: Bool { return elements.count < minKeys } internal var isTooLarge: Bool { return elements.count > maxKeys } internal var isBalanced: Bool { return elements.count >= minKeys && elements.count <= maxKeys } } //MARK: Sequence extension BTreeNode: Sequence { var isEmpty: Bool { return count == 0 } func makeIterator() -> Iterator { return BTreeIterator(BTreeStrongPath(root: self, offset: 0)) } /// Call `body` on each element in self in the same order as a for-in loop. func forEach(_ body: (Element) throws -> ()) rethrows { if isLeaf { for element in elements { try body(element) } } else { for i in 0 ..< elements.count { try children[i].forEach(body) try body(elements[i]) } try children[elements.count].forEach(body) } } /// A version of `forEach` that allows `body` to interrupt iteration by returning `false`. /// /// - Returns: `true` iff `body` returned true for all elements in the tree. @discardableResult func forEach(_ body: (Element) throws -> Bool) rethrows -> Bool { if isLeaf { for element in elements { guard try body(element) else { return false } } } else { for i in 0 ..< elements.count { guard try children[i].forEach(body) else { return false } guard try body(elements[i]) else { return false } } guard try children[elements.count].forEach(body) else { return false } } return true } } //MARK: Slots extension BTreeNode { internal func setElement(inSlot slot: Int, to element: Element) -> Element { let old = elements[slot] elements[slot] = element return old } internal func insert(_ element: Element, inSlot slot: Int) { elements.insert(element, at: slot) count += 1 } internal func append(_ element: Element) { elements.append(element) count += 1 } @discardableResult internal func remove(slot: Int) -> Element { count -= 1 return elements.remove(at: slot) } /// Does one step toward looking up an element with `key`, returning the slot index of a direct match (if any), /// and the slot index to use to continue descending. /// /// - Complexity: O(log(order)) @inline(__always) internal func slot(of key: Key, choosing selector: BTreeKeySelector = .first) -> (match: Int?, descend: Int) { switch selector { case .first, .any: var start = 0 var end = elements.count while start < end { let mid = start + (end - start) / 2 if elements[mid].0 < key { start = mid + 1 } else { end = mid } } return (start < elements.count && elements[start].0 == key ? start : nil, start) case .last: var start = -1 var end = elements.count - 1 while start < end { let mid = start + (end - start + 1) / 2 if elements[mid].0 > key { end = mid - 1 } else { start = mid } } return (start >= 0 && elements[start].0 == key ? start : nil, start + 1) case .after: var start = 0 var end = elements.count while start < end { let mid = start + (end - start) / 2 if elements[mid].0 <= key { start = mid + 1 } else { end = mid } } return (start < elements.count ? start : nil, start) } } /// Return the slot of the element at `offset` in the subtree rooted at this node. internal func slot(atOffset offset: Int) -> (index: Int, match: Bool, offset: Int) { assert(offset >= 0 && offset <= count) if offset == count { return (index: elements.count, match: isLeaf, offset: count) } if isLeaf { return (offset, true, offset) } else if offset <= count / 2 { var p = 0 for i in 0 ..< children.count - 1 { let c = children[i].count if offset == p + c { return (index: i, match: true, offset: p + c) } if offset < p + c { return (index: i, match: false, offset: p + c) } p += c + 1 } let c = children.last!.count precondition(count == p + c, "Invalid B-Tree") return (index: children.count - 1, match: false, offset: count) } var p = count for i in (1 ..< children.count).reversed() { let c = children[i].count if offset == p - (c + 1) { return (index: i - 1, match: true, offset: offset) } if offset > p - (c + 1) { return (index: i, match: false, offset: p) } p -= c + 1 } let c = children.first!.count precondition(p - c == 0, "Invalid B-Tree") return (index: 0, match: false, offset: c) } /// Return the offset of the element at `slot` in the subtree rooted at this node. internal func offset(ofSlot slot: Int) -> Int { let c = elements.count assert(slot >= 0 && slot <= c) if isLeaf { return slot } if slot == c { return count } if slot <= c / 2 { return children[0...slot].reduce(slot) { $0 + $1.count } } return count - children[slot + 1 ... c].reduce(c - slot) { $0 + $1.count } } /// Returns true iff the subtree at this node is guaranteed to contain the specified element /// with `key` (if it exists). /// Returns false if the key falls into the first or last child subtree, so containment depends /// on the contents of the ancestors of this node. internal func contains(_ key: Key, choosing selector: BTreeKeySelector) -> Bool { let firstKey = elements.first!.0 let lastKey = elements.last!.0 if key < firstKey { return false } if key == firstKey && selector == .first { return false } if key > lastKey { return false } if key == lastKey && (selector == .last || selector == .after) { return false } return true } } //MARK: Lookups extension BTreeNode { /// Returns the first element at or under this node, or `nil` if this node is empty. /// /// - Complexity: O(log(`count`)) var first: Element? { var node = self while let child = node.children.first { node = child } return node.elements.first } /// Returns the last element at or under this node, or `nil` if this node is empty. /// /// - Complexity: O(log(`count`)) var last: Element? { var node = self while let child = node.children.last { node = child } return node.elements.last } } //MARK: Splitting internal struct BTreeSplinter<Key: Comparable, Value> { let separator: (Key, Value) let node: BTreeNode<Key, Value> } extension BTreeNode { typealias Splinter = BTreeSplinter<Key, Value> /// Split this node into two, removing the high half of the nodes and putting them in a splinter. /// /// - Returns: A splinter containing the higher half of the original node. internal func split() -> Splinter { assert(isTooLarge) return split(at: elements.count / 2) } /// Split this node into two at the key at index `median`, removing all elements at or above `median` /// and putting them in a splinter. /// /// - Returns: A splinter containing the higher half of the original node. internal func split(at median: Int) -> Splinter { let count = elements.count let separator = elements[median] let node = BTreeNode(node: self, slotRange: median + 1 ..< count) elements.removeSubrange(median ..< count) if isLeaf { self.count = median } else { children.removeSubrange(median + 1 ..< count + 1) self.count = median + children.reduce(0, { $0 + $1.count }) } assert(node.depth == self.depth) return Splinter(separator: separator, node: node) } internal func insert(_ splinter: Splinter, inSlot slot: Int) { elements.insert(splinter.separator, at: slot) children.insert(splinter.node, at: slot + 1) } } //MARK: Removal extension BTreeNode { /// Reorganize the tree rooted at `self` so that the undersize child in `slot` is corrected. /// As a side effect of the process, `self` may itself become undersized, but all of its descendants /// become balanced. internal func fixDeficiency(_ slot: Int) { assert(!isLeaf && children[slot].isTooSmall) if slot > 0 && children[slot - 1].elements.count > minKeys { rotateRight(slot) } else if slot < children.count - 1 && children[slot + 1].elements.count > minKeys { rotateLeft(slot) } else if slot > 0 { // Collapse deficient slot into previous slot. collapse(slot - 1) } else { // Collapse next slot into deficient slot. collapse(slot) } } internal func rotateRight(_ slot: Int) { assert(slot > 0) makeChildUnique(slot) makeChildUnique(slot - 1) children[slot].elements.insert(elements[slot - 1], at: 0) if !children[slot].isLeaf { let lastGrandChildBeforeSlot = children[slot - 1].children.removeLast() children[slot].children.insert(lastGrandChildBeforeSlot, at: 0) children[slot - 1].count -= lastGrandChildBeforeSlot.count children[slot].count += lastGrandChildBeforeSlot.count } elements[slot - 1] = children[slot - 1].elements.removeLast() children[slot - 1].count -= 1 children[slot].count += 1 } internal func rotateLeft(_ slot: Int) { assert(slot < children.count - 1) makeChildUnique(slot) makeChildUnique(slot + 1) children[slot].elements.append(elements[slot]) if !children[slot].isLeaf { let firstGrandChildAfterSlot = children[slot + 1].children.remove(at: 0) children[slot].children.append(firstGrandChildAfterSlot) children[slot + 1].count -= firstGrandChildAfterSlot.count children[slot].count += firstGrandChildAfterSlot.count } elements[slot] = children[slot + 1].elements.remove(at: 0) children[slot].count += 1 children[slot + 1].count -= 1 } internal func collapse(_ slot: Int) { assert(slot < children.count - 1) makeChildUnique(slot) let next = children.remove(at: slot + 1) children[slot].elements.append(elements.remove(at: slot)) children[slot].count += 1 children[slot].elements.append(contentsOf: next.elements) children[slot].count += next.count if !next.isLeaf { children[slot].children.append(contentsOf: next.children) } assert(children[slot].isBalanced) } } //MARK: Join extension BTreeNode { /// Shift slots between `self` and `node` such that the number of elements in `self` becomes `target`. internal func shiftSlots(separator: Element, node: BTreeNode, target: Int) -> Splinter? { assert(self.depth == node.depth) let forward = target > self.elements.count let delta = abs(target - self.elements.count) if delta == 0 { return Splinter(separator: separator, node: node) } let lc = self.elements.count let rc = node.elements.count if (forward && delta >= rc + 1) || (!forward && delta >= lc + 1) { // Melt the entire right node into self. self.elements.append(separator) self.elements.append(contentsOf: node.elements) self.children.append(contentsOf: node.children) node.elements = [] node.children = [] self.count += 1 + node.count return nil } let rsep: Element if forward { // Transfer slots from right to left assert(lc + delta < self.order) assert(delta <= rc) rsep = node.elements[delta - 1] self.elements.append(separator) self.elements.append(contentsOf: node.elements.prefix(delta - 1)) self.count += delta node.elements.removeFirst(delta) node.count -= delta if !self.isLeaf { let children = node.children.prefix(delta) let dc = children.reduce(0) { $0 + $1.count } self.children.append(contentsOf: children) self.count += dc node.children.removeFirst(delta) node.count -= dc } } else { // Transfer slots from left to right assert(rc + delta < node.order) assert(delta <= lc) rsep = self.elements[lc - delta] node.elements.insert(separator, at: 0) node.elements.insert(contentsOf: self.elements.suffix(delta - 1), at: 0) node.count += delta self.elements.removeSubrange(lc - delta ..< lc) self.count -= delta if !self.isLeaf { let children = self.children.suffix(delta) let dc = children.reduce(0) { $0 + $1.count } node.children.insert(contentsOf: children, at: 0) node.count += dc self.children.removeSubrange(lc + 1 - delta ..< lc + 1) self.count -= dc } } if node.children.count == 1 { return Splinter(separator: rsep, node: node.makeChildUnique(0)) } return Splinter(separator: rsep, node: node) } func swapContents(with other: Node) { precondition(self._depth == other._depth) precondition(self._order == other._order) swap(&self.elements, &other.elements) swap(&self.children, &other.children) swap(&self.count, &other.count) } /// Create and return a new B-tree consisting of elements of `left`,`separator` and the elements of `right`, /// in this order. /// /// If you need to keep `left` and `right` intact, clone them before calling this function. /// /// - Requires: `l <= separator.0 && separator.0 <= r` for all keys `l` in `left` and all keys `r` in `right`. /// - Complexity: O(log(left.count + right.count)) internal static func join(left: BTreeNode, separator: (Key, Value), right: BTreeNode) -> BTreeNode { precondition(left.order == right.order) let order = left.order let depthDelta = left.depth - right.depth let append = depthDelta >= 0 let stock = append ? left : right let scion = append ? right : left // We'll graft the scion onto the stock. // First, find the insertion point, and preemptively update node counts on the way there. var path = [stock] var node = stock let c = scion.count for _ in 0 ..< abs(depthDelta) { node.count += c + 1 node = node.makeChildUnique(append ? node.children.count - 1 : 0) path.append(node) } // Graft the scion into the stock by inserting the contents of its root into `node`. if !append { node.swapContents(with: scion) } assert(node.depth == scion.depth) let slotCount = node.elements.count + 1 + scion.elements.count let target = slotCount < order ? slotCount : slotCount / 2 var splinter = node.shiftSlots(separator: separator, node: scion, target: target) if splinter != nil { assert(splinter!.node.isBalanced) path.removeLast() while let s = splinter, !path.isEmpty { let node = path.removeLast() node.insert(s, inSlot: append ? node.elements.count : 0) splinter = node.isTooLarge ? node.split() : nil } if let s = splinter { return BTreeNode(left: stock, separator: s.separator, right: s.node) } } return stock } }
mit
4a8acb130744cad72b33131cefcf946f
35.066884
120
0.57402
4.195256
false
false
false
false
kadarandras/KASpotlightHelper
Example/KASpotlightHelper/SearchableItem.swift
1
1284
// // SearchableItem.swift // KASpotlightHelper // // Created by Andras on 09/03/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import KASpotlightHelper class SearchableItem: NSObject, NSCoding, KASpotlightIndexableItem { var id: String var title: String var image: UIImage? init(title: String, image: UIImage?) { self.id = NSUUID().UUIDString self.title = title self.image = image } required init?(coder aDecoder: NSCoder) { self.id = aDecoder.decodeObjectForKey("id") as! String self.title = aDecoder.decodeObjectForKey("title") as! String self.image = aDecoder.decodeObjectForKey("image") as? UIImage } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.id, forKey: "id") aCoder.encodeObject(self.title, forKey: "title") if let image = self.image { aCoder.encodeObject(image, forKey: "image") } } func spotlightId() -> String { return self.id } func spotlightTitle() -> String { return self.title } func spotlightThumbnailData() -> NSData? { return image != nil ? UIImageJPEGRepresentation(image!, 1.0) : nil } }
mit
04e076dc69648070fd41416254162312
23.673077
74
0.613406
4.262458
false
false
false
false
937447974/YJCocoa
YJCocoa/Classes/AppFrameworks/Foundation/Directory/YJDirectory.swift
1
1777
// // YJDirectory.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/5/27. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import UIKit /// 应用内目录 public let YJDirectoryS = YJDirectory() /// 应用内目录 @objcMembers open class YJDirectory: NSObject { /// HomeDirectoryPath public let homePath: String! /// DocumentDirectoryPath public let documentPath: String! /// LibraryDirectoryPath public let libraryPath: String! /// CachesDirectoryPath public let cachesPath: String! /// TemporaryDirectoryPath public let tempPath: String! /// HomeDirectoryURL public let homeURL: URL! /// DocumentDirectoryPath public let documentURL: URL! /// LibraryDirectoryPath public let libraryURL: URL! /// CachesDirectoryPath public let cachesURL: URL! /// TemporaryDirectoryPath public let tempURL: URL! public override init() { self.homePath = NSHomeDirectory() self.documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! self.libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first! self.cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! self.tempPath = NSTemporaryDirectory() self.homeURL = URL(fileURLWithPath: self.homePath) self.documentURL = URL(fileURLWithPath: self.documentPath) self.libraryURL = URL(fileURLWithPath: self.libraryPath) self.cachesURL = URL(fileURLWithPath: self.cachesPath) self.tempURL = URL(fileURLWithPath: self.tempPath) } }
mit
9e2c34640c55433530782e1a2019f5db
30.035714
113
0.701956
4.697297
false
false
false
false
Allow2CEO/browser-ios
DeviceDetector.swift
1
578
/* 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 /// Checks what device model is used based on its screen height. struct DeviceDetector { static var iPhone4s: Bool { return UIScreen.main.nativeBounds.height == 960 } static var iPhoneX: Bool { return UIScreen.main.nativeBounds.height == 2436 } static let isIpad = UIDevice.current.userInterfaceIdiom == .pad }
mpl-2.0
54ebd5abe081abdba3920568a6641e53
31.111111
70
0.693772
4.128571
false
false
false
false
prebid/prebid-mobile-ios
EventHandlers/PrebidMobileMAXAdapters/Sources/PrebidMAXMediationAdapter.swift
1
2178
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import PrebidMobile import AppLovinSDK public let MAXCustomParametersKey = "custom_parameters" @objc(PrebidMAXMediationAdapter) public class PrebidMAXMediationAdapter: ALMediationAdapter { // MARK: - Banner public weak var bannerDelegate: MAAdViewAdapterDelegate? public var displayView: PBMDisplayView? // MARK: - Interstitial public weak var interstitialDelegate: MAInterstitialAdapterDelegate? public var interstitialController: InterstitialController? public var interstitialAdAvailable = false // MARK: - Rewarded public weak var rewardedDelegate: MARewardedAdapterDelegate? // MARK: - Native public weak var nativeDelegate: MANativeAdAdapterDelegate? public override func initialize(with parameters: MAAdapterInitializationParameters, completionHandler: @escaping (MAAdapterInitializationStatus, String?) -> Void) { super.initialize(with: parameters, completionHandler: completionHandler) Targeting.shared.subjectToCOPPA = ALPrivacySettings.isAgeRestrictedUser() } public override var sdkVersion: String { return Prebid.shared.version } public override var adapterVersion: String { MAXConstants.PrebidMAXAdapterVersion } public override func destroy() { bannerDelegate = nil displayView = nil interstitialDelegate = nil interstitialController = nil rewardedDelegate = nil nativeDelegate = nil super.destroy() } }
apache-2.0
b3028ffdc0c0b49bf5b8bd05d84552f6
30.405797
168
0.722197
4.95881
false
false
false
false
wenghengcong/Coderpursue
BeeFun/Pods/SwiftyStoreKit/SwiftyStoreKit/PaymentsController.swift
1
4439
// // PaymentsController.swift // SwiftyStoreKit // // Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com) // // 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 StoreKit struct Payment: Hashable { let product: SKProduct let quantity: Int let atomically: Bool let applicationUsername: String let simulatesAskToBuyInSandbox: Bool let callback: (TransactionResult) -> Void func hash(into hasher: inout Hasher) { hasher.combine(product) hasher.combine(quantity) hasher.combine(atomically) hasher.combine(applicationUsername) hasher.combine(simulatesAskToBuyInSandbox) } static func == (lhs: Payment, rhs: Payment) -> Bool { return lhs.product.productIdentifier == rhs.product.productIdentifier } } class PaymentsController: TransactionController { private var payments: [Payment] = [] private func findPaymentIndex(withProductIdentifier identifier: String) -> Int? { for payment in payments where payment.product.productIdentifier == identifier { return payments.firstIndex(of: payment) } return nil } func hasPayment(_ payment: Payment) -> Bool { return findPaymentIndex(withProductIdentifier: payment.product.productIdentifier) != nil } func append(_ payment: Payment) { payments.append(payment) } func processTransaction(_ transaction: SKPaymentTransaction, on paymentQueue: PaymentQueue) -> Bool { let transactionProductIdentifier = transaction.payment.productIdentifier guard let paymentIndex = findPaymentIndex(withProductIdentifier: transactionProductIdentifier) else { return false } let payment = payments[paymentIndex] let transactionState = transaction.transactionState if transactionState == .purchased { let purchase = PurchaseDetails(productId: transactionProductIdentifier, quantity: transaction.payment.quantity, product: payment.product, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !payment.atomically) payment.callback(.purchased(purchase: purchase)) if payment.atomically { paymentQueue.finishTransaction(transaction) } payments.remove(at: paymentIndex) return true } if transactionState == .failed { payment.callback(.failed(error: transactionError(for: transaction.error as NSError?))) paymentQueue.finishTransaction(transaction) payments.remove(at: paymentIndex) return true } if transactionState == .restored { print("Unexpected restored transaction for payment \(transactionProductIdentifier)") } return false } func transactionError(for error: NSError?) -> SKError { let message = "Unknown error" let altError = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: [ NSLocalizedDescriptionKey: message ]) let nsError = error ?? altError return SKError(_nsError: nsError) } func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction] { return transactions.filter { !processTransaction($0, on: paymentQueue) } } }
mit
b95987e80c0b3397b6068eeaf52aaf54
36.940171
263
0.702185
5.216216
false
false
false
false
x331275955/-
xiong-练习微博(视频)/xiong-练习微博(视频)/RootView/BaseTableViewController.swift
1
1502
// // BaseTableViewController.swift // xiong-练习微博(视频) // // Created by 王晨阳 on 15/9/12. // Copyright © 2015年 IOS. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController , VisitorViewDelegate{ /// 记录用户是否登录属性 var userLogin = UserAccount.userLogon // 判断是否是新用户 var newUser :Bool? /// 定义view var visitor : VisitorView? /// 改写loadView 使其判定用户是否登录 override func loadView() { userLogin ? super.loadView() : setupVisitorView() } /// 设置访客视图 private func setupVisitorView(){ visitor = VisitorView() visitor?.delegate = self view = visitor // 设置BarButtonItem的文字和点击 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorViewWillLogin") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorViewWillRegister") } // MARK: - 代理方法 func visitorViewWillLogin() { let nav = UINavigationController(rootViewController: OAuthViewController()) presentViewController(nav, animated: true, completion: nil) } func visitorViewWillRegister() { print("点击了注册按钮") } }
mit
b36b442a7add8754d846e625cb167a3d
25.134615
156
0.639441
4.906137
false
false
false
false
apple/swift-experimental-string-processing
Sources/_RegexParser/Regex/AST/MatchingOptions.swift
1
6062
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 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 // //===----------------------------------------------------------------------===// extension AST { /// An option, written in source, that changes matching semantics. public struct MatchingOption: Hashable { public enum Kind: Hashable { // PCRE options case caseInsensitive // i case allowDuplicateGroupNames // J case multiline // m case namedCapturesOnly // n case singleLine // s case reluctantByDefault // U case extended // x case extraExtended // xx // ICU options case unicodeWordBoundaries // w // Oniguruma options case asciiOnlyDigit // D case asciiOnlyPOSIXProps // P case asciiOnlySpace // S case asciiOnlyWord // W // Oniguruma text segment options (these are mutually exclusive and cannot // be unset, only flipped between) case textSegmentGraphemeMode // y{g} case textSegmentWordMode // y{w} // Swift semantic matching level case graphemeClusterSemantics // X case unicodeScalarSemantics // u case byteSemantics // b // Swift-only default possessive quantifier case possessiveByDefault // t.b.d. } public var kind: Kind public var location: SourceLocation public init(_ kind: Kind, location: SourceLocation) { self.kind = kind self.location = location } /// If this is either the regular or extra extended syntax option. public var isAnyExtended: Bool { switch kind { case .extended, .extraExtended: return true default: return false } } public var isTextSegmentMode: Bool { switch kind { case .textSegmentGraphemeMode, .textSegmentWordMode: return true default: return false } } public var isSemanticMatchingLevel: Bool { switch kind { case .graphemeClusterSemantics, .unicodeScalarSemantics, .byteSemantics: return true default: return false } } } /// A sequence of matching options, written in source. public struct MatchingOptionSequence: Hashable { /// If the sequence starts with a caret '^', its source location, or nil /// otherwise. If this is set, it indicates that all the matching options /// are unset, except the ones in `adding`. public var caretLoc: SourceLocation? /// The options to add. public var adding: [MatchingOption] /// The location of the '-' between the options to add and options to /// remove. public var minusLoc: SourceLocation? /// The options to remove. public var removing: [MatchingOption] public init(caretLoc: SourceLocation?, adding: [MatchingOption], minusLoc: SourceLocation?, removing: [MatchingOption]) { self.caretLoc = caretLoc self.adding = adding self.minusLoc = minusLoc self.removing = removing } /// Whether this set of matching options first resets the options before /// adding onto them. public var resetsCurrentOptions: Bool { caretLoc != nil } } } extension AST.MatchingOptionSequence { public init(adding: [AST.MatchingOption]) { self.init(caretLoc: nil, adding: adding, minusLoc: nil, removing: []) } public init(removing: [AST.MatchingOption]) { self.init(caretLoc: nil, adding: [], minusLoc: nil, removing: removing) } } extension AST.MatchingOption: _ASTPrintable { public var _dumpBase: String { "\(kind)" } } extension AST.MatchingOptionSequence: _ASTPrintable { public var _dumpBase: String { """ adding: \(adding), removing: \(removing), \ resetsCurrentOptions: \(resetsCurrentOptions) """ } } extension AST { /// Global matching option specifiers. /// /// Unlike `MatchingOptionSequence`, /// these options must appear at the start of the pattern, /// and they apply to the entire pattern. public struct GlobalMatchingOption: _ASTNode, Hashable { /// Determines the definition of a newline for the '.' character class and /// when parsing end-of-line comments. public enum NewlineMatching: Hashable { /// (*CR*) case carriageReturnOnly /// (*LF) case linefeedOnly /// (*CRLF) case carriageAndLinefeedOnly /// (*ANYCRLF) case anyCarriageReturnOrLinefeed /// (*ANY) case anyUnicode /// (*NUL) case nulCharacter } /// Determines what `\R` matches. public enum NewlineSequenceMatching: Hashable { /// (*BSR_ANYCRLF) case anyCarriageReturnOrLinefeed /// (*BSR_UNICODE) case anyUnicode } public enum Kind: Hashable { /// (*LIMIT_DEPTH=d) case limitDepth(AST.Atom.Number) /// (*LIMIT_HEAP=d) case limitHeap(AST.Atom.Number) /// (*LIMIT_MATCH=d) case limitMatch(AST.Atom.Number) /// (*NOTEMPTY) case notEmpty /// (*NOTEMPTY_ATSTART) case notEmptyAtStart /// (*NO_AUTO_POSSESS) case noAutoPossess /// (*NO_DOTSTAR_ANCHOR) case noDotStarAnchor /// (*NO_JIT) case noJIT /// (*NO_START_OPT) case noStartOpt /// (*UTF) case utfMode /// (*UCP) case unicodeProperties case newlineMatching(NewlineMatching) case newlineSequenceMatching(NewlineSequenceMatching) } public var kind: Kind public var location: SourceLocation public init(_ kind: Kind, _ location: SourceLocation) { self.kind = kind self.location = location } } }
apache-2.0
57d920e437bf77977ffee72b9fd48016
26.429864
80
0.605906
4.575094
false
false
false
false
modocache/Gift
Gift/Error/Domain.swift
1
978
/** Reserved for errors that occurred from within libgit2 function calls. */ public let libGit2ErrorDomain = "com.libgit2" /** Reserved for errors that occurred from within Gift function calls, either because of an unexpected code path, or because of user error. */ public let giftErrorDomain = "com.libgit2.gift" /** Error codes for errors that occurred from within Gift function calls. */ public enum GiftErrorCode: Int { /** An error occurred when attempting to parse an NSURL object. */ case InvalidURI = 1 /** An error occurred when attempting to convert a C string to a Swift String. */ case StringConversionFailure = 2 /** An error occurred when attempting to convert a libgit2 enum raw value to a Gift enum value. */ case EnumConversionFailure = 3 /** An error occurred when attempting to pass a Swift closure through to a C callback function used by libgit2. */ case CFunctionCallbackConversionFailure = 4 }
mit
134003f4c36a124eaa4184191158cdd5
25.432432
78
0.723926
4.445455
false
false
false
false
poulpix/PXGoogleDirections
Sources/PXGoogleDirections/PXLocation.swift
1
6157
// // PXLocation.swift // PXGoogleDirections // // Created by Romain on 01/03/2015. // Copyright (c) 2015 RLT. All rights reserved. // import Foundation import CoreLocation import UIKit /// Specifies a location, either by coordinates or by name public enum PXLocation { /// Specifies a location by latitude and longitude coordinates case coordinateLocation(CLLocationCoordinate2D) /// Specifies a location by name, city and/or country case specificLocation(String?, String?, String?) /// Specifies a location by a single string address case namedLocation(String) /// Specifies a location by a Google Place ID case googlePlaceId(String) fileprivate var centerCoordinate: CLLocationCoordinate2D? { switch self { case let .coordinateLocation(loc): return loc default: return nil } } /** Returns `true` if a location is indeed specifically defined. - returns: `true` if the object holds a specific location, `false` otherwise */ public func isSpecified() -> Bool { switch self { case let .specificLocation(address, city, country): return (address ?? "").count > 0 || (city ?? "").count > 0 || (country ?? "").count > 0 case let .namedLocation(address): return address.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).count > 0 default: return true } } /** Tries to open the selected location in the Google Maps app. - parameter mapMode: the kind of map shown (if not specified, the current application settings will be used) - parameter view: turns specific views on/off, multiple values can be set using a comma-separator (if the parameter is specified with no value, then it will clear all views) - parameter zoom: specifies the zoom level of the map - parameter callbackURL: the URL to call when complete ; often this will be a URL scheme allowing users to return to the original application - parameter callbackName: the name of the application sending the callback request (short names are preferred) - parameter fallbackToAppleMaps: `true` to fall back to Apple Maps in case Google Maps is not installed, `false` otherwise - returns: `true` if opening in the Google Maps is available, `false` otherwise */ public func openInGoogleMaps(mapMode: PXGoogleMapsMode?, view: Set<PXGoogleMapsView>?, zoom: UInt?, callbackURL: URL?, callbackName: String?, fallbackToAppleMaps: Bool = true) -> Bool { // Prepare the base URL parameters with provided arguments let params = PXGoogleDirections.handleGoogleMapsURL(center: centerCoordinate, mapMode: mapMode, view: view, zoom: zoom) // Build the Google Maps URL and open it if let url = PXGoogleDirections.buildGoogleMapsURL(params: params, callbackURL: callbackURL, callbackName: callbackName) { UIApplication.shared.openURL(url) return true } else { // Apply fallback strategy if fallbackToAppleMaps { let params = PXGoogleDirections.handleAppleMapsURL(center: centerCoordinate, mapMode: mapMode, view: view, zoom: zoom) let p = (params.count > 0) ? "?" + params.joined(separator: "&") : "" UIApplication.shared.openURL(URL(string: "https://maps.apple.com/\(p)")!) return true } } return false } /** Tries to launch the Google Maps app and searches for the specified query. - parameter query: the search query string - parameter mapMode: the kind of map shown (if not specified, the current application settings will be used) - parameter view: turns specific views on/off, multiple values can be set using a comma-separator (if the parameter is specified with no value, then it will clear all views) - parameter zoom: specifies the zoom level of the map - parameter callbackURL: the URL to call when complete ; often this will be a URL scheme allowing users to return to the original application - parameter callbackName: the name of the application sending the callback request (short names are preferred) - parameter fallbackToAppleMaps: `true` to fall back to Apple Maps in case Google Maps is not installed, `false` otherwise - returns: `true` if opening in the Google Maps is available, `false` otherwise */ public func searchInGoogleMaps(_ query: String, mapMode: PXGoogleMapsMode?, view: Set<PXGoogleMapsView>?, zoom: UInt?, callbackURL: URL?, callbackName: String?, fallbackToAppleMaps: Bool = true) -> Bool { // Prepare the base URL parameters with provided arguments var params = PXGoogleDirections.handleGoogleMapsURL(center: centerCoordinate, mapMode: mapMode, view: view, zoom: zoom) // Add the query string params.append("q=\(query.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)") // Build the Google Maps URL and open it if let url = PXGoogleDirections.buildGoogleMapsURL(params: params, callbackURL: callbackURL, callbackName: callbackName) { UIApplication.shared.openURL(url) return true } else { // Apply fallback strategy if fallbackToAppleMaps { var params = PXGoogleDirections.handleAppleMapsURL(center: centerCoordinate, mapMode: mapMode, view: view, zoom: zoom) params.append("q=\(query.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)") let p = (params.count > 0) ? "?" + params.joined(separator: "&") : "" UIApplication.shared.openURL(URL(string: "https://maps.apple.com/\(p)")!) return true } } return false } } extension PXLocation: CustomStringConvertible { public var description: String { switch (self) { case let .coordinateLocation(coords): return "\(coords.latitude),\(coords.longitude)" case let .specificLocation(name, city, country): var locationFullName = "" if let n = name { locationFullName = n } if let c = city { let separator = (locationFullName.lengthOfBytes(using: String.Encoding.utf8) > 0) ? "," : "" locationFullName += "\(separator)\(c)" } if let c = country { let separator = (locationFullName.lengthOfBytes(using: String.Encoding.utf8) > 0) ? "," : "" locationFullName += "\(separator)\(c)" } return locationFullName case let .namedLocation(address): return address case let .googlePlaceId(placeId): return "place_id:\(placeId)" } } }
bsd-3-clause
b493edf73530cf9cdee8d7af28b6f6d5
43.294964
205
0.734449
3.972258
false
false
false
false
tgyhlsb/RxSwiftExt
Source/RxSwift/pausableBuffered.swift
2
3462
// // pausableBuffered.swift // RxSwiftExt // // Created by Tanguy Helesbeux on 24/05/2017. // Copyright © 2017 RxSwiftCommunity. All rights reserved. // import Foundation import RxSwift extension ObservableType { /** Pauses the elements of the source observable sequence based on the latest element from the second observable sequence. While paused, elements from the source are buffered, limited to a maximum number of element. When resumed, all bufered elements are flushed as single events in a contiguous stream. - seealso: [pausable operator on reactivex.io](http://reactivex.io/documentation/operators/backpressure.html) - parameter pauser: The observable sequence used to pause the source observable sequence. - parameter limit: The maximum number of element buffered. Pass `nil` to buffer all elements without limit. Default 1. - parameter flushOnCompleted: If `true` bufered elements will be flushed when the source completes. Default `true`. - parameter flushOnError: If `true` bufered elements will be flushed when the source errors. Default `true`. - returns: The observable sequence which is paused and resumed based upon the pauser observable sequence. */ public func pausableBuffered<P : ObservableType> (_ pauser: P, limit: Int? = 1, flushOnCompleted: Bool = true, flushOnError: Bool = true) -> Observable<E> where P.E == Bool { return Observable<E>.create { observer in var buffer: [E] = [] if let limit = limit { buffer.reserveCapacity(limit) } var paused = true let lock = NSRecursiveLock() let flush = { for value in buffer { observer.onNext(value) } buffer.removeAll(keepingCapacity: limit != nil) } let boundaryDisposable = pauser.subscribe { event in lock.lock(); defer { lock.unlock() } switch event { case .next(let resume): paused = !resume if resume && buffer.count > 0 { flush() } case .completed: observer.onCompleted() case .error(let error): observer.onError(error) } } let disposable = self.subscribe { event in lock.lock(); defer { lock.unlock() } switch event { case .next(let element): if paused { buffer.append(element) if let limit = limit, buffer.count > limit { buffer.remove(at: 0) } } else { observer.onNext(element) } case .completed: if flushOnCompleted { flush() } observer.onCompleted() case .error(let error): if flushOnError { flush() } observer.onError(error) } } return Disposables.create([disposable, boundaryDisposable]) } } }
mit
8e2dc9825650bd04b024a6c6919e7aa8
36.215054
178
0.519503
5.519936
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift
1
18533
import XCTest import GRDB // A -> A // A -> B1 // A -> B2 private struct A : TableRecord { static let databaseTableName = "a" static let parent = belongsTo(A.self) static let child = hasOne(A.self) static let b1 = belongsTo(B.self, key: "b1", using: ForeignKey(["bid1"])) static let b2 = belongsTo(B.self, key: "b2", using: ForeignKey(["bid2"])) } private struct B : TableRecord { static let databaseTableName = "b" static let a1 = hasOne(A.self, key: "a1", using: ForeignKey(["bid1"])) static let a2 = hasOne(A.self, key: "a1", using: ForeignKey(["bid2"])) } /// Tests for table name conflicts, recursive associations, /// user-defined table aliases, and expressions that involve several tables. class AssociationTableAliasTestsSQLTests : GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() } try db.create(table: "a") { t in t.column("id", .integer).primaryKey() t.column("bid1", .integer).references("b") t.column("bid2", .integer).references("b") t.column("parentId", .integer).references("a") t.column("name", .text) } } } func testTableAliasBasics() throws { // A table reference qualifies all unqualified selectables, expressions, and orderings let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { let alias = TableAlias() let name = Column("name") let condition = name != nil && alias[name] == "foo" let expectedSQL = """ SELECT "name" \ FROM "a" \ WHERE ("id" = 1) AND ("name" IS NOT NULL) AND ("name" = 'foo') \ GROUP BY "name" \ HAVING "name" \ ORDER BY "name" """ do { let request = A .aliased(alias) .select(name) .filter(key: 1) .filter(condition) .group(name) .having(name) .order(name) try assertEqualSQL(db, request, expectedSQL) } do { let request = A .select(name) .filter(key: 1) .filter(condition) .group(name) .having(name) .order(name) .aliased(alias) try assertEqualSQL(db, request, expectedSQL) } } do { let alias = TableAlias(name: "customA") let name = Column("name") let condition = name != nil && alias[name] == "foo" let expectedSQL = """ SELECT "customA"."name" \ FROM "a" "customA" \ WHERE ("customA"."id" = 1) AND ("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo') \ GROUP BY "customA"."name" \ HAVING "customA"."name" \ ORDER BY "customA"."name" """ do { let request = A .aliased(alias) .select(name) .filter(key: 1) .filter(condition) .group(name) .having(name) .order(name) try assertEqualSQL(db, request, expectedSQL) } do { let request = A .select(name) .filter(key: 1) .filter(condition) .group(name) .having(name) .order(name) .aliased(alias) try assertEqualSQL(db, request, expectedSQL) } } } } func testRecursiveRelationDepth1() throws { // A.include(A.parent) // A.include(A.child) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try assertEqualSQL(db, A.including(required: A.parent), """ SELECT "a1".*, "a2".* \ FROM "a" "a1" \ JOIN "a" "a2" ON "a2"."id" = "a1"."parentId" """) try assertEqualSQL(db, A.including(required: A.child), """ SELECT "a1".*, "a2".* \ FROM "a" "a1" \ JOIN "a" "a2" ON "a2"."parentId" = "a1"."id" """) } } func testRecursiveRelationDepth2() throws { // A.include(B1).include(A) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = A .including(required: A.b1 .including(required: B.a2)) try assertEqualSQL(db, request, """ SELECT "a1".*, "b".*, "a2".* \ FROM "a" "a1" \ JOIN "b" ON "b"."id" = "a1"."bid1" \ JOIN "a" "a2" ON "a2"."bid2" = "b"."id" """) } } func testMultipleForeignKeys() throws { // A // .include(B1) // .include(B2) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = A .including(required: A.b1) .including(required: A.b2) try assertEqualSQL(db, request, """ SELECT "a".*, "b1".*, "b2".* \ FROM "a" \ JOIN "b" "b1" ON "b1"."id" = "a"."bid1" \ JOIN "b" "b2" ON "b2"."id" = "a"."bid2" """) } } func testRecursiveThroughMultipleForeignKeys() throws { // A // .include(B1.include(A)) // .include(B2.include(A)) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = A .including(required: A.b1 .including(required: B.a2)) .including(required: A.b2 .including(required: B.a1)) try assertEqualSQL(db, request, """ SELECT "a1".*, "b1".*, "a2".*, "b2".*, "a3".* \ FROM "a" "a1" \ JOIN "b" "b1" ON "b1"."id" = "a1"."bid1" \ JOIN "a" "a2" ON "a2"."bid2" = "b1"."id" \ JOIN "b" "b2" ON "b2"."id" = "a1"."bid2" \ JOIN "a" "a3" ON "a3"."bid1" = "b2"."id" """) } } func testUserDefinedAlias() throws { // A // .aliased("customA") // .include(B1.aliased("customB")) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let aAlias1 = TableAlias(name: "customA1") // On TableMapping and QueryInterfaceRequest let bAlias = TableAlias(name: "customB") // On BelongsToAssociation let aAlias2 = TableAlias(name: "customA2") // On HasOneAssociation let expectedSQL = """ SELECT "customA1".*, "customB".*, "customA2".* \ FROM "a" "customA1" \ JOIN "b" "customB" ON "customB"."id" = "customA1"."bid1" \ JOIN "a" "customA2" ON "customA2"."bid2" = "customB"."id" """ do { // Alias first let request = A .aliased(aAlias1) .including(required: A.b1 .aliased(bAlias) .including(required: B.a2 .aliased(aAlias2))) try assertEqualSQL(db, request, expectedSQL) } do { // Alias last let request = A .including(required: A.b1 .including(required: B.a2 .aliased(aAlias2)) .aliased(bAlias)) .aliased(aAlias1) try assertEqualSQL(db, request, expectedSQL) } } } func testUserInducedNameConflict() throws { // A.include(B1.aliased("a")) // A.aliased("b").include(B1) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { let bAlias = TableAlias(name: A.databaseTableName.lowercased()) let request = A.including(required: A.b1.aliased(bAlias)) try assertEqualSQL(db, request, """ SELECT "a1".*, "a".* \ FROM "a" "a1" \ JOIN "b" "a" ON "a"."id" = "a1"."bid1" """) } do { let bAlias = TableAlias(name: A.databaseTableName.uppercased()) let request = A.including(required: A.b1.aliased(bAlias)) try assertEqualSQL(db, request, """ SELECT "a1".*, "A".* \ FROM "a" "a1" \ JOIN "b" "A" ON "A"."id" = "a1"."bid1" """) } do { let aAlias = TableAlias(name: B.databaseTableName.lowercased()) let request = A.aliased(aAlias).including(required: A.b1) try assertEqualSQL(db, request, """ SELECT "b".*, "b1".* \ FROM "a" "b" \ JOIN "b" "b1" ON "b1"."id" = "b"."bid1" """) } do { let aAlias = TableAlias(name: B.databaseTableName.uppercased()) let request = A.aliased(aAlias).including(required: A.b1) try assertEqualSQL(db, request, """ SELECT "B".*, "b1".* \ FROM "a" "B" \ JOIN "b" "b1" ON "b1"."id" = "B"."bid1" """) } } } func testCrossTableExpressions() throws { // A // .include(B1.include(A)) // .include(B2.include(A)) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let rootA = TableAlias() let A1 = TableAlias() let A2 = TableAlias() let name = Column("name") let condition = name != nil && rootA[name] > A1[name] && A2[name] == "foo" let expectedSQL = """ SELECT "a1".*, "b1".*, "a2".*, "b2".*, "a3".* \ FROM "a" "a1" \ JOIN "b" "b1" ON "b1"."id" = "a1"."bid1" \ JOIN "a" "a2" ON "a2"."bid2" = "b1"."id" \ JOIN "b" "b2" ON "b2"."id" = "a1"."bid2" \ JOIN "a" "a3" ON "a3"."bid1" = "b2"."id" \ WHERE ("a1"."name" IS NOT NULL) AND ("a1"."name" > "a3"."name") AND ("a2"."name" = 'foo') """ do { // Filter first let request = A .filter(condition) .aliased(rootA) .including(required: A.b1 .including(required: B.a2.aliased(A2))) .including(required: A.b2 .including(required: B.a1.aliased(A1))) try assertEqualSQL(db, request, expectedSQL) } do { // Filter last let request = A .aliased(rootA) .including(required: A.b1 .including(required: B.a2.aliased(A2))) .including(required: A.b2 .including(required: B.a1.aliased(A1))) .filter(condition) try assertEqualSQL(db, request, expectedSQL) } } } func testAssociationRewrite() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { let request: QueryInterfaceRequest<A> = { let parentAlias = TableAlias() let name = Column("name") return A .joining(required: A.parent.aliased(parentAlias)) .filter(parentAlias[name] == "foo") }() let request2: QueryInterfaceRequest<A> = { let parentAlias = TableAlias() let name = Column("name") return request .joining(optional: A.parent.aliased(parentAlias)) .order(parentAlias[name]) }() let request3 = request2.including(optional: A.parent) try assertEqualSQL(db, request3, """ SELECT "a1".*, "a2".* \ FROM "a" "a1" \ JOIN "a" "a2" ON "a2"."id" = "a1"."parentId" \ WHERE "a2"."name" = 'foo' \ ORDER BY "a2"."name" """) } do { let request: QueryInterfaceRequest<A> = { let parentAlias = TableAlias(name: "parent") let name = Column("name") return A .joining(required: A.parent.aliased(parentAlias)) .filter(parentAlias[name] == "foo") }() let request2: QueryInterfaceRequest<A> = { let parentAlias = TableAlias() let name = Column("name") return request .joining(optional: A.parent.aliased(parentAlias)) .order(parentAlias[name]) }() let request3 = request2.including(optional: A.parent) try assertEqualSQL(db, request3, """ SELECT "a".*, "parent".* \ FROM "a" \ JOIN "a" "parent" ON "parent"."id" = "a"."parentId" \ WHERE "parent"."name" = 'foo' \ ORDER BY "parent"."name" """) } do { let request: QueryInterfaceRequest<A> = { let parentAlias = TableAlias() let name = Column("name") return A .joining(required: A.parent.aliased(parentAlias)) .filter(parentAlias[name] == "foo") }() let request2: QueryInterfaceRequest<A> = { let parentAlias = TableAlias(name: "parent") let name = Column("name") return request .joining(optional: A.parent.aliased(parentAlias)) .order(parentAlias[name]) }() let request3 = request2.including(optional: A.parent) try assertEqualSQL(db, request3, """ SELECT "a".*, "parent".* \ FROM "a" \ JOIN "a" "parent" ON "parent"."id" = "a"."parentId" \ WHERE "parent"."name" = 'foo' \ ORDER BY "parent"."name" """) } do { let request: QueryInterfaceRequest<A> = { let parentAlias = TableAlias(name: "parent") let name = Column("name") return A .joining(required: A.parent.aliased(parentAlias)) .filter(parentAlias[name] == "foo") }() let request2: QueryInterfaceRequest<A> = { let parentAlias = TableAlias(name: "parent") let name = Column("name") return request .joining(optional: A.parent.aliased(parentAlias)) .order(parentAlias[name]) }() let request3 = request2.including(optional: A.parent) try assertEqualSQL(db, request3, """ SELECT "a".*, "parent".* \ FROM "a" \ JOIN "a" "parent" ON "parent"."id" = "a"."parentId" \ WHERE "parent"."name" = 'foo' \ ORDER BY "parent"."name" """) } do { let request: QueryInterfaceRequest<A> = { let parentAlias = TableAlias() let name = Column("name") return A .joining(required: A.parent.aliased(parentAlias)) .filter(parentAlias[name] == "foo") }() let request2: QueryInterfaceRequest<A> = { let parentAlias = TableAlias() let name = Column("name") return request .joining(optional: A.parent.aliased(parentAlias)) .order(parentAlias[name]) }() let parentAlias = TableAlias(name: "parent") let request3 = request2.including(optional: A.parent.aliased(parentAlias)) try assertEqualSQL(db, request3, """ SELECT "a".*, "parent".* \ FROM "a" \ JOIN "a" "parent" ON "parent"."id" = "a"."parentId" \ WHERE "parent"."name" = 'foo' \ ORDER BY "parent"."name" """) } } } }
mit
747b874aadb0b4b69bdec6473cae7209
37.934874
114
0.408784
4.65069
false
false
false
false
yangyueguang/MyCocoaPods
Extension/Date+Extension.swift
1
6418
// // Date+Extension.swift import Foundation private var moren :TimeInterval = Foundation.Date().timeIntervalSince1970 public extension Date { var timeInterval:TimeInterval { get { guard let isFinished = objc_getAssociatedObject(self, &moren) as? TimeInterval else { return Foundation.Date().timeIntervalSince1970 } return isFinished } set { objc_setAssociatedObject(self, &moren, newValue, .OBJC_ASSOCIATION_ASSIGN) } } /// 获取当前时间戳 var timeStamp: Int64 { return Int64(floor(Date().timeIntervalSince1970 * 1000)) } /// 获取年月日时分秒对象 var components: DateComponents { return Calendar.current.dateComponents([.year, .month, .weekday, .day, .hour, .minute, .second, .nanosecond], from: self) } mutating func addDay(_ day:Int) { timeInterval += Double(day) * 24 * 3600 } mutating func addHour(_ hour:Int) { timeInterval += Double(hour) * 3600 } mutating func addMinute(_ minute:Int) { timeInterval += Double(minute) * 60 } mutating func addSecond(_ second:Int) { timeInterval += Double(second) } mutating func addMonth(month m:Int) { let (year, month, day) = getDay() let (hour, minute, second) = getTime() if let date = (Calendar.current as NSCalendar).date(era: year / 100, year: year, month: month + m, day: day, hour: hour, minute: minute, second: second, nanosecond: 0) { timeInterval = date.timeIntervalSince1970 } else { timeInterval += Double(m) * 30 * 24 * 3600 } } mutating func addYear(year y:Int) { let (year, month, day) = getDay() let (hour, minute, second) = getTime() if let date = (Calendar.current as NSCalendar).date(era: year / 100, year: year + y, month: month, day: day, hour: hour, minute: minute, second: second, nanosecond: 0) { timeInterval = date.timeIntervalSince1970 } else { timeInterval += Double(y) * 365 * 24 * 3600 } } /// 日期加减 func adding(_ component: Calendar.Component, value: Int) -> Date { return Calendar.current.date(byAdding: component, value: value, to: self)! } /// let (year, month, day) = date.getDay() func getDay() -> (year:Int, month:Int, day:Int) { var year:Int = 0, month:Int = 0, day:Int = 0 let date = Foundation.Date(timeIntervalSince1970: timeInterval) (Calendar.current as NSCalendar).getEra(nil, year: &year, month: &month, day: &day, from: date) return (year, month, day) } /// let (hour, minute, second) = date.getTime() func getTime() -> (hour:Int, minute:Int, second:Int) { var hour:Int = 0, minute:Int = 0, second:Int = 0 let date = Foundation.Date(timeIntervalSince1970: timeInterval) (Calendar.current as NSCalendar).getHour(&hour, minute: &minute, second: &second, nanosecond: nil, from: date) return (hour, minute, second) } /// 本月开始日期 func startOfMonth() -> Date { let components = Calendar.current.dateComponents([.year, .month], from: self) return Calendar.current.date(from: components)! } /// 本月结束日期 func endOfMonth(returnEndTime:Bool = false) -> Date { let components = NSDateComponents() components.month = 1 if returnEndTime { components.second = -1 } else { components.day = -1 } return Calendar.current.date(byAdding: components as DateComponents, to: startOfMonth())! } /// 这个月有多少天 func numberOfDaysInMonth() -> Int { return (Calendar.current.range(of: .day, in: .month, for: self)?.count)! } /// NSString转NSDate func dateFrom(_ string: String, format: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: string) } /// NSDate转NSString func stringFrom(_ date: Date, format: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: date) } /// 日期之间的距离 func distanceWithDate(_ date: Date) -> DateComponents { let calendar = Calendar(identifier: .gregorian) return calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self, to: date) } /// 星期几 func weekString() -> String { let week = components.weekday ?? 0 var str_week: String switch week % 7 { case 1:str_week = "周日" case 2:str_week = "周一" case 3:str_week = "周二" case 4:str_week = "周三" case 5:str_week = "周四" case 6:str_week = "周五" default:str_week = "周六" } return str_week } func timeToNow() -> String { var timeString = "" let late = TimeInterval(timeIntervalSince1970 * 1) let dat = Date(timeIntervalSinceNow: 0) let now = TimeInterval(dat.timeIntervalSince1970 * 1) let cha = TimeInterval((now - late) > 0 ? (now - late) : 0) if Int(cha / 60) < 1 { timeString = "刚刚" } else if Int(cha / 3600) < 1 { timeString = "\(cha / 60)" timeString = (timeString as NSString).substring(to: timeString.count - 7) timeString = "\(timeString) 分前" } else if Int(cha / 3600) > 1 && Int(cha / 3600) < 12 { timeString = "\(cha / 3600)" timeString = (timeString as NSString).substring(to: timeString.count - 7) timeString = "\(timeString) 小时前" } else if Int(cha / 3600) < 24 { timeString = "今天" } else if Int(cha / 3600) < 48 { timeString = "昨天" } else if cha / 3600 / 24 < 10 { timeString = String(format: "%.0f 天前", cha / 3600 / 24) } else if cha / 3600 / 24 < 365 { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM月dd日" timeString = dateFormatter.string(from: self) } else { timeString = "\(Int(cha) / 3600 / 24 / 365)年前" } return timeString } }
mit
695ef3603457eab6bdc279b974517048
34.931034
177
0.579655
4.078278
false
false
false
false
inderdhir/SwiftWeather
DatWeatherDoe/Model/WeatherCondition.swift
1
521
// // WeatherCondition.swift // DatWeatherDoe // // Created by Inder Dhir on 1/29/16. // Copyright © 2016 Inder Dhir. All rights reserved. // enum WeatherCondition: String { case sunny = "Sunny" case partlyCloudy = "Partly cloudy" case cloudy = "Cloudy" case mist = "Mist" case snow = "Snow" case freezingRain = "Freezing rain" case heavyRain = "Heavy rain" case partlyCloudyRain = "Partly cloudy with rain" case lightRain = "Light rain" case thunderstorm = "Thunderstorm" }
apache-2.0
fbab5f3c49cdc18a6e729a06bb45aad0
25
53
0.665385
3.636364
false
false
false
false
Sajjon/ViewComposer
Example/Source/Views/TriangleView.swift
1
5747
// // TriangleView.swift // Example // // Created by Alexander Cyon on 2017-06-02. // Copyright © 2017 Alexander Cyon. All rights reserved. // import UIKit import ViewComposer final class TriangleView: UIView, Composable { typealias Style = ViewStyle var fillColor: UIColor? var fillStyle: TriangleFillStyle? let style: ViewStyle init(_ style: ViewStyle? = nil) { let style = style.merge(slave: .default) self.style = style super.init(frame: .zero) compose(with: style) } required init(coder: NSCoder) { fatalError("needed by compiler") } override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext(), let fillColor = fillColor, let fillStyle = fillStyle else { return } context.setFillColor(fillColor.cgColor) context.beginPath() draw(rect, in: context, with: fillStyle) context.closePath() context.fillPath() } } private extension TriangleView { func draw(_ rect: CGRect, in context: CGContext, with fillStyle: TriangleFillStyle) { switch fillStyle { case .lowerAcute: drawLowerAcute(rect, in: context) case .lowerGrave: drawLowerGrave(rect, in: context) case .upperAcute: drawUpperAcute(rect, in: context) case .upperGrave: drawUpperGrave(rect, in: context) } } // _Acute_ means this: ´ or even more clear: / and filling the lower half with the fillColor func drawLowerAcute(_ rect: CGRect, in context: CGContext) { context.move(to: CGPoint(x: 0, y: rect.maxY)) context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) context.addLine(to: CGPoint(x: rect.maxX, y: 0)) } // _Grave_ means this: ` or even more clear: \ and filling the lower half with the fillColor func drawLowerGrave(_ rect: CGRect, in context: CGContext) { context.move(to: CGPoint(x: 0, y: 0)) context.addLine(to: CGPoint(x: 0, y: rect.maxY)) context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) } // _Acute_ means this: ´ or even more clear: / and filling the upper half with the fillColor func drawUpperAcute(_ rect: CGRect, in context: CGContext) { context.move(to: CGPoint(x: 0, y: 0)) context.addLine(to: CGPoint(x: 0, y: rect.maxY)) context.addLine(to: CGPoint(x: rect.maxX, y: 0)) context.addLine(to: CGPoint(x: 0, y: 0)) } // _Grave_ means this: ` or even more clear: \ and filling the upper half with the fillColor func drawUpperGrave(_ rect: CGRect, in context: CGContext) { context.move(to: CGPoint(x: 0, y: 0)) context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) context.addLine(to: CGPoint(x: rect.maxX, y: 0)) context.addLine(to: CGPoint(x: 0, y: 0)) } } extension ViewStyle: CustomAttributeMerger { public typealias CustomAttribute = TriangleViewStyle } private extension Optional where Wrapped == ViewStyle { func merge(slave: Wrapped) -> Wrapped { guard let `self` = self else { return slave } return self.customMerge(slave: slave, into: self) } } private extension ViewStyle { static let `default`: ViewStyle = [.custom(TriangleViewStyle([.fillColor(.red), .fillStyle(.upperAcute)])), .color(.blue)] } public enum TriangleViewAttribute { case fillStyle(TriangleFillStyle) case fillColor(UIColor) } public enum TriangleFillStyle { case lowerAcute, lowerGrave, upperAcute, upperGrave } public struct TriangleViewStyle: Attributed { public static var customStyler: AnyCustomStyler<TriangleViewStyle>? public static var duplicatesHandler: AnyDuplicatesHandler<TriangleViewStyle>? public var startIndex: Int = 0 public let attributes: [TriangleViewAttribute] public static var mergeInterceptors: [MergeInterceptor.Type] = [] public init(attributes: [TriangleViewAttribute]) { self.attributes = attributes } public func install(on styleable: Any) { guard let triangleView = styleable as? TriangleView else { return } triangleView.apply(self) } } private extension TriangleView { func apply(_ style: TriangleViewStyle) { style.attributes.forEach { switch $0 { case .fillStyle(let fillStyle): self.fillStyle = fillStyle case .fillColor(let fillColor): self.fillColor = fillColor } } setNeedsDisplay() } } //MARK: Making TriangleViewAttribute AssociatedValueStrippable, typically we want to automate this using `Sourcery`... extension TriangleViewAttribute: Equatable { public static func == (lhs: TriangleViewAttribute, rhs: TriangleViewAttribute) -> Bool { return lhs.stripped == rhs.stripped } } extension TriangleViewAttribute: AssociatedValueEnumExtractor { public var associatedValue: Any? { switch self { case .fillColor(let fillColor): return fillColor case .fillStyle(let fillStyle): return fillStyle } } } extension TriangleViewAttribute: AssociatedValueStrippable { public typealias Stripped = TriangleViewAttributeStripped public var stripped: Stripped { let stripped: Stripped switch self { case .fillColor: stripped = .fillColor case .fillStyle: stripped = .fillStyle } return stripped } } public enum TriangleViewAttributeStripped: String, StrippedRepresentation { case fillStyle, fillColor }
mit
f4562c25b40d78378587957d93502761
30.911111
126
0.643802
4.16836
false
false
false
false
austinzheng/SwiftRational
SwiftRational/rational.swift
1
8906
// // rational.swift // SwiftRationalSampleApp // // Created by Austin Zheng on 2/20/15. // Copyright (c) 2015 Austin Zheng. All rights reserved. // import Foundation /// A rational number, described by an integer numerator and an integer denominator. public struct Rational : AbsoluteValuable, Comparable, FloatLiteralConvertible, Hashable, Printable { // INVARIANT: A rational is always stored as an irreducable fraction. Rationals built from other numeric types are // fully reduced at initialization. If this invariant is violated, rational operations are not guaranteed to return // the correct results. // 10^maximumPower is the maximum possible denominator when constructing a rational from a double. // We calculate this by taking the floor of the base-10 log of Int.max. (This value is cached.) private static var maximumPower : Int = Int(log10(Double(Int.max))) /// The numerator of the rational number. public let numerator : Int /// The denominator of the rational number. public let denominator : Int public var hashValue : Int { return numerator ^ denominator } public var description : String { return "\(numerator)/\(denominator)" } /// The rational number's value, as a double-precision floating-point value. public var doubleValue : Double { return Double(numerator) / Double(denominator) } /// The rational number's multiplicative inverse, or nil if the inverse would be x/0. public var inverse : Rational? { return numerator == 0 ? nil : Rational(denominator, numerator) } // Initialize a Rational from a numerator and a denominator. public init(_ n: Int, _ d:Int=1 ) { if d == 0 { fatalError("Rational cannot be initialized with a denominator of 0") } let common = gcd(abs(n), abs(d)) if d < 0 { numerator = -n/common denominator = -d/common } else { numerator = n/common denominator = d/common } } // Initialize a Rational from an integer or an integer literal. public init(integerLiteral value: Int) { self.init(value, 1) } // Initialize a Rational from a double. public init(floatLiteral value: Double) { if (value.isInfinite || value.isNaN || value.isSubnormal) { fatalError("Rational can only be constructed using a normal double.") } var n = abs(value) var d = 1 as Double for i in 0..<Rational.maximumPower { if n % 1 == 0 { break } n *= 10 d *= 10 } self.init((value.isSignMinus ? -1 : 1) * lround(n), Int(d)) } public init( value: Double) { self.init( floatLiteral: value ) } } // MARK: Math public func ==(lhs: Rational, rhs: Rational) -> Bool { return lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator } public func <(lhs: Rational, rhs: Rational) -> Bool { return lhs.numerator * rhs.denominator < lhs.denominator * rhs.numerator } public prefix func -(arg: Rational) -> Rational { return Rational(-arg.numerator, arg.denominator) } public func +(lhs: Rational, rhs: Rational) -> Rational { if (lhs.denominator == rhs.denominator) { return Rational(lhs.numerator + rhs.numerator, lhs.denominator) } let n = lhs.numerator * rhs.denominator + lhs.denominator * rhs.numerator let d = lhs.denominator * rhs.denominator return Rational(n, d) } public func -(lhs: Rational, rhs: Rational) -> Rational { if (lhs.denominator == rhs.denominator) { return Rational(lhs.numerator - rhs.numerator, lhs.denominator) } let n = lhs.numerator * rhs.denominator - lhs.denominator * rhs.numerator let d = lhs.denominator * rhs.denominator return Rational(n, d) } public func *(lhs: Rational, rhs: Rational) -> Rational { let n = lhs.numerator * rhs.numerator let d = lhs.denominator * rhs.denominator return Rational(n, d) } public func /(lhs: Rational, rhs: Rational) -> Rational { return lhs * (rhs).inverse! } public func += ( inout lhs:Rational, rhs:Rational ) { lhs = lhs + rhs } public func -= ( inout lhs:Rational, rhs:Rational ) { lhs = lhs - rhs } public func *= ( inout lhs:Rational, rhs:Rational ) { lhs = lhs * rhs } public func /= ( inout lhs:Rational, rhs:Rational ) { lhs = lhs / rhs } // RationalConvertible public protocol RationalConvertible { var rationalValue:Rational{ get set } } extension Rational:RationalConvertible{ public var rationalValue:Rational { get { return self } set( newValue ){ self = newValue } } } extension Double:RationalConvertible{ public var rationalValue:Rational { get { return Rational( floatLiteral:self ) } set( newValue ){ self = newValue.doubleValue } } } extension Int:RationalConvertible{ public var rationalValue:Rational { get { return Rational( integerLiteral:self ) } set( newValue ){ self = Int( newValue.doubleValue ) } } } // MARK: RationalConvertible math public func == (lhs: RationalConvertible, rhs: RationalConvertible) -> Bool { return lhs.rationalValue == rhs.rationalValue } public func < (lhs: RationalConvertible, rhs: RationalConvertible) -> Bool { return lhs.rationalValue < rhs.rationalValue } public prefix func - ( arg: RationalConvertible) -> RationalConvertible { return -arg.rationalValue } public func + (lhs: RationalConvertible, rhs: RationalConvertible) -> Rational { return lhs.rationalValue + rhs.rationalValue } public func - (lhs: RationalConvertible, rhs: RationalConvertible) -> Rational { return lhs.rationalValue - rhs.rationalValue } public func * (lhs: RationalConvertible, rhs: RationalConvertible) -> Rational { return lhs.rationalValue * rhs.rationalValue } public func / (lhs: RationalConvertible, rhs: RationalConvertible) -> Rational { return lhs.rationalValue / rhs.rationalValue } public func += ( inout lhs:Rational, rhs:RationalConvertible ) { let r = rhs.rationalValue lhs = lhs + r } public func -= ( inout lhs:Rational, rhs:RationalConvertible ) { let r = rhs.rationalValue lhs = lhs - r } public func *= ( inout lhs:Rational, rhs:RationalConvertible ) { let r = rhs.rationalValue lhs = lhs * r } public func /= ( inout lhs:Rational, rhs:RationalConvertible ) { let r = rhs.rationalValue lhs = lhs / r } // MARK: Supplementary math public extension Rational { static func abs(x: Rational) -> Rational { let n = x.numerator return Rational((n < 0 ? -n : n), x.denominator) } /// Add `lhs` and `rhs`, returning a result and a `Bool` that is true iff the operation caused an arithmetic overflow. static func addWithOverflow(lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { if (lhs.denominator == rhs.denominator) { let (n, didOverflow) = Int.addWithOverflow(lhs.numerator, rhs.numerator) return (Rational(n, lhs.denominator), didOverflow) } let (ad, of1) = Int.multiplyWithOverflow(lhs.numerator, rhs.denominator) let (bc, of2) = Int.multiplyWithOverflow(lhs.denominator, rhs.numerator) let (adPbc, of3) = Int.addWithOverflow(ad, bc) let (bd, of4) = Int.multiplyWithOverflow(lhs.denominator, rhs.denominator) return (Rational(adPbc, bd), of1 || of2 || of3 || of4) } /// Subtract `lhs` and `rhs`, returning a result and a `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { if (lhs.denominator == rhs.denominator) { let (n, didOverflow) = Int.subtractWithOverflow(lhs.numerator, rhs.numerator) return (Rational(n, lhs.denominator), didOverflow) } let (ad, f1) = Int.multiplyWithOverflow(lhs.numerator, rhs.denominator) let (bc, f2) = Int.multiplyWithOverflow(lhs.denominator, rhs.numerator) let (adMbc, f3) = Int.subtractWithOverflow(ad, bc) let (bd, f4) = Int.multiplyWithOverflow(lhs.denominator, rhs.denominator) return (Rational(adMbc, bd), f1 || f2 || f3 || f4) } /// Multiply `lhs` and `rhs`, returning a result and a `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { let (ac, f1) = Int.multiplyWithOverflow(lhs.numerator, rhs.numerator) let (bd, f2) = Int.multiplyWithOverflow(lhs.denominator, rhs.denominator) return (Rational(ac, bd), f1 || f2) } /// Divide `lhs` and `rhs`, returning a result and a `Bool` that is true iff the operation caused an arithmetic /// overflow. static func divideWithOverflow(lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { let (ac, f1) = Int.multiplyWithOverflow(lhs.numerator, rhs.numerator) let (bd, f2) = Int.multiplyWithOverflow(lhs.denominator, rhs.denominator) return (Rational(ac, bd).inverse!, f1 || f2) } } // MARK: Utilities /// Return the greatest common divisor for the two integer arguments. This function uses the iterative Euclidean /// algorithm for calculating GCD. func gcd(u: Int, v: Int) -> Int { var a = u var b = v while b != 0 { let t = b b = a % b a = t } return a }
mit
58f7689f708be1aba886674fdc2bec1a
27.544872
119
0.702672
3.413568
false
false
false
false
szk-atmosphere/SAParallaxViewControllerSwift
SAParallaxViewControllerSwiftExample/SAParallaxViewControllerSwiftExample/ViewController.swift
2
2563
// // ViewController.swift // SAParallaxViewControllerSwiftExample // // Created by 鈴木大貴 on 2015/02/02. // Copyright (c) 2015年 鈴木大貴. All rights reserved. // import UIKit import SAParallaxViewControllerSwift class ViewController: SAParallaxViewController { let titleList: [String] = ["Girl with Room", "Beautiful sky", "Music Festival", "Fashion show", "Beautiful beach", "Pizza and beer"] convenience init() { self.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() } //MARK: - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let rawCell = super.collectionView(collectionView, cellForItemAt: indexPath) guard let cell = rawCell as? SAParallaxViewCell else { return rawCell } for case let view as UILabel in cell.containerView.accessoryView.subviews { view.removeFromSuperview() } let index = (indexPath as NSIndexPath).row % 6 let imageName = String(format: "image%d", index + 1) if let image = UIImage(named: imageName) { cell.setImage(image) } let label = UILabel(frame: cell.containerView.accessoryView.bounds) label.textAlignment = .center label.text = titleList[index] label.textColor = .white label.font = .systemFont(ofSize: 30) cell.containerView.accessoryView.addSubview(label) return cell } //MARK: - UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { super.collectionView(collectionView, didSelectItemAt: indexPath) guard let cells = collectionView.visibleCells as? [SAParallaxViewCell] else { return } let containerView = SATransitionContainerView(frame: view.bounds) containerView.setViews(cells, view: view) let viewController = DetailViewController() viewController.transitioningDelegate = self viewController.trantisionContainerView = containerView present(viewController, animated: true, completion: nil) } }
mit
d9dea096ef4595536d8ad14571baaa65
35.884058
136
0.672692
5.1002
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/RemoteNotifications/Sources/RemoteNotificationsKitMock/MockNotificationServiceContainer.swift
1
1871
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import UIKit @testable import RemoteNotificationsKit class MockRemoteNotificationServiceContainer: RemoteNotificationServiceContaining, RemoteNotificationTokenSending, RemoteNotificationDeviceTokenReceiving, RemoteNotificationBackgroundReceiving { var authorizer: RemoteNotificationAuthorizing var backgroundReceiver: RemoteNotificationBackgroundReceiving { self } var tokenSender: RemoteNotificationTokenSending { self } var tokenReceiver: RemoteNotificationDeviceTokenReceiving { self } init(authorizer: RemoteNotificationAuthorizing) { self.authorizer = authorizer sendTokenIfNeededSubject.send(completion: .finished) } var sendTokenIfNeededSubject = PassthroughSubject<Void, RemoteNotificationTokenSenderError>() var sendTokenIfNeededPublisherCalled = false func sendTokenIfNeeded() -> AnyPublisher<Void, RemoteNotificationTokenSenderError> { sendTokenIfNeededPublisherCalled = true return sendTokenIfNeededSubject .eraseToAnyPublisher() } var appDidFailToRegisterForRemoteNotificationsCalled = false func appDidFailToRegisterForRemoteNotifications(with error: Error) { appDidFailToRegisterForRemoteNotificationsCalled = true } var appDidRegisterForRemoteNotificationsCalled: (called: Bool, token: Data?) = (false, nil) func appDidRegisterForRemoteNotifications(with deviceToken: Data) { appDidRegisterForRemoteNotificationsCalled = (true, deviceToken) } func didReceiveRemoteNotification( _ userInfo: [AnyHashable: Any], onApplicationState applicationState: UIApplication.State, fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) {} }
lgpl-3.0
237818f6aef971b593748a9d7fd050bc
31.241379
97
0.764171
6.111111
false
false
false
false
PJayRushton/stats
Stats/StatsNumbersViewController.swift
1
4669
// // StatsNumbersViewController.swift // Stats // // Created by Parker Rushton on 4/24/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit import IGListKit import SpreadsheetView class StatsNumbersViewController: Component, AutoStoryboardInitializable { @IBOutlet weak var spreadsheetView: SpreadsheetView! fileprivate let selectedBackground = UIColor.mainAppColor.withAlphaComponent(0.2) fileprivate var allStats: [Stat] { return core.state.statState.currentStats?.stats.values.flatMap { $0 } ?? [] } fileprivate var currentPlayers = [Player]() { didSet { spreadsheetView.reloadData() } } fileprivate var sortSection = 0 { didSet { updatePlayerOrder() } } override func viewDidLoad() { super.viewDidLoad() spreadsheetView.dataSource = self spreadsheetView.delegate = self spreadsheetView.register(StatCell.self, forCellWithReuseIdentifier: StatCell.reuseIdentifier) } override func update(with state: AppState) { currentPlayers = state.playerState.currentStatPlayers updatePlayerOrder() } } // MARK: - Internal extension StatsNumbersViewController { fileprivate func updatePlayerOrder() { if sortSection == 0 { currentPlayers.sort() return } let selectedStatType = statType(for: sortSection) var selectedStats = stats(ofType: selectedStatType) selectedStats.sort(by: >) let idOrder = selectedStats.map { $0.playerId } currentPlayers.sort { idOrder.index(of: $0.id)! < idOrder.index(of: $1.id)! } } fileprivate func stats(ofType type: StatType) -> [Stat] { return allStats.filter { $0.type == type } } } // MARK: - SpreadsheetView extension StatsNumbersViewController: SpreadsheetViewDataSource { func numberOfColumns(in spreadsheetView: SpreadsheetView) -> Int { return StatType.allValues.count + 1 } func numberOfRows(in spreadsheetView: SpreadsheetView) -> Int { return currentPlayers.count + 1 } func spreadsheetView(_ spreadsheetView: SpreadsheetView, widthForColumn column: Int) -> CGFloat { return column == 0 ? 130 : 80 } func spreadsheetView(_ spreadsheetView: SpreadsheetView, heightForRow row: Int) -> CGFloat { return 60 } func statType(for section: Int) -> StatType { return StatType.allValues[section - 1] } func player(forRow row: Int) -> Player { return currentPlayers[row - 1] } func stat(at indexPath: IndexPath) -> Stat? { guard indexPath.section != 0 || indexPath.row != 0 else { fatalError() } let statTypeAtSection = statType(for: indexPath.section) let stats = self.stats(ofType: statTypeAtSection) let playerForRow = player(forRow: indexPath.row) return stats.first(where: { $0.player == playerForRow }) } func spreadsheetView(_ spreadsheetView: SpreadsheetView, cellForItemAt indexPath: IndexPath) -> Cell? { var title = "" let alignment = NSTextAlignment.center let fontSize: CGFloat = indexPath.section == 0 || indexPath.row == 0 ? 20 : 17 let cell = spreadsheetView.dequeueReusableCell(withReuseIdentifier: StatCell.reuseIdentifier, for: indexPath) as! StatCell switch (indexPath.section, indexPath.row) { case (0, 0): title = "Player" cell.backgroundColor = sortSection == 0 ? selectedBackground : .white case (0, _): title = player(forRow: indexPath.row).displayName cell.backgroundColor = .white case (_, 0): title = statType(for: indexPath.section).abbreviation cell.backgroundColor = sortSection == indexPath.section ? selectedBackground : .white default: title = stat(at: indexPath)?.displayString ?? "" cell.backgroundColor = .white } cell.update(with: title, alignment: alignment, fontSize: fontSize) return cell } func frozenColumns(in spreadsheetView: SpreadsheetView) -> Int { return 1 } func frozenRows(in spreadsheetView: SpreadsheetView) -> Int { return 1 } } extension StatsNumbersViewController: SpreadsheetViewDelegate { func spreadsheetView(_ spreadsheetView: SpreadsheetView, didSelectItemAt indexPath: IndexPath) { guard indexPath.row == 0 else { return } sortSection = indexPath.section } }
mit
8eaae2d9fe282b83183dff837c9057fd
29.710526
130
0.637746
4.658683
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/CreateAccount/CreateAccountStepTwoReducer.swift
1
17073
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BlockchainNamespace import Combine import ComposableArchitecture import ComposableNavigation import FeatureAuthenticationDomain import Localization import SwiftUI import ToolKit import UIComponentsKit import WalletPayloadKit public enum CreateAccountStepTwoRoute: NavigationRoute { public func destination(in store: Store<CreateAccountStepTwoState, CreateAccountStepTwoAction>) -> some View { Text(String(describing: self)) } } public enum CreateAccountStepTwoIds { public struct CreationId: Hashable {} public struct ImportId: Hashable {} public struct RecaptchaId: Hashable {} } public enum CreateAccountContextStepTwo: Equatable { case importWallet(mnemonic: String) case createWallet var mnemonic: String? { switch self { case .importWallet(let mnemonic): return mnemonic case .createWallet: return nil } } } public struct CreateAccountStepTwoState: Equatable, NavigationState { public enum InputValidationError: Equatable { case invalidEmail case weakPassword case noCountrySelected case noCountryStateSelected case termsNotAccepted } public enum InputValidationState: Equatable { case unknown case valid case invalid(InputValidationError) var isInvalid: Bool { switch self { case .invalid: return true case .valid, .unknown: return false } } } public enum Field: Equatable { case email case password } enum AddressSegmentPicker: Hashable { case country case countryState } public var route: RouteIntent<CreateAccountStepTwoRoute>? public var context: CreateAccountContextStepTwo public var country: SearchableItem<String> public var countryState: SearchableItem<String>? public var referralCode: String // User Input @BindableState public var emailAddress: String @BindableState public var password: String @BindableState public var termsAccepted: Bool = false // Form interaction @BindableState public var passwordFieldTextVisible: Bool = false @BindableState public var selectedInputField: Field? // Validation public var validatingInput: Bool = false public var passwordStrength: PasswordValidationScore public var inputValidationState: InputValidationState public var failureAlert: AlertState<CreateAccountStepTwoAction>? public var isCreatingWallet = false var isCreateButtonDisabled: Bool { validatingInput || inputValidationState.isInvalid || isCreatingWallet } public init( context: CreateAccountContextStepTwo, country: SearchableItem<String>, countryState: SearchableItem<String>?, referralCode: String ) { self.context = context self.country = country self.countryState = countryState self.referralCode = referralCode emailAddress = "" password = "" passwordStrength = .none inputValidationState = .unknown } } public enum CreateAccountStepTwoAction: Equatable, NavigationAction, BindableAction { public enum AlertAction: Equatable { case show(title: String, message: String) case dismiss } case onAppear case alert(AlertAction) case binding(BindingAction<CreateAccountStepTwoState>) // use `createAccount` to perform the account creation. this action is fired after the user confirms the details and the input is validated. case createOrImportWallet(CreateAccountContextStepTwo) case createAccount(Result<String, GoogleRecaptchaError>) case importAccount(_ mnemonic: String) case createButtonTapped case didValidateAfterFormSubmission case didUpdatePasswordStrenght(PasswordValidationScore) case didUpdateInputValidation(CreateAccountStepTwoState.InputValidationState) case openExternalLink(URL) case onWillDisappear case route(RouteIntent<CreateAccountStepTwoRoute>?) case validatePasswordStrength case accountRecoveryFailed(WalletRecoveryError) case accountCreation(Result<WalletCreatedContext, WalletCreationServiceError>) case accountImported(Result<Either<WalletCreatedContext, EmptyValue>, WalletCreationServiceError>) case walletFetched(Result<Either<EmptyValue, WalletFetchedContext>, WalletFetcherServiceError>) case informWalletFetched(WalletFetchedContext) // required for legacy flow case triggerAuthenticate case none } struct CreateAccountStepTwoEnvironment { let mainQueue: AnySchedulerOf<DispatchQueue> let passwordValidator: PasswordValidatorAPI let externalAppOpener: ExternalAppOpener let analyticsRecorder: AnalyticsEventRecorderAPI let walletRecoveryService: WalletRecoveryService let walletCreationService: WalletCreationService let walletFetcherService: WalletFetcherService let checkReferralClient: CheckReferralClientAPI? let featureFlagsService: FeatureFlagsServiceAPI let recaptchaService: GoogleRecaptchaServiceAPI let app: AppProtocol? init( mainQueue: AnySchedulerOf<DispatchQueue>, passwordValidator: PasswordValidatorAPI, externalAppOpener: ExternalAppOpener, analyticsRecorder: AnalyticsEventRecorderAPI, walletRecoveryService: WalletRecoveryService, walletCreationService: WalletCreationService, walletFetcherService: WalletFetcherService, featureFlagsService: FeatureFlagsServiceAPI, recaptchaService: GoogleRecaptchaServiceAPI, checkReferralClient: CheckReferralClientAPI? = nil, app: AppProtocol? = nil ) { self.mainQueue = mainQueue self.passwordValidator = passwordValidator self.externalAppOpener = externalAppOpener self.analyticsRecorder = analyticsRecorder self.walletRecoveryService = walletRecoveryService self.walletCreationService = walletCreationService self.walletFetcherService = walletFetcherService self.checkReferralClient = checkReferralClient self.featureFlagsService = featureFlagsService self.recaptchaService = recaptchaService self.app = app } } typealias CreateAccountStepTwoLocalization = LocalizationConstants.FeatureAuthentication.CreateAccount let createAccountStepTwoReducer = Reducer< CreateAccountStepTwoState, CreateAccountStepTwoAction, CreateAccountStepTwoEnvironment // swiftlint:disable:next closure_body_length > { state, action, environment in switch action { case .binding(\.$emailAddress): return Effect(value: .didUpdateInputValidation(.unknown)) case .binding(\.$password): return .merge( Effect(value: .didUpdateInputValidation(.unknown)), Effect(value: .validatePasswordStrength) ) case .binding(\.$termsAccepted): return Effect(value: .didUpdateInputValidation(.unknown)) case .createAccount(.success(let recaptchaToken)): // by this point we have validated all the fields neccessary state.isCreatingWallet = true let accountName = CreateAccountStepTwoLocalization.defaultAccountName return .merge( Effect(value: .triggerAuthenticate), .cancel(id: CreateAccountStepTwoIds.RecaptchaId()), environment.walletCreationService .createWallet( state.emailAddress, state.password, accountName, recaptchaToken ) .receive(on: environment.mainQueue) .catchToEffect() .cancellable(id: CreateAccountStepTwoIds.CreationId(), cancelInFlight: true) .map(CreateAccountStepTwoAction.accountCreation) ) case .createAccount(.failure(let error)): state.isCreatingWallet = false let title = LocalizationConstants.Errors.error let message = String(describing: error) return .merge( Effect( value: .alert( .show(title: title, message: message) ) ), .cancel(id: CreateAccountStepTwoIds.RecaptchaId()) ) case .createOrImportWallet(.createWallet): guard state.inputValidationState == .valid else { return .none } return environment.recaptchaService.verifyForSignup() .receive(on: environment.mainQueue) .catchToEffect() .cancellable(id: CreateAccountStepTwoIds.RecaptchaId(), cancelInFlight: true) .map(CreateAccountStepTwoAction.createAccount) case .createOrImportWallet(.importWallet(let mnemonic)): guard state.inputValidationState == .valid else { return .none } return Effect(value: .importAccount(mnemonic)) case .importAccount(let mnemonic): state.isCreatingWallet = true let accountName = CreateAccountStepTwoLocalization.defaultAccountName return .merge( Effect(value: .triggerAuthenticate), environment.walletCreationService .importWallet( state.emailAddress, state.password, accountName, mnemonic ) .receive(on: environment.mainQueue) .catchToEffect() .cancellable(id: CreateAccountStepTwoIds.ImportId(), cancelInFlight: true) .map(CreateAccountStepTwoAction.accountImported) ) case .accountCreation(.failure(let error)), .accountImported(.failure(let error)): state.isCreatingWallet = false let title = LocalizationConstants.Errors.error let message = String(describing: error) return .merge( Effect( value: .alert( .show(title: title, message: message) ) ), .cancel(id: CreateAccountStepTwoIds.CreationId()), .cancel(id: CreateAccountStepTwoIds.ImportId()) ) case .accountCreation(.success(let context)), .accountImported(.success(.left(let context))): return .concatenate( Effect(value: .triggerAuthenticate), environment .saveReferral(with: state.referralCode) .fireAndForget(), .merge( .cancel(id: CreateAccountStepTwoIds.CreationId()), .cancel(id: CreateAccountStepTwoIds.ImportId()), environment .walletCreationService .setResidentialInfo(state.country.id, state.countryState?.id) .receive(on: environment.mainQueue) .eraseToEffect() .fireAndForget(), environment.walletCreationService .updateCurrencyForNewWallets(state.country.id, context.guid, context.sharedKey) .receive(on: environment.mainQueue) .eraseToEffect() .fireAndForget(), environment.walletFetcherService .fetchWallet(context.guid, context.sharedKey, context.password) .receive(on: environment.mainQueue) .catchToEffect() .map(CreateAccountStepTwoAction.walletFetched) ) ) case .walletFetched(.success(.left(.noValue))): // do nothing, this for the legacy JS, to be removed return .none case .walletFetched(.success(.right(let context))): return Effect(value: .informWalletFetched(context)) case .walletFetched(.failure(let error)): let title = LocalizationConstants.ErrorAlert.title let message = error.errorDescription ?? LocalizationConstants.ErrorAlert.message return Effect( value: .alert( .show(title: title, message: message) ) ) case .informWalletFetched: return .none case .accountImported(.success(.right(.noValue))): // this will only be true in case of legacy wallet return .cancel(id: CreateAccountStepTwoIds.ImportId()) case .createButtonTapped: state.validatingInput = true state.selectedInputField = nil return Effect.concatenate( environment .validateInputs(state: state) .map(CreateAccountStepTwoAction.didUpdateInputValidation) .receive(on: environment.mainQueue) .eraseToEffect(), Effect(value: .didValidateAfterFormSubmission) ) case .didValidateAfterFormSubmission: guard !state.inputValidationState.isInvalid else { return .none } return Effect(value: .createOrImportWallet(state.context)) case .didUpdatePasswordStrenght(let score): state.passwordStrength = score return .none case .didUpdateInputValidation(let validationState): state.validatingInput = false state.inputValidationState = validationState return .none case .openExternalLink(let url): environment.externalAppOpener.open(url) return .none case .onWillDisappear: return .none case .route(let route): state.route = route return .none case .validatePasswordStrength: return environment .passwordValidator .validate(password: state.password) .map(CreateAccountStepTwoAction.didUpdatePasswordStrenght) .receive(on: environment.mainQueue) .eraseToEffect() case .accountRecoveryFailed(let error): let title = LocalizationConstants.Errors.error let message = error.localizedDescription return Effect(value: .alert(.show(title: title, message: message))) case .alert(.show(let title, let message)): state.failureAlert = AlertState( title: TextState(verbatim: title), message: TextState(verbatim: message), dismissButton: .default( TextState(LocalizationConstants.okString), action: .send(.alert(.dismiss)) ) ) return .none case .alert(.dismiss): state.failureAlert = nil return .none case .triggerAuthenticate: return .none case .none: return .none case .binding: return .none case .onAppear: return .none } } .binding() .analytics() extension CreateAccountStepTwoEnvironment { fileprivate func validateInputs( state: CreateAccountStepTwoState ) -> AnyPublisher<CreateAccountStepTwoState.InputValidationState, Never> { guard state.emailAddress.isEmail else { return .just(.invalid(.invalidEmail)) } let didAcceptTerm = state.termsAccepted return passwordValidator .validate(password: state.password) .map { passwordStrength -> CreateAccountStepTwoState.InputValidationState in guard passwordStrength.isValid else { return .invalid(.weakPassword) } guard didAcceptTerm else { return .invalid(.termsNotAccepted) } return .valid } .eraseToAnyPublisher() } func saveReferral(with code: String) -> Effect<Void, Never> { if code.isNotEmpty { app?.post(value: code, of: blockchain.user.creation.referral.code) } return .none } } // MARK: - Private extension Reducer where Action == CreateAccountStepTwoAction, State == CreateAccountStepTwoState, Environment == CreateAccountStepTwoEnvironment { /// Helper function for analytics tracking fileprivate func analytics() -> Self { combined( with: Reducer< CreateAccountStepTwoState, CreateAccountStepTwoAction, CreateAccountStepTwoEnvironment > { state, action, environment in switch action { case .createButtonTapped: if case .importWallet = state.context { environment.analyticsRecorder.record( event: .importWalletConfirmed ) } return .none case .accountCreation(.success): environment.analyticsRecorder.record( event: AnalyticsEvents.New.SignUpFlow.walletSignedUp ) return .none default: return .none } } ) } }
lgpl-3.0
51e1a66c8410244b9f3b359cba50b4d6
32.940358
144
0.644271
5.656726
false
false
false
false
yanif/circator
MetabolicCompass/View Controller/RadarViewController.swift
1
15238
// // RadarViewController.swift // MetabolicCompass // // Created by Yanif Ahmad on 2/6/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import Foundation import HealthKit import MCCircadianQueries import MetabolicCompassKit import Charts import Crashlytics import SwiftDate import Async /** This class controls the display of the Radar screen (2nd view of dashboard). The radar screen gives a spider like view of how the users data compares to the population data. Our user input, to this date, suggests that many users prefer this to the numbers on the first view of the dashboard. - note: use of logistic function (normalizeType) to enable shared plot */ class RadarViewController : UIViewController, ChartViewDelegate { var logisticParametersByType : [Bool: [String: (Double, Double)]] = [ true: [ HKCategoryTypeIdentifierSleepAnalysis : (6.7,0.328), HKQuantityTypeIdentifierBodyMass : (88.7,0.0248), HKQuantityTypeIdentifierBodyMassIndex : (28.6,0.0768), HKQuantityTypeIdentifierHeartRate : (69.0,0.0318), HKQuantityTypeIdentifierBloodPressureSystolic : (119.6,0.01837), HKQuantityTypeIdentifierStepCount : (6000,0.000366), HKQuantityTypeIdentifierActiveEnergyBurned : (2750,0.00079899), HKQuantityTypeIdentifierUVExposure : (12.0,0.183), HKWorkoutTypeIdentifier : (12.0,0.183), HKQuantityTypeIdentifierDietaryEnergyConsumed : (2794.5,0.000786), HKQuantityTypeIdentifierDietaryProtein : (106.6,0.0206), HKQuantityTypeIdentifierDietaryCarbohydrates : (333.6,0.0067), HKQuantityTypeIdentifierDietarySugar : (149.4,0.0147), HKQuantityTypeIdentifierDietaryFiber : (18.8,0.11687), HKQuantityTypeIdentifierDietaryFatTotal : (102.6,0.2142), HKQuantityTypeIdentifierDietaryFatSaturated : (33.5,0.0656), HKQuantityTypeIdentifierDietaryFatMonounsaturated : (38.2,0.0575), HKQuantityTypeIdentifierDietaryFatPolyunsaturated : (21.9,0.10003), HKQuantityTypeIdentifierDietaryCholesterol : (375.5,0.00585), HKQuantityTypeIdentifierDietarySodium : (4463.8,0.0004922), HKQuantityTypeIdentifierDietaryCaffeine : (173.1,0.01269), HKQuantityTypeIdentifierDietaryWater : (1208.5,0.001818) ], false: [HKCategoryTypeIdentifierSleepAnalysis : (6.9,0.318), HKQuantityTypeIdentifierBodyMass : (77.0,0.0285), HKQuantityTypeIdentifierBodyMassIndex : (29.1,0.0755), HKQuantityTypeIdentifierHeartRate : (74,0.02969), HKQuantityTypeIdentifierBloodPressureSystolic : (111.1,0.01978), HKQuantityTypeIdentifierStepCount : (6000,0.000366), HKQuantityTypeIdentifierActiveEnergyBurned : (2750,0.00079899), HKQuantityTypeIdentifierUVExposure : (12,0.183), HKWorkoutTypeIdentifier : (12.0,0.183), HKQuantityTypeIdentifierDietaryEnergyConsumed : (1956.3,0.0011), HKQuantityTypeIdentifierDietaryProtein : (73.5,0.02989), HKQuantityTypeIdentifierDietaryCarbohydrates : (246.4,0.0089), HKQuantityTypeIdentifierDietarySugar : (115.4,0.0190), HKQuantityTypeIdentifierDietaryFiber : (15.2,0.14455), HKQuantityTypeIdentifierDietaryFatTotal : (73.5,0.02989), HKQuantityTypeIdentifierDietaryFatSaturated : (24.5,0.08968), HKQuantityTypeIdentifierDietaryFatMonounsaturated : (26.6,0.0826), HKQuantityTypeIdentifierDietaryFatPolyunsaturated : (16.1,0.1365), HKQuantityTypeIdentifierDietaryCholesterol : (258,0.008516), HKQuantityTypeIdentifierDietarySodium : (3138.7,0.000700), HKQuantityTypeIdentifierDietaryCaffeine : (137.4,0.01599), HKQuantityTypeIdentifierDietaryWater : (1127.7,0.001948) ]] var logisticTypeAsMale = true lazy var healthFormatter : SampleFormatter = { return SampleFormatter() }() lazy var radarChart: MetabolicRadarChartView = { let chart = MetabolicRadarChartView() chart.renderer = MetabolicChartRender(chart: chart, animator: chart.chartAnimator, viewPortHandler: chart.viewPortHandler) chart.animate(xAxisDuration: 1.0, yAxisDuration: 1.0) chart.delegate = self chart.descriptionText = "" chart.rotationEnabled = false chart.highlightPerTapEnabled = false chart.yAxis.axisMinValue = 0.1 chart.yAxis.axisRange = 1.0 chart.yAxis.drawLabelsEnabled = false chart.xAxis.drawLabelsEnabled = false chart.webColor = UIColor.colorWithHexString("#042652")! chart.webAlpha = 1.0 let legend = chart.legend legend.enabled = true legend.position = ScreenManager.sharedInstance.radarLegendPosition() legend.font = ScreenManager.appFontOfSize(12) legend.textColor = UIColor.colorWithHexString("#ffffff", alpha: 0.3)! legend.xEntrySpace = 50.0 legend.yEntrySpace = 5.0 return chart }() var radarTip: TapTip! = nil var radarTipDummyLabel: UILabel! = nil var initialImage : UIImage! = nil var initialMsg : String! = "HealthKit not authorized" var authorized : Bool = false { didSet { configureViews() radarChart.layoutIfNeeded() reloadData() } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(contentDidChange), name: PMDidUpdateBalanceSampleTypesNotification, object: nil) logContentView() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) logContentView(false) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.authorized = AccountManager.shared.isHealthKitAuthorized } override func viewDidLoad() { super.viewDidLoad() configureViews() radarChart.layoutIfNeeded() reloadData() } func logContentView(asAppear: Bool = true) { Answers.logContentViewWithName("Balance", contentType: asAppear ? "Appear" : "Disappear", contentId: NSDate().toString(DateFormat.Custom("YYYY-MM-dd:HH")), customAttributes: nil) } func contentDidChange() { Async.main { self.reloadData() } } func configureViews() { if authorized { configureAuthorizedView() } else { configureUnauthorizedView() } } func configureAuthorizedView() { view.subviews.forEach { $0.removeFromSuperview() } radarChart.translatesAutoresizingMaskIntoConstraints = false view.addSubview(radarChart) let rcConstraints: [NSLayoutConstraint] = [ radarChart.topAnchor.constraintEqualToAnchor(view.topAnchor), radarChart.leftAnchor.constraintEqualToAnchor(view.leftAnchor), radarChart.rightAnchor.constraintEqualToAnchor(view.rightAnchor), //radarChart.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor), radarChart.bottomAnchor.constraintGreaterThanOrEqualToAnchor(view.bottomAnchor, constant: -ScreenManager.sharedInstance.radarChartBottomIndent()) ] view.addConstraints(rcConstraints) radarTipDummyLabel = UILabel() radarTipDummyLabel.userInteractionEnabled = false radarTipDummyLabel.enabled = false radarTipDummyLabel.translatesAutoresizingMaskIntoConstraints = false view.addSubview(radarTipDummyLabel) view.addConstraints([ view.centerXAnchor.constraintEqualToAnchor(radarTipDummyLabel.centerXAnchor), view.centerYAnchor.constraintEqualToAnchor(radarTipDummyLabel.centerYAnchor), radarTipDummyLabel.widthAnchor.constraintEqualToConstant(1), radarTipDummyLabel.heightAnchor.constraintEqualToConstant(1), ]) let desc = "Your Balance chart compares your health metrics relative to each other, and to our study population. A person with average measures across the board would show a uniform shape." radarTip = TapTip(forView: radarTipDummyLabel, withinView: view, text: desc, width: 350, numTaps: 2, numTouches: 2, asTop: false) radarChart.addGestureRecognizer(radarTip.tapRecognizer) radarChart.userInteractionEnabled = true } func configureUnauthorizedView() { let iview = UIImageView() iview.image = initialImage iview.contentMode = .ScaleAspectFit iview.tintColor = Theme.universityDarkTheme.foregroundColor let lbl = UILabel() lbl.textAlignment = .Center lbl.lineBreakMode = .ByWordWrapping lbl.numberOfLines = 0 lbl.text = initialMsg lbl.textColor = Theme.universityDarkTheme.foregroundColor iview.translatesAutoresizingMaskIntoConstraints = false lbl.translatesAutoresizingMaskIntoConstraints = false view.addSubview(iview) view.addSubview(lbl) let constraints: [NSLayoutConstraint] = [ iview.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor), iview.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor, constant: -50), lbl.topAnchor.constraintEqualToAnchor(iview.bottomAnchor), lbl.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor), iview.widthAnchor.constraintEqualToConstant(100), iview.heightAnchor.constraintEqualToConstant(100), lbl.widthAnchor.constraintEqualToAnchor(view.widthAnchor, constant: -50) ] view.addConstraints(constraints) } // MARK: - Radar chart func normalizeType(type: HKSampleType, quantity: Double) -> Double { if let sex = MCHealthManager.sharedManager.getBiologicalSex(), paramdict = logisticParametersByType[sex.biologicalSex == HKBiologicalSex.Male], (x0, k) = paramdict[type.identifier] { return min(1.0,(1 / (1 + exp(-k * (quantity - x0)))) + 0.2) } return 1 / (1 + exp(-quantity)) } private let appearanceProvider = DashboardMetricsAppearanceProvider() func indEntry(i: Int) -> MetabolicDataEntry { let type = PreviewManager.balanceSampleTypes[i] let samples = MCHealthManager.sharedManager.mostRecentSamples[type] ?? [] let val = healthFormatter.numberFromSamples(samples) guard !val.isNaN else { return MetabolicDataEntry(value: 0.8, xIndex: i, pointColor: appearanceProvider.colorForSampleType(type.identifier, active: true), image: appearanceProvider.imageForSampleType(type.identifier, active: true)) } let nval = normalizeType(type, quantity: val) return MetabolicDataEntry(value: nval, xIndex: i, pointColor: appearanceProvider.colorForSampleType(type.identifier, active: true), image: appearanceProvider.imageForSampleType(type.identifier, active: true)) } func popEntry(i: Int) -> MetabolicDataEntry { let type = PreviewManager.balanceSampleTypes[i] let samples = PopulationHealthManager.sharedManager.mostRecentAggregates[type] ?? [] let val = healthFormatter.numberFromSamples(samples) guard !val.isNaN else { return MetabolicDataEntry(value: 0.8, xIndex: i, pointColor: appearanceProvider.colorForSampleType(type.identifier, active: true), image: appearanceProvider.imageForSampleType(type.identifier, active: true)) } let nval = normalizeType(type, quantity: val) return MetabolicDataEntry(value: nval, xIndex: i, pointColor: appearanceProvider.colorForSampleType(type.identifier, active: true), image: appearanceProvider.imageForSampleType(type.identifier, active: true)) } func reloadData() { let sampleTypeRange = 0..<(min(PreviewManager.balanceSampleTypes.count, 8)) let sampleTypes = sampleTypeRange.map { PreviewManager.balanceSampleTypes[$0] } let indData = sampleTypeRange.map(indEntry) let popData = sampleTypeRange.map(popEntry) let indDataSet = MetabolicChartDataSet(yVals: indData, label: NSLocalizedString("Individual value", comment: "Individual")) indDataSet.fillColor = UIColor.colorWithHexString("#427DC9", alpha: 1.0)! indDataSet.setColor(indDataSet.fillColor) indDataSet.drawFilledEnabled = true indDataSet.lineWidth = 1.0 indDataSet.fillAlpha = 0.5 indDataSet.showPoints = true indDataSet.highlightColor = UIColor.clearColor() indDataSet.highlightCircleFillColor = UIColor.redColor() indDataSet.highlightCircleStrokeColor = UIColor.whiteColor() indDataSet.highlightCircleStrokeWidth = 1 indDataSet.highlightCircleInnerRadius = 0 indDataSet.highlightCircleOuterRadius = 5 indDataSet.drawHighlightCircleEnabled = false let popDataSet = MetabolicChartDataSet(yVals: popData, label: NSLocalizedString("Population value", comment: "Population")) popDataSet.fillColor = UIColor.lightGrayColor() popDataSet.setColor(popDataSet.fillColor.colorWithAlphaComponent(0.75)) popDataSet.drawFilledEnabled = true popDataSet.lineWidth = 1.0 popDataSet.fillAlpha = 0.5 popDataSet.drawHighlightCircleEnabled = false let xVals = sampleTypes.map { type in return HMConstants.sharedInstance.healthKitShortNames[type.identifier]! } let data = RadarChartData(xVals: xVals, dataSets: [indDataSet, popDataSet]) data.setDrawValues(false) radarChart.data = data radarChart.highlightValue(xIndex: 0, dataSetIndex: 0, callDelegate: false) radarChart.xAxis.labelTextColor = .whiteColor() radarChart.xAxis.labelFont = UIFont.systemFontOfSize(12, weight: UIFontWeightRegular) radarChart.yAxis.drawLabelsEnabled = false radarChart.notifyDataSetChanged() radarChart.valuesToHighlight() } }
apache-2.0
18b318f1ed258b6866ca7454a5624c83
47.525478
292
0.651637
5.101105
false
false
false
false
che1404/RGViperChat
RGViperChat/Authorization/Interactor/AuthorizationInteractorSpec.swift
1
2939
// // Created by Roberto Garrido // Copyright (c) 2017 Roberto Garrido. All rights reserved. // import Quick import Nimble import Cuckoo @testable import RGViperChat class AuthorizationInteractorSpec: QuickSpec { var interactor: AuthorizationInteractor! var mockPresenter: MockAuthorizationInteractorOutputProtocol! var mockAPIDataManager: MockAuthorizationAPIDataManagerInputProtocol! var mockLocalDataManager: MockAuthorizationLocalDataManagerInputProtocol! override func spec() { beforeEach { self.mockPresenter = MockAuthorizationInteractorOutputProtocol() self.mockAPIDataManager = MockAuthorizationAPIDataManagerInputProtocol() self.mockLocalDataManager = MockAuthorizationLocalDataManagerInputProtocol() self.interactor = AuthorizationInteractor() self.interactor.presenter = self.mockPresenter self.interactor.APIDataManager = self.mockAPIDataManager self.interactor.localDataManager = self.mockLocalDataManager } context("When a login use case is selected") { beforeEach { stub(self.mockAPIDataManager) { mock in when(mock).login(withEmail: anyString(), password: anyString(), completion: anyClosure()).then { _, _, completion in completion(false) } } self.interactor.login(withEmail: "roberto@robertogarrido.com", password: "viperchat") } it("Logs in against the API data manager") { verify(self.mockAPIDataManager).login(withEmail: anyString(), password: anyString(), completion: anyClosure()) } it("Logs in using the credentials of the view") { verify(self.mockAPIDataManager).login(withEmail: equal(to: "roberto@robertogarrido.com"), password: equal(to: "viperchat"), completion: anyClosure()) } context("When the login was successful") { beforeEach { stub(self.mockAPIDataManager) { mock in when(mock).login(withEmail: anyString(), password: anyString(), completion: anyClosure()).then { _, _, completion in completion(true) } } stub(self.mockPresenter) { mock in when(mock).successfulLogin().thenDoNothing() } self.interactor.login(withEmail: "roberto@robertogarrido.com", password: "viperchat") } it("Responds the presenter with successful login") { verify(self.mockPresenter).successfulLogin() } } } afterEach { self.interactor = nil self.mockPresenter = nil self.mockAPIDataManager = nil } } }
mit
c3d19d4f711b6322e53ac3a41d4264a8
39.260274
165
0.601565
5.442593
false
false
false
false
NachoSoto/AsyncImageView
AsyncImageViewTests/ImageInflaterRendererSpec.swift
1
17571
// // ImageInflaterRendererSpec.swift // AsyncImageView // // Created by Nacho Soto on 11/28/15. // Copyright © 2015 Nacho Soto. All rights reserved. // import Quick import Nimble import AsyncImageView class ImageInflaterRendererSpec: QuickSpec { override func spec() { describe("ImageInflaterRenderer") { context("Aspect Fit") { it("returns identity frame if sizes match") { let size = CGSize.random() let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: size, inSize: size ) expect(result) == CGRect(origin: CGPoint.zero, size: size) } it("reduces size if aspect ratio matches, but canvas is smaller") { let imageSize = CGSize.random() let canvasSize = CGSize(width: imageSize.width * 0.4, height: imageSize.height * 0.4) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) expect(result) == CGRect(origin: CGPoint.zero, size: canvasSize) } it("scales up size if aspect ratio matches, but canvas is bigger") { let imageSize = CGSize.random() let canvasSize = CGSize(width: imageSize.width * 2, height: imageSize.height * 2) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) expect(result) == CGRect(origin: CGPoint.zero, size: canvasSize) } it("scales and centers image vertically if height matches, but canvas width is smaller") { let imageSize = CGSize(width: 1242, height: 240) let canvasSize = CGSize(width: 750, height: 240) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) let expectedHeight = canvasSize.height * (canvasSize.width / imageSize.width) // preserve aspect ratio expect(result.origin) == CGPoint(x: 0, y: (expectedHeight - canvasSize.height) / -2.0) expect(result.size.width).to(beCloseTo(canvasSize.width)) expect(result.size.height).to(beCloseTo(expectedHeight)) } it("centers horizontally if height matches, but canvas width is bigger") { let imageSize = CGSize(width: 1242, height: 240) let canvasSize = CGSize(width: 1334, height: 240) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) expect(result.origin) == CGPoint(x: (imageSize.width - canvasSize.width) / -2.0, y: 0) expect(result.size) == imageSize } it("scales and centers image horizontally if width matches, but canvas height is smaller") { let imageSize = CGSize(width: 1242, height: 240) let canvasSize = CGSize(width: 1242, height: 100) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) let expectedWidth = canvasSize.width * (canvasSize.height / imageSize.height) // preserve aspect ratio expect(result.origin) == CGPoint(x: (expectedWidth - canvasSize.width) / -2.0, y: 0) expect(result.size.width).to(beCloseTo(expectedWidth)) expect(result.size.height).to(beCloseTo(canvasSize.height)) } it("centers vertically if width matches, but canvas height is bigger") { let imageSize = CGSize(width: 1242, height: 240) let canvasSize = CGSize(width: 1242, height: 300) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) expect(result.origin) == CGPoint(x: 0, y: (imageSize.height - canvasSize.height) / -2.0) expect(result.size) == imageSize } context("aspect ratio and image size are different") { context("image size is smaller") { it("image aspect ratio is smaller") { let imageSize = CGSize(width: 30, height: 40) let canvasSize = CGSize(width: 50, height: 60) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) expect(result.origin.x).to(beCloseTo(2.5)) expect(result.origin.y).to(beCloseTo(0)) expect(result.size.width).to(beCloseTo(45)) expect(result.size.height).to(beCloseTo(60)) } it("image aspect ratio is bigger") { let imageSize = CGSize(width: 50, height: 60) let canvasSize = CGSize(width: 60, height: 80) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) expect(result.origin.x).to(beCloseTo(0)) expect(result.origin.y).to(beCloseTo(4)) expect(result.size.width).to(beCloseTo(60)) expect(result.size.height).to(beCloseTo(72)) } } context("image size is bigger") { it("image aspect ratio is smaller") { let imageSize = CGSize(width: 60, height: 80) let canvasSize = CGSize(width: 50, height: 60) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) expect(result.origin.x).to(beCloseTo(2.5)) expect(result.origin.y).to(beCloseTo(0)) expect(result.size.width).to(beCloseTo(45)) expect(result.size.height).to(beCloseTo(60)) } it("image aspect ratio is bigger") { let imageSize = CGSize(width: 100, height: 120) let canvasSize = CGSize(width: 60, height: 80) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFit( imageSize: imageSize, inSize: canvasSize ) expect(result.origin.x).to(beCloseTo(0)) expect(result.origin.y).to(beCloseTo(4)) expect(result.size.width).to(beCloseTo(60)) expect(result.size.height).to(beCloseTo(72)) } } } } context("Aspect Fill") { it("returns identity frame if sizes match") { let size = CGSize.random() let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: size, inSize: size ) expect(result) == CGRect(origin: CGPoint.zero, size: size) } it("reduces size if aspect ratio matches, but canvas is smaller") { let imageSize = CGSize.random() let canvasSize = CGSize(width: imageSize.width * 0.4, height: imageSize.height * 0.4) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) expect(result) == CGRect(origin: CGPoint.zero, size: canvasSize) } it("scales up size if aspect ratio matches, but canvas is bigger") { let imageSize = CGSize.random() let canvasSize = CGSize(width: imageSize.width * 2, height: imageSize.height * 2) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) expect(result) == CGRect(origin: CGPoint.zero, size: canvasSize) } it("centers image horizontally if height matches, but canvas width is smaller") { let imageSize = CGSize(width: 1242, height: 240) let canvasSize = CGSize(width: 750, height: 240) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) expect(result.origin) == CGPoint(x: (imageSize.width - canvasSize.width) / -2.0, y: 0) expect(result.size) == imageSize } it("scales image and centers horizontally if height matches, but canvas width is bigger") { let imageSize = CGSize(width: 1242, height: 240) let canvasSize = CGSize(width: 1334, height: 240) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) let expectedHeight = canvasSize.height * (canvasSize.width / imageSize.width) // preserve aspect ratio expect(result.origin.x).to(beCloseTo(0)) expect(result.origin.y).to(beCloseTo((canvasSize.height - expectedHeight) / 2.0)) expect(result.size.width).to(beCloseTo(canvasSize.width)) expect(result.size.height).to(beCloseTo(expectedHeight)) } it("centers image vertically if width matches, but canvas height is smaller") { let imageSize = CGSize(width: 1242, height: 240) let canvasSize = CGSize(width: 1242, height: 100) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) expect(result.origin) == CGPoint(x: 0, y: (imageSize.height - canvasSize.height) / -2.0) expect(result.size) == imageSize } it("scales image and centers vertically if width matches, but canvas height is bigger") { let imageSize = CGSize(width: 1242, height: 240) let canvasSize = CGSize(width: 1242, height: 300) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) let expectedWidth = canvasSize.width * (canvasSize.height / imageSize.height) // preserve aspect ratio // TODO: write matcher for `CGRect`. expect(result.origin.x).to(beCloseTo((canvasSize.width - expectedWidth) / 2.0)) expect(result.origin.y).to(beCloseTo(0)) expect(result.size.width).to(beCloseTo(expectedWidth)) expect(result.size.height).to(beCloseTo(canvasSize.height)) } context("aspect ratio and image size are different") { context("image size is smaller") { it("image aspect ratio is smaller") { let imageSize = CGSize(width: 30, height: 40) let canvasSize = CGSize(width: 50, height: 60) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) expect(result.origin.x).to(beCloseTo(0)) expect(result.origin.y).to(beCloseTo(-3.3333)) expect(result.size.width).to(beCloseTo(50)) expect(result.size.height).to(beCloseTo(66.6666)) } it("image aspect ratio is bigger") { let imageSize = CGSize(width: 50, height: 60) let canvasSize = CGSize(width: 60, height: 80) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) expect(result.origin.x).to(beCloseTo(-3.3333)) expect(result.origin.y).to(beCloseTo(0)) expect(result.size.width).to(beCloseTo(66.6666)) expect(result.size.height).to(beCloseTo(80)) } } context("image size is bigger") { it("image aspect ratio is smaller") { let imageSize = CGSize(width: 60, height: 80) let canvasSize = CGSize(width: 50, height: 60) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) expect(result.origin.x).to(beCloseTo(0)) expect(result.origin.y).to(beCloseTo(-3.3333)) expect(result.size.width).to(beCloseTo(50)) expect(result.size.height).to(beCloseTo(66.6666)) } it("image aspect ratio is bigger") { let imageSize = CGSize(width: 100, height: 120) let canvasSize = CGSize(width: 60, height: 80) let result = InflaterSizeCalculator.drawingRectForRenderingWithAspectFill( imageSize: imageSize, inSize: canvasSize ) expect(result.origin.x).to(beCloseTo(-3.3333)) expect(result.origin.y).to(beCloseTo(0)) expect(result.size.width).to(beCloseTo(66.6666)) expect(result.size.height).to(beCloseTo(80)) } } } } } } }
mit
1631b4d9cf03fbe1da7b6e107f50cad5
50.676471
122
0.450028
6.182266
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/TriggerListViewController.swift
1
13312
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Buttons_Buttons import third_party_objective_c_material_components_ios_components_Collections_Collections import third_party_objective_c_material_components_ios_components_Palettes_Palettes import third_party_objective_c_material_components_ios_components_Typography_Typography protocol TriggerListDelegate: class { /// Called when the trigger list view controller updates triggers. func triggerListViewController(_ triggerListViewController: TriggerListViewController, didUpdateTriggers sensorTriggers: [SensorTrigger], withActiveTriggerIDs activeTriggerIDs: [String], forSensor sensor: Sensor) } /// View controller that displays a list of triggers for a sensor. Each can be modified. class TriggerListViewController: MaterialHeaderCollectionViewController, TriggerListCellDelegate, TriggerEditViewControllerDelegate { // MARK: - No triggers view class NoTriggersView: UIView { override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } private func configureView() { backgroundColor = .white let noTriggersLabel = UILabel() noTriggersLabel.alpha = MDCTypography.titleFontOpacity() noTriggersLabel.font = MDCTypography.titleFont() noTriggersLabel.text = String.emptyTriggerList noTriggersLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(noTriggersLabel) noTriggersLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true noTriggersLabel.topAnchor.constraint(equalTo: topAnchor, constant: 25).isActive = true let triggerImageView = UIImageView(image: UIImage(named: "ic_trigger_large")) triggerImageView.translatesAutoresizingMaskIntoConstraints = false addSubview(triggerImageView) triggerImageView.heightAnchor.constraint(equalToConstant: 100).isActive = true triggerImageView.widthAnchor.constraint(equalToConstant: 100).isActive = true triggerImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true triggerImageView.topAnchor.constraint(equalTo: noTriggersLabel.bottomAnchor).isActive = true } } // MARK: - TriggerListViewController // MARK: - Properties private var activeTriggerIDs: [String] private let addButton = MDCFloatingButton() private let addButtonPadding: CGFloat = 16 private weak var delegate: TriggerListDelegate? private let emptyView = NoTriggersView() private let sensor: Sensor private let triggerListCellIdentifier = "TriggerListCell" private let triggerListDataSource: TriggerListDataSource private var isEmptyViewHidden = true { didSet { guard isEmptyViewHidden != oldValue else { return } if isEmptyViewHidden { removeEmptyView() } else { addEmptyView() } } } private var horizontalPadding: CGFloat { var padding: CGFloat { switch displayType { case .compact, .compactWide: return 0 case .regular: return ViewConstants.cellHorizontalInsetRegularDisplayType case .regularWide: return ViewConstants.cellHorizontalInsetRegularWideDisplayType } } return padding + view.safeAreaInsetsOrZero.left + view.safeAreaInsetsOrZero.right } // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - sensorTriggers: The sensor triggers for a sensor. /// - activeTriggerIDs: The IDs of the triggers that are active. /// - sensor: The sensor to show sensor triggers for. /// - delegate: The sensor trigger list delgate. /// - analyticsReporter: An AnalyticsReporter. init(sensorTriggers: [SensorTrigger], activeTriggerIDs: [String], sensor: Sensor, delegate: TriggerListDelegate, analyticsReporter: AnalyticsReporter) { self.activeTriggerIDs = activeTriggerIDs self.sensor = sensor self.delegate = delegate triggerListDataSource = TriggerListDataSource(sensorTriggers: sensorTriggers) super.init(analyticsReporter: analyticsReporter) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override func viewDidLoad() { super.viewDidLoad() // Always register collection view cells early to avoid a reload occurring first. collectionView?.register(TriggerListCell.self, forCellWithReuseIdentifier: triggerListCellIdentifier) accessibilityViewIsModal = true styler.cellStyle = .default appBar.headerViewController.headerView.backgroundColor = .appBarReviewBackgroundColor collectionView?.backgroundColor = .white if isPresented && UIDevice.current.userInterfaceIdiom == .pad { appBar.hideStatusBarOverlay() } // Title. title = String.triggerListTitle + " " + sensor.name // Close button navigationItem.leftBarButtonItem = MaterialCloseBarButtonItem(target: self, action: #selector(closeButtonPressed)) // Add button. view.addSubview(addButton) addButton.setImage(UIImage(named: "ic_add"), for: .normal) addButton.tintColor = .white addButton.setBackgroundColor(MDCPalette.blue.tint600, for: .normal) addButton.addTarget(self, action: #selector(addButtonPressed), for: .touchUpInside) addButton.translatesAutoresizingMaskIntoConstraints = false addButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -addButtonPadding).isActive = true addButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -addButtonPadding).isActive = true addButton.accessibilityLabel = String.btnAddNewTrigger // Show the empty view if the data source doesn't have items. self.isEmptyViewHidden = self.triggerListDataSource.hasItems } override func accessibilityPerformEscape() -> Bool { callDelegateWithUpdatedTriggers() dismiss(animated: true) return true } // MARK: - Private private func addEmptyView() { emptyView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(emptyView, belowSubview: addButton) emptyView.topAnchor.constraint(equalTo: appBar.navigationBar.bottomAnchor).isActive = true emptyView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true emptyView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true emptyView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } private func removeEmptyView() { emptyView.removeFromSuperview() } /// Whether or not a trigger is active. Exposed for testing. func isTriggerActive(_ trigger: SensorTrigger) -> Bool { return activeTriggerIDs.contains(trigger.triggerID) } private func callDelegateWithUpdatedTriggers() { delegate?.triggerListViewController(self, didUpdateTriggers: triggerListDataSource.triggers, withActiveTriggerIDs: activeTriggerIDs, forSensor: sensor) } private func showTriggerEditViewController(with trigger: SensorTrigger, isEditMode: Bool) { let triggerEditViewController = TriggerEditViewController(sensorTrigger: trigger, sensor: sensor, delegate: self, isEditMode: isEditMode, analyticsReporter: analyticsReporter) self.navigationController?.pushViewController(triggerEditViewController, animated: true) } // MARK: - User actions @objc private func addButtonPressed() { // Show the edit view controller for a new trigger. showTriggerEditViewController(with: SensorTrigger(sensorID: sensor.sensorId), isEditMode: false) } @objc private func closeButtonPressed() { callDelegateWithUpdatedTriggers() dismiss(animated: true) } // MARK: - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return triggerListDataSource.numberOfItems } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: triggerListCellIdentifier, for: indexPath) if let triggerListCell = cell as? TriggerListCell { let trigger = triggerListDataSource.item(at: indexPath) triggerListCell.delegate = self triggerListCell.textLabel.text = trigger.textDescription(for: sensor) triggerListCell.aSwitch.isOn = isTriggerActive(trigger) } return cell } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.size.width - horizontalPadding, height: TriggerListCell.height) } override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { // Don't show selection highlight ink. return false } override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { // Trigger cells aren't selectable. return false } // MARK: - TriggerListCellDelegate func triggerListCellSwitchValueChanged(_ triggerListCell: TriggerListCell) { guard let indexPath = collectionView?.indexPath(for: triggerListCell) else { return } let trigger = triggerListDataSource.item(at: indexPath) if triggerListCell.aSwitch.isOn { activeTriggerIDs.append(trigger.triggerID) } else { guard let index = activeTriggerIDs.firstIndex(where: { $0 == trigger.triggerID }) else { return } activeTriggerIDs.remove(at: index) } callDelegateWithUpdatedTriggers() } func triggerListCellMenuButtonPressed(_ triggerListCell: TriggerListCell) { let popUpMenu = PopUpMenuViewController() popUpMenu.addAction(PopUpMenuAction(title: String.actionEdit, icon: UIImage(named: "ic_edit")) { (_) in guard let indexPath = self.collectionView?.indexPath(for: triggerListCell) else { return } let trigger = self.triggerListDataSource.item(at: indexPath) self.showTriggerEditViewController(with: trigger, isEditMode: true) }) popUpMenu.addAction(PopUpMenuAction(title: String.actionDelete, icon: UIImage(named: "ic_delete")) { (_) in guard let indexPath = self.collectionView?.indexPath(for: triggerListCell), let removedTrigger = self.triggerListDataSource.removeItem(at: indexPath) else { return } self.collectionView?.deleteItems(at: [indexPath]) self.isEmptyViewHidden = self.triggerListDataSource.hasItems // Allow the user to undo the delete action. showUndoSnackbar(withMessage: String.sensorTriggerDeleted, undoBlock: { self.triggerListDataSource.insertItem(removedTrigger, atIndex: indexPath.item) self.collectionView?.insertItems(at: [indexPath]) self.isEmptyViewHidden = self.triggerListDataSource.hasItems }) }) popUpMenu.present(from: self, position: .sourceView(triggerListCell.menuButton)) } // MARK: - TriggerEditViewControllerDelegate func triggerEditViewController(_ triggerEditViewController: TriggerEditViewController, didEditTrigger trigger: SensorTrigger) { // If the item has an index path, reload it. Otherwise, add the item and insert it. if let indexPathOfItem = triggerListDataSource.indexPathOfItem(trigger) { collectionView?.reloadItems(at: [indexPathOfItem]) } else { triggerListDataSource.addItem(trigger) activeTriggerIDs.append(trigger.triggerID) collectionView?.insertItems(at: [triggerListDataSource.indexPathOfLastItem]) isEmptyViewHidden = triggerListDataSource.hasItems } } }
apache-2.0
abcc1d153069cce9902cb6d9b801a34b
38.975976
100
0.698768
5.316294
false
false
false
false
mattermost/mattermost-mobile
ios/Mattermost/NotificationHelper.swift
1
3658
import Foundation import Gekidou import UserNotifications import UIKit @objc class NotificationHelper: NSObject { @objc public static let `default` = NotificationHelper() private let notificationCenter = UNUserNotificationCenter.current() @objc func getDeliveredNotifications(completionHandler: @escaping ([UNNotification]) -> Void) { notificationCenter.getDeliveredNotifications(completionHandler: completionHandler) } @objc func clearChannelOrThreadNotifications(userInfo: NSDictionary) { let channelId = userInfo["channel_id"] as? String let rootId = userInfo["root_id"] as? String ?? "" let crtEnabled = userInfo["is_crt_enabled"] as? Bool ?? false let serverId = userInfo["server_id"] as? String ?? "" let skipThreadNotification = !rootId.isEmpty && crtEnabled guard let serverUrl = try? Gekidou.Database.default.getServerUrlForServer(serverId) else { return } if !skipThreadNotification && channelId != nil { removeChannelNotifications(serverUrl: serverUrl, channelId: channelId!) try? Gekidou.Database.default.resetMyChannelMentions(serverUrl, channelId!) } else if !rootId.isEmpty { removeThreadNotifications(serverUrl: serverUrl, threadId: rootId) try? Gekidou.Database.default.resetThreadMentions(serverUrl, rootId) } let mentions = Gekidou.Database.default.getTotalMentions() UIApplication.shared.applicationIconBadgeNumber = mentions } @objc func removeChannelNotifications(serverUrl: String, channelId: String) { getDeliveredNotifications(completionHandler: {notifications in var notificationIds = [String]() for notification in notifications { let request = notification.request let content = request.content let identifier = request.identifier let cId = content.userInfo["channel_id"] as? String let rootId = content.userInfo["root_id"] as? String ?? "" let crtEnabled = content.userInfo["is_crt_enabled"] as? Bool ?? false let skipThreadNotification = !rootId.isEmpty && crtEnabled if cId == channelId && !skipThreadNotification { notificationIds.append(identifier) } } self.notificationCenter.removeDeliveredNotifications(withIdentifiers: notificationIds) }) } @objc func removeThreadNotifications(serverUrl: String, threadId: String) { getDeliveredNotifications(completionHandler: {notifications in var notificationIds = [String]() for notification in notifications { let request = notification.request let content = request.content let identifier = request.identifier let postId = content.userInfo["post_id"] as? String let rootId = content.userInfo["root_id"] as? String if rootId == threadId || postId == threadId { notificationIds.append(identifier) } } self.notificationCenter.removeDeliveredNotifications(withIdentifiers: notificationIds) }) } @objc func removeServerNotifications(serverUrl: String) { getDeliveredNotifications(completionHandler: {notifications in var notificationIds = [String]() for notification in notifications { let request = notification.request let content = request.content let identifier = request.identifier let url = content.userInfo["server_url"] as? String if url == serverUrl { notificationIds.append(identifier) } } self.notificationCenter.removeDeliveredNotifications(withIdentifiers: notificationIds) }) } }
apache-2.0
b35e441e3f9b717b258ce51bb8d149c6
37.104167
97
0.696829
5.052486
false
false
false
false
naokits/bluemix-swift-demo-ios
Pods/BMSAnalyticsAPI/Source/Logger.swift
2
12052
/* *     Copyright 2016 IBM Corp. *     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. */ // MARK: LogLevel /** Used in the `Logger` class, the `LogLevel` denotes the log severity. Lower integer raw values indicate higher severity. */ public enum LogLevel: Int { case None, Analytics, Fatal, Error, Warn, Info, Debug public var stringValue: String { get { switch self { case .None: return "NONE" case .Analytics: return "ANALYTICS" case .Fatal: return "FATAL" case .Error: return "ERROR" case .Warn: return "WARN" case .Info: return "INFO" case .Debug: return "DEBUG" } } } } // MARK: - LoggerDelegate // Contains functionality to write logs to file and send them to an analytics server // This protocol is implemented in the BMSAnalytics framework public protocol LoggerDelegate { var isUncaughtExceptionDetected: Bool { get set } func logMessageToFile(message: String, level: LogLevel, loggerName: String, calledFile: String, calledFunction: String, calledLineNumber: Int, additionalMetadata: [String: AnyObject]?) } // MARK: - Logger /** `Logger` provides a wrapper to Swift's `print()` function, with additional information such as the file, function, and line where the log was called. It supports logging at different levels of verbosity (see the `LogLevel` enum) and filtering by `LogLevel` to limit the log output to the console. Multiple `Logger` instances can be created with different package names using the `loggerForName` method. - Important: All of the below functionality will be added to `Logger` if the `BMSAnalytics` framework is added to your project. `BMSAnalytics` extends `Logger` to allow storing log messages and sending them to an analytics server. When the `enabled` property is set to `true` (which is the default value), logs will be persisted to a file on the client device in the following JSON format: { "timestamp" : "17-02-2013 13:54:27:123", // "dd-MM-yyyy hh:mm:ss:S" "level" : "ERROR", // FATAL || ERROR || WARN || INFO || DEBUG "name" : "your_logger_name", // The name of the Logger (typically a class name or app name) "msg" : "the message", // Some log message "metadata" : {"some key": "some value"}, // Additional JSON metadata (only for Analytics logging) } Logs are accumulated persistently to the log file until the file size is greater than the `Logger.maxLogStoreSize` property. At this point, half of the old logs will be deleted to make room for new log data. Log file data is sent to the Bluemix server when the Logger `send()` method is called, provided that the file is not empty and the BMSClient was initialized via the `initializeWithBluemixAppRoute()` method. When the log data is successfully uploaded, the persisted local log data is deleted. - Note: The `Logger` class sets an uncaught exception handler to log application crashes. If you wish to set your own exception handler, do so **before** calling `Logger.loggerForName()` or the `Logger` exception handler will be overwritten. */ public class Logger { // MARK: Properties (API) /// The name that identifies this Logger instance public let name: String /// Only logs that are at or above this level will be output to the console. /// Defaults to the `LogLevel.Debug`. /// /// Set the value to `LogLevel.None` to turn off all logging. public static var logLevelFilter: LogLevel = LogLevel.Debug /// If set to `false`, the internal BMSCore debug logs will not be displayed on the console. public static var sdkDebugLoggingEnabled: Bool = false /// Determines whether logs get written to file on the client device. /// Must be set to `true` to be able to send logs to the Bluemix server. public static var logStoreEnabled: Bool = false /// The maximum file size (in bytes) for log storage. /// Both the Analytics and Logger log files are limited by `maxLogStoreSize`. public static var maxLogStoreSize: UInt64 = 100000 /// True if the app crashed recently due to an uncaught exception. /// This property will be set back to `false` if the logs are sent to the server. public static var isUncaughtExceptionDetected: Bool { get { return Logger.delegate?.isUncaughtExceptionDetected ?? false } set { Logger.delegate?.isUncaughtExceptionDetected = newValue } } // MARK: Properties (internal) // Used to persist all logs to the device's file system and send logs to the analytics server // Public access required by BMSAnalytics framework, which is required to initialize this property public static var delegate: LoggerDelegate? // Each logger instance is distinguished only by its "name" property internal static var loggerInstances: [String: Logger] = [:] // Prefix for all internal logger names public static let bmsLoggerPrefix = "bmssdk." // MARK: Initializers /** Create a Logger instance that will be identified by the supplied name. If a Logger instance with that name already exists, the existing instance will be returned. - parameter loggerName: The name that identifies this Logger instance - returns: A Logger instance */ public static func logger(forName loggerName: String) -> Logger { if let existingLogger = Logger.loggerInstances[loggerName] { return existingLogger } else { let newLogger = Logger(name: loggerName) Logger.loggerInstances[loggerName] = newLogger return newLogger } } private init(name: String) { self.name = name } // MARK: Methods (API) /** Log at the Debug LogLevel. - parameter message: The message to log - Note: Do not supply values for the `file`, `function`, or `line` parameters. These parameters take default values to automatically record the file, function, and line in which this method was called. */ public func debug(message: String, file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) { logMessage(message, level: LogLevel.Debug, calledFile: file, calledFunction: function, calledLineNumber: line) } /** Log at the Info LogLevel. - parameter message: The message to log - Note: Do not supply values for the `file`, `function`, or `line` parameters. These parameters take default values to automatically record the file, function, and line in which this method was called. */ public func info(message: String, file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) { logMessage(message, level: LogLevel.Info, calledFile: file, calledFunction: function, calledLineNumber: line) } /** Log at the Warn LogLevel. - parameter message: The message to log - Note: Do not supply values for the `file`, `function`, or `line` parameters. These parameters take default values to automatically record the file, function, and line in which this method was called. */ public func warn(message: String, file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) { logMessage(message, level: LogLevel.Warn, calledFile: file, calledFunction: function, calledLineNumber: line) } /** Log at the Error LogLevel. - parameter message: The message to log - Note: Do not supply values for the `file`, `function`, or `line` parameters. These parameters take default values to automatically record the file, function, and line in which this method was called. */ public func error(message: String, file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) { logMessage(message, level: LogLevel.Error, calledFile: file, calledFunction: function, calledLineNumber: line) } /** Log at the Fatal LogLevel. - parameter message: The message to log - Note: Do not supply values for the `file`, `function`, or `line` parameters. These parameters take default values to automatically record the file, function, and line in which this method was called. */ public func fatal(message: String, file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) { logMessage(message, level: LogLevel.Fatal, calledFile: file, calledFunction: function, calledLineNumber: line) } // Equivalent to the other log methods, but this method accepts data as JSON rather than a string internal func analytics(metadata: [String: AnyObject], file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) { logMessage("", level: LogLevel.Analytics, calledFile: file, calledFunction: function, calledLineNumber: line, additionalMetadata: metadata) } // MARK: Methods (internal) // This is the master function that handles all of the logging, including level checking, printing to console, and writing to file // All other log functions below this one are helpers for this function internal func logMessage(message: String, level: LogLevel, calledFile: String, calledFunction: String, calledLineNumber: Int, additionalMetadata: [String: AnyObject]? = nil) { // The level must exceed the Logger.logLevelFilter, or we do nothing guard level.rawValue <= Logger.logLevelFilter.rawValue else { return } if self.name.hasPrefix(Logger.bmsLoggerPrefix) && !Logger.sdkDebugLoggingEnabled && level == LogLevel.Debug { // Don't show our internal logs in the console. } else { // Print to console Logger.printLogToConsole(message, loggerName: self.name, level: level, calledFunction: calledFunction, calledFile: calledFile, calledLineNumber: calledLineNumber) } Logger.delegate?.logMessageToFile(message, level: level, loggerName: self.name, calledFile: calledFile, calledFunction: calledFunction, calledLineNumber: calledLineNumber, additionalMetadata: additionalMetadata) } // Format: [DEBUG] [bmssdk.logger] logMessage in Logger.swift:234 :: "Some random message" // Public access required by BMSAnalytics framework public static func printLogToConsole(logMessage: String, loggerName: String, level: LogLevel, calledFunction: String, calledFile: String, calledLineNumber: Int) { // Suppress console log output for apps that are being released to the App Store #if !RELEASE_BUILD if level != LogLevel.Analytics { print("[\(level.stringValue)] [\(loggerName)] \(calledFunction) in \(calledFile):\(calledLineNumber) :: \(logMessage)") } #endif } }
mit
8d422d48600d5f365a026ac94f6d618a
42.716364
295
0.653718
4.772529
false
false
false
false
shjborage/iOS-Guide
Swift/SwiftPlayground.playground/Pages/4. Enumerations&Structures.xcplaygroundpage/Contents.swift
1
1506
//: [Previous](@previous) import Foundation var str = "Hi, Enumerations and Structures" //: [Next](@next) enum Rank: Int { case ace = 1 case two, three, four, five, six, seven, eight, nine, ten case jack, queen, king func desc() -> String { switch self { case .ace: return "ace" case .jack: return "jack" case .queen: return "queen" case .king: return "king" default: return String(self.rawValue) } } func isEqualtoRank(_ rank : Rank) -> Bool { return rank.rawValue == self.rawValue } } let ace = Rank.ace; print(ace) ace.rawValue print(Rank.king.rawValue) Rank.king.desc() ace.isEqualtoRank(Rank.king) ace.isEqualtoRank(Rank.two) ace.isEqualtoRank(Rank.ace) //if let threeDesc = Rank.init(rawValue: 23) { if let threeDesc = Rank.init(rawValue: 3) { print(threeDesc.desc()) } else { print("unknown") } enum ServerResponse { case result(String, String) case failure(String) case unknown(String) } let success = ServerResponse.result("6:00 am", "8:09 pm") let failure = ServerResponse.failure("Out of cheese.") let unknown = ServerResponse.unknown("unknowned") switch unknown { case let .result(sunrise, sunset): print("Sunrise is at \(sunrise) and sunset is at \(sunset).") case let .failure(message): print("Failure... \(message)") case let .unknown(message): print("asdf: \(message)") }
mit
e0f7f6f6a4027b9df70d6200334a60e2
20.826087
65
0.611554
3.620192
false
false
false
false
karwa/swift-corelibs-foundation
Foundation/NSURLResponse.swift
3
16512
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /// An `NSURLResponse` object represents a URL load response in a /// manner independent of protocol and URL scheme. /// /// `NSURLResponse` encapsulates the metadata associated /// with a URL load. Note that NSURLResponse objects do not contain /// the actual bytes representing the content of a URL. See /// `NSURLSession` for more information about receiving the content /// data for a URL load. public class NSURLResponse : NSObject, NSSecureCoding, NSCopying { static public func supportsSecureCoding() -> Bool { return true } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(_ aCoder: NSCoder) { NSUnimplemented() } public override func copy() -> AnyObject { return copyWithZone(nil) } public func copyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() } /// Initialize an NSURLResponse with the provided values. /// /// This is the designated initializer for NSURLResponse. /// - Parameter URL: the URL /// - Parameter mimeType: the MIME content type of the response /// - Parameter expectedContentLength: the expected content length of the associated data /// - Parameter textEncodingName the name of the text encoding for the associated data, if applicable, else nil /// - Returns: The initialized NSURLResponse. public init(url: NSURL, mimeType: String?, expectedContentLength length: Int, textEncodingName name: String?) { self.url = url self.mimeType = mimeType self.expectedContentLength = Int64(length) self.textEncodingName = name let c = url.lastPathComponent self.suggestedFilename = (c?.isEmpty ?? true) ? "Unknown" : c } /// The URL of the receiver. /*@NSCopying*/ public private(set) var url: NSURL? /// The MIME type of the receiver. /// /// The MIME type is based on the information provided /// from an origin source. However, that value may be changed or /// corrected by a protocol implementation if it can be determined /// that the origin server or source reported the information /// incorrectly or imprecisely. An attempt to guess the MIME type may /// be made if the origin source did not report any such information. public private(set) var mimeType: String? /// The expected content length of the receiver. /// /// Some protocol implementations report a content length /// as part of delivering load metadata, but not all protocols /// guarantee the amount of data that will be delivered in actuality. /// Hence, this method returns an expected amount. Clients should use /// this value as an advisory, and should be prepared to deal with /// either more or less data. /// /// The expected content length of the receiver, or `-1` if /// there is no expectation that can be arrived at regarding expected /// content length. public private(set) var expectedContentLength: Int64 /// The name of the text encoding of the receiver. /// /// This name will be the actual string reported by the /// origin source during the course of performing a protocol-specific /// URL load. Clients can inspect this string and convert it to an /// NSStringEncoding or CFStringEncoding using the methods and /// functions made available in the appropriate framework. public private(set) var textEncodingName: String? /// A suggested filename if the resource were saved to disk. /// /// The method first checks if the server has specified a filename /// using the content disposition header. If no valid filename is /// specified using that mechanism, this method checks the last path /// component of the URL. If no valid filename can be obtained using /// the last path component, this method uses the URL's host as the /// filename. If the URL's host can't be converted to a valid /// filename, the filename "unknown" is used. In mose cases, this /// method appends the proper file extension based on the MIME type. /// /// This method always returns a valid filename. public private(set) var suggestedFilename: String? } /// A Response to an HTTP URL load. /// /// An NSHTTPURLResponse object represents a response to an /// HTTP URL load. It is a specialization of NSURLResponse which /// provides conveniences for accessing information specific to HTTP /// protocol responses. public class NSHTTPURLResponse : NSURLResponse { /// Initializer for NSHTTPURLResponse objects. /// /// - Parameter url: the URL from which the response was generated. /// - Parameter statusCode: an HTTP status code. /// - Parameter httpVersion: The version of the HTTP response as represented by the server. This is typically represented as "HTTP/1.1". /// - Parameter headerFields: A dictionary representing the header keys and values of the server response. /// - Returns: the instance of the object, or `nil` if an error occurred during initialization. public init?(url: NSURL, statusCode: Int, httpVersion: String?, headerFields: [String : String]?) { self.statusCode = statusCode self.allHeaderFields = headerFields ?? [:] super.init(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil) expectedContentLength = getExpectedContentLength(fromHeaderFields: headerFields) ?? -1 suggestedFilename = getSuggestedFilename(fromHeaderFields: headerFields) ?? "Unknown" if let type = ContentTypeComponents(headerFields: headerFields) { mimeType = type.mimeType.lowercased() textEncodingName = type.textEncoding?.lowercased() } } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } /// The HTTP status code of the receiver. public let statusCode: Int /// Returns a dictionary containing all the HTTP header fields /// of the receiver. /// /// By examining this header dictionary, clients can see /// the "raw" header information which was reported to the protocol /// implementation by the HTTP server. This may be of use to /// sophisticated or special-purpose HTTP clients. /// /// - Returns: A dictionary containing all the HTTP header fields of the /// receiver. /// /// - Important: This is an *experimental* change from the /// `[NSObject: AnyObject]` type that Darwin Foundation uses. public let allHeaderFields: [String: String] /// Convenience method which returns a localized string /// corresponding to the status code for this response. /// - Parameter forStatusCode: the status code to use to produce a localized string. public class func localizedString(forStatusCode statusCode: Int) -> String { switch statusCode { case 100: return "Continue" case 101: return "Switching Protocols" case 102: return "Processing" case 100...199: return "Informational" case 200: return "OK" case 201: return "Created" case 202: return "Accepted" case 203: return "Non-Authoritative Information" case 204: return "No Content" case 205: return "Reset Content" case 206: return "Partial Content" case 207: return "Multi-Status" case 208: return "Already Reported" case 226: return "IM Used" case 200...299: return "Success" case 300: return "Multiple Choices" case 301: return "Moved Permanently" case 302: return "Found" case 303: return "See Other" case 304: return "Not Modified" case 305: return "Use Proxy" case 307: return "Temporary Redirect" case 308: return "Permanent Redirect" case 300...399: return "Redirection" case 400: return "Bad Request" case 401: return "Unauthorized" case 402: return "Payment Required" case 403: return "Forbidden" case 404: return "Not Found" case 405: return "Method Not Allowed" case 406: return "Not Acceptable" case 407: return "Proxy Authentication Required" case 408: return "Request Timeout" case 409: return "Conflict" case 410: return "Gone" case 411: return "Length Required" case 412: return "Precondition Failed" case 413: return "Payload Too Large" case 414: return "URI Too Long" case 415: return "Unsupported Media Type" case 416: return "Range Not Satisfiable" case 417: return "Expectation Failed" case 421: return "Misdirected Request" case 422: return "Unprocessable Entity" case 423: return "Locked" case 424: return "Failed Dependency" case 426: return "Upgrade Required" case 428: return "Precondition Required" case 429: return "Too Many Requests" case 431: return "Request Header Fields Too Large" case 451: return "Unavailable For Legal Reasons" case 400...499: return "Client Error" case 500: return "Internal Server Error" case 501: return "Not Implemented" case 502: return "Bad Gateway" case 503: return "Service Unavailable" case 504: return "Gateway Timeout" case 505: return "HTTP Version Not Supported" case 506: return "Variant Also Negotiates" case 507: return "Insufficient Storage" case 508: return "Loop Detected" case 510: return "Not Extended" case 511: return "Network Authentication Required" case 500...599: return "Server Error" default: return "Server Error" } } } /// Parses the expected content length from the headers. /// /// Note that the message content length is different from the message /// transfer length. /// The transfer length can only be derived when the Transfer-Encoding is identity (default). /// For compressed content (Content-Encoding other than identity), there is not way to derive the /// content length from the transfer length. private func getExpectedContentLength(fromHeaderFields headerFields: [String : String]?) -> Int64? { guard let f = headerFields, let contentLengthS = valueForCaseInsensitiveKey("content-length", fields: f), let contentLength = Int64(contentLengthS) else { return nil } return contentLength } /// Parses the suggested filename from the `Content-Disposition` header. /// /// - SeeAlso: [RFC 2183](https://tools.ietf.org/html/rfc2183) private func getSuggestedFilename(fromHeaderFields headerFields: [String : String]?) -> String? { // Typical use looks like this: // Content-Disposition: attachment; filename="fname.ext" guard let f = headerFields, let contentDisposition = valueForCaseInsensitiveKey("content-disposition", fields: f), let field = contentDisposition.httpHeaderParts else { return nil } for part in field.parameters where part.attribute == "filename" { return part.value?.pathComponents.map{ $0 == "/" ? "" : $0}.joined(separator: "_") } return nil } /// Parts corresponding to the `Content-Type` header field in a HTTP message. private struct ContentTypeComponents { /// For `text/html; charset=ISO-8859-4` this would be `text/html` let mimeType: String /// For `text/html; charset=ISO-8859-4` this would be `ISO-8859-4`. Will be /// `nil` when no `charset` is specified. let textEncoding: String? } extension ContentTypeComponents { /// Parses the `Content-Type` header field /// /// `Content-Type: text/html; charset=ISO-8859-4` would result in `("text/html", "ISO-8859-4")`, while /// `Content-Type: text/html` would result in `("text/html", nil)`. init?(headerFields: [String : String]?) { guard let f = headerFields, let contentType = valueForCaseInsensitiveKey("content-type", fields: f), let field = contentType.httpHeaderParts else { return nil } for parameter in field.parameters where parameter.attribute == "charset" { self.mimeType = field.value self.textEncoding = parameter.value return } self.mimeType = field.value self.textEncoding = nil } } /// A type with paramteres /// /// RFC 2616 specifies a few types that can have parameters, e.g. `Content-Type`. /// These are specified like so /// ``` /// field = value *( ";" parameter ) /// value = token /// ``` /// where parameters are attribute/value as specified by /// ``` /// parameter = attribute "=" value /// attribute = token /// value = token | quoted-string /// ``` private struct ValueWithParameters { let value: String let parameters: [Parameter] struct Parameter { let attribute: String let value: String? } } private extension String { /// Split the string at each ";", remove any quoting. /// /// The trouble is if there's a /// ";" inside something that's quoted. And we can escape the separator and /// the quotes with a "\". var httpHeaderParts: ValueWithParameters? { var type: String? var parameters: [ValueWithParameters.Parameter] = [] let ws = NSCharacterSet.whitespaces() func append(_ string: String) { if type == nil { type = string } else { if let r = string.range(of: "=") { let name = string[string.startIndex..<r.lowerBound].trimmingCharacters(in: ws) let value = string[r.upperBound..<string.endIndex].trimmingCharacters(in: ws) parameters.append(ValueWithParameters.Parameter(attribute: name, value: value)) } else { let name = string.trimmingCharacters(in: ws) parameters.append(ValueWithParameters.Parameter(attribute: name, value: nil)) } } } let escape = UnicodeScalar(0x5c) // \ let quote = UnicodeScalar(0x22) // " let separator = UnicodeScalar(0x3b) // ; enum State { case nonQuoted(String) case nonQuotedEscaped(String) case quoted(String) case quotedEscaped(String) } var state = State.nonQuoted("") for next in unicodeScalars { switch (state, next) { case (.nonQuoted(let s), separator): append(s) state = .nonQuoted("") case (.nonQuoted(let s), escape): state = .nonQuotedEscaped(s + String(next)) case (.nonQuoted(let s), quote): state = .quoted(s) case (.nonQuoted(let s), _): state = .nonQuoted(s + String(next)) case (.nonQuotedEscaped(let s), _): state = .nonQuoted(s + String(next)) case (.quoted(let s), quote): state = .nonQuoted(s) case (.quoted(let s), escape): state = .quotedEscaped(s + String(next)) case (.quoted(let s), _): state = .quoted(s + String(next)) case (.quotedEscaped(let s), _): state = .quoted(s + String(next)) } } switch state { case .nonQuoted(let s): append(s) case .nonQuotedEscaped(let s): append(s) case .quoted(let s): append(s) case .quotedEscaped(let s): append(s) } guard let t = type else { return nil } return ValueWithParameters(value: t, parameters: parameters) } } private func valueForCaseInsensitiveKey(_ key: String, fields: [String: String]) -> String? { let kk = key.lowercased() for (k, v) in fields { if k.lowercased() == kk { return v } } return nil }
apache-2.0
0413a338aa9ebc64ef1952146e5ea661
40.802532
141
0.636931
4.763993
false
false
false
false
cam-hop/APIUtility
RxSwiftFluxDemo/RxSwiftFluxDemo/Extension/UITableViewCellExtension.swift
2
2088
// // UITableViewCellExtension.swift // DemoApp // // Created by DUONG VANHOP on 2017/06/14. // Copyright © 2017年 DUONG VANHOP. All rights reserved. // import UIKit extension UITableView { func reloadToStartPosition(includeInset: Bool = false) { reloadData() contentOffset = includeInset ? CGPoint(x: 0, y: contentInset.top) : .zero } //register. func registerCell<T: CellNibable>(cell: T.Type) { register(cell.nib, forCellReuseIdentifier: cell.identifier) } func registerHeaderFooterView<T: ReusableViewNibable>(headerFooterView: T.Type) { register(headerFooterView.nib, forHeaderFooterViewReuseIdentifier: headerFooterView.identifier) } //dequeue. func dequeueReusableCellWithIdentifier<T>(identifier: String) -> T { return dequeueReusableCell(withIdentifier: identifier) as! T } func dequeueReusableCellWithIdentifier<T>(identifier: String, forIndexPath indexPath: IndexPath) -> T { return dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! T } func dequeueReusableCell<T: CellNibable>(type: T.Type) -> T { return dequeueReusableCell(withIdentifier: type.identifier) as! T } func dequeueReusableCell<T: CellNibable>(type: T.Type, forIndexPath indexPath: IndexPath) -> T { return dequeueReusableCell(withIdentifier: type.identifier, for: indexPath) as! T } func dequeueReusableHeaderFooterViewWithIdentifier<T>(identifier: String) -> T { return dequeueReusableHeaderFooterView(withIdentifier: identifier) as! T } func dequeueReusableHeaderFooterView<T: ReusableViewNibable>(type: T.Type) -> T { return dequeueReusableHeaderFooterViewWithIdentifier(identifier: type.identifier) } } extension UITableView { func cellsForRowAtIndexPathRow<T>(row: Int) -> [T] { guard let indexPaths = indexPathsForVisibleRows else { return [] } let cells = indexPaths.filter { $0.row == row }.map { cellForRow(at: $0) } return cells.flatMap { $0 as? T } } }
mit
3ca10621b8f1945665e86840c810c720
33.180328
107
0.698801
4.685393
false
false
false
false
malcommac/SwiftRichString
Sources/SwiftRichString/Extensions/AttributedString+Extension.swift
1
8401
// // SwiftRichString // Elegant Strings & Attributed Strings Toolkit for Swift // // Created by Daniele Margutti. // Copyright © 2018 Daniele Margutti. All rights reserved. // // Web: http://www.danielemargutti.com // Email: hello@danielemargutti.com // Twitter: @danielemargutti // // // 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 #if os(OSX) import AppKit #else import UIKit #endif //MARK: - AttributedString Extension // The following methods are used to alter an existing attributed string with attributes specified by styles. public extension AttributedString { /// Append existing style's attributed, registered in `StyleManager`, to the receiver string (or substring). /// /// - Parameters: /// - style: valid style name registered in `StyleManager`. /// If invalid, the same instance of the receiver is returned unaltered. /// - range: range of substring where style is applied, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func add(style: String, range: NSRange? = nil) -> AttributedString { guard let style = Styles[style] else { return self } return style.add(to: self, range: range) } /// Append ordered sequence of styles registered in `StyleManager` to the receiver. /// Styles are merged in order to produce a single attribute dictionary which is therefore applied to the string. /// /// - Parameters: /// - styles: ordered list of styles to apply. /// - range: range of substring where style is applied, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func add(styles: [String], range: NSRange? = nil) -> AttributedString { guard let styles = Styles[styles] else { return self } return styles.mergeStyle().set(to: self, range: range) } /// Replace any existing attributed string's style into the receiver/substring of the receiver /// with the style which has the specified name and is registered into `StyleManager`. /// /// - Parameters: /// - style: style name to apply. Style instance must be registered in `StyleManager` to be applied. /// - range: range of substring where style is applied, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func set(style: String, range: NSRange? = nil) -> AttributedString { guard let style = Styles[style] else { return self } return style.set(to: self, range: range) } /// Replace any existing attributed string's style into the receiver/substring of the receiver /// with a style which is an ordered merge of styles passed. /// Styles are passed as name and you must register them into `StyleManager` before using this function. /// /// - Parameters: /// - styles: styles name to apply. Instances must be registered into `StyleManager`. /// - range: range of substring where style is applied, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func set(styles: [String], range: NSRange? = nil) -> AttributedString { guard let styles = Styles[styles] else { return self } return styles.mergeStyle().set(to: self, range: range) } /// Append passed style to the receiver. /// /// - Parameters: /// - style: style to apply. /// - range: range of substring where style is applied, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func add(style: StyleProtocol, range: NSRange? = nil) -> AttributedString { return style.add(to: self, range: range) } /// Append passed sequences of styles to the receiver. /// Sequences are merged in order in a single style's attribute which is therefore applied to the string. /// /// - Parameters: /// - styles: styles to apply, in order. /// - range: range of substring where style is applied, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func add(styles: [StyleProtocol], range: NSRange? = nil) -> AttributedString { return styles.mergeStyle().add(to: self, range: range) } /// Replace the attributes of the string with passed style. /// /// - Parameters: /// - style: style to apply. /// - range: range of substring where style is applied, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func set(style: StyleProtocol, range: NSRange? = nil) -> AttributedString { return style.set(to: self, range: range) } /// Replace the attributes of the string with a style which is an ordered merge of passed /// styles sequence. /// /// - Parameters: /// - styles: ordered list of styles to apply. /// - range: range of substring where style is applied, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func set(styles: [StyleProtocol], range: NSRange? = nil) -> AttributedString { return styles.mergeStyle().set(to: self, range: range) } /// Remove passed attribute's keys from the receiver. /// /// - Parameters: /// - keys: attribute's keys to remove. /// - range: range of substring where style will be removed, `nil` to use the entire string. /// - Returns: same instance of the receiver with - eventually - modified attributes. @discardableResult func removeAttributes(_ keys: [NSAttributedString.Key], range: NSRange) -> Self { keys.forEach { self.removeAttribute($0, range: range) } return self } /// Remove all keys defined into passed style from the receiver. /// /// - Parameter style: style to use. /// - Returns: same instance of the receiver with - eventually - modified attributes. func remove(_ style: StyleProtocol) -> Self { self.removeAttributes(Array(style.attributes.keys), range: NSMakeRange(0, self.length)) return self } } //MARK: - Operations /// Merge two attributed string in a single new attributed string. /// /// - Parameters: /// - lhs: attributed string. /// - rhs: attributed string. /// - Returns: new attributed string concatenation of two strings. public func + (lhs: AttributedString, rhs: AttributedString) -> AttributedString { let final = NSMutableAttributedString(attributedString: lhs) final.append(rhs) return final } /// Merge a plain string with an attributed string to produce a new attributed string. /// /// - Parameters: /// - lhs: plain string. /// - rhs: attributed string. /// - Returns: new attributed string. public func + (lhs: String, rhs: AttributedString) -> AttributedString { let final = NSMutableAttributedString(string: lhs) final.append(rhs) return final } /// Merge an attributed string with a plain string to produce a new attributed string. /// /// - Parameters: /// - lhs: attributed string. /// - rhs: plain string. /// - Returns: new attributed string. public func + (lhs: AttributedString, rhs: String) -> AttributedString { let final = NSMutableAttributedString(attributedString: lhs) final.append(NSMutableAttributedString(string: rhs)) return final }
mit
ae636adc8d87ea351478e2d2218afddc
40.791045
114
0.716905
3.964134
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/MakerBasics/LayoutPropertyCanStoreMiddleLeftType.swift
1
2584
// // LayoutPropertyCanStoreMiddleLeftType.swift // NotAutoLayout // // Created by 史翔新 on 2017/11/12. // Copyright © 2017年 史翔新. All rights reserved. // import UIKit public protocol LayoutPropertyCanStoreMiddleLeftType: LayoutMakerPropertyType { associatedtype WillSetMiddleLeftProperty: LayoutMakerPropertyType func storeMiddleLeft(_ middleLeft: LayoutElement.Point) -> WillSetMiddleLeftProperty } private extension LayoutMaker where Property: LayoutPropertyCanStoreMiddleLeftType { func storeMiddleLeft(_ middleLeft: LayoutElement.Point) -> LayoutMaker<Property.WillSetMiddleLeftProperty> { let newProperty = self.didSetProperty.storeMiddleLeft(middleLeft) let newMaker = self.changintProperty(to: newProperty) return newMaker } } extension LayoutMaker where Property: LayoutPropertyCanStoreMiddleLeftType { public func setMiddleLeft(to middleLeft: Point) -> LayoutMaker<Property.WillSetMiddleLeftProperty> { let middleLeft = LayoutElement.Point.constant(middleLeft) let maker = self.storeMiddleLeft(middleLeft) return maker } public func setMiddleLeft(by middleLeft: @escaping (_ property: ViewLayoutGuides) -> Point) -> LayoutMaker<Property.WillSetMiddleLeftProperty> { let middleLeft = LayoutElement.Point.byParent(middleLeft) let maker = self.storeMiddleLeft(middleLeft) return maker } public func pinMiddleLeft(to referenceView: UIView?, with middleLeft: @escaping (ViewPinGuides.Point) -> Point) -> LayoutMaker<Property.WillSetMiddleLeftProperty> { return self.pinMiddleLeft(by: { [weak referenceView] in referenceView }, with: middleLeft) } public func pinMiddleLeft(by referenceView: @escaping () -> UIView?, with middleLeft: @escaping (ViewPinGuides.Point) -> Point) -> LayoutMaker<Property.WillSetMiddleLeftProperty> { let middleLeft = LayoutElement.Point.byReference(referenceGetter: referenceView, middleLeft) let maker = self.storeMiddleLeft(middleLeft) return maker } } public protocol LayoutPropertyCanStoreMiddleLeftToEvaluateFrameType: LayoutPropertyCanStoreMiddleLeftType { func evaluateFrame(middleLeft: LayoutElement.Point, parameters: IndividualFrameCalculationParameters) -> Rect } extension LayoutPropertyCanStoreMiddleLeftToEvaluateFrameType { public func storeMiddleLeft(_ middleLeft: LayoutElement.Point) -> IndividualProperty.Layout { let layout = IndividualProperty.Layout(frame: { (parameters) -> Rect in return self.evaluateFrame(middleLeft: middleLeft, parameters: parameters) }) return layout } }
apache-2.0
0429e8801c22cea453d08bb2ac4b6d1d
28.528736
181
0.781627
4.414089
false
false
false
false
stripe/stripe-ios
StripeIdentity/StripeIdentityTests/Unit/VerificationSheetAnalyticsTest.swift
1
2676
// // VerificationSheetAnalyticsTest.swift // StripeIdentityTests // // Created by Mel Ludowise on 3/12/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // @_spi(STP) import StripeCore import XCTest @testable import StripeIdentity final class VerificationSheetAnalyticsTest: XCTestCase { func testVerificationSheetFailedAnalyticEncoding() { let analytic = VerificationSheetFailedAnalytic( verificationSessionId: nil, error: IdentityVerificationSheetError.unknown(debugDescription: "some description") ) XCTAssertNotNil(analytic.error) let errorDict = analytic.error.serializeForLogging() XCTAssertNil(errorDict["user_info"]) XCTAssertEqual(errorDict["code"] as? Int, 1) XCTAssertEqual( errorDict["domain"] as? String, "StripeIdentity.IdentityVerificationSheetError" ) } func testVerificationSheetCompletionAnalyticCompleted() { let analytic = VerificationSheetCompletionAnalytic.make( verificationSessionId: "session_id", sessionResult: .flowCompleted ) guard let closedAnalytic = analytic as? VerificationSheetClosedAnalytic else { return XCTFail("Expected `VerificationSheetClosedAnalytic`") } XCTAssertEqual(closedAnalytic.verificationSessionId, "session_id") XCTAssertEqual(closedAnalytic.sessionResult, "flow_completed") } func testVerificationSheetCompletionAnalyticCanceled() { let analytic = VerificationSheetCompletionAnalytic.make( verificationSessionId: "session_id", sessionResult: .flowCanceled ) guard let closedAnalytic = analytic as? VerificationSheetClosedAnalytic else { return XCTFail("Expected `VerificationSheetClosedAnalytic`") } XCTAssertEqual(closedAnalytic.verificationSessionId, "session_id") XCTAssertEqual(closedAnalytic.sessionResult, "flow_canceled") } func testVerificationSheetCompletionAnalyticFailed() { let analytic = VerificationSheetCompletionAnalytic.make( verificationSessionId: "session_id", sessionResult: .flowFailed( error: IdentityVerificationSheetError.unknown(debugDescription: "some description") ) ) guard let failedAnalytic = analytic as? VerificationSheetFailedAnalytic else { return XCTFail("Expected `VerificationSheetFailedAnalytic`") } XCTAssertEqual(failedAnalytic.verificationSessionId, "session_id") XCTAssert(failedAnalytic.error is IdentityVerificationSheetError) } }
mit
d0c40f87f88ddc9d747f99b5ca32a882
36.152778
99
0.699065
5.459184
false
true
false
false
shial4/api-loltracker
Sources/App/Models/User.swift
1
1907
// // User.swift // lolTracker-API // // Created by Shial on 16/01/2017. // // import Foundation import Vapor import Fluent final class User: Model { var exists: Bool = false public var id: Node? var summonerId: Node? var facebook: String init(facebook: String, summonerId: Node? = nil) { self.id = nil self.summonerId = summonerId self.facebook = facebook } required init(node: Node, in context: Context) throws { id = try node.extract("id") facebook = try node.extract("facebook") do { summonerId = try node.extract("summoner_id") } catch { return } } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "facebook": facebook, "summoner_id": summonerId ]) } } extension User: Preparation { static func prepare(_ database: Database) throws { try database.create(entity, closure: { (user) in user.id() user.string("facebook") user.parent(Summoner.self, optional: true) }) } static func revert(_ database: Database) throws { try database.delete(entity) } } extension User { func from(facebook id: String) throws -> User { guard let user = try User.query().filter("facebook", .equals, id).first() else { return User(facebook: facebook) } return user } func summoner() throws -> Summoner? { guard let id = summonerId else { throw Abort.notFound } return try parent(id, nil, Summoner.self).get() } func summoners() throws -> [Summoner]? { guard let id = summonerId else { throw Abort.notFound } return try parent(id, nil, Summoner.self).all() } }
mit
678bc00504c597831addab6f909067df
22.8375
88
0.551652
4.219027
false
false
false
false
anthonygeranio/CloudKit-To-Do-List
C2D/CloudKitToDoList/ASGNewTaskViewController.swift
1
1749
// // ASGNewTaskViewController.swift // CloudKitToDoList // // Created by Anthony Geranio on 1/15/15. // Copyright (c) 2015 Sleep Free. All rights reserved. // import Foundation import UIKit import CloudKit class ASGNewTaskViewController: UIViewController, UITableViewDelegate, UITextViewDelegate { // UITextView for task description. @IBOutlet var taskDescriptionTextView: UITextView! // Function to add a task to the iCloud database func addTask() { navigationController?.popViewControllerAnimated(true) // Create record to save tasks var record: CKRecord = CKRecord(recordType: "task") // Save task description for key: taskKey record.setObject(self.taskDescriptionTextView.text, forKey: "taskKey") // Create the private database for the user to save their data to var database: CKDatabase = CKContainer.defaultContainer().privateCloudDatabase // Save the data to the database for the record: task func recordSaved(record: CKRecord?, error: NSError?) { if (error != nil) { // handle it println(error) } } // Save data to the database for the record: task database.saveRecord(record, completionHandler: recordSaved) } // MARK: Lifecycle override func viewDidLoad() { // Create done button to add a task var doneButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("addTask")) self.navigationItem.rightBarButtonItem = doneButton self.taskDescriptionTextView.becomeFirstResponder() } }
mit
75cfea3bb9332538d19739a67fe62783
32
150
0.655803
5.268072
false
false
false
false
CodePath2017Group4/travel-app
RoadTripPlanner/FriendsListViewController.swift
1
6552
// // FriendsListViewController.swift // RoadTripPlanner // // Created by Diana Fisher on 10/23/17. // Copyright © 2017 RoadTripPlanner. All rights reserved. // import UIKit import Parse class FriendsListViewController: UIViewController { static func storyboardInstance() -> FriendsListViewController? { let storyboard = UIStoryboard(name: "FriendsListViewController", bundle: nil) return storyboard.instantiateInitialViewController() as? FriendsListViewController } @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! var trip: Trip? var knownTripMember: [TripMember] = [] var friends: [(PFUser, TripMember?)] = [] var selectedIndex: Int = -1 var delegate: InviteUserDelegate? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Constants.Colors.ViewBackgroundColor tableView.delegate = self tableView.dataSource = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 80 navigationItem.title = "Invite Friends" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Invite", style: .plain, target: self, action: #selector(inviteTapped)) searchBar.tintColor = Constants.Colors.NavigationBarLightTintColor ParseBackend.getUsers { (users, error) in if error == nil { self.zipFriendsAndKnownUsers(users: users!) DispatchQueue.main.async { self.tableView.reloadData() } } else { log.error(error!) } } } private func zipFriendsAndKnownUsers(users: [PFUser]) { self.friends = [] for user in users { var found: TripMember? = nil for curMember in self.knownTripMember { if (curMember.user.username == user.username) { log.info("User is already on the trip!") found = curMember } } self.friends.append((user, found)) } } // override func viewWillDisappear(_ animated: Bool) { // super.viewWillDisappear(animated) // // navigationController?.navigationBar.tintColor = UIColor.white // let textAttributes = [NSForegroundColorAttributeName:UIColor.white] // navigationController?.navigationBar.titleTextAttributes = textAttributes // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func inviteTapped(_ sender: Any) { // Add selected user to the trip guard let trip = self.trip else { log.info("No trip to add friends to") return } guard selectedIndex >= 0 else { log.info("No friend is selected") return } guard friends[self.selectedIndex].1 == nil else { log.info("User is already on the trip!") return } let selectedUser = friends[self.selectedIndex].0 let tripMember = TripMember(user: selectedUser, isCreator: false, trip: trip) friends[self.selectedIndex].1 = tripMember if let delegate = self.delegate { delegate.addInvitation(tripMember: tripMember) } tripMember.saveInBackground(block: { (success, error) in if (error != nil) { log.error("Error inviting trip member: \(error!)") } else { log.info("TripMember invited") } }) self.tableView.reloadData() } } extension FriendsListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return friends.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.ReuseableCellIdentifiers.FriendUserCell, for: indexPath) as! FriendUserCell cell.user = friends[indexPath.row].0 if let tripMember = friends[indexPath.row].1 { if (tripMember.isCreatingUser) { cell.setStatus(onTrip: InviteStatus.Confirmed.hashValue) } else { cell.setStatus(onTrip: tripMember.status) } } else { cell.setStatus(onTrip: -1) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (self.selectedIndex >= 0) { tableView.deselectRow(at: IndexPath(row: self.selectedIndex, section: 0), animated: true) } self.selectedIndex = indexPath.row } // ParseBackend.getTripsCreatedByUser(user: selectedUser) { (trips, error) in // if (error == nil) { // log.info("\(selectedUser.username ?? "") has created \(trips!.count) trips.") // for trip in trips! { // log.info(trip.name!) // // let members = trip.getTripMembers() // log.info("There are \(members.count) members on this trip.") // for m in members { // m.fetchIfNeededInBackground(block: { (object: PFObject?, error: Error?) in // let user = m.user // user.fetchIfNeededInBackground(block: { (object: PFObject?, error: Error?) in // log.info("\(m.user.username ?? "No name") has status \(m.status)") // }) // }) // // // } // } // } // } // trip.saveInBackground { (success, error) in // if success { // log.info("Trip saved") // } else { // guard let error = error else { // log.error("Unknown error occurred saving trip \(trip.name)") // return // } // log.error("Error saving trip: \(error)") // } // } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } }
mit
eacc38cbe04ce0328fa60b4378b37391
35.19337
150
0.561136
5.09409
false
false
false
false
daltoniam/Jazz
Sources/Jazz.swift
1
6313
// // Animator.swift // // Created by Dalton Cherry on 3/10/15. // Copyright (c) 2015 Vluxe. All rights reserved. // import UIKit public enum CurveType { case linear case easeIn case easeOut case easeInOut } class Pending { let duration: Double let animations: (() -> Void) let type: CurveType var delay: Double? init(_ duration: Double, _ type: CurveType = .linear, _ animations: @escaping (() -> Void)) { self.duration = duration self.animations = animations self.type = type } } open class Jazz { fileprivate var pending = Array<Pending>() //convenience that starts the running public init(_ duration: Double = 0.25, type: CurveType = .linear, animations: @escaping (() -> Void)) { play(duration, type: type, animations: animations) } public init(delayTime: Double) { delay(delayTime) } //queue some animations @discardableResult open func play(_ duration: Double = 0.25, delay: Double = 0, type: CurveType = .linear, animations: @escaping (() -> Void)) -> Jazz { var should = false if pending.count == 0 { should = true } pending.append(Pending(duration,.linear,animations)) if should { start(pending[0]) } return self } //An animation finished running @discardableResult open func delay(_ time: Double) -> Jazz { let anim = Pending(0,.linear,{}) anim.delay = time var should = false if pending.count == 0 { should = true } pending.append(anim) if should { start(pending[0]) } return self } //turn a CurveType into the corresponding UIViewAnimationCurve class open func valueForCurve(_ type: CurveType) -> UIViewAnimationCurve { switch type { case .easeIn: return .easeIn case .easeInOut: return .easeInOut case .easeOut: return .easeOut default: return .linear } } class open func timeFunctionForCurve(_ type: CurveType) -> CAMediaTimingFunction { return CAMediaTimingFunction(name: timingFunctionNameForCurve(type)) } //turn a CurveType into the corresponding UIViewAnimationCurve class fileprivate func timingFunctionNameForCurve(_ type: CurveType) -> String { switch type { case .easeIn: return kCAMediaTimingFunctionEaseIn case .easeInOut: return kCAMediaTimingFunctionEaseInEaseOut case .easeOut: return kCAMediaTimingFunctionEaseOut default: return kCAMediaTimingFunctionLinear } } //create a basic animation from the standard properties class open func createAnimation(_ duration: CFTimeInterval = CATransaction.animationDuration(), type: CAMediaTimingFunction = Jazz.timingFunction(), key: String) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: key) animation.duration = duration //animation.beginTime = CACurrentMediaTime() + delay animation.timingFunction = type return animation } //get the timing function or use the default one class open func timingFunction() -> CAMediaTimingFunction { if let type = CATransaction.animationTimingFunction() { return type } return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) } //creates a random key that is for a single animation class open func oneShotKey() -> String { let letters = "abcdefghijklmnopqurstuvwxyz" var str = "" for _ in 0 ..< 14 { let start = Int(arc4random() % 14) str.append(letters[letters.characters.index(letters.startIndex, offsetBy: start)]) } return "vluxe\(str)" } //private method that actually runs the animation fileprivate func start(_ current: Pending) { if let d = current.delay { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(d * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { self.doFinish() } } else { UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(current.duration) UIView.setAnimationCurve(Jazz.valueForCurve(current.type)) CATransaction.setCompletionBlock { self.doFinish() } current.animations() UIView.commitAnimations() } } //finish a pending animation fileprivate func doFinish() { pending.remove(at: 0) if pending.count > 0 { start(pending[0]) } } //built in handy animations ///Public class methods to manipulate views ///Change the frame of a view open class func updateFrame(_ view :UIView, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { var fr = view.frame fr.origin.x = x fr.origin.y = y fr.size.width = width fr.size.height = height view.frame = fr } //move the view around open class func moveView(_ view :UIView, x: CGFloat, y: CGFloat) { updateFrame(view, x: x, y: y, width: view.frame.size.width, height: view.frame.size.height) } //change the size of the view open class func resizeView(_ view :UIView, width: CGFloat, height: CGFloat) { updateFrame(view, x: view.frame.origin.x, y: view.frame.origin.y, width: width, height: height) } //expand the size of the view open class func expandView(_ view :UIView, scale: CGFloat) { let w = view.frame.size.width*scale let h = view.frame.size.height*scale let x = view.frame.origin.x - (w - view.frame.size.width)/2 let y = view.frame.origin.y - (h - view.frame.size.height)/2 updateFrame(view, x: x, y: y, width: w, height: h) } //rotate the view open class func rotateView(_ view: UIView, degrees: CGFloat) { view.transform = view.transform.rotated(by: degreesToRadians(degrees)); } open class func degreesToRadians(_ degrees: CGFloat) -> CGFloat { return ((3.14159265359 * degrees)/180) } }
apache-2.0
a61f6debbe54dab1e9354738d7a57599
32.226316
156
0.61207
4.641912
false
false
false
false
eneko/SourceDocs
Sources/SourceDocsLib/DocumentationGenerator/DocumentationGenerator.swift
1
9933
// // DocumentationGenerator.swift // SourceDocsLib // // Created by Eneko Alonso on 4/26/20. // import Foundation import SourceKittenFramework /// Configuration for DocumentationGenerator /// /// - Parameters: /// - allModules: Generate documentation for all modules in a Swift package. /// - spmModule: Generate documentation for Swift Package Manager module. /// - moduleName: Generate documentation for a Swift module. /// - linkBeginningText: The text to begin links with. Defaults to an empty string. /// - linkEndingText: The text to end links with. Defaults to '.md'. /// - inputFolder: Path to the input directory. /// - outputFolder: Output directory. /// - minimumAccessLevel: The minimum access level to generate documentation. Defaults to public. /// - includeModuleNameInPath: Include the module name as part of the output folder path. Defaults to false. /// - clean: Delete output folder before generating documentation. Defaults to false. /// - collapsibleBlocks: Put methods, properties and enum cases inside collapsible blocks. Defaults to false. /// - tableOfContents: Generate a table of contents with properties and methods for each type. Defaults to false. /// - xcodeArguments: Array of `String` arguments to pass to xcodebuild. Defaults to an empty array. /// - reproducibleDocs: generate documentation that is reproducible: only depends on the sources. /// For example, this will avoid adding timestamps on the generated files. Defaults to false. public struct DocumentOptions { public let allModules: Bool public let spmModule: String? public let moduleName: String? public let linkBeginningText: String public let linkEndingText: String public let inputFolder: String public let outputFolder: String public let minimumAccessLevel: AccessLevel public var includeModuleNameInPath: Bool public let clean: Bool public let collapsibleBlocks: Bool public let tableOfContents: Bool public let xcodeArguments: [String] public let reproducibleDocs: Bool public init(allModules: Bool, spmModule: String?, moduleName: String?, linkBeginningText: String = "", linkEndingText: String = ".md", inputFolder: String, outputFolder: String, minimumAccessLevel: AccessLevel = .public, includeModuleNameInPath: Bool = false, clean: Bool = false, collapsibleBlocks: Bool = false, tableOfContents: Bool = false, xcodeArguments: [String] = [], reproducibleDocs: Bool = false) { self.allModules = allModules self.spmModule = spmModule self.moduleName = moduleName self.linkBeginningText = linkBeginningText self.linkEndingText = linkEndingText self.inputFolder = inputFolder self.outputFolder = outputFolder self.minimumAccessLevel = minimumAccessLevel self.includeModuleNameInPath = includeModuleNameInPath self.clean = clean self.collapsibleBlocks = collapsibleBlocks self.tableOfContents = tableOfContents self.xcodeArguments = xcodeArguments self.reproducibleDocs = reproducibleDocs } } public final class DocumentationGenerator { var options: DocumentOptions let markdownIndex: MarkdownIndex public init(options: DocumentOptions) { self.options = options self.markdownIndex = MarkdownIndex() } public func run() throws { markdownIndex.reset() do { if options.allModules { options.includeModuleNameInPath = true try PackageLoader.resolveDependencies(at: options.inputFolder) let packageDump = try PackageLoader.loadPackageDump(from: options.inputFolder) for target in packageDump.targets where target.type == .regular { let docs = try parseSPMModule(moduleName: target.name, path: options.inputFolder) try generateDocumentation(docs: docs, module: target.name, options: options) } } else if let module = options.spmModule { let docs = try parseSPMModule(moduleName: module, path: options.inputFolder) try generateDocumentation(docs: docs, module: module, options: options) } else if let module = options.moduleName { let docs = try parseSwiftModule(moduleName: module, args: options.xcodeArguments, path: options.inputFolder) try generateDocumentation(docs: docs, module: module, options: options) } else { let docs = try parseXcodeProject(args: options.xcodeArguments, path: options.inputFolder) try generateDocumentation(docs: docs, module: "", options: options) } fputs("Done 🎉\n".green, stdout) } catch let error as SourceDocsError { throw error } catch let error { throw SourceDocsError.internalError(message: error.localizedDescription) } } private func parseSPMModule(moduleName: String, path: String) throws -> [SwiftDocs] { fputs("Processing SwiftPM module \(moduleName)...\n", stdout) guard let docs = Module(spmName: moduleName, inPath: path)?.docs else { let message = "Error: Failed to generate documentation for SwiftPM module '\(moduleName)'." throw SourceDocsError.internalError(message: message) } return docs } private func parseSwiftModule(moduleName: String, args: [String], path: String) throws -> [SwiftDocs] { fputs("Processing Swift module \(moduleName)...\n", stdout) guard let docs = Module(xcodeBuildArguments: args, name: moduleName, inPath: path)?.docs else { let message = "Error: Failed to generate documentation for module '\(moduleName)'." throw SourceDocsError.internalError(message: message) } return docs } private func parseXcodeProject(args: [String], path: String) throws -> [SwiftDocs] { fputs("Processing Xcode project with arguments \(args)...\n", stdout) guard let docs = Module(xcodeBuildArguments: args, name: nil, inPath: path)?.docs else { throw SourceDocsError.internalError(message: "Error: Failed to generate documentation.") } return docs } private func generateDocumentation(docs: [SwiftDocs], module: String, options: DocumentOptions) throws { let docsPath = options.includeModuleNameInPath ? "\(options.outputFolder)/\(module)" : options.outputFolder if options.clean { try DocumentationEraser(docsPath: docsPath).run() } process(docs: docs) try markdownIndex.write(to: docsPath, linkBeginningText: options.linkBeginningText, linkEndingText: options.linkEndingText, options: options) markdownIndex.reset() } private func process(docs: [SwiftDocs]) { let dictionaries = docs.compactMap { $0.docsDictionary.bridge() as? SwiftDocDictionary } process(dictionaries: dictionaries) } private func process(dictionaries: [SwiftDocDictionary]) { dictionaries.forEach { process(dictionary: $0) } } private func process(dictionary: SwiftDocDictionary) { let markdownOptions = MarkdownOptions(collapsibleBlocks: options.collapsibleBlocks, tableOfContents: options.tableOfContents, minimumAccessLevel: options.minimumAccessLevel) if let value: String = dictionary.get(.kind), let kind = SwiftDeclarationKind(rawValue: value) { if kind == .struct, let item = MarkdownObject(dictionary: dictionary, options: markdownOptions) { markdownIndex.structs.append(item) } else if kind == .class, let item = MarkdownObject(dictionary: dictionary, options: markdownOptions) { markdownIndex.classes.append(item) } else if let item = MarkdownExtension(dictionary: dictionary, options: markdownOptions) { markdownIndex.extensions.append(item) } else if let item = MarkdownEnum(dictionary: dictionary, options: markdownOptions) { markdownIndex.enums.append(item) } else if let item = MarkdownProtocol(dictionary: dictionary, options: markdownOptions) { markdownIndex.protocols.append(item) } else if let item = MarkdownTypealias(dictionary: dictionary, options: markdownOptions) { markdownIndex.typealiases.append(item) } else if kind == .functionFree, let item = MarkdownMethod(dictionary: dictionary, options: markdownOptions) { markdownIndex.methods.append(item) } } if let substructure = dictionary[SwiftDocKey.substructure.rawValue] as? [SwiftDocDictionary] { let substructureWithParent: [SwiftDocDictionary] if let parentName: String = dictionary.get(.name) { substructureWithParent = substructure.map { var dict = $0 dict.parentNames.append(parentName) return dict } } else { substructureWithParent = substructure } process(dictionaries: substructureWithParent) } } } extension DocumentationGenerator { static func generateFooter(reproducibleDocs: Bool) -> String { var footer = """ This file was generated by [SourceDocs](https://github.com/eneko/SourceDocs) """ if reproducibleDocs == false { footer.append(" on \(Date().description)") } return footer } }
mit
4d8ea4a211a2b05d1d0d2422c99290f8
46.740385
115
0.651863
5.071502
false
false
false
false
bhajian/raspi-remote
Carthage/Checkouts/ios-sdk/Source/AlchemyVisionV1/Tests/AlchemyVisionTests.swift
1
34452
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import XCTest import AlchemyVisionV1 class AlchemyVisionTests: XCTestCase { private var alchemyVision: AlchemyVision! private let timeout: NSTimeInterval = 10.0 private var car: NSData! private var obama: NSData! private var sign: NSData! private var thomas: NSData! private var html: NSURL! private var htmlContents: String! private let htmlImageName = "cp_1234354872_16947v1-max-250x250.jpg" private let obamaURL = "https://www.whitehouse.gov/sites/whitehouse.gov/files/images/" + "Administration/People/president_official_portrait_lores.jpg" private let carURL = "https://raw.githubusercontent.com/watson-developer-cloud/" + "java-sdk/master/src/test/resources/visual_recognition/car.png" private let signURL = "https://cdn.rawgit.com/watson-developer-cloud/ios-sdk/master/Source/" + "AlchemyVisionV1/Tests/sign.jpg" private let htmlURL = "https://cdn.rawgit.com/watson-developer-cloud/ios-sdk/master/Source" + "/AlchemyVisionV1/Tests/example.html" // MARK: - Test Configuration /** Set up for each test by instantiating the service. */ override func setUp() { super.setUp() continueAfterFailure = false instantiateAlchemyVision() loadResources() } /** Instantiate Alchemy Vision. */ func instantiateAlchemyVision() { let bundle = NSBundle(forClass: self.dynamicType) guard let file = bundle.pathForResource("Credentials", ofType: "plist"), let credentials = NSDictionary(contentsOfFile: file) as? [String: String], let apiKey = credentials["AlchemyAPIKey"] else { XCTFail("Unable to read credentials.") return } alchemyVision = AlchemyVision(apiKey: apiKey) } /** Load image files with class examples and test images. */ func loadResources() { let bundle = NSBundle(forClass: self.dynamicType) guard let car = NSData(contentsOfURL: bundle.URLForResource("car", withExtension: "png")!), let obama = NSData(contentsOfURL: bundle.URLForResource("obama", withExtension: "jpg")!), let sign = NSData(contentsOfURL: bundle.URLForResource("sign", withExtension: "jpg")!), let thomas = NSData(contentsOfURL: bundle.URLForResource("thomas", withExtension: "png")!), let html = bundle.URLForResource("example", withExtension: "html") else { XCTFail("Unable to locate testing resources.") return } self.car = car self.obama = obama self.sign = sign self.thomas = thomas self.html = html self.htmlContents = try? String(contentsOfURL: html) guard self.htmlContents != nil else { XCTFail("Unable to load html example as String.") return } } /** Fail false negatives. */ func failWithError(error: NSError) { XCTFail("Positive test failed with error: \(error)") } /** Fail false positives. */ func failWithResult<T>(result: T) { XCTFail("Negative test returned a result.") } /** Wait for expectations. */ func waitForExpectations() { waitForExpectationsWithTimeout(timeout) { error in XCTAssertNil(error, "Timeout") } } // MARK: - Positive Tests func testGetRankedImageFaceTagsImage1() { let description = "Perform face recognition on an uploaded image." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageFaceTags(image: obama, failure: failWithError) { faceTags in // verify faceTags structure XCTAssertEqual(faceTags.status, "OK") XCTAssertEqual(faceTags.totalTransactions, 4) XCTAssertNil(faceTags.url) XCTAssertEqual(faceTags.imageFaces.count, 1) let face = faceTags.imageFaces.first // verify face age XCTAssertEqual(face?.age.ageRange, "55-64") XCTAssert(face?.age.score >= 0.0) XCTAssert(face?.age.score <= 1.0) // verify face gender XCTAssertEqual(face?.gender.gender, "MALE") XCTAssert(face?.gender.score >= 0.0) XCTAssert(face?.gender.score <= 1.0) // verify face location XCTAssert(face?.height >= 0) XCTAssert(face?.height <= 300) XCTAssert(face?.width >= 0) XCTAssert(face?.width <= 300) XCTAssert(face?.positionX >= 0) XCTAssert(face?.positionX <= 300) XCTAssert(face?.positionY >= 0) XCTAssert(face?.positionY <= 300) // verify face identity (We know Obama is a celebrity and we should get an Identity -> Fore Unwrap) XCTAssertEqual(face?.identity!.name, "Barack Obama") XCTAssert(face?.identity!.score >= 0.0) XCTAssert(face?.identity!.score <= 1.0) // verify face identity knowledge graph XCTAssertNil(face?.identity!.knowledgeGraph) // verify face identity disambiguation XCTAssertEqual(face?.identity!.disambiguated.name, "Barack Obama") XCTAssertEqual(face?.identity!.disambiguated.website, "http://www.whitehouse.gov/") XCTAssertEqual(face?.identity!.disambiguated.dbpedia, "http://dbpedia.org/resource/Barack_Obama") XCTAssertEqual(face?.identity!.disambiguated.yago, "http://yago-knowledge.org/resource/Barack_Obama") XCTAssertNil(face?.identity!.disambiguated.opencyc) XCTAssertNil(face?.identity!.disambiguated.umbel) XCTAssertEqual(face?.identity!.disambiguated.freebase, "http://rdf.freebase.com/ns/m.02mjmr") XCTAssertNil(face?.identity!.disambiguated.crunchbase) XCTAssert(face?.identity!.disambiguated.subType?.contains("Person") == true) XCTAssert(face?.identity!.disambiguated.subType?.contains("Politician") == true) XCTAssert(face?.identity!.disambiguated.subType?.contains("President") == true) expectation.fulfill() } waitForExpectations() } func testGetRankedImageFaceTagsImage2() { let description = "Perform face recognition on an uploaded image." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageFaceTags(image: obama, knowledgeGraph: true, failure: failWithError) { faceTags in // verify faceTags structure XCTAssertEqual(faceTags.status, "OK") XCTAssertEqual(faceTags.totalTransactions, 5) XCTAssertNil(faceTags.url) XCTAssertEqual(faceTags.imageFaces.count, 1) let face = faceTags.imageFaces.first // verify face age XCTAssertEqual(face?.age.ageRange, "55-64") XCTAssert(face?.age.score >= 0.0) XCTAssert(face?.age.score <= 1.0) // verify face gender XCTAssertEqual(face?.gender.gender, "MALE") XCTAssert(face?.gender.score >= 0.0) XCTAssert(face?.gender.score <= 1.0) // verify face location XCTAssert(face?.height >= 0) XCTAssert(face?.height <= 300) XCTAssert(face?.width >= 0) XCTAssert(face?.width <= 300) XCTAssert(face?.positionX >= 0) XCTAssert(face?.positionX <= 300) XCTAssert(face?.positionY >= 0) XCTAssert(face?.positionY <= 300) // verify face identity (We know Obama is a celebrity and we should get an Identity -> Fore Unwrap) XCTAssertEqual(face?.identity!.name, "Barack Obama") XCTAssert(face?.identity!.score >= 0.0) XCTAssert(face?.identity!.score <= 1.0) // verify face identity knowledge graph XCTAssertEqual(face?.identity!.knowledgeGraph?.typeHierarchy, "/people/politicians/democrats/barack obama") // verify face identity disambiguation XCTAssertEqual(face?.identity!.disambiguated.name, "Barack Obama") XCTAssertEqual(face?.identity!.disambiguated.website, "http://www.whitehouse.gov/") XCTAssertEqual(face?.identity!.disambiguated.dbpedia, "http://dbpedia.org/resource/Barack_Obama") XCTAssertEqual(face?.identity!.disambiguated.yago, "http://yago-knowledge.org/resource/Barack_Obama") XCTAssertNil(face?.identity!.disambiguated.opencyc) XCTAssertNil(face?.identity!.disambiguated.umbel) XCTAssertEqual(face?.identity!.disambiguated.freebase, "http://rdf.freebase.com/ns/m.02mjmr") XCTAssertNil(face?.identity!.disambiguated.crunchbase) XCTAssert(face?.identity!.disambiguated.subType?.contains("Person") == true) XCTAssert(face?.identity!.disambiguated.subType?.contains("Politician") == true) XCTAssert(face?.identity!.disambiguated.subType?.contains("President") == true) expectation.fulfill() } waitForExpectations() } func testGetRankedImageFaceTagsImageWithoutIdentity() { let description = "Perform face recognition on an uploaded image with no Celebrity Identity." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageFaceTags(image: thomas, failure: failWithError) { faceTags in // verify faceTags structure XCTAssertEqual(faceTags.status, "OK") XCTAssertEqual(faceTags.totalTransactions, 4) XCTAssertNil(faceTags.url) XCTAssertEqual(faceTags.imageFaces.count, 1) let face = faceTags.imageFaces.first // verify face identity (We know Thomas is a not a celebrity right now -> No Identitiy) XCTAssert(face?.identity == nil) expectation.fulfill() } waitForExpectations() } func testGetRankedImageFaceTagsURL1() { let description = "Perform face recognition on the image at a given URL." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageFaceTags(url: obamaURL, failure: failWithError) { faceTags in // verify faceTags structure XCTAssertEqual(faceTags.status, "OK") XCTAssertEqual(faceTags.totalTransactions, 4) XCTAssertEqual(faceTags.url, self.obamaURL) XCTAssertEqual(faceTags.imageFaces.count, 1) let face = faceTags.imageFaces.first // verify face age XCTAssertEqual(face?.age.ageRange, "55-64") XCTAssert(face?.age.score >= 0.0) XCTAssert(face?.age.score <= 1.0) // verify face gender XCTAssertEqual(face?.gender.gender, "MALE") XCTAssert(face?.gender.score >= 0.0) XCTAssert(face?.gender.score <= 1.0) // verify face location XCTAssert(face?.height >= 0) XCTAssert(face?.height <= 300) XCTAssert(face?.width >= 0) XCTAssert(face?.width <= 300) XCTAssert(face?.positionX >= 0) XCTAssert(face?.positionX <= 300) XCTAssert(face?.positionY >= 0) XCTAssert(face?.positionY <= 300) // verify face identity XCTAssertEqual(face?.identity!.name, "Barack Obama") XCTAssert(face?.identity!.score >= 0.0) XCTAssert(face?.identity!.score <= 1.0) // verify face identity knowledge graph XCTAssertNil(face?.identity!.knowledgeGraph) // verify face identity disambiguation XCTAssertEqual(face?.identity!.disambiguated.name, "Barack Obama") XCTAssertEqual(face?.identity!.disambiguated.website, "http://www.whitehouse.gov/") XCTAssertEqual(face?.identity!.disambiguated.dbpedia, "http://dbpedia.org/resource/Barack_Obama") XCTAssertEqual(face?.identity!.disambiguated.yago, "http://yago-knowledge.org/resource/Barack_Obama") XCTAssertNil(face?.identity!.disambiguated.opencyc) XCTAssertNil(face?.identity!.disambiguated.umbel) XCTAssertEqual(face?.identity!.disambiguated.freebase, "http://rdf.freebase.com/ns/m.02mjmr") XCTAssertNil(face?.identity!.disambiguated.crunchbase) XCTAssert(face?.identity!.disambiguated.subType?.contains("Person") == true) XCTAssert(face?.identity!.disambiguated.subType?.contains("Politician") == true) XCTAssert(face?.identity!.disambiguated.subType?.contains("President") == true) expectation.fulfill() } waitForExpectations() } func testGetRankedImageFaceTagsURL2() { let description = "Perform face recognition on the image at a given URL." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageFaceTags(url: obamaURL, knowledgeGraph: true, failure: failWithError) { faceTags in // verify faceTags structure XCTAssertEqual(faceTags.status, "OK") XCTAssertEqual(faceTags.totalTransactions, 5) XCTAssertEqual(faceTags.url, self.obamaURL) XCTAssertEqual(faceTags.imageFaces.count, 1) let face = faceTags.imageFaces.first // verify face age XCTAssertEqual(face?.age.ageRange, "55-64") XCTAssert(face?.age.score >= 0.0) XCTAssert(face?.age.score <= 1.0) // verify face gender XCTAssertEqual(face?.gender.gender, "MALE") XCTAssert(face?.gender.score >= 0.0) XCTAssert(face?.gender.score <= 1.0) // verify face location XCTAssert(face?.height >= 0) XCTAssert(face?.height <= 300) XCTAssert(face?.width >= 0) XCTAssert(face?.width <= 300) XCTAssert(face?.positionX >= 0) XCTAssert(face?.positionX <= 300) XCTAssert(face?.positionY >= 0) XCTAssert(face?.positionY <= 300) // verify face identity (We know Obama is a celebrity and we should get an Identity -> Fore Unwrap) XCTAssertEqual(face?.identity!.name, "Barack Obama") XCTAssert(face?.identity!.score >= 0.0) XCTAssert(face?.identity!.score <= 1.0) // verify face identity knowledge graph XCTAssertEqual(face?.identity!.knowledgeGraph?.typeHierarchy, "/people/politicians/democrats/barack obama") // verify face identity disambiguation XCTAssertEqual(face?.identity!.disambiguated.name, "Barack Obama") XCTAssertEqual(face?.identity!.disambiguated.website, "http://www.whitehouse.gov/") XCTAssertEqual(face?.identity!.disambiguated.dbpedia, "http://dbpedia.org/resource/Barack_Obama") XCTAssertEqual(face?.identity!.disambiguated.yago, "http://yago-knowledge.org/resource/Barack_Obama") XCTAssertNil(face?.identity!.disambiguated.opencyc) XCTAssertNil(face?.identity!.disambiguated.umbel) XCTAssertEqual(face?.identity!.disambiguated.freebase, "http://rdf.freebase.com/ns/m.02mjmr") XCTAssertNil(face?.identity!.disambiguated.crunchbase) XCTAssert(face?.identity!.disambiguated.subType?.contains("Person") == true) XCTAssert(face?.identity!.disambiguated.subType?.contains("Politician") == true) XCTAssert(face?.identity!.disambiguated.subType?.contains("President") == true) expectation.fulfill() } waitForExpectations() } func testGetImageHTMLFile1() { let description = "Identify the primary image in an HTML file." let expectation = expectationWithDescription(description) alchemyVision.getImage(html: html, failure: failWithError) { imageLinks in XCTAssertEqual(imageLinks.status, "OK") XCTAssertEqual(imageLinks.url, "") XCTAssert(imageLinks.image.containsString(self.htmlImageName)) expectation.fulfill() } waitForExpectations() } func testGetImageHTMLFile2() { let description = "Identify the primary image in an HTML file." let expectation = expectationWithDescription(description) alchemyVision.getImage(html: html, url: htmlURL, failure: failWithError) { imageLinks in XCTAssertEqual(imageLinks.status, "OK") XCTAssertEqual(imageLinks.url, self.htmlURL) XCTAssert(imageLinks.image.containsString(self.htmlImageName)) expectation.fulfill() } waitForExpectations() } func testGetImageHTMLContents1() { let description = "Identify the primary image in an HTML document." let expectation = expectationWithDescription(description) alchemyVision.getImage(html: htmlContents, failure: failWithError) { imageLinks in XCTAssertEqual(imageLinks.status, "OK") XCTAssertEqual(imageLinks.url, "") XCTAssert(imageLinks.image.containsString(self.htmlImageName)) expectation.fulfill() } waitForExpectations() } func testGetImageHTMLContents2() { let description = "Identify the primary image in an HTML document." let expectation = expectationWithDescription(description) alchemyVision.getImage(html: htmlContents, url: htmlURL, failure: failWithError) { imageLinks in XCTAssertEqual(imageLinks.status, "OK") XCTAssertEqual(imageLinks.url, self.htmlURL) XCTAssert(imageLinks.image.containsString(self.htmlImageName)) expectation.fulfill() } waitForExpectations() } func testGetImageURL() { let description = "Identify the primary image at a given URL." let expectation = expectationWithDescription(description) alchemyVision.getImage(url: htmlURL, failure: failWithError) { imageLinks in XCTAssertEqual(imageLinks.status, "OK") XCTAssertEqual(imageLinks.url, self.htmlURL) XCTAssert(imageLinks.image.containsString(self.htmlImageName)) expectation.fulfill() } waitForExpectations() } func testGetRankedImageKeywordsImage1() { let description = "Perform image tagging on an uploaded image." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageKeywords(image: car, failure: failWithError) { imageKeywords in // verify imageKeywords structure XCTAssertEqual(imageKeywords.status, "OK") XCTAssertEqual(imageKeywords.url, "") XCTAssertEqual(imageKeywords.totalTransactions, 4) XCTAssertEqual(imageKeywords.imageKeywords.count, 4) // verify first keyword XCTAssertEqual(imageKeywords.imageKeywords[0].text, "car") XCTAssert(imageKeywords.imageKeywords[0].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[0].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[0].knowledgeGraph) // verify second keyword XCTAssertEqual(imageKeywords.imageKeywords[1].text, "race") XCTAssert(imageKeywords.imageKeywords[1].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[1].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[1].knowledgeGraph) // verify third keyword XCTAssertEqual(imageKeywords.imageKeywords[2].text, "racing") XCTAssert(imageKeywords.imageKeywords[2].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[2].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[2].knowledgeGraph) // verify fourth keyword XCTAssertEqual(imageKeywords.imageKeywords[3].text, "motorsport") XCTAssert(imageKeywords.imageKeywords[3].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[3].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[3].knowledgeGraph) expectation.fulfill() } waitForExpectations() } func testGetRankedImageKeywordsImage2() { let description = "Perform image tagging on an uploaded image." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageKeywords(image: car, forceShowAll: true, knowledgeGraph: true, failure: failWithError) { imageKeywords in // verify imageKeywords structure XCTAssertEqual(imageKeywords.status, "OK") XCTAssertEqual(imageKeywords.url, "") XCTAssertEqual(imageKeywords.totalTransactions, 5) XCTAssertEqual(imageKeywords.imageKeywords.count, 7) // verify first keyword XCTAssertEqual(imageKeywords.imageKeywords[0].text, "car") XCTAssert(imageKeywords.imageKeywords[0].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[0].score <= 1.0) XCTAssertEqual(imageKeywords.imageKeywords[0].knowledgeGraph?.typeHierarchy, "/vehicles/car") // verify second keyword XCTAssertEqual(imageKeywords.imageKeywords[1].text, "race") XCTAssert(imageKeywords.imageKeywords[1].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[1].score <= 1.0) XCTAssertEqual(imageKeywords.imageKeywords[1].knowledgeGraph?.typeHierarchy, "/concepts/factors/characteristics/race") // verify third keyword XCTAssertEqual(imageKeywords.imageKeywords[2].text, "racing") XCTAssert(imageKeywords.imageKeywords[2].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[2].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[2].knowledgeGraph) // verify fourth keyword XCTAssertEqual(imageKeywords.imageKeywords[3].text, "motorsport") XCTAssert(imageKeywords.imageKeywords[3].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[3].score <= 1.0) XCTAssertEqual(imageKeywords.imageKeywords[3].knowledgeGraph?.typeHierarchy, "/activities/sports/motorsport") expectation.fulfill() } waitForExpectations() } func testGetRankedImageKeywordsURL1() { let description = "Perform image tagging on the primary image at a given URL." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageKeywords(url: carURL, failure: failWithError) { imageKeywords in // verify imageKeywords structure XCTAssertEqual(imageKeywords.status, "OK") XCTAssertEqual(imageKeywords.url, self.carURL) XCTAssertEqual(imageKeywords.totalTransactions, 4) XCTAssertEqual(imageKeywords.imageKeywords.count, 4) // verify first keyword XCTAssertEqual(imageKeywords.imageKeywords[0].text, "car") XCTAssert(imageKeywords.imageKeywords[0].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[0].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[0].knowledgeGraph) // verify second keyword XCTAssertEqual(imageKeywords.imageKeywords[1].text, "race") XCTAssert(imageKeywords.imageKeywords[1].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[1].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[1].knowledgeGraph) // verify third keyword XCTAssertEqual(imageKeywords.imageKeywords[2].text, "racing") XCTAssert(imageKeywords.imageKeywords[2].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[2].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[2].knowledgeGraph) // verify fourth keyword XCTAssertEqual(imageKeywords.imageKeywords[3].text, "motorsport") XCTAssert(imageKeywords.imageKeywords[3].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[3].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[3].knowledgeGraph) expectation.fulfill() } waitForExpectations() } func testGetRankedImageKeywordsURL2() { let description = "Perform image tagging on the primary image at a given URL." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageKeywords(url: carURL, forceShowAll: true, knowledgeGraph: true, failure: failWithError) { imageKeywords in // verify imageKeywords structure XCTAssertEqual(imageKeywords.status, "OK") XCTAssertEqual(imageKeywords.url, self.carURL) XCTAssertEqual(imageKeywords.totalTransactions, 5) XCTAssertEqual(imageKeywords.imageKeywords.count, 7) // verify first keyword XCTAssertEqual(imageKeywords.imageKeywords[0].text, "car") XCTAssert(imageKeywords.imageKeywords[0].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[0].score <= 1.0) XCTAssertEqual(imageKeywords.imageKeywords[0].knowledgeGraph?.typeHierarchy, "/vehicles/car") // verify second keyword XCTAssertEqual(imageKeywords.imageKeywords[1].text, "race") XCTAssert(imageKeywords.imageKeywords[1].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[1].score <= 1.0) XCTAssertEqual(imageKeywords.imageKeywords[1].knowledgeGraph?.typeHierarchy, "/concepts/factors/characteristics/race") // verify third keyword XCTAssertEqual(imageKeywords.imageKeywords[2].text, "racing") XCTAssert(imageKeywords.imageKeywords[2].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[2].score <= 1.0) XCTAssertNil(imageKeywords.imageKeywords[2].knowledgeGraph) // verify fourth keyword XCTAssertEqual(imageKeywords.imageKeywords[3].text, "motorsport") XCTAssert(imageKeywords.imageKeywords[3].score >= 0.0) XCTAssert(imageKeywords.imageKeywords[3].score <= 1.0) XCTAssertEqual(imageKeywords.imageKeywords[3].knowledgeGraph?.typeHierarchy, "/activities/sports/motorsport") expectation.fulfill() } waitForExpectations() } func testGetRankedImageSceneTextImage() { let description = "Identify text in an uploaded image." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageSceneText(image: sign, failure: failWithError) { sceneTexts in // verify sceneTexts structure XCTAssertEqual(sceneTexts.status, "OK") XCTAssertNil(sceneTexts.url) XCTAssertEqual(sceneTexts.totalTransactions, 0) XCTAssertEqual(sceneTexts.sceneText, "notice\nincreased\ntrain traffic") // verify first scene text line let line = sceneTexts.sceneTextLines.first XCTAssert(line?.confidence >= 0.0) XCTAssert(line?.confidence <= 1.0) XCTAssert(line?.region.height >= 0) XCTAssert(line?.region.height <= 150) XCTAssert(line?.region.width >= 0) XCTAssert(line?.region.width <= 150) XCTAssert(line?.region.x >= 0) XCTAssert(line?.region.x <= 500) XCTAssert(line?.region.y >= 0) XCTAssert(line?.region.y <= 500) XCTAssertEqual(line?.text, "notice") // verify first scene text line words let words = line?.words.first XCTAssert(words?.confidence >= 0.0) XCTAssert(words?.confidence <= 1.0) XCTAssert(words?.region.height >= 0) XCTAssert(words?.region.height <= 150) XCTAssert(words?.region.width >= 0) XCTAssert(words?.region.width <= 150) XCTAssert(words?.region.x >= 0) XCTAssert(words?.region.x <= 500) XCTAssert(words?.region.y >= 0) XCTAssert(words?.region.y <= 500) XCTAssertEqual(words?.text, "notice") expectation.fulfill() } waitForExpectations() } func testGetRankedImageSceneTextURL() { let description = "Identify text in the primary image at a given URL." let expectation = expectationWithDescription(description) alchemyVision.getRankedImageSceneText(url: signURL, failure: failWithError) { sceneTexts in // verify sceneTexts structure XCTAssertEqual(sceneTexts.status, "OK") XCTAssertEqual(sceneTexts.url, self.signURL) XCTAssertEqual(sceneTexts.totalTransactions, 0) XCTAssertEqual(sceneTexts.sceneText, "notice\nincreased\ntrain traffic") // verify first scene text line let line = sceneTexts.sceneTextLines.first XCTAssert(line?.confidence >= 0.0) XCTAssert(line?.confidence <= 1.0) XCTAssert(line?.region.height >= 0) XCTAssert(line?.region.height <= 150) XCTAssert(line?.region.width >= 0) XCTAssert(line?.region.width <= 150) XCTAssert(line?.region.x >= 0) XCTAssert(line?.region.x <= 500) XCTAssert(line?.region.y >= 0) XCTAssert(line?.region.y <= 500) XCTAssertEqual(line?.text, "notice") // verify first scene text line words let words = line?.words.first XCTAssert(words?.confidence >= 0.0) XCTAssert(words?.confidence <= 1.0) XCTAssert(words?.region.height >= 0) XCTAssert(words?.region.height <= 150) XCTAssert(words?.region.width >= 0) XCTAssert(words?.region.width <= 150) XCTAssert(words?.region.x >= 0) XCTAssert(words?.region.x <= 500) XCTAssert(words?.region.y >= 0) XCTAssert(words?.region.y <= 500) XCTAssertEqual(words?.text, "notice") expectation.fulfill() } waitForExpectations() } // MARK: - Negative Tests func testGetRankedImageFaceTagsWithInvalidURL() { let description = "Perform face recognition at an invalid URL." let expectation = expectationWithDescription(description) let failure = { (error: NSError) in XCTAssertEqual(error.code, 400) expectation.fulfill() } let url = "this-url-is-invalid" alchemyVision.getRankedImageFaceTags(url: url, failure: failure, success: failWithResult) waitForExpectations() } func testGetImageWithInvalidHTML() { let description = "Identify the primary image in an invalid HTML document." let expectation = expectationWithDescription(description) let failure = { (error: NSError) in XCTAssertEqual(error.code, 400) expectation.fulfill() } let html = "this-html-is-invalid" alchemyVision.getImage(html: html, failure: failure, success: failWithResult) waitForExpectations() } func testGetImageWithInvalidURL() { let description = "Identify the primary image at an invalid URL." let expectation = expectationWithDescription(description) let failure = { (error: NSError) in XCTAssertEqual(error.code, 400) expectation.fulfill() } let url = "this-url-is-invalid" alchemyVision.getImage(url: url, failure: failure, success: failWithResult) waitForExpectations() } func testGetRankedImageKeywordsWithInvalidURL() { let description = "Perform image tagging on the primary image at an invalid URL." let expectation = expectationWithDescription(description) let failure = { (error: NSError) in XCTAssertEqual(error.code, 400) expectation.fulfill() } let url = "this-url-is-invalid" alchemyVision.getRankedImageKeywords(url: url, failure: failure, success: failWithResult) waitForExpectations() } func testGetRankedImageSceneTextWithInvalidURL() { let description = "Identify text in the primary image at an invalid URL." let expectation = expectationWithDescription(description) let failure = { (error: NSError) in XCTAssertEqual(error.code, 400) expectation.fulfill() } let url = "this-url-is-invalid" alchemyVision.getRankedImageSceneText(url: url, failure: failure, success: failWithResult) waitForExpectations() } }
mit
0122fd2de3da9347327b961f758ccf55
44.272011
142
0.621851
4.894445
false
false
false
false
okerivy/AlgorithmLeetCode
AlgorithmLeetCode/AlgorithmLeetCode/M_116_PopulatingNextRightPointersInEachNode.swift
1
3761
// // M_116_PopulatingNextRightPointersInEachNode.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/20. // Copyright © 2017年 okerivy. All rights reserved. // https://leetcode.com/problems/populating-next-right-pointers-in-each-node import Foundation // MARK: - 题目名称: 116. Populating Next Right Pointers in Each Node /* MARK: - 所属类别: 标签: Tree, Depth-first Search 相关题目: (M) Populating Next Right Pointers in Each Node II (M) Binary Tree Right Side View */ /* MARK: - 题目英文: Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Note: You may only use constant extra space. You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). For example, Given the following perfect binary tree, 1 / \ 2 3 / \ / \ 4 5 6 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL */ /* MARK: - 题目翻译: 给定二叉树 struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } 填充下一个指针指向它的右下一个节点。如果没有右下一个节点,则下一个指针应该设置为null。 最初,所有下一个指针都设置为null。 注: 您只能使用常量额外空间。 你可以假设它是一个完美的二叉树(即,所有的叶子都在同一水平,并且每个父母都有两个孩子)。 例如, 给出了以下完全二叉树, 1 / \ 2 3 / \ / \ 4 5 6 7 调用函数后,树应该看起来像: 1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL */ /* MARK: - 解题思路: 需要在一棵完全二叉树中使用next指针连接旁边的节点,我们可以发现一些规律。 如果一个子节点是根节点的左子树,那么它的next就是该根节点的右子树,譬如上面例子中的4,它的next就是2的右子树5。 如果一个子节点是根节点的右子树,那么它的next就是该根节点next节点的左子树。譬如上面的5,它的next就是2的next(也就是3)的左子树。 first指针用来表示一层的第一个元素 */ /* MARK: - 复杂度分析: */ // MARK: - 代码: private class Solution { func connect(_ root: inout TreeNode?) { if root == nil { return } var p: TreeNode? = root var first: TreeNode? = nil while p != nil { //记录下层第一个左子树 if first == nil { first = p?.left } //如果有左子树,那么next就是父节点 if p?.left != nil { p?.left?.next = p?.right } else { //叶子节点了,遍历结束 break } //如果有next,那么设置右子树的next if p?.next != nil{ p?.right?.next = p?.next?.left p = p?.next continue } else { //转到下一层 p = first first = nil } } } } // MARK: - 测试代码: func PopulatingNextRightPointersInEachNode() { var root1 = CreateBinaryTree().convertArrayToTree([1, 2, 3, 4, 5, 6, 7]) print(Solution().connect(&root1)) }
mit
38a643a14aa4ddf106574c0944b60152
17.911392
132
0.558568
3.099585
false
false
false
false
RailwayStations/Bahnhofsfotos
Modules/Domain/Sources/Entities/Station.swift
1
1258
// // Station.swift // Bahnhofsfotos // // Created by Miguel Dönicke on 16.12.16. // Copyright © 2016 MrHaitec. All rights reserved. // import MapKit public struct Station { public let id: Int // Bahnhofsnummer public let name: String // Bahnhofsname public let country: String public let lat: Double public let lon: Double public let photographer: String? public let photographerUrl: String? public let photoUrl: String? public let license: String? public let DS100: String? public var hasPhoto: Bool { return photoUrl != nil } public init(id: Int, name: String, country: String, lat: Double, lon: Double, photographer: String?, photographerUrl: String?, photoUrl: String?, license: String?, DS100: String?) { self.id = id self.name = name self.country = country self.lat = lat self.lon = lon self.photographer = photographer self.photographerUrl = photographerUrl self.photoUrl = photoUrl self.license = license self.DS100 = DS100 } }
apache-2.0
cc4fcfaec59aa2372c5482fdc4da6624
25.166667
52
0.562102
4.214765
false
false
false
false
indragiek/Ares
client/AresKit/Client.swift
1
8164
// // Client.swift // Ares // // Created by Indragie on 1/30/16. // Copyright © 2016 Indragie Karunaratne. All rights reserved. // import Foundation import Alamofire private let UserDefaultsDeviceUUIDKey = "deviceUUID"; private let DefaultAPIURL = NSURL(string: "http://yourappname.heroku.com")! public final class Client { public static let ErrorDomain = "AresKitClientErrorDomain" public static let APIErrorKey = "api_error" public enum ErrorCode: Int { case APIError case InvalidJSONResponse } private let manager: Manager private let URL: NSURL public init(URL: NSURL = DefaultAPIURL, configuration: NSURLSessionConfiguration = .defaultSessionConfiguration()) { self.URL = URL self.manager = Manager(configuration: configuration) } // MARK: API public func register(user: User, completionHandler: Result<CreatedUser, NSError> -> Void) { let request = Request( method: .POST, path: "/register", parameters: [ "username": user.username, "password": user.password ] ) requestModel(request, completionHandler: completionHandler) } public func authenticate(user: User, completionHandler: Result<AccessToken, NSError> -> Void) { let request = Request( method: .POST, path: "/authenticate", parameters: [ "username": user.username, "password": user.password ] ) requestModel(request, completionHandler: completionHandler) } public func registerDevice(accessToken: AccessToken, pushToken: String? = nil, completionHandler: Result<RegisteredDevice, NSError> -> Void) { var parameters = [ "uuid": deviceUUID, "device_name": getDeviceName(), "token": accessToken.token ] if let pushToken = pushToken { parameters["push_token"] = pushToken } let request = Request( method: .POST, path: "/register_device", parameters: parameters ) requestModel(request, completionHandler: completionHandler) } public func getDevices(accessToken: AccessToken, completionHandler: Result<[RegisteredDevice], NSError> -> Void) { let request = Request(method: .GET, path: "/devices", parameters: [ "token": accessToken.token ]) requestModelArray(request, completionHandler: completionHandler) } public func send(accessToken: AccessToken, filePath: String, device: RegisteredDevice, completionHandler: Result<Void, NSError> -> Void) { let request = Request(method: .POST, path: "/send", parameters: [ "token": accessToken.token, "file_path": filePath, "to_id": device.uuid, "from_id": deviceUUID ]) requestVoid(request, completionHandler: completionHandler) } public var deviceUUID: String { let ud = NSUserDefaults.standardUserDefaults() let UUID: String if let storedUUID = ud.stringForKey(UserDefaultsDeviceUUIDKey) { UUID = storedUUID } else { UUID = NSUUID().UUIDString ud.setObject(UUID, forKey: UserDefaultsDeviceUUIDKey) } return UUID } // MARK: Primitives private struct Request { let method: Alamofire.Method let path: String let parameters: [String: AnyObject] } private static let InvalidJSONResponseError = NSError(domain: ErrorDomain, code: ErrorCode.InvalidJSONResponse.rawValue, userInfo: nil) private func requestModel<T: JSONDeserializable>(request: Request, completionHandler: Result<T, NSError> -> Void) { requestJSON(request) { result in switch result { case let .Success(json): if let json = json as? JSONDictionary, model = T(JSON: json) { completionHandler(.Success(model)) } else { completionHandler(.Failure(self.dynamicType.InvalidJSONResponseError)) } case let .Failure(error): completionHandler(.Failure(error)) } } } private func requestModelArray<T: JSONDeserializable>(request: Request, completionHandler: Result<[T], NSError> -> Void) { requestJSON(request) { result in switch result { case let .Success(json): if let jsonArray = json as? [JSONDictionary] { var models = [T]() for deviceDict in jsonArray { if let model = T(JSON: deviceDict) { models.append(model) } else { completionHandler(.Failure(self.dynamicType.InvalidJSONResponseError)) return } } completionHandler(.Success(models)) } else { completionHandler(.Failure(self.dynamicType.InvalidJSONResponseError)) } case let .Failure(error): completionHandler(.Failure(error)) } } } private func requestJSON(request: Request, completionHandler: Result<AnyObject, NSError> -> Void) { guard let components = NSURLComponents(URL: URL, resolvingAgainstBaseURL: false) else { fatalError("Invalid API base URL: \(URL)") } components.path = request.path guard let requestURL = components.URL else { fatalError("Unable to construct request URL") } manager.request(request.method, requestURL, parameters: request.parameters, encoding: .URL) .responseJSON { response in switch response.result { case let .Success(responseObject): if let json = responseObject as? JSONDictionary { if let success = json["success"] as? Bool, result = json["result"] where success { completionHandler(.Success(result)) } else { let error = self.dynamicType.constructAPIErrorFromJSON(json) completionHandler(.Failure(error)) } } else { completionHandler(.Failure(self.dynamicType.InvalidJSONResponseError)) } case let .Failure(error): completionHandler(.Failure(error)) } } } private func requestVoid(request: Request, completionHandler: Result<Void, NSError> -> Void) { requestJSON(request) { result in switch result { case .Success: completionHandler(.Success(())) case let .Failure(error): completionHandler(.Failure(error)) } } } private static func constructAPIErrorFromJSON(json: JSONDictionary) -> NSError { var userInfo = [String: AnyObject]() if let error = json["error"] as? String { userInfo[APIErrorKey] = error if let description = localizedDescriptionForAPIError(error) { userInfo[NSLocalizedDescriptionKey] = description } } return NSError(domain: ErrorDomain, code: ErrorCode.APIError.rawValue, userInfo: userInfo) } } private func localizedDescriptionForAPIError(error: String) -> String? { switch error { case "USER_EXISTS": return "A user with the specified username already exists."; case "USER_DOES_NOT_EXIST": return "A user with the specified username does not exist."; case "PASSWORD_INCORRECT": return "The specified password is incorrect."; case "INVALID_TOKEN": return "The specified access token is invalid."; default: return nil } }
mit
72206fbef00ed20ec7b23a5ab16da87e
36.791667
146
0.576014
5.416722
false
false
false
false
openHPI/xikolo-ios
iOS/ViewControllers/Account/VideoStreamingSettingsViewController.swift
1
3958
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import UIKit class VideoStreamingSettingsViewController: UITableViewController { // data source override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else { return VideoQuality.orderedValues.count } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 1: return NSLocalizedString("settings.video-quality.section-header.on cellular", comment: "section title for video quality on cellular connection") case 2: return NSLocalizedString("settings.video-quality.section-header.on wifi", comment: "section title for video quality on wifi connection") default: return nil } } // delegate override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "AutoPlayCell", for: indexPath) cell.textLabel?.text = NSLocalizedString("settings.video-auto-play.title", comment: "cell title for video auto play") let toggle = UISwitch() toggle.isOn = !UserDefaults.standard.disableVideoAutoPlay toggle.addTarget(self, action: #selector(changeVideoAutoPlay(sender:)), for: .valueChanged) cell.accessoryView = toggle return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsOptionBasicCell", for: indexPath) let videoQuality = VideoQuality.orderedValues[indexPath.row] cell.textLabel?.text = videoQuality.description if let videoQualityKeyPath = self.videoQualityKeyPath(for: indexPath.section) { let currentVideoQuality = UserDefaults.standard[keyPath: videoQualityKeyPath] cell.accessoryType = videoQuality == currentVideoQuality ? .checkmark : .none } return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let videoQualityKeyPath = self.videoQualityKeyPath(for: indexPath.section) else { return } let oldVideoQuality = UserDefaults.standard[keyPath: videoQualityKeyPath] let newVideoQuality = VideoQuality.orderedValues[indexPath.row] if oldVideoQuality != newVideoQuality { // update preferred video quality UserDefaults.standard[keyPath: videoQualityKeyPath] = newVideoQuality if let oldVideoQualityRow = VideoQuality.orderedValues.firstIndex(of: oldVideoQuality) { let oldVideoQualityIndexPath = IndexPath(row: oldVideoQualityRow, section: indexPath.section) tableView.reloadRows(at: [oldVideoQualityIndexPath, indexPath], with: .none) } else { let indexSet = IndexSet(integer: indexPath.section) tableView.reloadSections(indexSet, with: .none) } } } private func videoQualityKeyPath(for section: Int) -> ReferenceWritableKeyPath<UserDefaults, VideoQuality>? { switch section { case 1: return \UserDefaults.videoQualityOnCellular case 2: return \UserDefaults.videoQualityOnWifi default: return nil } } @objc private func changeVideoAutoPlay(sender: UISwitch) { UserDefaults.standard.disableVideoAutoPlay = !sender.isOn } }
gpl-3.0
1f8b5d1c2c0a800decba3a1fdff653d6
39.793814
113
0.6419
5.518828
false
false
false
false
TellMeAMovieTeam/TellMeAMovie_iOSApp
TellMeAMovie/Pods/TMDBSwift/Sources/Models/PersonMDB.swift
1
12176
// // PeopleMDB.swift // MDBSwiftWrapper // // Created by George Kye on 2016-03-08. // Copyright © 2016 George KyeKye. All rights reserved. // //MARK: Person public struct PersonMDB: ArrayObject{ public var adult: Bool! public var also_known_as: [String]? public var biography: String? public var birthday: String? public var deathday: String? public var homepage: String? public var id: Int! public var imdb_id: String? public var name: String! public var place_of_birth: String? public var popularity: Int! public var profile_path: String? public init(results: JSON){ adult = results["adult"].bool also_known_as = results["also_known_as"].arrayObject as? [String] biography = results["biography"].string birthday = results["birthday"].string deathday = results["deathday"].string homepage = results["homepage"].string id = results["id"].int imdb_id = results["imdb_id"].string name = results["name"].string place_of_birth = results["place_of_birth"].string popularity = results["popularity"].int profile_path = results["profile_path"].string } ///Get the general person information for a specific id. public static func person_id(_ api_key: String!, personID: Int!, completion: @escaping (_ clientReturn: ClientReturn, _ data: PersonMDB?) ->()) ->(){ let urlType = String(personID) Client.Person(urlType, api_key: api_key, language: nil, page: nil){ apiReturn in var data: PersonMDB? if(apiReturn.error == nil){ data = PersonMDB.init(results: apiReturn.json!) } completion(apiReturn, data) } } ///Get the movie credits for a specific person id. public static func movie_credits(_ api_key: String!, personID: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: PersonMovieCredits?) -> ()) ->(){ let urlType = String(personID) + "/movie_credits" Client.Person(urlType, api_key: api_key, language: language, page: nil){ apiReturn in var data: PersonMovieCredits? if(apiReturn.error == nil){ data = PersonMovieCredits.init(json: apiReturn.json!) } completion(apiReturn, data) } } ///Get the TV credits for a specific person id. public static func tv_credits(_ api_key: String!, personID: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: PersonTVCredits?) -> ()) ->(){ let urlType = String(personID) + "/tv_credits" Client.Person(urlType, api_key: api_key, language: language, page: nil){ apiReturn in var data: PersonTVCredits? if(apiReturn.error == nil){ data = PersonTVCredits.init(json: apiReturn.json!) } completion(apiReturn, data) } } ///Get the combined (movie and TV) credits for a specific person id. public static func combined_credits(_ api_key: String!, personID: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: PersonCreditsCombined?) -> ()) ->(){ let urlType = String(personID) + "/combined_credits" Client.Person(urlType, api_key: api_key, language: language, page: nil){ apiReturn in var data: PersonCreditsCombined? if(apiReturn.error == nil){ data = PersonCreditsCombined.init(json: apiReturn.json!) } completion(apiReturn, data) } } ///Get the external ids for a specific person id. public static func externalIDS(_ api_key: String!, personID: Int!, completion: @escaping (_ clientReturn: ClientReturn, _ data: ExternalIdsMDB?) -> ()) -> (){ Client.Person( String(personID) + "/external_ids", api_key: api_key, language: nil, page: nil){ apiReturn in var data: ExternalIdsMDB? if(apiReturn.error == nil){ data = ExternalIdsMDB.init(results: apiReturn.json!) } completion(apiReturn, data) } } ///Get the images for a specific person id. public static func images(_ api_key: String!, personID: Int!, completion: @escaping (_ client: ClientReturn, _ data: [Images_MDB]?) -> ()) -> (){ Client.Person( String(personID) + "/images", api_key: api_key, language: nil, page: nil){ apiReturn in var images: [Images_MDB]? if(apiReturn.error == nil){ images = Images_MDB.initialize(json: apiReturn.json!["profiles"]) } completion(apiReturn, images) } } ///Get the images that have been tagged with a specific person id. Will return all of the image results with a media object mapped for each image. public static func tagged_images(_ api_key: String!, personID: Int!, page: Int?, completion: @escaping (_ client: ClientReturn, _ data: TaggedImages?) -> ()) -> (){ Client.Person( String(personID) + "/tagged_images", api_key: api_key, language: nil, page: page){ apiReturn in var images: TaggedImages? if(apiReturn.error == nil){ images = TaggedImages.init(json: apiReturn.json!) } completion(apiReturn, images) } } ///Get the latest person id. public static func latest(_ api_key: String!, completion: @escaping (_ clientReturn: ClientReturn, _ data: PersonMDB?) -> ()) -> (){ Client.Person("latest", api_key: api_key, language: nil, page: nil){ apiReturn in var data: PersonMDB? if(apiReturn.error == nil){ data = PersonMDB.init(results: apiReturn.json!) } completion(apiReturn, data) } } ///Get the list of popular people on The Movie Database. This list refreshes every day. public static func popular(_ api_key: String!, page: Int?, completion: @escaping (_ clientReturn: ClientReturn, _ data: [PersonResults]?) -> ()) -> (){ Client.Person("popular", api_key: api_key, language: nil, page: page){ apiReturn in var data: [PersonResults]? if(apiReturn.error == nil){ data = PersonResults.initialize(json: apiReturn.json!["results"]) } completion(apiReturn, data) } } ///Retrive data by append multiple person methods. Initlization of object has to be done manually. Exepect PersonMDB public static func personAppendTo(_ api_key: String!, personID: Int!, append_to: [String], completion: @escaping (_ clientReturn: ClientReturn, _ data: PersonMDB?, _ json: JSON?) ->()) ->(){ let urlType = String(personID) Client.Person(urlType, api_key: api_key, language: nil, page: nil, append_to: append_to){ apiReturn in var data: PersonMDB? if(apiReturn.error == nil){ data = PersonMDB.init(results: apiReturn.json!) } completion(apiReturn, data, apiReturn.json) } } } ///TODO: popular, taggedImages, tv & movies credits import Foundation //MARK: Movie Crew & TV Crew common open class PersonCrewCommon: ArrayObject{ open var poster_path: String? open var credit_id: String! open var department: String! open var id: Int! open var job: String! required public init(results: JSON){ poster_path = results["poster_path"].string credit_id = results["credit_id"].string department = results["department"].string id = results["id"].int job = results["job"].string } } //MARK: Movie Crew open class PersonMovieCrew: PersonCrewCommon{ open var adult: Bool! open var original_title: String! open var release_date: String! open var title: String! required public init(results: JSON){ super.init(results: results) adult = results["adult"].bool original_title = results["original_title"].string release_date = results["release_date"].string title = results["title"].string } } //MARK: TV Crew open class PersonTVCrew: PersonCrewCommon{ open var episode_count: Int! open var first_air_date: String! open var name: String! open var original_name: String! required public init(results: JSON) { super.init(results: results) episode_count = results["episode_count"].int first_air_date = results["first_air_date"].string name = results["name"].string original_name = results["original_name"].string } } open class PersonMovieTVCastCommon: ArrayObject{ open var poster_path: String? open var credit_id: String! open var id: Int! open var character: String! required public init(results: JSON){ poster_path = results["poster_path"].string credit_id = results["credit_id"].string id = results["id"].int character = results["character"].string } } //MARK: TV CAST open class PersonTVCast: PersonMovieTVCastCommon{ open var episode_count: Int! open var first_air_date: String! open var name: String! open var original_name: String! required public init(results: JSON) { super.init(results: results) episode_count = results["episode_count"].int first_air_date = results["first_air_date"].string name = results["name"].string original_name = results["original_name"].string } } //MARK: Movie Cast open class PersonMovieCast: PersonMovieTVCastCommon{ open var adult: Bool! open var original_title: String! open var release_date: String! open var title: String! required public init(results: JSON){ super.init(results: results) adult = results["adult"].bool original_title = results["original_title"].string release_date = results["release_date"].string title = results["title"].string } } public struct PersonTVCredits{ public var crew: [PersonTVCrew] public var cast: [PersonTVCast] public var id: Int! public init(json: JSON){ crew = PersonTVCrew.initialize(json: json["crew"]) cast = PersonTVCast.initialize(json: json["cast"]) id = json["id"].int } } public struct PersonMovieCredits{ public var crew: [PersonMovieCrew] public var cast: [PersonMovieCast] public var id: Int! init(json: JSON){ crew = PersonMovieCrew.initialize(json: json["crew"]) cast = PersonMovieCast.initialize(json: json["cast"]) id = json["id"].int } } public struct PersonCreditsCombined{ public var tvCredits: (crew: [PersonTVCrew]?, cast: [PersonTVCast]?) public var movieCredits: (crew: [PersonMovieCrew]?, cast: [PersonMovieCast]?) public var id: Int? public init(json: JSON){ var tvCrew = [PersonTVCrew]() var tvCast = [PersonTVCast]() var movieCrew = [PersonMovieCrew]() var movieCast = [PersonMovieCast]() json["crew"].forEach(){ if $0.1["media_type"] == "tv'"{ tvCrew.append(PersonTVCrew.init(results: $0.1)) }else{ movieCrew.append(PersonMovieCrew.init(results: $0.1)) } } json["cast"].forEach(){ if $0.1["media_type"] == "tv"{ tvCast.append(PersonTVCast.init(results: $0.1)) }else{ movieCast.append(PersonMovieCast.init(results: $0.1)) } } id = json["id"].int tvCredits = (tvCrew, tvCast) movieCredits = (movieCrew, movieCast) } } open class TaggedImagesCommon: Images_MDB{ open var id: String! open var image_type: String! open var media_type: String! required public init(results: JSON) { super.init(results: results) id = results["id"].string image_type = results["image_type"].string media_type = results["media_type"].string } } open class TaggedImagesMovie: TaggedImagesCommon{ open var media: DiscoverMovieMDB! public required init(results: JSON) { super.init(results: results) media = DiscoverMovieMDB.init(results: results["media"]) } } open class TaggedImagesTV: TaggedImagesCommon{ open var media: DiscoverTVMDB! public required init(results: JSON) { super.init(results: results) media = DiscoverTVMDB.init(results: results["media"]) } } public struct TaggedImages{ public var tvImages = [TaggedImagesTV]() public var movieImages = [TaggedImagesMovie]() public var id: Int! public var pageResults: PageResultsMDB! public init(json: JSON){ id = json["id"].int pageResults = PageResultsMDB.init(results: json) json["results"].forEach(){ if $0.1["media_type"] == "movie"{ movieImages.append(TaggedImagesMovie.init(results: $0.1)) }else{ tvImages.append(TaggedImagesTV.init(results: $0.1)) } } } }
apache-2.0
651876b1f36537caee7ad59e3456d3d6
31.728495
192
0.662998
3.808258
false
false
false
false
hooman/swift
test/Concurrency/Runtime/async_task_locals_copy_to_async.swift
2
4739
// REQUIRES: rdar80824152 // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime @available(SwiftStdlib 5.5, *) enum TL { @TaskLocal static var number: Int = 0 @TaskLocal static var other: Int = 0 } @available(SwiftStdlib 5.5, *) @discardableResult func printTaskLocal<V>( _ key: TaskLocal<V>, _ expected: V? = nil, file: String = #file, line: UInt = #line ) -> V? { let value = key.get() print("\(key) (\(value)) at \(file):\(line)") if let expected = expected { assert("\(expected)" == "\(value)", "Expected [\(expected)] but found: \(value), at \(file):\(line)") } return expected } // ==== ------------------------------------------------------------------------ @available(SwiftStdlib 5.5, *) func copyTo_async() async { await TL.$number.withValue(1111) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (1111) await TL.$number.withValue(2222) { await TL.$other.withValue(9999) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2222) printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999) let handle = Task { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2222) printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999) TL.$number.withValue(3333) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (3333) printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999) } } _ = await handle.value } } } } @available(SwiftStdlib 5.5, *) func copyTo_async_noWait() async { print(#function) TL.$number.withValue(1111) { TL.$number.withValue(2222) { TL.$other.withValue(9999) { Task { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2222) printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999) TL.$number.withValue(3333) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (3333) printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999) } } } } } let second = UInt64(100_000_000) // ns await Task.sleep(2 * second) } @available(SwiftStdlib 5.5, *) class CustomClass { @TaskLocal static var current: CustomClass? init() { print("init \(ObjectIdentifier(self))") } deinit { print("deinit \(ObjectIdentifier(self))") } } @available(SwiftStdlib 5.5, *) func test_unstructured_retains() async { let instance = CustomClass() CustomClass.$current.withValue(instance) { print("BEFORE send: \(String(reflecting: CustomClass.current))") // don't await on the un-structured tasks on purpose, we want to see that the tasks // themselves keep the object alive even if we don't hold onto them Task { print("in async task: \(String(reflecting: CustomClass.current))") } Task { print("in async task: \(String(reflecting: CustomClass.current))") } print("AFTER send: \(String(reflecting: CustomClass.current))") } // CHECK: init // CHECK: BEFORE send: Optional(main.CustomClass) // CHECK: in async task: Optional(main.CustomClass) // CHECK: in async task: Optional(main.CustomClass) // the deinit MUST NOT happen before the async tasks runs // CHECK: deinit await Task.sleep(2 * 1_000_000_000) } @available(SwiftStdlib 5.5, *) func test_unstructured_noValues() async { await Task { // no values to copy }.value } @available(SwiftStdlib 5.5, *) func downloadImage(from url: String) async throws -> String { await Task.sleep(10_000) return "" } @available(SwiftStdlib 5.5, *) func test_unstructured_noValues_childTasks() async { @Sendable func work() async throws { let handle = Task { try await downloadImage(from: "") } } // these child tasks have a parent pointer in their task local storage. // we must not copy it when performing the copyTo for a new unstructured task. async let one = work() async let two = work() async let three = work() try! await one try! await two try! await three } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await copyTo_async() await copyTo_async_noWait() await test_unstructured_retains() await test_unstructured_noValues() await test_unstructured_noValues_childTasks() } }
apache-2.0
7821cc9873692fd8d1dc6fe8c1daaf0f
27.721212
130
0.637265
3.785144
false
false
false
false
marklin2012/iOS_Animation
Section4/Chapter21/O2Cook_completed/O2Cook/ViewController.swift
2
4281
// // ViewController.swift // O2Cook // // Created by O2.LinYi on 16/3/21. // Copyright © 2016年 jd.com. All rights reserved. // import UIKit let herbs = HerbModel.all() class ViewController: UIViewController { @IBOutlet var listView: UIScrollView! @IBOutlet var bgImage: UIImageView! var selectedImage: UIImageView? let transition = PopAnimator() // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() if listView.subviews.count < herbs.count { listView.viewWithTag(0)?.tag = 1000 // prevent confusion when looking up images setupList() } transition.dismissCompletion = { self.selectedImage!.hidden = false } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } // MARK: - view setup // add all images to the list func setupList() { for var i=0; i < herbs.count; i++ { // create image view let imageView = UIImageView(image: UIImage(named: herbs[i].image)) imageView.tag = i + 100 imageView.contentMode = .ScaleAspectFill imageView.userInteractionEnabled = true imageView.layer.cornerRadius = 20 imageView.layer.masksToBounds = true listView.addSubview(imageView) // attach tap detector imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTapImageView:")) } listView.backgroundColor = UIColor.clearColor() positionListItems() } // position all images inside the list func positionListItems() { let itemHeight: CGFloat = listView.frame.height * 1.33 let aspectRatio = UIScreen.mainScreen().bounds.height / UIScreen.mainScreen().bounds.width let itemWidth: CGFloat = itemHeight / aspectRatio print("width: \(itemWidth)") let horizontalPadding: CGFloat = 10.0 for var i = 0; i < herbs.count; i++ { let imageView = listView.viewWithTag(i+100) as! UIImageView imageView.frame = CGRect(x: CGFloat(i+1) * horizontalPadding + CGFloat(i) * itemWidth, y: 0, width: itemWidth, height: itemHeight) print("frame: \(imageView.frame)") } listView.contentSize = CGSize(width: CGFloat(herbs.count) * (itemWidth+horizontalPadding) + horizontalPadding, height: 0) } func didTapImageView(tap: UITapGestureRecognizer) { selectedImage = tap.view as? UIImageView let index = tap.view!.tag - 100 let selectedHerb = herbs[index] //present details view controller let herbDetails = storyboard!.instantiateViewControllerWithIdentifier("HerbDetailsViewController") as! HerbDetailsViewController herbDetails.herb = selectedHerb herbDetails.transitioningDelegate = self presentViewController(herbDetails, animated: true, completion: nil) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition({ (context) -> Void in self.bgImage.alpha = (size.width > size.height) ? 0.25 : 0.55 self.positionListItems() }, completion: nil) } } extension ViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.originFrame = selectedImage!.superview!.convertRect(selectedImage!.frame, toView: nil) transition.presenting = true selectedImage!.hidden = true return transition } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.presenting = false return transition } }
mit
b7e5d2a47b20006a5a4b640e1a8f066b
33.780488
217
0.650771
5.401515
false
false
false
false
jonnyleeharris/ento
Ento/ento/core/Family.swift
1
1819
// // Created by Jonathan Harris on 30/06/2015. // Copyright © 2015 Jonathan Harris. All rights reserved. // import Foundation private enum MatchType : Int { case Any, All, None } public class FamilyBuilder { } public class Family : Hashable { private static var familyIndex:Int = 0; private var familyID:Int; private var matchType:MatchType; public var hashValue:Int { get { return self.familyID; } } private var components:Array<AnyClass>; private init(components : Array<AnyClass>, matchType:MatchType) { self.familyID = ++Family.familyIndex; self.components = components; self.matchType = matchType; } public class func all(components: AnyClass...) -> Family { return Family(components: components, matchType: MatchType.All); } public class func any(components: AnyClass...) -> Family { return Family(components: components, matchType: MatchType.Any); } public class func none(components: AnyClass...) -> Family { return Family(components: components, matchType: MatchType.None); } public func matches(entity:Entity) -> Bool { switch(self.matchType) { case .All: return matchAll(entity); case .Any: return matchAny(entity); case .None: return matchNone(entity); } } private func matchAll(entity:Entity) -> Bool { for match in self.components { if(!entity.has(match)) { return false; } } return true; } private func matchAny(entity:Entity) -> Bool { for match in self.components { if(entity.has(match)) { return true; } } return false; } private func matchNone(entity:Entity) -> Bool { for match in self.components { if(entity.has(match)) { return false; } } return true; } } public func == (lhs:Family, rhs:Family) -> Bool { return lhs.hashValue == rhs.hashValue; }
mit
ec54e1497d0be579f3e9fe351e596207
18.548387
67
0.678768
3.348066
false
false
false
false
PauloMigAlmeida/Signals
SwiftSignalKit/Bag.swift
1
753
import Foundation public final class Bag<T> { public typealias Index = Int private var nextIndex: Index = 0 private var items: [T] = [] private var itemKeys: [Index] = [] public func add(item: T) -> Index { let key = self.nextIndex self.nextIndex++ self.items.append(item) self.itemKeys.append(key) return key } public func remove(index: Index) { var i = 0 for key in self.itemKeys { if key == index { self.items.removeAtIndex(i) self.itemKeys.removeAtIndex(i) break } i++ } } public func copyItems() -> [T] { return self.items } }
mit
9cd094303de0ad3e45794a9106e62afd
21.818182
46
0.501992
4.327586
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/array_enum/main.swift
2
511
enum x : String { case patatino } struct y { var z: x? } func main() -> Int { var a = y() a.z = x.patatino var j = [a] return 0 //%self.expect('frame var -d run-target a', substrs=['(a.y) a = (z = patatino)']) //%self.expect('expr -d run-target -- a', substrs=['(a.y) $R0 = (z = patatino)']) //%self.expect('frame var -d run-target j', substrs=['[0] = (z = patatino)']) //%self.expect('expr -d run-target -- j', substrs=['[0] = (z = patatino)']) } let _ = main()
apache-2.0
f1e2739129ae172d4fe835d4ba1e7c2f
25.894737
92
0.51272
2.838889
false
false
false
false
HQL-yunyunyun/SinaWeiBo
SinaWeiBo/SinaWeiBo/Class/Tool/HQLNetWorkTool.swift
1
1761
// // HQLNetWorkTool.swift // SinaWeiBo // // Created by 何启亮 on 16/5/13. // Copyright © 2016年 HQL. All rights reserved. // import UIKit import AFNetworking // 请求方法枚举 enum RequestMethod: String { case GET = "GET" case POST = "POST" } class HQLNetWorkTool: NSObject { // 单例 static let shareInstance: HQLNetWorkTool = HQLNetWorkTool() // afnsession属性 private let afnManage: AFHTTPSessionManager = { let afn = AFHTTPSessionManager(baseURL: NSURL(string: "https://api.weibo.com/")) // 给解析器添加 "text/plain" 类型 acceptableContentTypes 是 NSSet 集合,直接用insert 方法添加 afn.responseSerializer.acceptableContentTypes?.insert("text/plain") return afn }() // 封装方法 // 如果直接使用AFN的GET和POST方法,如果AFN改变了方法名或参数改变了,哪项目中直接使用AFN.GET和POST的地方都需要改变 // 自己封装GET 和 POST方法,项目中要使用GET和POST就用我们封装好的,到时如果如果AFN改变了方法名或参数改变了,只需要改我们封装的方法 /// 封装AFN的GET和POST,通过参数来确定使用GET还是POST func request(method: RequestMethod, URLString: String,parameters: AnyObject?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?){ if method == RequestMethod.GET{ afnManage.GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure) }else if method == RequestMethod.POST{ afnManage.POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure) } } }
apache-2.0
526418e87ba535ee9687e57fb6e8fe89
31
192
0.680707
3.670823
false
false
false
false
argon/mas
MasKit/Commands/Info.swift
1
1641
// // Info.swift // mas-cli // // Created by Denis Lebedev on 21/10/2016. // Copyright © 2016 Andrew Naylor. All rights reserved. // import Commandant import Foundation /// Displays app details. Uses the iTunes Lookup API: /// https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#lookup public struct InfoCommand: CommandProtocol { public let verb = "info" public let function = "Display app information from the Mac App Store" private let storeSearch: StoreSearch /// Designated initializer. public init(storeSearch: StoreSearch = MasStoreSearch()) { self.storeSearch = storeSearch } /// Runs the command. public func run(_ options: InfoOptions) -> Result<(), MASError> { do { guard let result = try storeSearch.lookup(app: options.appId) else { print("No results found") return .failure(.noSearchResultsFound) } print(AppInfoFormatter.format(app: result)) } catch { // Bubble up MASErrors if let error = error as? MASError { return .failure(error) } return .failure(.searchFailed) } return .success(()) } } public struct InfoOptions: OptionsProtocol { let appId: Int static func create(_ appId: Int) -> InfoOptions { return InfoOptions(appId: appId) } public static func evaluate(_ mode: CommandMode) -> Result<InfoOptions, CommandantError<MASError>> { return create <*> mode <| Argument(usage: "ID of app to show info") } }
mit
74dc2b8cf5663157e5ed6567351359e7
27.77193
106
0.62378
4.350133
false
false
false
false
joerocca/GitHawk
Pods/Tabman/Sources/Tabman/TabmanBar/Transitioning/ItemTransition/TabmanItemColorCrossfadeTransition.swift
1
2972
// // TabmanItemColorCrossfadeTransition.swift // Tabman // // Created by Merrick Sapsford on 14/03/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit import Pageboy /// TabmanItemColorCrossfadeTransition /// /// Transition that cross-fades colors on the selected and unselected items to signify the active item. class TabmanItemColorCrossfadeTransition: TabmanItemTransition { override func transition(withPosition position: CGFloat, direction: PageboyViewController.NavigationDirection, indexRange: Range<Int>, bounds: CGRect) { guard let bar = tabmanBar as? TabmanButtonBar else { return } let (lowerIndex, upperIndex) = TabmanPositionalUtil.lowerAndUpperIndex(forPosition: position, minimum: indexRange.lowerBound, maximum: indexRange.upperBound) guard bar.buttons.count > max(upperIndex, lowerIndex) else { return } let lowerButton = bar.buttons[lowerIndex] let upperButton = bar.buttons[upperIndex] let targetButton = direction == .forward ? upperButton : lowerButton let oldTargetButton = direction == .forward ? lowerButton : upperButton var integral: Float = 0.0 let transitionProgress = CGFloat(modff(Float(position), &integral)) let relativeProgress = direction == .forward ? transitionProgress : 1.0 - transitionProgress self.updateButtons(inBar: bar, withTargetButton: targetButton, oldTargetButton: oldTargetButton, progress: relativeProgress) } private func updateButtons(inBar bar: TabmanButtonBar, withTargetButton targetButton: UIButton, oldTargetButton: UIButton, progress: CGFloat) { guard targetButton !== oldTargetButton else { bar.focussedButton = targetButton return } let targetColor = UIColor.interpolate(betweenColor: bar.color, and: bar.selectedColor, percent: progress) let oldTargetColor = UIColor.interpolate(betweenColor: bar.color, and: bar.selectedColor, percent: 1.0 - progress) targetButton.tintColor = targetColor targetButton.setTitleColor(targetColor, for: .normal) oldTargetButton.tintColor = oldTargetColor oldTargetButton.setTitleColor(oldTargetColor, for: .normal) } }
mit
519440f57012658ecb71e6ad256cb45b
41.442857
110
0.555369
5.883168
false
false
false
false
CoderAlexChan/AlexCocoa
String/String+encode.swift
1
1710
// // String+encode.swift // Main // // Created by 陈文强 on 2017/5/17. // Copyright © 2017年 陈文强. All rights reserved. // import Foundation // MARK: - base64 Encod/Decode extension String { /// Create a new string from a base64 string (if applicable). /// /// - Parameter base64: base64 string. init?(base64: String) { if let str = base64.base64Decoded { self.init(str) return } return nil } /// String decoded from base64 (if applicable). public var base64Decoded: String? { // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift guard let decodedData = Data(base64Encoded: self) else { return nil } return String(data: decodedData, encoding: .utf8) } /// String encoded in base64 (if applicable). public var base64Encoded: String? { // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift let plainData = self.data(using: .utf8) return plainData?.base64EncodedString() } /// Readable string from a URL string. public var urlDecoded: String { return removingPercentEncoding ?? self } /// URL escaped string. public var urlEncoded: String { return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self } /// Convert URL string to readable string. public mutating func urlDecode() { self = removingPercentEncoding ?? self } /// Escape string. public mutating func urlEncode() { self = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self } }
mit
331ed1d2403e004fab6242dd1085fb52
26.786885
85
0.623009
4.269521
false
false
false
false
zarkopopovski/IOS-Tutorials
UISwitchControlTutorial/UISwitchControlTutorial/ViewController.swift
1
1489
// // ViewController.swift // UISwitchControlTutorial // // Created by Zarko Popovski on 8/5/16. // Copyright © 2016 ZPOTutorials. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var switchControl: UISwitch! @IBOutlet weak var stateLabel: UILabel! @IBOutlet weak var buttonChangeState: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if switchControl.on { stateLabel.text = "UISwitch State On" } else { stateLabel.text = "UISwitch State Off" } } @IBAction func changeStateAction(sender: UISwitch) { if sender.on { stateLabel.text = "UISwitch State On" } else { stateLabel.text = "UISwitch State Off" } } @IBAction func manuallyChangeStateAction(sender: AnyObject) { if switchControl.on { switchControl.setOn(false, animated: true) stateLabel.text = "UISwitch State Off" } else { switchControl.setOn(true, animated: true) stateLabel.text = "UISwitch State On" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ae433b400ef46b3845c9db2eb44e65e5
21.892308
80
0.577957
4.894737
false
false
false
false
audiokit/AudioKit
Tests/AudioKitTests/Node Tests/Effects Tests/DynaRageCompressorTests.swift
2
2649
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AudioKit import XCTest class DynaRangeCompressorTests: XCTestCase { func testAttackTime() { let engine = AudioEngine() let input = Oscillator() engine.output = DynaRageCompressor(input, ratio: 10, attackDuration: 21) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testDefault() { let engine = AudioEngine() let input = Oscillator() engine.output = DynaRageCompressor(input) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testParameters() { let engine = AudioEngine() let input = Oscillator() engine.output = DynaRageCompressor(input, ratio: 10, threshold: -1, attackDuration: 21, releaseDuration: 22) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testRage() { let engine = AudioEngine() let input = Oscillator() engine.output = DynaRageCompressor(input, ratio: 10, rage: 10) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testRatio() { let engine = AudioEngine() let input = Oscillator() engine.output = DynaRageCompressor(input, ratio: 10) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testReleaseTime() { let engine = AudioEngine() let input = Oscillator() engine.output = DynaRageCompressor(input, ratio: 10, releaseDuration: 22) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testThreshold() { let engine = AudioEngine() let input = Oscillator() engine.output = DynaRageCompressor(input, ratio: 10, threshold: -1) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } }
mit
d26aee146b8051088baa937a74afe96f
31.304878
100
0.586259
4.371287
false
true
false
false
rechsteiner/LayoutEngine
LayoutEngineTests/LayoutEngineTests.swift
1
3997
import UIKit import Nimble import Quick import LayoutEngine class LayoutEngineTests: QuickSpec { override func spec() { describe("LayoutEngine") { describe("stacking views") { var firstView: UIView! var secondView: UIView! var thirdView: UIView! beforeEach { firstView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 10)) secondView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20)) thirdView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 30)) } it("stack views on top of each-other") { let firstLayout = ViewLayout(view: firstView) let secondLayout = ViewLayout(view: secondView) let thirdLayout = ViewLayout(view: thirdView) let height = LayoutEngine.stackViews([firstLayout, secondLayout, thirdLayout], width: 320) expect(firstView.frame.origin.y).to(equal(0)) expect(secondView.frame.origin.y).to(equal(10)) expect(thirdView.frame.origin.y).to(equal(30)) expect(height).to(equal(60)) } it("float views to the left") { let firstMetric = ViewDefaultMetric(direction: .left) let firstLayout = ViewLayout(view: firstView, metric: firstMetric) let _ = LayoutEngine.stackViews([firstLayout], width: 320) expect(firstView.frame.origin.x).to(equal(0)) } it("float views to the right") { let firstMetric = ViewDefaultMetric(direction: .right) let firstLayout = ViewLayout(view: firstView, metric: firstMetric) let _ = LayoutEngine.stackViews([firstLayout], width: 320) expect(firstView.frame.origin.x).to(equal(220)) } it("adds global insets to views") { let firstLayout = ViewLayout(view: firstView) let insets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50) let height = LayoutEngine.stackViews([firstLayout], metric: ViewDefaultMetric(insets: insets), width: 320 ) expect(firstView.frame.origin.x).to(equal(50)) expect(firstView.frame.origin.y).to(equal(50)) expect(height).to(equal(110)) } it("adds insets to views") { let insets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50) let firstMetric = ViewDefaultMetric(insets: insets) let firstLayout = ViewLayout(view: firstView, metric: firstMetric) let secondLayout = ViewLayout(view: secondView) let height = LayoutEngine.stackViews([firstLayout, secondLayout], width: 320) expect(firstView.frame.origin.x).to(equal(50)) expect(firstView.frame.origin.y).to(equal(50)) expect(secondView.frame.origin.x).to(equal(0)) expect(secondView.frame.origin.y).to(equal(110)) expect(height).to(equal(130)) } it("accounts for hidden views") { let firstMetric = ViewDefaultMetric(hidden: true) let firstLayout = ViewLayout(view: firstView, metric: firstMetric) let secondLayout = ViewLayout(view: secondView) let height = LayoutEngine.stackViews([firstLayout, secondLayout], width: 320) expect(firstView.isHidden).to(beTrue()) expect(secondView.frame.origin.y).to(equal(0)) expect(height).to(equal(20)) } it("ignores insets on hidden views") { let firstMetric = ViewDefaultMetric( insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), hidden: true) let firstLayout = ViewLayout(view: firstView, metric: firstMetric) let secondLayout = ViewLayout(view: secondView) let height = LayoutEngine.stackViews([firstLayout, secondLayout], width: 320) expect(firstView.isHidden).to(beTrue()) expect(secondView.frame.origin.y).to(equal(0)) expect(height).to(equal(20)) } } } } }
mit
bef6fe447acf0b4aab5c628d0f3f263a
38.186275
100
0.618214
4.141969
false
false
false
false
Lves/LLRefresh
LLRefreshDemo/Demos/Customer/LLRefreshBGImageHeader.swift
1
724
// // LLRefreshBGImageHeader.swift // LLRefreshDemo // // Created by 李兴乐 on 2016/12/9. // Copyright © 2016年 com.lvesli. All rights reserved. // 带有背景图片的刷新header import UIKit import LLRefresh class LLRefreshBGImageHeader: LLRefreshNormalHeader { fileprivate lazy var bgImageView: UIImageView = { let bgImageView = UIImageView(image: UIImage(named:"refresh_bg")) self.insertSubview(bgImageView, at: 0) return bgImageView }() //MARK: - 集成父类方法 override func placeSubViews() { super.placeSubViews() bgImageView.ll_x = 0 bgImageView.ll_y = -(bgImageView.ll_h - ll_h) bgImageView.ll_w = ll_w } }
mit
7251336c257f9b7c828eb7f192e46fcc
22.62069
73
0.649635
3.682796
false
false
false
false
luksfarris/SwiftRandomForest
SwiftRandomForest/Readers/CSVReader.swift
1
3477
//MIT License // //Copyright (c) 2017 Lucas Farris // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. import UIKit class CSVReader<T:Numeric>: NSObject { private var encoding:String.Encoding = .utf8 private var hasHeader:Bool = false init(encoding:String.Encoding, hasHeader:Bool) { self.encoding = encoding self.hasHeader = hasHeader } private func stringFromFile(filename:String) -> String? { let bundle = Bundle.main; let path = bundle.path(forResource:filename, ofType:"csv") if let validPath = path { do { let response = try NSData(contentsOfFile: validPath, options: .mappedIfSafe) let text = String(data: Data.init(referencing:response), encoding: self.encoding) if let validText = text { return validText } else { print ("Bad encoding") } } catch { print("Error reading file") } } else { print("Bad path") } return nil } public func parseFileWith(name:String) -> Matrix<T>? { if let file = self.stringFromFile(filename: name) { let allLines = file.components(separatedBy: NSCharacterSet.newlines) let features = allLines[0].components(separatedBy: ",") let badLines = 1 + (hasHeader ? 1:0) let dataset = Matrix<T>.init(rows: allLines.count-badLines, columns: features.count) dataset.outputClasses = [] for line in allLines { if (hasHeader) { hasHeader = false; continue } if (line==""){ continue } let textFeatures = line.components(separatedBy: ",") let numberFeatures = textFeatures.map({ (feat:String) -> T in return T.parse(text: feat) }) for feat in numberFeatures { dataset.append(feat) } if (!dataset.outputClasses!.contains(numberFeatures[features.count-1])) { dataset.outputClasses!.append(numberFeatures[features.count-1]) } } return dataset } return nil } }
mit
95ba5524dd9eb07eeca9e59a3c05a903
37.208791
97
0.585562
4.931915
false
false
false
false
KellenYangs/KLSwiftTest_05_05
VC跳转/VC跳转/CustomNavigationAnimationController.swift
1
2783
// // CustomNavigationAnimationController.swift // VC跳转 // // Created by bcmac3 on 16/5/30. // Copyright © 2016年 KellenYangs. All rights reserved. // import UIKit class CustomNavigationAnimationController: NSObject { var reverse: Bool = false } extension CustomNavigationAnimationController: UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 1.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView()! let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) let toView = toVC!.view! let fromView = fromVC!.view! let direction: CGFloat = reverse ? -1 : 1; let const: CGFloat = -0.005 toView.layer.anchorPoint = CGPointMake(direction == 1 ? 0 : 1, 0.5) fromView.layer.anchorPoint = CGPointMake(direction == 1 ? 1 : 0, 0.5) var viewFromTransform: CATransform3D = CATransform3DMakeRotation(direction * CGFloat(M_PI_2), 0.0, 1.0, 0.0) var viewToTransform: CATransform3D = CATransform3DMakeRotation(-direction * CGFloat(M_PI_2), 0.0, 1.0, 0.0) viewFromTransform.m34 = const viewToTransform.m34 = const containerView.transform = CGAffineTransformMakeTranslation(direction * containerView.frame.size.width / 2.0, 0) toView.layer.transform = viewToTransform containerView.addSubview(toView) UIView.animateWithDuration(transitionDuration(transitionContext), animations: { containerView.transform = CGAffineTransformMakeTranslation(-direction * containerView.frame.size.width / 2.0, 0) fromView.layer.transform = viewFromTransform toView.layer.transform = CATransform3DIdentity }, completion: { finished in containerView.transform = CGAffineTransformIdentity fromView.layer.transform = CATransform3DIdentity toView.layer.transform = CATransform3DIdentity fromView.layer.anchorPoint = CGPointMake(0.5, 0.5) toView.layer.anchorPoint = CGPointMake(0.5, 0.5) if (transitionContext.transitionWasCancelled()) { toView.removeFromSuperview() } else { fromView.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } }
mit
142f67abca28c28cf41158737f202313
42.390625
124
0.664625
5.518887
false
false
false
false
jphacks/TK_08
iOS/Demo/PushCatchDemo/iBeaconDemo/ViewController.swift
1
5350
// // ViewController.swift // iBeaconDemo // // Created by Go Sato on 2015/11/21. // Copyright © 2015年 go. All rights reserved. // // Thank you Fumitoshi Ogata's code // https://github.com/oggata/iBeaconDemo/blob/master/iBeaconDemo/ViewController.swift // import UIKit //------go import CoreLocation // class ViewController: UIViewController,CLLocationManagerDelegate{ @IBOutlet weak var status: UILabel! @IBOutlet weak var uuid: UILabel! @IBOutlet weak var major: UILabel! @IBOutlet weak var accuracy: UILabel! @IBOutlet weak var rssi: UILabel! @IBOutlet weak var distance: UILabel! let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate var isChange:Bool = false //--------go //UUIDは送信機側とフォーマットも合わせる let proximityUUID = NSUUID(UUIDString:"B9407F30-F5F8-466E-AFF9-33333B57FE6D") var region = CLBeaconRegion() //ロケーションマネージャー作成 var manager = CLLocationManager() //majorIDリスト用のグローバル変数 var majorIDList:[NSNumber] = [] var majorIDListOld:[NSNumber] = [] //----------- var trackLocationManager : CLLocationManager! override func viewDidLoad() { super.viewDidLoad() //------go //Beacon領域の生成 region = CLBeaconRegion(proximityUUID:proximityUUID!,identifier:"AirMeet") //デリゲートの設定 manager.delegate = self switch CLLocationManager.authorizationStatus() { case .Authorized, .AuthorizedWhenInUse: //iBeaconによる領域観測を開始する print("観測開始") //self.status.text = "Starting Monitor" self.manager.startRangingBeaconsInRegion(self.region) case .NotDetermined: print("許可承認") //self.status.text = "Starting Monitor" //デバイスに許可を促す let deviceVer = UIDevice.currentDevice().systemVersion if(Int(deviceVer.substringToIndex(deviceVer.startIndex.advancedBy(1))) >= 8){ //iOS8以降は許可をリクエストする関数をCallする self.manager.requestAlwaysAuthorization() print("OK") }else{ self.manager.startRangingBeaconsInRegion(self.region) } case .Restricted, .Denied: //デバイスから拒否状態 print("Restricted") //self.status.text = "Restricted Monitor" } } ///-----go func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region:CLBeaconRegion) { majorIDList = [] if(beacons.count == 0) { //リストに何も受信していないことを表示 print("nothing") return } //複数あった場合は一番先頭のものを処理する let beacon = beacons[0] //ここでつっこみ for i in 0..<beacons.count{ majorIDList.append(beacons[i].major) } //重複捨て if(beacons.count != 0){ let set = NSOrderedSet(array: majorIDList) majorIDList = set.array as! [NSNumber] } //-------go //ここで変更があったか検証します //サーバーにアクセス if(majorIDList.count != majorIDListOld.count){ print("change list") print(majorIDList) majorIDListOld = majorIDList isChange = true print(beacon.major) AppDelegate().pushControll() }else{ print("same") isChange = false } /* beaconから取得できるデータ proximityUUID : regionの識別子(アプリで予め決定) major : 識別子1(イベント情報登録後にサーバーから発行) proximity : 相対距離 accuracy : 精度 rssi : 電波強度 */ if (beacon.proximity == CLProximity.Unknown) { self.distance.text = "Unknown Proximity" reset() return } else if (beacon.proximity == CLProximity.Immediate) { self.distance.text = "Immediate" } else if (beacon.proximity == CLProximity.Near) { self.distance.text = "Near" } else if (beacon.proximity == CLProximity.Far) { self.distance.text = "Far" } self.status.text = "OK" self.uuid.text = beacon.proximityUUID.UUIDString self.major.text = "\(beacon.major)" self.accuracy.text = "\(beacon.accuracy)" self.rssi.text = "\(beacon.rssi)" } func reset(){ self.status.text = "none" self.uuid.text = "none" self.major.text = "none" self.accuracy.text = "none" self.rssi.text = "none" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f289d77fd3146bdaf5c01c9e6cb728ce
29.4125
123
0.558068
4.301503
false
false
false
false
rileytestut/RSTWebViewController
RSTWebViewController/RSTWebViewController/RSTWebViewController.swift
1
24396
// // RSTWebViewController.swift // RSTWebViewController // // Created by Riley Testut on 12/23/14. // Copyright (c) 2014 Riley Testut. All rights reserved. // import UIKit import WebKit public extension RSTWebViewController { //MARK: Update UI func updateToolbarItems() { if self.webView.loading { self.refreshButton = self.stopLoadingButton } else { self.refreshButton = self.reloadButton } if self.showsDoneButton && self.doneButton == nil { self.doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismissWebViewController:") } else if !self.showsDoneButton && self.doneButton != nil { self.doneButton = nil } self.backButton.enabled = self.webView.canGoBack self.forwardButton.enabled = self.webView.canGoForward if self.traitCollection.horizontalSizeClass == .Regular { self.toolbarItems = nil let fixedSpaceItem = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil) fixedSpaceItem.width = 20.0 let reloadButtonFixedSpaceItem = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil) reloadButtonFixedSpaceItem.width = fixedSpaceItem.width if self.refreshButton == self.stopLoadingButton { reloadButtonFixedSpaceItem.width = fixedSpaceItem.width + 1 } var items = [self.shareButton, fixedSpaceItem, self.refreshButton, reloadButtonFixedSpaceItem, self.forwardButton, fixedSpaceItem, self.backButton, fixedSpaceItem] if self.showsDoneButton { items.insert(fixedSpaceItem, atIndex: 0) items.insert(self.doneButton!, atIndex: 0) } self.navigationItem.rightBarButtonItems = items } else { // We have to set rightBarButtonItems instead of simply rightBarButtonItem to properly clear previous buttons self.navigationItem.rightBarButtonItems = self.showsDoneButton ? [self.doneButton!] : nil let flexibleSpaceItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) self.toolbarItems = [self.backButton, flexibleSpaceItem, self.forwardButton, flexibleSpaceItem, self.refreshButton, flexibleSpaceItem, self.shareButton] } } } public class RSTWebViewController: UIViewController { //MARK: Public Properties // WKWebView used to display webpages public private(set) var webView: WKWebView // UIBarButton items. Customizable, and subclasses can override updateToolbarItems() to arrange them however they want public var backButton: UIBarButtonItem = UIBarButtonItem(image: nil, style: .Plain, target: nil, action: "goBack:") public var forwardButton: UIBarButtonItem = UIBarButtonItem(image: nil, style: .Plain, target: nil, action: "goForward:") public var shareButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: nil, action: "shareLink:") public var reloadButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: nil, action: "refresh:") public var stopLoadingButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: nil, action: "refresh:") public var doneButton: UIBarButtonItem? // Set to true when presenting modally to show a Done button that'll dismiss itself. public var showsDoneButton: Bool = false { didSet { self.updateToolbarItems() } } // Array of activity types that should not be displayed in the UIActivityViewController share sheet public var excludedActivityTypes: [String]? // Array of application-specific UIActivities to handle sharing links via UIActivityViewController public var applicationActivities: [UIActivity]? //MARK: Private Properties private let initialReqest: NSURLRequest? private let progressView = UIProgressView() private var ignoreUpdateProgress: Bool = false private var refreshButton: UIBarButtonItem //MARK: Initializers public required init(request: NSURLRequest?) { self.initialReqest = request let configuration = WKWebViewConfiguration() self.webView = WKWebView(frame: CGRectZero, configuration: configuration) self.refreshButton = self.reloadButton super.init(nibName: nil, bundle: nil) self.initialize() } public convenience init (URL: NSURL?) { if let URL = URL { self.init(request: NSURLRequest(URL: URL)) } else { self.init(request: nil) } } public convenience init (address: String?) { if let address = address { self.init(URL: NSURL(string: address)) } else { self.init(URL: nil) } } public required init(coder: NSCoder) { let configuration = WKWebViewConfiguration() self.webView = WKWebView(frame: CGRectZero, configuration: configuration) self.refreshButton = self.reloadButton self.initialReqest = nil super.init(coder: coder) self.initialize() } private func initialize() { self.progressView.progressViewStyle = .Bar self.progressView.autoresizingMask = .FlexibleWidth | .FlexibleTopMargin self.progressView.progress = 0.5 self.progressView.alpha = 0.0 self.progressView.hidden = true self.backButton.target = self self.forwardButton.target = self self.reloadButton.target = self self.stopLoadingButton.target = self self.shareButton.target = self let bundle = NSBundle(forClass: RSTWebViewController.self) self.backButton.image = UIImage(named: "back_button", inBundle: bundle, compatibleWithTraitCollection: nil) self.forwardButton.image = UIImage(named: "forward_button", inBundle: bundle, compatibleWithTraitCollection: nil) } deinit { self.stopKeyValueObserving() } //MARK: UIViewController public override func loadView() { self.startKeyValueObserving() if let request = self.initialReqest { self.webView.loadRequest(request) } self.view = self.webView } public override func viewDidLoad() { super.viewDidLoad() self.updateToolbarItems() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.webView.estimatedProgress < 1.0 { self.transitionCoordinator()?.animateAlongsideTransition( { (context) in self.showProgressBar(animated: true) }) { (context) in if context.isCancelled() { self.hideProgressBar(animated: false) } } } if self.traitCollection.horizontalSizeClass == .Regular { self.navigationController?.setToolbarHidden(true, animated: false) } else { self.navigationController?.setToolbarHidden(false, animated: false) } self.updateToolbarItems() } public override func viewWillDisappear(animated: Bool) { super.viewDidDisappear(animated) var shouldHideToolbarItems = true if let toolbarItems = self.navigationController?.topViewController.toolbarItems { if toolbarItems.count > 0 { shouldHideToolbarItems = false } } if shouldHideToolbarItems { self.navigationController?.setToolbarHidden(true, animated: false) } self.transitionCoordinator()?.animateAlongsideTransition( { (context) in self.hideProgressBar(animated: true) }) { (context) in if context.isCancelled() && self.webView.estimatedProgress < 1.0 { self.showProgressBar(animated: false) } } } public override func didMoveToParentViewController(parent: UIViewController?) { if parent == nil { self.webView.stopLoading() } } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: Layout public override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition({ (context) in if self.traitCollection.horizontalSizeClass == .Regular { self.navigationController?.setToolbarHidden(true, animated: true) } else { self.navigationController?.setToolbarHidden(false, animated: true) } }, completion: nil) } public override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) self.updateToolbarItems() } //MARK: KVO public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) { if context == RSTWebViewControllerContext { let webView = (object as! WKWebView) switch keyPath { case "title": self.updateTitle(webView.title) case "estimatedProgress": self.updateProgress(Float(webView.estimatedProgress)) case "loading": self.updateLoadingStatus(status: webView.loading) case "canGoBack", "canGoForward": self.updateToolbarItems() default: println("Unknown KVO keypath") } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } } // Cannot be private or else they will crash upon being called ಠ_ಠ internal extension RSTWebViewController { //MARK: Dismissal func dismissWebViewController(sender: UIBarButtonItem) { self.parentViewController?.dismissViewControllerAnimated(true, completion: nil) } //MARK: Toolbar Items func goBack(button: UIBarButtonItem) { self.webView.goBack() } func goForward(button: UIBarButtonItem) { self.webView.goForward() } func refresh(button: UIBarButtonItem) { if self.webView.loading { self.ignoreUpdateProgress = true self.webView.stopLoading() } else { if self.webView.URL == nil && self.webView.backForwardList.backList.count == 0 && self.initialReqest != nil { self.webView.loadRequest(self.initialReqest!) } else { self.webView.reload() } } } func shareLink(button: UIBarButtonItem) { let activityItem = RSTURLActivityItem(URL: self.webView.URL ?? NSURL()) activityItem.title = self.webView.title if self.excludedActivityTypes == nil || (self.excludedActivityTypes != nil && !contains(self.excludedActivityTypes!, RSTActivityTypeOnePassword)) { #if DEBUG // If UIApplication.rst_sharedApplication() is nil, we are running in an application extension, meaning NSBundle.mainBundle() will return the extension bundle, not the container app's // Because of this, we can't check to see if the Imported UTIs have been added, but since the assert is purely for debugging, it's not that big of an issue if UIApplication.rst_sharedApplication() != nil { var importedOnePasswordUTI = false var importedURLUTI = false if let importedUTIs = NSBundle.mainBundle().objectForInfoDictionaryKey("UTImportedTypeDeclarations") as! [[String: AnyObject]]? { for importedUTI in importedUTIs { let identifier = importedUTI["UTTypeIdentifier"] as! String if identifier == "org.appextension.fill-webview-action" { importedOnePasswordUTI = true } else if identifier == "com.rileytestut.RSTWebViewController.url" { let UTIs = importedUTI["UTTypeConformsTo"] as! [String] if contains(UTIs, "org.appextension.fill-webview-action") && contains(UTIs, "public.url") { importedURLUTI = true break } } if importedOnePasswordUTI && importedURLUTI { break } } } assert(importedOnePasswordUTI && importedURLUTI, "Either the 1Password Extension UTI, the RSTWebViewController URL UTI, or both, have not been properly declared as Imported UTIs. Please see the RSTWebViewController README for details on how to add them.") } #endif let onePasswordURLScheme = NSURL(string: "org-appextension-feature-password-management://") // If we're running in an application extension, there is no way to detect if 1Password is installed. // Because of this, if UIApplication.rst_sharedApplication() == nil, we'll simply assume it is installed, since there's no harm in doing so if UIApplication.rst_sharedApplication() == nil || (onePasswordURLScheme != nil && UIApplication.rst_sharedApplication().canOpenURL(onePasswordURLScheme!)) { activityItem.typeIdentifier = "com.rileytestut.RSTWebViewController.url" RSTOnePasswordExtension.sharedExtension().createExtensionItemForWebView(self.webView, completion: { (extensionItem, error) in activityItem.setItem(extensionItem, forActivityType: "com.agilebits.onepassword-ios.extension") activityItem.setItem(extensionItem, forActivityType: "com.agilebits.beta.onepassword-ios.extension") self.presentActivityViewControllerWithItems([activityItem], fromBarButtonItem: button) }) return } } self.presentActivityViewControllerWithItems([activityItem], fromBarButtonItem: button) } func presentActivityViewControllerWithItems(activityItems: [AnyObject], fromBarButtonItem barButtonItem: UIBarButtonItem) { var applicationActivities = self.applicationActivities ?? [UIActivity]() if let excludedActivityTypes = self.excludedActivityTypes { if !contains(excludedActivityTypes, RSTActivityTypeSafari) { applicationActivities.append(RSTSafariActivity()) } if !contains(excludedActivityTypes, RSTActivityTypeChrome) { applicationActivities.append(RSTChromeActivity()) } } else { applicationActivities.append(RSTSafariActivity()) applicationActivities.append(RSTChromeActivity()) } let reloadButtonTintColor = self.reloadButton.tintColor let stopLoadingButtonTintColor = self.stopLoadingButton.tintColor let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: applicationActivities) activityViewController.excludedActivityTypes = self.excludedActivityTypes activityViewController.modalPresentationStyle = .Popover activityViewController.popoverPresentationController?.barButtonItem = barButtonItem activityViewController.completionWithItemsHandler = { activityType, success, items, error in if RSTOnePasswordExtension.sharedExtension().isOnePasswordExtensionActivityType(activityType) { RSTOnePasswordExtension.sharedExtension().fillReturnedItems(items, intoWebView: self.webView, completion: nil) } // Because tint colors aren't properly updated when views aren't in a view hierarchy, we manually fix any erroneous tint colors self.progressView.tintColorDidChange() let systemTintColor = UIColor(red: 0, green: 0.478431, blue: 1, alpha: 1) // If previous tint color is nil, we need to temporarily set the tint color to something else or it won't visually update the tint color if reloadButtonTintColor == nil { self.reloadButton.tintColor = systemTintColor } if stopLoadingButtonTintColor == nil { self.stopLoadingButton.tintColor = systemTintColor } self.reloadButton.tintColor = reloadButtonTintColor self.stopLoadingButton.tintColor = stopLoadingButtonTintColor } self.presentViewController(activityViewController, animated: true, completion: nil) } } private let RSTWebViewControllerContext = UnsafeMutablePointer<()>() private extension RSTWebViewController { //MARK: KVO func startKeyValueObserving() { self.webView.addObserver(self, forKeyPath: "title", options:nil, context: RSTWebViewControllerContext) self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: nil, context: RSTWebViewControllerContext) self.webView.addObserver(self, forKeyPath: "loading", options: nil, context: RSTWebViewControllerContext) self.webView.addObserver(self, forKeyPath: "canGoBack", options: nil, context: RSTWebViewControllerContext) self.webView.addObserver(self, forKeyPath: "canGoForward", options: nil, context: RSTWebViewControllerContext) } func stopKeyValueObserving() { self.webView.removeObserver(self, forKeyPath: "title", context: RSTWebViewControllerContext) self.webView.removeObserver(self, forKeyPath: "estimatedProgress", context: RSTWebViewControllerContext) self.webView.removeObserver(self, forKeyPath: "loading", context: RSTWebViewControllerContext) self.webView.removeObserver(self, forKeyPath: "canGoBack", context: RSTWebViewControllerContext) self.webView.removeObserver(self, forKeyPath: "canGoForward", context: RSTWebViewControllerContext) } //MARK: Update UI func updateTitle(title: String?) { self.title = title } func updateLoadingStatus(status loading: Bool) { self.updateToolbarItems() if let application = UIApplication.rst_sharedApplication() { if loading { application.networkActivityIndicatorVisible = true } else { application.networkActivityIndicatorVisible = false } } } func updateProgress(progress: Float) { if self.progressView.hidden { self.showProgressBar(animated: true) } if self.ignoreUpdateProgress { self.ignoreUpdateProgress = false self.hideProgressBar(animated: true) } else if progress < self.progressView.progress { // If progress is less than self.progressView.progress, another webpage began to load before the first one completed // In this case, we set the progress back to 0.0, and then wait until the next updateProgress, because it results in a much better animation self.progressView.setProgress(0.0, animated: false) } else { UIView.animateWithDuration(0.4, animations: { self.progressView.setProgress(progress, animated: true) }, completion: { (finished) in if progress == 1.0 { // This delay serves two purposes. One, it keeps the progress bar on screen just a bit longer so it doesn't appear to disappear too quickly. // Two, it allows us to prevent the progress bar from disappearing if the user actually started loading another webpage before the current one finished loading. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64((0.2 * Float(NSEC_PER_SEC)))), dispatch_get_main_queue(), { if self.webView.estimatedProgress == 1.0 { self.hideProgressBar(animated: true) } }) } }); } } func showProgressBar(#animated: Bool) { let navigationBarBounds = self.navigationController?.navigationBar.bounds ?? CGRectZero self.progressView.frame = CGRect(x: 0, y: navigationBarBounds.height - self.progressView.bounds.height, width: navigationBarBounds.width, height: self.progressView.bounds.height) self.navigationController?.navigationBar.addSubview(self.progressView) self.progressView.setProgress(Float(self.webView.estimatedProgress), animated: false) self.progressView.hidden = false if animated { UIView.animateWithDuration(0.4) { self.progressView.alpha = 1.0 } } else { self.progressView.alpha = 1.0 } } func hideProgressBar(#animated: Bool) { if animated { UIView.animateWithDuration(0.4, animations: { self.progressView.alpha = 0.0 }, completion: { (finished) in self.progressView.setProgress(0.0, animated: false) self.progressView.hidden = true self.progressView.removeFromSuperview() }) } else { self.progressView.alpha = 0.0 // Completion self.progressView.setProgress(0.0, animated: false) self.progressView.hidden = true self.progressView.removeFromSuperview() } } }
mit
0b1cb6ec1a12ad47c67c330b4d51e506
35.353204
275
0.586053
5.979897
false
false
false
false
orta/Swift-at-Artsy
Beginners/Lesson Four/Lesson Four.playground/Contents.swift
1
16528
import Foundation /*: Great, lesson 4 - almost done! ### Overview of last week In lesson three we expanded our knowledge of structs, and added a new language concept - functions. We created some blueprints for creating objects that could represent some real data. Then we showed how you can declare a chunk of code and give it a name, by using functions you can work with different levels of abstractions. We then moved on to applying a function to a struct blueprint so that we could use the same code in different places where we might use that object. ### Shows We're going to have a really pragmatic lesson today. We know enough of the fundamentals now, that we can start replicating some of the Artsy iOS codebase. Notably, the shows page. This one from the [Yossi Milo Gallery](https://www.artsy.net/yossi-milo-gallery) - [Light, Paper, Process: Reinventing Photography](https://www.artsy.net/show/yossi-milo-gallery-light-paper-process-reinventing-photography) ![images/shows.png](images/shows.png) Let's try and break down what we see here: * We show installation shots at the top of the screen * Under the install shots, there is a share this button * Then the name of the Partner * The name of the show * The date range for the show * The address of the show * A follow gallery button * A list of artworks, for each artwork we show: * The Artwork image * We'll skip the Artwork's Artist - call this homework if you'd like. * Artwork's name, and the date So the aim of this lesson is that we have an ASCII image of the show page in the console in Xcode. In order to do this, we're going to represent all _images_ as text. The only thing we will *not* be doing, is having two columns of Artworks. Sorry. So we'll be aiming for something that looks a bit like this in the Xcode console: /*: ---------------------------------------------- [ ] [ ] [ ] [ ] [ ] ---------------------------------------------- * * * * * [ ^ ] Yossi Milo Gallery [ FOLLOW GALLERY ] Light, Paper, Process: Reinventing Photography Apr 14th - Sep 6th The J.Paul Getty Museum, LA --------------------------------------- [ ] [ ] [ ] --------------------------------------- Defender Argo, 1910 --------------------------------------- [ ] [ ] [ ] [ ] [ ] --------------------------------------- Anthony & Scoville, 1910 /*: #### Xcode console The Xcode console is a tool at the bottom of the playground, when you use `print` it will send that text to that logger section. You can access it either by pressing `cmd + shift + y` together or tapping the little square in the bottom left. ![images/console.png](images/console.png) ### The Show Let's start with the Show object. We'll create a `struct` blueprint to represent the show: */ struct Show { var name: String var openingDate: NSDate var closingDate: NSDate } /*: We're going to need a few more things: * A way to draw the installation shot image * A way to represent the Partner relationship * A way to show the date range for the show * A way to hold a collection of Artworks We'll go through these incrementally. Let's look at a way to draw the installation image. We can use a function to draw the installation image. */ func drawInstallationImage() { print("----------------------------------------------") print("") print(" [ ] [ ] [ ] [ ] [ ]") print("") print("----------------------------------------------") print(" * * * * *") print("") } /*: This will print out the installation image once we call it. Let's move it on to the Show struct: */ struct Show { var name: String var openingDate: NSDate var closingDate: NSDate func drawInstallationImage() { print("----------------------------------------------") print("") print(" [ ] [ ] [ ] [ ] [ ]") print("") print("----------------------------------------------") print(" * * * * *") print("") } } /*: This is great. Let's see it in our console. To do that we have to make an instance of our Show. Because we have two dates, this is going to be a bit more complicated than normal. In order to have a date object we have to create a date formatter. A date formatter can create a date from some text. */ var formatter = NSDateFormatter() formatter.dateFormat = "dd-MM-yyyy" /*: This says create a `NSDateFormatter` and give it a date format that makes sense. E.g. day-month-year. From here we can use the formatter variable to create dates for us, so let's make the start/end dates. */ var startDate = formatter.dateFromString("14-04-2015")! var endDate = formatter.dateFromString("6-09-2015")! /*: Perfect, we even have the playground re-enforce that this worked right. Let's just ignore the `!` at the end for now, it's likely we'll not go over this at all in our lessons. However if you want to learn more, check out [Swift Optionals](http://www.appcoda.com/beginners-guide-optionals-swift/) ![images/dates.png](images/dates.png) Awesome. We have enough to create a `Show` now. */ var show = Show(name: "Light, Paper, Process: Reinventing Photography", openingDate: startDate, closingDate: endDate) /*: Finally, kick off `drawInstallationImage` function and check your console. ![images/shots.png](images/shots.png) Great. We're getting there. #### Partnerships Let's look at the partner relationship. A Partner in Artsy could be a gallery, museum, auction, fair or more. We don't need to care too much about the [specifics](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it), so lets just make a generic `Partner` `struct` that has a name. Note: this needs to go above the `Show` blueprint. */ struct Partner { var name:String; } /*: That's all we need for this demo. We want to say that a show has a `Partner` so lets add a var to the `Show`. */ struct Show { var name: String var openingDate: NSDate var closingDate: NSDate var partner: Partner [...] /*: This will break our show at the bottom, because it now also needs a `Partner` object. Let's update that. */ var partner = Partner(name: "Yossi Milo Gallery") var show = Show(name: "Light, Paper, Process: Reinventing Photography", openingDate: startDate, closingDate: endDate, partner: partner) /*: 👍 ### When does this finish? Let's take a look at the date range. Let's create a function on the `Show` that creates a date range like we want to see. */ struct Show { [...] func drawShowRange() { var formatter = NSDateFormatter() formatter.dateFormat = "MM-dd" var end = formatter.stringFromDate(self.openingDate) var start = formatter.stringFromDate(self.closingDate) print("\(end) - \(start)") } /*: uh oh! Lots of yellow here. ![images/yellow.png](images/yellow.png) So, we've been using `var` everywhere, because I want to re-enforce the "variables" idea. However, in Swift the language designers would prefer that you declare if a variable is going to change or not. In this case, we are not making changes to these variables so we should declare them using `let` instead. This tells other programmers that no-one will be making changes to this variable, so it represents only one thing and it will not change for as long as it exists. */ struct Show { [...] func drawShowRange() { let formatter = NSDateFormatter() formatter.dateFormat = "MM-dd" let end = formatter.stringFromDate(self.openingDate) let start = formatter.stringFromDate(self.closingDate) print("\(end) - \(start)") } /*: Finally let's wrap up our work on the Show by adding an array of `Artwork`s. We can use our `Artwork` declaration from last week. */ struct Artwork { var name: String var medium: String var availability: String var date: String } /*: Put this above the `Show` `struct` also. We want to make an array of `Artwork`s. This is pretty simple instead of writing `var artworks: Artwork` like you would for one artwork, you do `var artworks: [Artwork]` which implies it's a collection of `Artwork` objects. */ struct Show { var name: String var openingDate: NSDate var closingDate: NSDate var partner: Partner var artworks: [Artworks] [...] /*: This, again, will break our `Show(` function, so let's make two `Artwork` objects: */ var defender = Artwork(name: "Defender Argo", medium: "Print", availability: "For Sale", date: "1910") var burke = Artwork(name: "Burke & James Rexo", medium: "Print", availability: "For Sale", date: "1910") /*: Next up we can fix our `Show(`: */ var show = Show(name: "Light, Paper, Process: Reinventing Photography", openingDate: startDate, closingDate: endDate, partner: partner, artworks: [defender, burke]) /*: So we have put the two artwork objects created above, `defender` and `burke` in to the Show as an array using `[defender, burke]`. OK, that's everything we need from the `Show`'s perspective. Let's devote some time to improving the output. Let's think in objects. We want an object that represents the Show Page. This is the object that we can use to show things like the share button, or the follow gallery button. It is a higher level of abstraction above the Artwork. We're now dealing with a pure abstraction. It's only going to need a `Show`. We'll use it to hold functions. Let's make a `printPage` function. Add this directly after the `Show` declaration. */ struct ShowPage { var show: Show func drawPage() { // do nothing } } /*: Great. Let's make one at the bottom of our playground. Replacing */ show.drawInstallationImage() show.drawShowRange() /*: with */ var showPage = ShowPage(show: show) showPage.drawPage() /*: This removes all the console output, that's ok. We're going to start building it back up now. We should move the `show.drawInstallationImage()` into the `drawPage` function. */ struct ShowPage { [...] func drawPage() { self.show.drawInstallationImage() } } /*: Perfect, now it's the role of the `ShowPage` to start piecing together our drawing! Give the `ShowPage` a function to draw the share button` */ struct ShowPage { [...] func drawShareButton() { print(" [ ^ ]") } } /*: Then call it from the `drawPage` function via `self.drawSharePage()`. Awesome. Next up is the partner name and the follow button. We'll make a function called `drawPartnerCallToAction` to display that. */ struct ShowPage { [...] func drawPartnerCallToAction() { print("\(self.show.partner.name) [ FOLLOW GALLERY ]") } } /*: and call that from the `drawPage` with `self.drawPartnerCallToAction()`. By this point your `drawPage` should look like: */ struct ShowPage { [...] func drawPage() { self.show.drawInstallationImage() self.drawShareButton() self.drawPartnerCallToAction() } } /*: Which will echo out in the console something like this: /*: ---------------------------------------------- [ ] [ ] [ ] [ ] [ ] ---------------------------------------------- * * * * * [ ^ ] Yossi Milo Gallery [ FOLLOW GALLERY ] /*: Awesome. Next up, we want to print the show name. Append `print(self.show.name)` to the end of your `drawShow` function. The show availability date can be done with `self.show.drawShowRange()`. Finally to wrap up this section we want to add the partner's location. Let's quickly go add this in. */ struct Show { var name: String var location: String var openingDate: NSDate var closingDate: NSDate var partner: Partner var artworks: [Artwork] [...] /*: Note that the order is important. I put it next to name, as they feel closely linked, this means we have to add the location to the `Show(` call in the same place. This means our variable looks like: */ var show = Show(name: "Light, Paper, Process: Reinventing Photography", location: "The J.Paul Getty Museum, LA", openingDate: startDate, closingDate: endDate, partner: partner, artworks: [defender, burke]) /*: Awesome, add the location to the `drawPage`. It should look like this: */ struct Show { [...] func drawPage() { self.show.drawInstallationImage() self.drawShareButton() self.drawPartnerCallToAction() print(self.show.name) self.show.drawShowRange() print(self.show.location) } [...] /*: Which prints out our header as expected! All that's left is showing the artworks. We get to use the `for` statement that we used back in week one. Let's start out by printing the artworks name. Append this to the bottom of `drawPage`. */ for artwork in self.show.artworks { print(artwork.name) } /*: We want to show artworks that have different heights. In order to do this we have to let an `Artwork` declare how many lines tall it is. Let's amend the `Artwork`. */ struct Artwork { var name: String var medium: String var availability: String var date: String var height: Int [...] /*: This breaks our artwork declarations below. So they should look like: */ var defender = Artwork(name: "Defender Argo", medium: "Print", availability: "For Sale", date: "1910", height: 3) var burke = Artwork(name: "Burke & James Rexo", medium: "Print", availability: "For Sale", date: "1910", height: 5) /*: Now we can draw an artwork! Let's start by drawing the top and bottom of our artwork in the loop. */ struct Show { [...] func drawPage() { [...] for artwork in self.show.artworks { print(" ---------------------------------------") // draw the middle print(" ---------------------------------------") print(artwork.name) } } [...] /*: Now we want to figure out this "draw the middle bit". We want to draw `x` amount of lines, that correspond to the artwork's height. So let's use another for loop. This time using a range of from `0` to the artwork's height. */ for _ in 0 ..< artwork.height { print(" [ ]") } /*: We're using the `_` to say that we don't want to do anything with the variable that the `for loop` gives us. With that in you should add an extra line of text before an artwork, and move the artwork name across to add up some polish. `drawPage` should look look like: */ struct ShowPage { var show: Show func drawPage() { self.show.drawInstallationImage() self.drawShareButton() self.drawPartnerCallToAction() print(self.show.name) self.show.drawShowRange() print(self.show.location) for artwork in self.show.artworks { print("") print(" ---------------------------------------") for _ in 0 ..< artwork.height { print(" [ ]") } print(" ---------------------------------------") print(" \(artwork.name)") } } } /*: Check your console, we've done it. That's it for today. We've not strictly learned any new things, but we've started to hopefully form connections between the things we have learned already and see how we can really model how we would build a page on Artsy with that knowledge. ### Overview In lesson one, we learned about some of the primitives that Swift gives us. Mainly `Int`s and `String`s, and how to use an `if` and `for` to run different code paths. In lesson two, we improved our primitive knowledge with Bools, and enums. Did a lot of `if` statements and some boolean algebra. Then started using `struct`s to represent ideas. In lesson three we talked about schools of thought for programming, then started looking at how we can give a collection of code a name - known as a function. Then we moved the code on to a struct to keep the code together logically. In lesson four, we have * Looked at drawing a page from the Artsy iOS app * Connected a lot of objects and functions together to form a real-world use-case. Ish. Why not take what we've learned, and add an `Artist` to an object. Then show the `Artist`'s name under an artwork in the playground? */
cc0-1.0
5fd1a54572b9df33a51063231da2b349
30.59847
475
0.640545
3.905696
false
false
false
false
thedreamer979/Calvinus
Calvin/NoteManager.swift
1
2090
// // NoteManager.swift // Calvin // // Created by Arion Zimmermann on 11.03.17. // Copyright © 2017 AZEntreprise. All rights reserved. // import UIKit var notes = [String : [String]]() func readNotes() { if let array = UserDefaults.standard.dictionary(forKey: "notes") { for element in array { notes[element.key] = (element.value as! String).components(separatedBy: "|") } print(array) } else { UserDefaults.standard.set([String : String](), forKey: "notes") } } func writeNotes() { var dictionary = [String : String]() for key in notes.keys { let elements = notes[key] var buffer = String() for element in elements! { buffer += element.replacingOccurrences(of: "|", with: "-") + "|" } if !buffer.isEmpty { dictionary[key] = buffer[buffer.startIndex..<buffer.index(before: buffer.endIndex)] } } UserDefaults.standard.set(dictionary, forKey: "notes") } func moyenne(of: String) -> Double { if let array = notes[of] { var i = 0.0 var count = 0.0 for element in array { if !element.isEmpty { let tabs = element.components(separatedBy: "\t") if tabs.count > 1 { let multiplier = Double(tabs[1].replacingOccurrences(of: "x", with: ""))! if let note = Double(element.components(separatedBy: " ")[0]) { i += note * multiplier } else { i += Double(tabs[0])! * multiplier } count += multiplier } } } return round(Double(i / count) * 10.0) / 10.0 } else { return -1 } } func colorAlgorithm(withNote: Double) -> UIColor { return UIColor(red: CGFloat(1.0 - (withNote - 3) / 3.0), green: CGFloat((withNote - 3) / 3.0), blue: 0.0, alpha: 1.0) }
gpl-3.0
2e24dc9397192869ad87f91248f4df6e
26.486842
121
0.497367
4.194779
false
false
false
false
nerdishbynature/octokit.swift
OctoKit/NotificationThread.swift
1
15907
import Foundation import RequestKit #if canImport(FoundationNetworking) import FoundationNetworking #endif // MARK: - Model open class NotificationThread: Codable { open internal(set) var id: String? = "-1" open var unread: Bool? open var reason: Reason? open var updatedAt: Date? open var lastReadAt: Date? open private(set) var subject = Subject() open private(set) var repository = Repository() enum CodingKeys: String, CodingKey { case id case unread case reason case updatedAt = "updated_at" case lastReadAt = "last_read_at" case subject case repository } public class Subject: Codable { open internal(set) var id: Int = -1 open var title: String? open var url: String? open var latestCommentUrl: String? open var type: String? enum CodingKeys: String, CodingKey { case title case url case latestCommentUrl = "latest_comment_url" case type } } public enum Reason: String, Codable { case assign case author case comment case invitation case manual case mention case reviewRequested = "review_requested" case securityAlert = "security_alert" case stateChange = "state_change" case subscribed case teamMention = "team_mention" } } open class ThreadSubscription: Codable { open internal(set) var id: Int? = -1 open var subscribed: Bool? open var ignored: Bool? open var reason: String? open var url: String? open var threadUrl: String? enum CodingKeys: String, CodingKey { case id case subscribed case ignored case reason case url case threadUrl = "thread_url" } } // MARK: - Request public extension Octokit { /** List all notifications for the current user, sorted by most recently updated. - parameter session: RequestKitURLSession, defaults to URLSession.shared - parameter all: show notifications marked as read `false` by default. - parameter participating: only shows notifications in which the user is directly participating or mentioned. `false` by default. - parameter page: Current page for notification pagination. `1` by default. - parameter perPage: Number of notifications per page. `100` by default. - parameter completion: Callback for the outcome of the fetch. */ @discardableResult func myNotifications(_ session: RequestKitURLSession = URLSession.shared, all: Bool = false, participating: Bool = false, page: String = "1", perPage: String = "100", completion: @escaping (_ response: Result<[NotificationThread], Error>) -> Void) -> URLSessionDataTaskProtocol? { let router = NotificationRouter.readNotifications(configuration, all, participating, page, perPage) return router.load(session, dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter), expectedResultType: [NotificationThread].self) { notifications, error in if let error = error { completion(.failure(error)) } else { if let notifications = notifications { completion(.success(notifications)) } } } } /** Marks All Notifications As read - parameter session: RequestKitURLSession, defaults to URLSession.shared - parameter lastReadAt: Describes the last point that notifications were checked `last_read_at` by default. - parameter read: Whether the notification has been read `false` by default. - parameter completion: Callback for the outcome of the fetch. */ @discardableResult func markNotificationsRead(_ session: RequestKitURLSession = URLSession.shared, lastReadAt: String = "last_read_at", read: Bool = false, completion: @escaping (_ response: Error?) -> Void) -> URLSessionDataTaskProtocol? { let router = NotificationRouter.markNotificationsRead(configuration, lastReadAt, read) return router.load(session, completion: completion) } /** Marks All Notifications As read - parameter session: RequestKitURLSession, defaults to URLSession.shared - parameter threadId: The ID of the Thread. - parameter completion: Callback for the outcome of the fetch. */ @discardableResult func getNotificationThread(_ session: RequestKitURLSession = URLSession.shared, threadId: String, completion: @escaping (_ response: Result<NotificationThread, Error>) -> Void) -> URLSessionDataTaskProtocol? { let router = NotificationRouter.getNotificationThread(configuration, threadId) return router.load(session, dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter), expectedResultType: NotificationThread.self) { notification, error in if let error = error { completion(.failure(error)) } else { if let notification = notification { completion(.success(notification)) } } } } /** Get a thread subscription for the authenticated user - parameter session: RequestKitURLSession, defaults to URLSession.shared - parameter threadId: The ID of the Thread. - parameter completion: Callback for the outcome of the fetch. */ @discardableResult func getThreadSubscription(_ session: RequestKitURLSession = URLSession.shared, threadId: String, completion: @escaping (_ response: Result<ThreadSubscription, Error>) -> Void) -> URLSessionDataTaskProtocol? { let router = NotificationRouter.getThreadSubscription(configuration, threadId) return router.load(session, dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter), expectedResultType: ThreadSubscription.self) { thread, error in if let error = error { completion(.failure(error)) } else { if let thread = thread { completion(.success(thread)) } } } } /** Sets a thread subscription for the authenticated user - parameter session: RequestKitURLSession, defaults to URLSession.shared - parameter threadId: The ID of the Thread. - parameter ignored: Whether to block all notifications from a thread `false` by default. - parameter completion: Callback for the outcome of the fetch. */ @discardableResult func setThreadSubscription(_ session: RequestKitURLSession = URLSession.shared, threadId: String, ignored: Bool = false, completion: @escaping (_ response: Result<ThreadSubscription, Error>) -> Void) -> URLSessionDataTaskProtocol? { let router = NotificationRouter.setThreadSubscription(configuration, threadId, ignored) return router.load(session, dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter), expectedResultType: ThreadSubscription.self) { thread, error in if let error = error { completion(.failure(error)) } else { if let thread = thread { completion(.success(thread)) } } } } /** Delete a thread subscription - parameter session: RequestKitURLSession, defaults to URLSession.shared - parameter threadId: The ID of the Thread. - parameter completion: Callback for the outcome of the fetch. */ @discardableResult func deleteThreadSubscription(_ session: RequestKitURLSession = URLSession.shared, threadId: String, completion: @escaping (_ response: Error?) -> Void) -> URLSessionDataTaskProtocol? { let router = NotificationRouter.deleteThreadSubscription(configuration, threadId) return router.load(session, completion: completion) } /** List all repository notifications for the current user, sorted by most recently updated. - parameter session: RequestKitURLSession, defaults to URLSession.shared - parameter owner: The name of the owner of the repository. - parameter repository: The name of the repository. - parameter all: show notifications marked as read `false` by default. - parameter participating: only shows notifications in which the user is directly participating or mentioned. `false` by default. - parameter since: Only show notifications updated after the given time. - parameter before: Only show notifications updated before the given time. - parameter page: Current page for notification pagination. `1` by default. - parameter perPage: Number of notifications per page. `100` by default. - parameter completion: Callback for the outcome of the fetch. */ @discardableResult func listRepositoryNotifications(_ session: RequestKitURLSession = URLSession.shared, owner: String, repository: String, all: Bool = false, participating: Bool = false, since: String? = nil, before: String? = nil, page: String = "1", perPage: String = "100", completion: @escaping (_ response: Result<[NotificationThread], Error>) -> Void) -> URLSessionDataTaskProtocol? { let router = NotificationRouter.listRepositoryNotifications(configuration, owner, repository, all, participating, since, before, perPage, page) return router.load(session, dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter), expectedResultType: [NotificationThread].self) { notifications, error in if let error = error { completion(.failure(error)) } else { if let notifications = notifications { completion(.success(notifications)) } } } } /** Marks All Repository Notifications As read - parameter session: RequestKitURLSession, defaults to URLSession.sharedSession() - parameter owner: The name of the owner of the repository. - parameter repository: The name of the repository. - parameter lastReadAt: Describes the last point that notifications were checked `last_read_at` by default. - parameter completion: Callback for the outcome of the fetch. */ @discardableResult func markRepositoryNotificationsRead(_ session: RequestKitURLSession = URLSession.shared, owner: String, repository: String, lastReadAt: String? = nil, completion: @escaping (_ response: Error?) -> Void) -> URLSessionDataTaskProtocol? { let router = NotificationRouter.markRepositoryNotificationsRead(configuration, owner, repository, lastReadAt) return router.load(session, completion: completion) } } // MARK: - Router enum NotificationRouter: Router { case readNotifications(Configuration, Bool, Bool, String, String) case markNotificationsRead(Configuration, String, Bool) case getNotificationThread(Configuration, String) case markNotificationThreadAsRead(Configuration, String) case getThreadSubscription(Configuration, String) case setThreadSubscription(Configuration, String, Bool) case deleteThreadSubscription(Configuration, String) case listRepositoryNotifications(Configuration, String, String, Bool, Bool, String?, String?, String, String) case markRepositoryNotificationsRead(Configuration, String, String, String?) var configuration: Configuration { switch self { case let .readNotifications(config, _, _, _, _): return config case let .markNotificationsRead(config, _, _): return config case let .getNotificationThread(config, _), let .markNotificationThreadAsRead(config, _): return config case let .getThreadSubscription(config, _): return config case let .setThreadSubscription(config, _, _): return config case let .deleteThreadSubscription(config, _): return config case let .listRepositoryNotifications(config, _, _, _, _, _, _, _, _): return config case let .markRepositoryNotificationsRead(config, _, _, _): return config } } var method: HTTPMethod { switch self { case .readNotifications, .getNotificationThread, .getThreadSubscription, .listRepositoryNotifications: return .GET case .markNotificationsRead, .setThreadSubscription, .markRepositoryNotificationsRead: return .PUT case .markNotificationThreadAsRead: return .POST case .deleteThreadSubscription: return .DELETE } } var encoding: HTTPEncoding { .url } var path: String { switch self { case .readNotifications, .markNotificationsRead: return "notifications" case let .getNotificationThread(_, threadID): return "notifications/threads/\(threadID)" case .markNotificationThreadAsRead: return "notifications/threads/" case let .getThreadSubscription(_, threadId), let .setThreadSubscription(_, threadId, _), let .deleteThreadSubscription(_, threadId): return "notifications/threads/\(threadId)/subscription" case let .listRepositoryNotifications(_, owner, repo, _, _, _, _, _, _), let .markRepositoryNotificationsRead(_, owner, repo, _): return "repos/\(owner)/\(repo)/notifications" } } var params: [String: Any] { switch self { case let .readNotifications(_, all, participating, page, perPage): return ["all": "\(all)", "participating": "\(participating)", "page": page, "per_page": perPage] case let .markNotificationsRead(_, lastReadAt, read): return ["last_read_at": lastReadAt, "read": "\(read)"] case .getNotificationThread: return [:] case let .markNotificationThreadAsRead(_, threadID): return ["thread_id": threadID] case .getThreadSubscription: return [:] case .setThreadSubscription: return [:] case .deleteThreadSubscription: return [:] case let .listRepositoryNotifications(_, _, _, all, participating, since, before, perPage, page): var params: [String: String] = [ "all": all.description, "participating": participating.description, "perPage": perPage, "page": page ] if let since = since { params["since"] = since } if let before = before { params["before"] = before } return params case let .markRepositoryNotificationsRead(_, _, _, lastReadAt): var params: [String: String] = [:] if let lastReadAt = lastReadAt { params["last_read_at"] = lastReadAt } return params } } }
mit
25f5ea0ec0c128b5411a8b93f1f57223
42.820937
189
0.617715
5.453205
false
true
false
false
netguru/inbbbox-ios
Unit Tests/ShotDetailsViewModelSpec.swift
1
5617
// // ShotDetailsViewModelSpec.swift // Inbbbox // // Created by Peter Bruz on 22/02/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import Quick import Nimble import PromiseKit import Dobby @testable import Inbbbox class ShotDetailsViewModelSpec: QuickSpec { override func spec() { var sut: ShotDetailsViewModel! var shot: ShotType! var commentsProviderMock: APICommentsProviderMock! var commentsRequesterMock: APICommentsRequesterMock! beforeEach { shot = Shot.fixtureShot() sut = ShotDetailsViewModel(shot: shot, isLiked: nil) commentsProviderMock = APICommentsProviderMock() commentsRequesterMock = APICommentsRequesterMock() sut.commentsProvider = commentsProviderMock sut.commentsRequester = commentsRequesterMock commentsProviderMock.provideCommentsForShotStub.on(any()) { _ in return Promise{ fulfill, _ in let json = JSONSpecLoader.sharedInstance.fixtureCommentsJSON(withCount: 10) let result = json.map { Comment.map($0) } var resultCommentTypes = [CommentType]() for comment in result { resultCommentTypes.append(comment) } fulfill(resultCommentTypes) } } commentsProviderMock.nextPageStub.on(any()) { _ in return Promise{ fulfill, _ in let json = JSONSpecLoader.sharedInstance.fixtureCommentsJSON(withCount: 5) let result = json.map { Comment.map($0) } var resultCommentTypes = [CommentType]() for comment in result { resultCommentTypes.append(comment) } fulfill(resultCommentTypes) } } commentsRequesterMock.postCommentForShotStub.on(any()) { _, _ in return Promise{ fulfill, _ in let result = Comment.fixtureComment() fulfill(result) } } commentsRequesterMock.deleteCommentStub.on(any()) { _, _ in return Promise<Void>(value: Void()) } } afterEach { shot = nil commentsProviderMock = nil sut = nil } describe("when newly initialized") { it("view model should have correct number of items") { expect(sut.itemsCount).to(equal(2)) } it("view model should have correct number of items") { expect(sut.itemsCount).to(equal(2)) } } describe("when comments are loaded for the first time") { var didReceiveResponse: Bool? beforeEach { didReceiveResponse = false waitUntil { done in sut.loadComments().then { result -> Void in didReceiveResponse = true done() }.catch { _ in fail("This should not be invoked") } } } afterEach { didReceiveResponse = nil } it("commments should be properly downloaded") { expect(didReceiveResponse).to(beTruthy()) expect(didReceiveResponse).toNot(beNil()) } it("view model should have correct number of items") { // 10 comments + operationCell + descriptionCell + loadMoreCell expect(sut.itemsCount).to(equal(13)) } } describe("when comments are loaded with pagination") { beforeEach { waitUntil { done in sut.loadComments().then { result in done() }.catch { _ in fail("This should not be invoked") } } waitUntil { done in sut.loadComments().then { result in done() }.catch { _ in fail("This should not be invoked") } } } it("view model should have correct number of items") { // 10 comments + 5 comments (nextPage) + operationCell + descriptionCell + loadMoreCell expect(sut.itemsCount).to(equal(18)) } } describe("when posting comment") { var didReceiveResponse: Bool? beforeEach { didReceiveResponse = false waitUntil { done in sut.postComment("fixture.message").then { result -> Void in didReceiveResponse = true done() }.catch { _ in fail("This should not be invoked") } } } afterEach { didReceiveResponse = nil } it("should be correctly added") { expect(didReceiveResponse).to(beTruthy()) expect(didReceiveResponse).toNot(beNil()) } } } }
gpl-3.0
0030ee4cfb20bb2c4902f8e7d45f954b
33.036364
103
0.473647
5.980831
false
false
false
false
carlodonzelli/TigerspikeInnovation
InnovationDayG5/LoginViewController.swift
1
3460
// // LoginViewController.swift // InnovationDayG5 // // Created by James Pang on 24/11/2016. // Copyright © 2016 CarloDonzelli. All rights reserved. // import UIKit import LocalAuthentication class LoginViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var touchIdButton: UIButton! @IBOutlet weak var loginButton: UIButton! { didSet { let bgImg = UIImage.withColor(UIColor(red: 1, green: 102/255, blue: 51/255, alpha: 1)) loginButton.setBackgroundImage(bgImg, for: .normal) loginButton.layer.cornerRadius = 6.0 } } let viewModel = LoginViewModel() override func viewDidLoad() { super.viewDidLoad() setupView() setupUsernameField() setupPasswordField() } @IBAction func touchIdButtonTapped(_ sender: AnyObject) { let authenticationContext = LAContext() var error: NSError? //Check if the device has a fingerpprint sensor //If not, show the user an alert view and bail out guard authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else { showError(message: error?.localizedDescription ?? "Sorry, cannot perform touch ID") return } authenticationContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Login via touch ID") { success, error in DispatchQueue.main.async { if success { self.pushMainViewController() } else { self.showError(message: error?.localizedDescription ?? "") } } } } @IBAction func loginButtonTapped(_ sender: AnyObject) { guard viewModel.canLogin else { showError(message: "Please enter a username or password") return } pushMainViewController() } func textFieldChanged(textField: UITextField) { if textField == usernameTextField { viewModel.username = textField.text ?? "" } else if textField == passwordTextField { viewModel.password = textField.text ?? "" } } func backgroundTapped() { view.endEditing(false) } } //MARK: - Private fileprivate extension LoginViewController { func pushMainViewController() { let storyboard = UIStoryboard(name: "Main", bundle: nil) if let homeViewController = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController { navigationController?.pushViewController(homeViewController, animated: true) } } } //MARK: - Setup fileprivate extension LoginViewController { func setupView() { let tap = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped)) view.addGestureRecognizer(tap) } func setupUsernameField() { usernameTextField.addTarget(self, action: #selector(textFieldChanged), for: .editingChanged) } func setupPasswordField() { passwordTextField.addTarget(self, action: #selector(textFieldChanged), for: .editingChanged) } }
mit
b4284c2e4ee51028e04c7ca08b003bed
29.610619
135
0.620411
5.597087
false
false
false
false
brentdax/swift
test/TypeCoercion/protocols.swift
8
8972
// RUN: %target-typecheck-verify-swift protocol MyPrintable { func print() } protocol Titled { var title : String { get set } } struct IsPrintable1 : FormattedPrintable, Titled, Document { var title = "" func print() {} func print(_: TestFormat) {} } // Printability is below struct IsPrintable2 { } struct IsNotPrintable1 { } struct IsNotPrintable2 { func print(_: Int) -> Int {} } struct Book : Titled { var title : String } struct Lackey : Titled { var title : String { get {} set {} } } struct Number { var title : Int } func testPrintableCoercion(_ ip1: IsPrintable1, ip2: IsPrintable2, inp1: IsNotPrintable1, inp2: IsNotPrintable2, op: OtherPrintable) { var p : MyPrintable = ip1 // okay p = ip1 // okay p = ip2 // okay p = inp1 // expected-error{{value of type 'IsNotPrintable1' does not conform to 'MyPrintable' in assignment}} p = inp2 // expected-error{{value of type 'IsNotPrintable2' does not conform to 'MyPrintable' in assignment}} p = op // expected-error{{value of type 'OtherPrintable' does not conform to 'MyPrintable' in assignment}} _ = p } func testTitledCoercion(_ ip1: IsPrintable1, book: Book, lackey: Lackey, number: Number, ip2: IsPrintable2) { var t : Titled = ip1 // okay t = ip1 t = book t = lackey t = number // expected-error{{value of type 'Number' does not conform to 'Titled' in assignment}} t = ip2 // expected-error{{value of type 'IsPrintable2' does not conform to 'Titled' in assignment}} _ = t } extension IsPrintable2 : MyPrintable { func print() {} } protocol OtherPrintable { func print() } struct TestFormat {} protocol FormattedPrintable : MyPrintable { func print(_: TestFormat) } struct NotFormattedPrintable1 { func print(_: TestFormat) { } } func testFormattedPrintableCoercion(_ ip1: IsPrintable1, ip2: IsPrintable2, fp: inout FormattedPrintable, p: inout MyPrintable, op: inout OtherPrintable, nfp1: NotFormattedPrintable1) { fp = ip1 fp = ip2 // expected-error{{value of type 'IsPrintable2' does not conform to 'FormattedPrintable' in assignment}} fp = nfp1 // expected-error{{value of type 'NotFormattedPrintable1' does not conform to 'FormattedPrintable' in assignment}} p = fp op = fp // expected-error{{value of type 'FormattedPrintable' does not conform to 'OtherPrintable' in assignment}} fp = op // expected-error{{value of type 'OtherPrintable' does not conform to 'FormattedPrintable' in assignment}} } protocol Document : Titled, MyPrintable { } func testMethodsAndVars(_ fp: FormattedPrintable, f: TestFormat, doc: inout Document) { fp.print(f) fp.print() doc.title = "Gone with the Wind" doc.print() } func testDocumentCoercion(_ doc: inout Document, ip1: IsPrintable1, l: Lackey) { doc = ip1 doc = l // expected-error{{value of type 'Lackey' does not conform to 'Document' in assignment}} } // Check coercion of references. func refCoercion(_ p: inout MyPrintable) { } var p : MyPrintable = IsPrintable1() var fp : FormattedPrintable = IsPrintable1() // expected-note@-1{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'FormattedPrintable'}} {{10-28=MyPrintable}} var ip1 : IsPrintable1 // expected-note@-1{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{11-23=MyPrintable}} refCoercion(&p) refCoercion(&fp) // expected-error@-1{{inout argument could be set to a value with a type other than 'FormattedPrintable'; use a value declared as type 'MyPrintable' instead}} refCoercion(&ip1) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'MyPrintable' instead}} do { var fp_2 = fp // expected-note@-1{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'FormattedPrintable'}} {{11-11=: MyPrintable}} var ip1_2 = ip1 // expected-note@-1{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{12-12=: MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'FormattedPrintable'; use a value declared as type 'MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'MyPrintable' instead}} } do { var fp_2 : FormattedPrintable = fp, ip1_2 = ip1 // expected-note@-1{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'FormattedPrintable'}} {{14-32=MyPrintable}} // expected-note@-2{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{44-44=: MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'FormattedPrintable'; use a value declared as type 'MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'MyPrintable' instead}} } do { var fp_2, fp_3 : FormattedPrintable // expected-note@-1{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'FormattedPrintable'}} {{20-38=MyPrintable}} // expected-note@-2{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'FormattedPrintable'}} {{20-38=MyPrintable}} fp_2 = fp fp_3 = fp refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'FormattedPrintable'; use a value declared as type 'MyPrintable' instead}} refCoercion(&fp_3) // expected-error@-1{{inout argument could be set to a value with a type other than 'FormattedPrintable'; use a value declared as type 'MyPrintable' instead}} } do { func wrapRefCoercion1(fp_2: inout FormattedPrintable, ip1_2: inout IsPrintable1) { // expected-note@-2{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'FormattedPrintable'}} {{31-55=MyPrintable}} // expected-note@-2{{change variable type to 'MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{32-50=MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'FormattedPrintable'; use a value declared as type 'MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'MyPrintable' instead}} } } do { // Make sure we don't add the fix-it for tuples: var (fp_2, ip1_2) = (fp, ip1) refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'FormattedPrintable'; use a value declared as type 'MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'MyPrintable' instead}} } do { // Make sure we don't add the fix-it for vars in different scopes: enum ParentScope { static var fp_2 = fp } refCoercion(&ParentScope.fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'FormattedPrintable'; use a value declared as type 'MyPrintable' instead}} } protocol IntSubscriptable { subscript(i: Int) -> Int { get } } struct IsIntSubscriptable : IntSubscriptable { subscript(i: Int) -> Int { get {} set {} } } struct IsDoubleSubscriptable { subscript(d: Double) -> Int { get {} set {} } } struct IsIntToStringSubscriptable { subscript(i: Int) -> String { get {} set {} } } func testIntSubscripting(i_s: inout IntSubscriptable, iis: IsIntSubscriptable, ids: IsDoubleSubscriptable, iiss: IsIntToStringSubscriptable) { var x = i_s[17] i_s[5] = 7 // expected-error{{cannot assign through subscript: subscript is get-only}} i_s = iis i_s = ids // expected-error{{value of type 'IsDoubleSubscriptable' does not conform to 'IntSubscriptable' in assignment}} i_s = iiss // expected-error{{value of type 'IsIntToStringSubscriptable' does not conform to 'IntSubscriptable' in assignment}} } protocol MyREPLPrintable { func myReplPrint() } extension Int : MyREPLPrintable { func myReplPrint() {} } extension String : MyREPLPrintable { func myReplPrint() {} } func doREPLPrint(_ p: MyREPLPrintable) { p.myReplPrint() } func testREPLPrintable() { let i : Int = 1 _ = i as MyREPLPrintable doREPLPrint(i) doREPLPrint(1) doREPLPrint("foo") } // Bool coercion if true as Bool {}
apache-2.0
34007d7c327884ac0e5ac44d6b522bd2
36.07438
162
0.682234
3.785654
false
false
false
false
cooliean/CLLKit
XLForm/Examples/Swift/SwiftExample/Others/CustomCells/XLFormCustomCell.swift
14
2501
// // XLFormCustomCell.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // 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. let XLFormRowDescriptorTypeCustom = "XLFormRowDescriptorTypeCustom" class XLFormCustomCell : XLFormBaseCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func configure() { super.configure() } override func update() { super.update() // override if let string = rowDescriptor?.value as? String { textLabel?.text = string } else { textLabel?.text = "Am a custom cell, select me!" } } override func formDescriptorCellDidSelectedWithFormController(controller: XLFormViewController!) { // custom code here // i.e new behaviour when cell has been selected if let string = rowDescriptor?.value as? String where string == "Am a custom cell, select me!" { self.rowDescriptor?.value = string } else { self.rowDescriptor?.value = "I can do any custom behaviour..." } update() controller.tableView.selectRowAtIndexPath(nil, animated: true, scrollPosition: .None) } }
mit
29f78f68a8e05d9ad1b707f3dd51ad2b
36.328358
104
0.684926
4.782027
false
false
false
false
GRSource/GRTabBarController
Example/Controllers/RootTabViewController.swift
1
2890
// // RootTabViewController.swift // GRTabBarController // // Created by iOS_Dev5 on 2017/2/9. // Copyright © 2017年 GRSource. All rights reserved. // import UIKit class RootTabViewController: GRTabBarController, GRTabBarControllerProtocol { override func viewDidLoad() { super.viewDidLoad() self.setupViewControllers() self.customizeTabBarForController() self.delegate = self } //MARK: - Methods func setupViewControllers() { let firstViewController = GRFirst_RootViewController() let firstNavigationController = UINavigationController.init(rootViewController: firstViewController) let secondViewController = GRSecond_RootViewController() let secondNavigationController = UINavigationController.init(rootViewController: secondViewController) let thirdViewController = GRThird_RootViewController() let thirdNavigationController = UINavigationController.init(rootViewController: thirdViewController) self.viewControllers = [firstNavigationController, secondNavigationController, thirdNavigationController] } func customizeTabBarForController() { let finishedImage = UIImage(named: "tabbar_selected_background") let unfinishedImage = UIImage(named: "tabbar_normal_background") let tabBarItemImages = ["first", "second", "third"] var index = 0 for item in self.tabBar.items { item.setBackgroundSelectedImage(finishedImage!, withUnselectedImage: unfinishedImage!) let selectedimage = UIImage(named: "\(tabBarItemImages[index])_selected") let unselectedimage = UIImage(named: "\(tabBarItemImages[index])_normal") item.setFinishedSelectedImage(selectedimage!, withFinishedUnselectedImage: unselectedimage!) item.title = tabBarItemImages[index] index+=1 } } //MARK: - RDVTabBarControllerDelegate func tabBarController(_ tabBarController: GRTabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { return true } func tabBarController(_ tabBarController: GRTabBarController, didSelectViewController viewController: UIViewController) { print("select \(viewController.title)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
80ee4f800956f538aed127394785aa68
35.544304
136
0.694839
5.671906
false
false
false
false
mvandervelden/iOSSystemIntegrationsDemo
SearchDemo/DataModel/Storage.swift
2
4554
import UIKit import CoreData class Storage { lazy var factory : DataFactory = { return DataFactory() }() var managedObjectContext : NSManagedObjectContext { return DataController.sharedInstance.managedObjectContext } let contactsFetch = NSFetchRequest(entityName: "Contact") let notesFetch = NSFetchRequest(entityName: "Note") let imagesFetch = NSFetchRequest(entityName: "Image") func prepare() { if !hasNotes() { createNotes() } if !hasImages() { createImages() } if !hasContacts() { createContacts() } } func allItems() -> [Indexable] { let noteList: [Indexable] = notes() let imageList: [Indexable] = images() let contactList: [Indexable] = contacts() return noteList + imageList + contactList } func createContacts() { factory.createContact("John Doe", phone: "+31 6 12 34 56 78", email: "john.doe@johndoe.com") } func createNotes() { factory.createNote(NSDate(), text: "Foo") factory.createNote(NSDate(), text: "Bar") } func createImages() { factory.createImage(NSDate(), title: "Apple", url: "http://logok.org/wp-content/uploads/2014/04/Apple-Logo-rainbow.png") factory.createImage(NSDate(), title: "Google", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png") } func hasNotes() -> Bool { return notes().count > 0 } func hasImages() -> Bool { return images().count > 0 } func hasContacts() -> Bool { return contacts().count > 0 } func notes() -> [Note] { do { return try managedObjectContext.executeFetchRequest(notesFetch) as! [Note] } catch { fatalError("Failed to fetch notes: \(error)") } } func images() -> [Image] { do { return try managedObjectContext.executeFetchRequest(imagesFetch) as! [Image] } catch { fatalError("Failed to fetch images: \(error)") } } func contacts() -> [Contact] { do { return try managedObjectContext.executeFetchRequest(contactsFetch) as! [Contact] } catch { fatalError("Failed to fetch contacts: \(error)") } } func getNoteByText(text: String) -> Note? { let noteRequest = NSFetchRequest(entityName: "Note") noteRequest.predicate = NSPredicate(format:"text == %@", text) do { let notesFound = try managedObjectContext.executeFetchRequest(noteRequest) as! [Note] return notesFound.first } catch { fatalError("Failed to fetch notes: \(error)") } } func getNoteById(id: String) -> Note? { let noteRequest = NSFetchRequest(entityName: "Note") noteRequest.predicate = NSPredicate(format:"id == %@", id) do { let notesFound = try managedObjectContext.executeFetchRequest(noteRequest) as! [Note] return notesFound.first } catch { fatalError("Failed to fetch notes: \(error)") } } func getImageByURL(url: String) -> Image? { let imageRequest = NSFetchRequest(entityName: "Image") imageRequest.predicate = NSPredicate(format:"url == %@", url) do { let imageFound = try managedObjectContext.executeFetchRequest(imageRequest) as! [Image] return imageFound.first } catch { fatalError("Failed to fetch images: \(error)") } } func getImageByTitle(title: String) -> Image? { let imageRequest = NSFetchRequest(entityName: "Image") imageRequest.predicate = NSPredicate(format:"title == %@", title) do { let imageFound = try managedObjectContext.executeFetchRequest(imageRequest) as! [Image] return imageFound.first } catch { fatalError("Failed to fetch images: \(error)") } } func getContactByEmail(email: String) -> Contact? { let contactRequest = NSFetchRequest(entityName: "Contact") contactRequest.predicate = NSPredicate(format:"email == %@", email) do { let contactFound = try managedObjectContext.executeFetchRequest(contactRequest) as! [Contact] return contactFound.first } catch { fatalError("Failed to fetch contacts: \(error)") } } }
mit
5e174550f8afc2c7e08a477009db0eeb
31.535714
178
0.591787
4.651685
false
false
false
false
sundeepgupta/foodup
FoodUp/HistoryBuilder.swift
1
758
import Foundation struct HistoryBuilder { private let dataController: DataController private let meals: [Meal] init(dataController: DataController) { self.dataController = dataController self.meals = dataController.meals() } func history() -> History { let smallCount = self.countFor(type: .Small) let mediumCount = self.countFor(type: .Medium) let largeCount = self.countFor(type: .Large) return History(smallCount: smallCount, mediumCount: mediumCount, largeCount: largeCount) } private func countFor(type type: MealType) -> Int { return self.meals.reduce(0) { memo, meal in return type == meal.type ? memo + 1 : memo } } }
unlicense
8b96897d0da4cb3622a8b977b50a9a87
29.36
96
0.631926
4.406977
false
false
false
false
glennposadas/gpkit-ios
GPKit/Categories/UITextField+GPKit.swift
1
3744
// // UITextField+GPKit.swift // GPKit // // Created by Glenn Posadas on 5/10/17. // Copyright © 2017 Citus Labs. All rights reserved. // import UIKit public extension UITextField { func selectedRange() -> NSRange? { let beginning = self.beginningOfDocument let selectedRange = self.selectedTextRange if let selectionStart = selectedRange?.start, let selectionEnd = selectedRange?.end { let location = self.offset(from: beginning, to: selectionStart) let length = self.offset(from: selectionStart, to: selectionEnd) return NSMakeRange(location, length) } return nil } /** - Validation for TextFields. - Call this extension function like this: - if (textField.hasContents()) then proceed */ public func hasContents() -> Bool { let whitespaceSet = CharacterSet.whitespaces if self.text == "" || self.text == "" { return false } if self.text!.trimmingCharacters(in: whitespaceSet).isEmpty || self.text!.trimmingCharacters(in: whitespaceSet).isEmpty { return false } return true } /** The function to be called for the alert. */ public func setupTextFieldWithDelegate( delegate: UITextFieldDelegate? = nil, textColor: UIColor, font: UIFont? = nil, placeholderText: String? = nil, imageIcon: UIImage?) { // The half of the height of the superview, which is the textField minus half of the height of imageView let y = (self.frame.size.height / 2) - 7.5 let imageView = UIImageView(frame: CGRect(x: 15, y: y, width: 15, height: 15)) if let imageIcon = imageIcon { imageView.image = imageIcon imageView.contentMode = .scaleAspectFill self.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 30)) self.backgroundColor = .clear } else { self.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) } self.leftViewMode = .always self.textColor = textColor self.tintColor = textColor for subview in self.subviews { subview.tintColor = textColor } if let delegate = delegate { self.delegate = delegate } self.addSubview(imageView) if let font = font { self.font = font } if let placeHolder = placeholderText { let localizedPlaceHolder = NSLocalizedString(placeHolder, comment: "") let attributedString = NSAttributedString(string: localizedPlaceHolder, attributes: [NSAttributedStringKey.foregroundColor: textColor]) self.attributedPlaceholder = attributedString } } /** The function to setup a textField for any input type */ public func setupTextFieldForInputType(inputType: UIKeyboardType) { //self.font = R.font.gothamBook(size: 14.0) self.keyboardType = inputType switch inputType { case .default: // for default self.autocapitalizationType = .words self.spellCheckingType = .yes self.autocorrectionType = .yes default: // for emails self.autocapitalizationType = .none self.spellCheckingType = .no self.autocorrectionType = .no } } }
mit
52253c883f99a1f42433c1652a172b4d
28.944
117
0.557841
5.264416
false
false
false
false
tjw/swift
stdlib/public/SDK/SpriteKit/SpriteKit.swift
2
4116
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import SpriteKit import simd // SpriteKit defines SKColor using a macro. #if os(macOS) public typealias SKColor = NSColor #elseif os(iOS) || os(tvOS) || os(watchOS) public typealias SKColor = UIColor #endif // this class only exists to allow AnyObject lookup of _copyImageData // since that method only exists in a private header in SpriteKit, the lookup // mechanism by default fails to accept it as a valid AnyObject call @objc class _SpriteKitMethodProvider : NSObject { override init() { _sanityCheckFailure("don't touch me") } @objc func _copyImageData() -> NSData! { return nil } } @available(iOS, introduced: 10.0) @available(macOS, introduced: 10.12) @available(tvOS, introduced: 10.0) @available(watchOS, introduced: 3.0) extension SKWarpGeometryGrid { /// Create a grid of the specified dimensions, source and destination positions. /// /// Grid dimensions (columns and rows) refer to the number of faces in each dimension. The /// number of vertices required for a given dimension is equal to (cols + 1) * (rows + 1). /// /// SourcePositions are normalized (0.0 - 1.0) coordinates to determine the source content. /// /// DestinationPositions are normalized (0.0 - 1.0) positional coordinates with respect to /// the node's native size. Values outside the (0.0-1.0) range are perfectly valid and /// correspond to positions outside of the native undistorted bounds. /// /// Source and destination positions are provided in row-major order starting from the top-left. /// For example the indices for a 2x2 grid would be as follows: /// /// [0]---[1]---[2] /// | | | /// [3]---[4]---[5] /// | | | /// [6]---[7]---[8] /// /// - Parameter columns: the number of columns to initialize the SKWarpGeometryGrid with /// - Parameter rows: the number of rows to initialize the SKWarpGeometryGrid with /// - Parameter sourcePositions: the source positions for the SKWarpGeometryGrid to warp from /// - Parameter destinationPositions: the destination positions for SKWarpGeometryGrid to warp to public convenience init(columns: Int, rows: Int, sourcePositions: [simd.float2] = [float2](), destinationPositions: [simd.float2] = [float2]()) { let requiredElementsCount = (columns + 1) * (rows + 1) switch (destinationPositions.count, sourcePositions.count) { case (0, 0): self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: nil) case (let dests, 0): _precondition(dests == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: destinationPositions) case (0, let sources): _precondition(sources == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: nil) case (let dests, let sources): _precondition(dests == requiredElementsCount && sources == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: destinationPositions) } } public func replacingBySourcePositions(positions source: [simd.float2]) -> SKWarpGeometryGrid { return self.__replacingSourcePositions(source) } public func replacingByDestinationPositions(positions destination: [simd.float2]) -> SKWarpGeometryGrid { return self.__replacingDestPositions(destination) } }
apache-2.0
b7af398ebdbaa2afb4f9f8adae76dbc0
47.423529
147
0.685131
4.243299
false
false
false
false
mkihmouda/ChatRoom
ChatRoom/BlureView.swift
1
840
// // BlureView.swift // YaTranslator // // Created by Mac on 12/5/16. // Copyright © 2016 Mac. All rights reserved. // import UIKit class BlureView: UIView { override func awakeFromNib() { self.addBlureEffects() } func addBlureEffects(){ let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = CGRect(origin: CGPoint(x: 0 ,y : 0 ), size: CGSize(width: self.frame.size.width , height: self.frame.size.height)) blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation blurEffectView.alpha = 0.75 self.addSubview(blurEffectView) self.sendSubview(toBack: blurEffectView) } }
mit
b8bab566eb524e2c8c3e2caa80e39bde
26.064516
146
0.646007
4.415789
false
false
false
false
lorentey/swift
test/PlaygroundTransform/nested_function.swift
9
2121
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -force-single-frontend-invocation -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/SilentPCMacroRuntime.swift %S/Inputs/PlaygroundsRuntime.swift // RUN: %target-build-swift -Xfrontend -playground -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift && %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift && %target-codesign %t/main2 // RUN: %target-run %t/main2 | %FileCheck %s // REQUIRES: executable_test import PlaygroundSupport #sourceLocation(file: "main.swift", line: 9) func returnSum() -> Int { var y = 10 func add() { y += 5 } add() let addAgain = { y += 5 } addAgain() let addMulti = { y += 5 _ = 0 // force a multi-statement closure } addMulti() return y } returnSum() // CHECK-NOT: __builtin // CHECK: [9:{{.*}}] __builtin_log_scope_entry // CHECK-NEXT: [10:{{.*}}] __builtin_log[y='10'] // CHECK-NEXT: [11:{{.*}}] __builtin_log_scope_entry // CHECK-NEXT: [12:{{.*}}] __builtin_log[y='15'] // CHECK-NEXT: [11:{{.*}}] __builtin_log_scope_exit // CHECK-NEXT: [15:{{.*}}] __builtin_log[addAgain='{{.*}}'] // CHECK-NEXT: [15:{{.*}}] __builtin_log_scope_entry // FIXME: We drop the log for the addition here. // CHECK-NEXT: [16:{{.*}}] __builtin_log[='()'] // CHECK-NEXT: [15:{{.*}}] __builtin_log_scope_exit // FIXME: There's an extra, unbalanced scope exit here. // CHECK-NEXT: [9:{{.*}}] __builtin_log_scope_exit // CHECK-NEXT: [19:{{.*}}] __builtin_log[addMulti='{{.*}}'] // CHECK-NEXT: [19:{{.*}}] __builtin_log_scope_entry // CHECK-NEXT: [20:{{.*}}] __builtin_log[y='25'] // CHECK-NEXT: [21:{{.*}}] __builtin_log[='0'] // CHECK-NEXT: [19:{{.*}}] __builtin_log_scope_exit // CHECK-NEXT: [24:{{.*}}] __builtin_log[='25'] // CHECK-NEXT: [9:{{.*}}] __builtin_log_scope_exit // CHECK-NEXT: [27:{{.*}}] __builtin_log[='25'] // CHECK-NOT: __builtin
apache-2.0
ee4f2acb245401701b749a586d164ba4
35.568966
262
0.612447
3.012784
false
false
false
false
pauljohanneskraft/Algorithms-and-Data-structures
AlgorithmsDataStructures/Classes/General/General.swift
1
1907
// // General.swift // Algorithms&DataStructures // // Created by Paul Kraft on 13.09.16. // Copyright © 2016 pauljohanneskraft. All rights reserved. // import Foundation public func * (lhs: String, rhs: UInt) -> String { guard rhs > 1 else { guard rhs > 0 else { return "" } return lhs } let result = lhs * (rhs >> 1) guard rhs & 0x1 == 0 else { return result + result + lhs } return result + result } public func * (lhs: UInt, rhs: String) -> String { return rhs * lhs } public func * (lhs: Int, rhs: String) -> String { return rhs * UInt(lhs) } public func * (lhs: String, rhs: Int) -> String { return lhs * UInt(rhs) } public enum DataStructureError: Error { case notIn, alreadyIn } extension Int { func description(radix: Int) -> String { guard radix > 0 && radix < 65 else { return "Cannot create description with radix: \(radix)" } let nums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/" .unicodeScalars.map { String($0) } var str = nums[self % radix] var num = self / radix while num != 0 { str = nums[num % radix] + str num /= radix } return str } } extension Sequence { public func shuffled() -> [Element] { return sorted(by: { _, _ in arc4random() & 1 == 0 }) } } extension Array { public mutating func shuffle() { sort(by: { _, _ in arc4random() & 1 == 0 }) } } extension Array where Element: Equatable { public mutating func remove(_ element: Element) { guard let index = index(of: element) else { return } remove(at: index) } } var cacheLineSize: Int { var a: size_t = 0 var b: size_t = MemoryLayout<Int>.size var c: size_t = 0 sysctlbyname("hw.cachelinesize", &a, &b, &c, 0) return a }
mit
6fe362f6be7919ac18855e7a7c56c2c5
21.963855
85
0.572928
3.686654
false
false
false
false
sindanar/PDStrategy
Example/PDStrategy/PDStrategy/StaticCellsTableDataSource.swift
1
1995
// // StaticCellsTableController.swift // PDStrategy // // Created by Pavel Deminov on 05/11/2017. // Copyright © 2017 Pavel Deminov. All rights reserved. // import UIKit enum StaticCellsTableType { case title; case titleValue; case titleValue2; case titleValueDate; case titleValueDate2; case titleValueDate3; case titleImage; } class StaticCellsTableDataSource: PDDataSource { override func setup() { let section = PDSection.instantiate() var items = [PDItem]() var item = PDItem.instantiate() item.title = "Title" item.type = StaticCellsTableType.title items.append(item) item = PDItem.instantiate() item.title = "Title" item.value = "Value" item.type = StaticCellsTableType.titleValue items.append(item) item = PDItem.instantiate() item.title = "Title2" item.value = "Value2" item.type = StaticCellsTableType.titleValue2 items.append(item) item = PDItem.instantiate() item.title = "Title" item.value = "Value" item.date = Date() item.type = StaticCellsTableType.titleValueDate items.append(item) item = PDItem.instantiate() item.title = "Title2" item.value = "Value2" item.date = Date() item.type = StaticCellsTableType.titleValueDate2 items.append(item) item = PDItem.instantiate() item.title = "Title3" item.value = "Value3" item.date = Date() item.type = StaticCellsTableType.titleValueDate3 items.append(item) item = PDItem.instantiate() item.title = "Title" item.image = #imageLiteral(resourceName: "image1") item.type = StaticCellsTableType.titleImage items.append(item) section.items = items sections = [section] } }
mit
f218232bbb3292559fb747f007d7d250
25.236842
58
0.588265
4.215645
false
false
false
false
zvonicek/ImageSlideshow
ImageSlideshow/Classes/Core/FullScreenSlideshowViewController.swift
1
3640
// // FullScreenSlideshowViewController.swift // ImageSlideshow // // Created by Petr Zvoníček on 31.08.15. // import UIKit @objcMembers open class FullScreenSlideshowViewController: UIViewController { open var slideshow: ImageSlideshow = { let slideshow = ImageSlideshow() slideshow.zoomEnabled = true slideshow.contentScaleMode = UIViewContentMode.scaleAspectFit slideshow.pageIndicatorPosition = PageIndicatorPosition(horizontal: .center, vertical: .bottom) // turns off the timer slideshow.slideshowInterval = 0 slideshow.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] return slideshow }() /// Close button open var closeButton = UIButton() /// Close button frame open var closeButtonFrame: CGRect? /// Closure called on page selection open var pageSelected: ((_ page: Int) -> Void)? /// Index of initial image open var initialPage: Int = 0 /// Input sources to open var inputs: [InputSource]? /// Background color open var backgroundColor = UIColor.black /// Enables/disable zoom open var zoomEnabled = true { didSet { slideshow.zoomEnabled = zoomEnabled } } fileprivate var isInit = true convenience init() { self.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .custom if #available(iOS 13.0, *) { // Use KVC to set the value to preserve backwards compatiblity with Xcode < 11 self.setValue(true, forKey: "modalInPresentation") } } override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = backgroundColor slideshow.backgroundColor = backgroundColor if let inputs = inputs { slideshow.setImageInputs(inputs) } view.addSubview(slideshow) // close button configuration closeButton.setImage(UIImage(named: "ic_cross_white", in: .module, compatibleWith: nil), for: UIControlState()) closeButton.addTarget(self, action: #selector(FullScreenSlideshowViewController.close), for: UIControlEvents.touchUpInside) view.addSubview(closeButton) } override open var prefersStatusBarHidden: Bool { return true } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if isInit { isInit = false slideshow.setCurrentPage(initialPage, animated: false) } } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) slideshow.slideshowItems.forEach { $0.cancelPendingLoad() } // Prevents broken dismiss transition when image is zoomed in slideshow.currentSlideshowItem?.zoomOut() } open override func viewDidLayoutSubviews() { if !isBeingDismissed { let safeAreaInsets: UIEdgeInsets if #available(iOS 11.0, *) { safeAreaInsets = view.safeAreaInsets } else { safeAreaInsets = UIEdgeInsets.zero } closeButton.frame = closeButtonFrame ?? CGRect(x: max(10, safeAreaInsets.left), y: max(10, safeAreaInsets.top), width: 40, height: 40) } slideshow.frame = view.frame } func close() { // if pageSelected closure set, send call it with current page if let pageSelected = pageSelected { pageSelected(slideshow.currentPage) } dismiss(animated: true, completion: nil) } }
mit
2d2695b5ede535a2a28e9c6757de684f
28.104
146
0.64541
5.174964
false
false
false
false
krzysztofzablocki/Sourcery
SourceryRuntime/Sources/AST/Attribute.swift
1
5505
import Foundation /// Describes Swift attribute @objcMembers public class Attribute: NSObject, AutoCoding, AutoEquatable, AutoDiffable, AutoJSExport { /// Attribute name public let name: String /// Attribute arguments public let arguments: [String: NSObject] // sourcery: skipJSExport let _description: String // sourcery: skipEquality, skipDescription, skipCoding, skipJSExport /// :nodoc: public var __parserData: Any? /// :nodoc: public init(name: String, arguments: [String: NSObject] = [:], description: String? = nil) { self.name = name self.arguments = arguments self._description = description ?? "@\(name)" } /// TODO: unify `asSource` / `description`? public var asSource: String { description } /// Attribute description that can be used in a template. public override var description: String { return _description } /// :nodoc: public enum Identifier: String { case convenience case required case available case discardableResult case GKInspectable = "gkinspectable" case objc case objcMembers case nonobjc case NSApplicationMain case NSCopying case NSManaged case UIApplicationMain case IBOutlet = "iboutlet" case IBInspectable = "ibinspectable" case IBDesignable = "ibdesignable" case autoclosure case convention case mutating case escaping case final case open case lazy case `public` = "public" case `internal` = "internal" case `private` = "private" case `fileprivate` = "fileprivate" case publicSetter = "setter_access.public" case internalSetter = "setter_access.internal" case privateSetter = "setter_access.private" case fileprivateSetter = "setter_access.fileprivate" case optional public init?(identifier: String) { let identifier = identifier.trimmingPrefix("source.decl.attribute.") if identifier == "objc.name" { self.init(rawValue: "objc") } else { self.init(rawValue: identifier) } } public static func from(string: String) -> Identifier? { switch string { case "GKInspectable": return Identifier.GKInspectable case "objc": return .objc case "IBOutlet": return .IBOutlet case "IBInspectable": return .IBInspectable case "IBDesignable": return .IBDesignable default: return Identifier(rawValue: string) } } public var name: String { switch self { case .GKInspectable: return "GKInspectable" case .objc: return "objc" case .IBOutlet: return "IBOutlet" case .IBInspectable: return "IBInspectable" case .IBDesignable: return "IBDesignable" case .fileprivateSetter: return "fileprivate" case .privateSetter: return "private" case .internalSetter: return "internal" case .publicSetter: return "public" default: return rawValue } } public var description: String { return hasAtPrefix ? "@\(name)" : name } public var hasAtPrefix: Bool { switch self { case .available, .discardableResult, .GKInspectable, .objc, .objcMembers, .nonobjc, .NSApplicationMain, .NSCopying, .NSManaged, .UIApplicationMain, .IBOutlet, .IBInspectable, .IBDesignable, .autoclosure, .convention, .escaping: return true default: return false } } } // sourcery:inline:Attribute.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let arguments: [String: NSObject] = aDecoder.decode(forKey: "arguments") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["arguments"])); fatalError() }; self.arguments = arguments guard let _description: String = aDecoder.decode(forKey: "_description") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["_description"])); fatalError() }; self._description = _description } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.arguments, forKey: "arguments") aCoder.encode(self._description, forKey: "_description") } // sourcery:end }
mit
fbe5b93cb93c117ce6e5812e32947aba
31.964072
267
0.553134
5.494012
false
false
false
false
redarcgroup/UIInsetLabel
Source/UsageExample.swift
1
341
let paddedLabel: UIInsetLabel = UIInsetLabel() paddedLabel.paddingInsets = UIEdgeInsets(top: 7.0, left: 7.0, bottom: 7.0, right: 7.0) //Swift 2.3 paddedLabel.font = UIFont.boldSystemFontOfSize(14.0) //Swift 3.0 paddedLabel.font = UIFont.boldSystemFont(ofSize: 14.0) paddedLabel.text = "Some sample text" self.view.addSubview(paddedLabel)
mit
3def06f223fd38d1008782d01d4697b0
30
86
0.762463
3.044643
false
false
false
false