repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
BNakum/Alamofire
refs/heads/master
Source/ParameterEncoding.swift
mit
19
// ParameterEncoding.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** HTTP method definitions. See https://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } // MARK: ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. */ public enum ParameterEncoding { case URL case URLEncodedInURL case JSON case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. - parameter URLRequest: The request to have parameters applied - parameter parameters: The parameters to apply - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { var mutableURLRequest = URLRequest.URLRequest guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil switch self { case .URL, .URLEncodedInURL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") } func encodesParametersInURL(method: Method) -> Bool { switch self { case .URLEncodedInURL: return true default: break } switch method { case .GET, .HEAD, .DELETE: return true default: return false } } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL } } else { if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: false ) } case .JSON: do { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .PropertyList(let format, let options): do { let data = try NSPropertyListSerialization.dataWithPropertyList( parameters, format: format, options: options ) mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .Custom(let closure): (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) } return (mutableURLRequest, encodingError) } /** Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - parameter key: The key of the query component. - parameter value: The value of the query component. - returns: The percent-escaped, URL encoded query string components. */ public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } /** Returns a percent-escaped string following RFC 3986 for a query string key or value. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent-escaped in the query string. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ public func escape(string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, OSX 10.10, *) { escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = index.advancedBy(batchSize, limit: string.endIndex) let range = Range(start: startIndex, end: endIndex) let substring = string.substringWithRange(range) escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring index = endIndex } } return escaped } }
8879064256358597b3fff66d1e877b22
43.353414
124
0.592629
false
false
false
false
youknowone/Say
refs/heads/master
iOS/Speaker.swift
gpl-3.0
1
// // Speaker.swift // BotTalk // // Created by Jeong YunWon on 2016. 7. 7.. // Copyright © 2016년 youknowone.org. All rights reserved. // import Foundation import AVFoundation public class Speaker: NSObject, AVSpeechSynthesizerDelegate { static let defaultSpeaker = Speaker() var volume: Float = 1.0 var mute = false var voice = AVSpeechSynthesisVoice(language: "en-US") // set default language : english (temporarily) var voices = AVSpeechSynthesisVoice.speechVoices() var delegate: SpeakerDelegate? var rate: Float = AVSpeechUtteranceDefaultSpeechRate let synthesizer = AVSpeechSynthesizer() override init() { super.init() self.synthesizer.delegate = self } public func stopSpeaking() { self.synthesizer.stopSpeaking(at: .word) } public func pauseSpeaking() { self.synthesizer.pauseSpeaking(at: .immediate) } public func continueSpeaking() { self.synthesizer.continueSpeaking() } public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { delegate?.speaker(speaker: self, didFinishSpeechString: utterance.speechString) } public func speakText(text: String) { let utterance = AVSpeechUtterance(string: text) utterance.volume = self.mute ? 0.0 : self.volume utterance.voice = self.voice utterance.rate = self.rate self.synthesizer.speak(utterance) } public func changeLanguage(language: String) { self.voice = AVSpeechSynthesisVoice(language: language) } } protocol SpeakerDelegate { func speaker(speaker: Speaker, didFinishSpeechString: String); }
cc7f6d0d29ea93bf53c89655f4e6637e
28.101695
111
0.687245
false
false
false
false
benzhipeng/BubbleTransition
refs/heads/master
Source/BubbleTransition.swift
mit
1
// // BubbleTransition.swift // BubbleTransition // // Created by Andrea Mazzini on 04/04/15. // Copyright (c) 2015 Fancy Pixel. All rights reserved. // import UIKit /** A custom modal transition that presents and dismiss a controller with an expanding bubble effect. */ public class BubbleTransition: NSObject, UIViewControllerAnimatedTransitioning { /** The point that originates the bubble. */ public var startingPoint = CGPointZero /** The transition duration. */ public var duration = 0.5 /** The transition direction. Either `.Present` or `.Dismiss.` */ public var transitionMode: BubbleTranisionMode = .Present /** The color of the bubble. Make sure that it matches the destination controller's background color. */ public var bubbleColor: UIColor = .whiteColor() private var bubble: UIView? // MARK: - UIViewControllerAnimatedTransitioning /** Required by UIViewControllerAnimatedTransitioning */ public func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return duration } /** Required by UIViewControllerAnimatedTransitioning */ public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView() if transitionMode == .Present { let presentedController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let presentedControllerView = transitionContext.viewForKey(UITransitionContextToViewKey)! let originalCenter = presentedControllerView.center let offset = sqrt(startingPoint.x * startingPoint.x + startingPoint.y * startingPoint.y) * 2 let size = CGSize(width: offset, height: offset) bubble = UIView(frame: CGRect(origin: CGPointZero, size: size)) bubble!.layer.cornerRadius = size.height / 2 bubble!.center = startingPoint bubble!.transform = CGAffineTransformMakeScale(0.001, 0.001) bubble!.backgroundColor = bubbleColor containerView.addSubview(bubble!) presentedControllerView.center = startingPoint presentedControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) presentedControllerView.alpha = 0 containerView.addSubview(presentedControllerView) UIView.animateWithDuration(duration, animations: { self.bubble!.transform = CGAffineTransformIdentity presentedControllerView.transform = CGAffineTransformIdentity presentedControllerView.alpha = 1 presentedControllerView.center = originalCenter }) { (_) -> Void in transitionContext.completeTransition(true) } } else { let returningController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let returningControllerView = transitionContext.viewForKey(UITransitionContextFromViewKey)! UIView.animateWithDuration(duration, animations: { self.bubble!.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.center = self.startingPoint returningControllerView.alpha = 0 }) { (_) -> Void in returningControllerView.removeFromSuperview() self.bubble!.removeFromSuperview() transitionContext.completeTransition(true) } } } /** The possible directions of the transition */ public enum BubbleTranisionMode: Int { case Present, Dismiss } }
958a0938a5221cf9c64b0e9ae71348f7
36.805825
119
0.672316
false
false
false
false
Workpop/meteor-ios
refs/heads/master
Examples/Todos/Todos/ListsViewController.swift
mit
1
// Copyright (c) 2014-2015 Martijn Walraven // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import CoreData import Meteor class ListsViewController: FetchedResultsTableViewController { @IBOutlet weak var userBarButtonItem: UIBarButtonItem! // MARK: - View Lifecycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "accountDidChange", name: METDDPClientDidChangeAccountNotification, object: Meteor) updateUserBarButtonItem() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: "accountDidChange", object: Meteor) } // MARK: - Content Loading override func configureSubscriptionLoader(subscriptionLoader: SubscriptionLoader) { subscriptionLoader.addSubscriptionWithName("publicLists") subscriptionLoader.addSubscriptionWithName("privateLists") } override func createFetchedResultsController() -> NSFetchedResultsController? { let fetchRequest = NSFetchRequest(entityName: "List") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "isPrivate", ascending: true), NSSortDescriptor(key: "name", ascending: true)] return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: "isPrivate", cacheName: nil) } // MARK: - FetchedResultsTableViewDataSourceDelegate func dataSource(dataSource: FetchedResultsTableViewDataSource, configureCell cell: UITableViewCell, forObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) { if let list = object as? List { cell.textLabel!.text = list.name cell.detailTextLabel!.text = "\(list.incompleteCount)" cell.imageView!.image = (list.user != nil) ? UIImage(named: "locked_icon") : nil } } func dataSource(dataSource: FetchedResultsTableViewDataSource, deleteObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) { if let list = object as? List { managedObjectContext.deleteObject(list) saveManagedObjectContext() } } // MARK: - Adding List @IBAction func addList() { let alertController = UIAlertController(title: nil, message: "Add List", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in } alertController.addAction(cancelAction) let addAction = UIAlertAction(title: "Add", style: .Default) { (action) in let nameTextField = alertController.textFields![0] as UITextField let name = nameTextField.text if name.isEmpty { return } let list = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: self.managedObjectContext) as List list.name = name list.incompleteCount = 0 self.saveManagedObjectContext() } alertController.addAction(addAction) alertController.addTextFieldWithConfigurationHandler { (textField) in textField.placeholder = "Name" textField.autocapitalizationType = .Words textField.returnKeyType = .Done textField.enablesReturnKeyAutomatically = true } presentViewController(alertController, animated: true, completion: nil) } // MARK: - Signing In and Out func accountDidChange() { dispatch_async(dispatch_get_main_queue()) { self.updateUserBarButtonItem() } } func updateUserBarButtonItem() { if Meteor.userID == nil { userBarButtonItem.image = UIImage(named: "user_icon") } else { userBarButtonItem.image = UIImage(named: "user_icon_selected") } } @IBAction func userButtonPressed() { if Meteor.userID == nil { performSegueWithIdentifier("SignIn", sender: nil) } else { showUserAlertSheet() } } func showUserAlertSheet() { let currentUser = self.currentUser let emailAddress = currentUser?.emailAddress let message = emailAddress != nil ? "Signed in as \(emailAddress!)." : "Signed in." let alertController = UIAlertController(title: nil, message: message, preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in } alertController.addAction(cancelAction) let signOutAction = UIAlertAction(title: "Sign Out", style: .Destructive) { (action) in Meteor.logoutWithCompletionHandler(nil) } alertController.addAction(signOutAction) if let popoverPresentationController = alertController.popoverPresentationController { popoverPresentationController.barButtonItem = userBarButtonItem } presentViewController(alertController, animated: true, completion: nil) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let selectedList = dataSource.selectedObject as? List { if let todosViewcontroller = (segue.destinationViewController as? UINavigationController)?.topViewController as? TodosViewController { todosViewcontroller.managedObjectContext = managedObjectContext todosViewcontroller.listID = selectedList.objectID } } } } @IBAction func unwindFromSignIn(segue: UIStoryboardSegue) { // Shouldn't be needed, but without it the modal view controller isn't dismissed on the iPad dismissViewControllerAnimated(true, completion: nil) } }
881e523b0fdf63989b77be49a50c80ca
37.289017
174
0.728412
false
false
false
false
Ifinity/ifinity-swift-example
refs/heads/master
IfinitySDK-swift/VenuesMapViewController.swift
mit
1
// // VenuesMapViewController.swift // IfinitySDK-swift // // Created by Ifinity on 15.12.2015. // Copyright © 2015 getifinity.com. All rights reserved. // import UIKit import ifinitySDK import MapKit import SVProgressHUD class VenuesMapViewController: UIViewController, MKMapViewDelegate, IFBluetoothManagerDelegate { @IBOutlet var mapView: MKMapView? var currentVenue: IFMVenue? var currentFloor: IFMFloorplan? override func viewDidLoad() { super.viewDidLoad() self.title = "Navigation" } override func viewWillAppear(animated: Bool) { // Start looking for beacons around me IFBluetoothManager.sharedManager().delegate = self IFBluetoothManager.sharedManager().startManager() NSNotificationCenter.defaultCenter().addObserver(self, selector: "addPush:", name: IFPushManagerNotificationPushAdd, object: nil) super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) IFBluetoothManager.sharedManager().delegate = nil NSNotificationCenter.defaultCenter().removeObserver(self, name: IFPushManagerNotificationPushAdd, object: nil) } //MARK: - Pushes func addPush(sender: AnyObject) { var dict: [NSObject : AnyObject] = sender.userInfo let push: IFMPush = dict["push"] as! IFMPush NSLog("Venue Map New Push: %@", push.name) } @IBAction func clearCaches(sender: AnyObject) { IFBluetoothManager.sharedManager().delegate = nil SVProgressHUD.showWithMaskType(.Black) IFDataManager.sharedManager().clearCaches() IFDataManager.sharedManager().loadDataForLocation(CLLocation(latitude: 52, longitude: 21), distance: 1000, withPublicVenues: true, successBlock: { (venues) -> Void in SVProgressHUD.dismiss() IFBluetoothManager.sharedManager().delegate = self }) { (error) -> Void in NSLog("LoadDataForLocation error %@", error) } } //MARK: - IFBluetoothManagerDelegates func manager(manager: IFBluetoothManager, didDiscoverActiveBeaconsForVenue venue: IFMVenue?, floorplan: IFMFloorplan) { guard venue != nil else { return } if Int(venue!.type) == IFMVenueTypeMap { NSLog("IFMVenueTypeMap %s", __FUNCTION__) self.currentVenue = venue self.currentFloor = floorplan IFBluetoothManager.sharedManager().delegate = nil self.performSegueWithIdentifier("IndoorLocation", sender: self) } else if Int(venue!.type) == IFMVenueTypeBeacon { NSLog("IFMVenueTypeBeacon %s", __FUNCTION__) if self.currentVenue?.remote_id == venue?.remote_id { return } // Center map to venue center coordinate let center = CLLocationCoordinate2DMake(Double(venue!.center_lat), Double(venue!.center_lng)) let venueAnnotation = VenueAnnotation(coordinate: center, title: venue!.name, subtitle: "") let distance: CLLocationDistance = 800.0 let camera = MKMapCamera(lookingAtCenterCoordinate: center, fromEyeCoordinate: center, eyeAltitude: distance) self.mapView?.addAnnotation(venueAnnotation) self.mapView?.setCamera(camera, animated: false) } self.currentVenue = venue } func manager(manager: IFBluetoothManager, didLostAllBeaconsForVenue venue: IFMVenue) { self.currentVenue = nil self.mapView?.removeAnnotations(self.mapView!.annotations) } func manager(manager: IFBluetoothManager, didLostAllBeaconsForFloorplan floorplan: IFMFloorplan) { self.currentFloor = nil self.mapView?.removeAnnotations(self.mapView!.annotations) } //MARK: - MKMapViewDelegate func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { // VenueAnnotation with some nice icon if annotation is VenueAnnotation { let annotationIdentifier: String = "venueIdentifier" let pinView: MKPinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier) pinView.pinTintColor = UIColor.greenColor() pinView.canShowCallout = true return pinView } return nil } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.destinationViewController is IndoorLocationViewController { (segue.destinationViewController as! IndoorLocationViewController).currentFloor = self.currentFloor } } }
7ee17f18c974c02856f320d47f13d229
37.685484
174
0.665207
false
false
false
false
honghaoz/ChouTi
refs/heads/master
Sources/DataStructures/OrderedDictionary.swift
mit
1
// Copyright © 2019 ChouTi. All rights reserved. import Foundation public struct OrderedDictionary<KeyType: Hashable, ValueType> { private(set) var array: [KeyType] = [] private(set) var dictionary: [KeyType: ValueType] = [:] public var count: Int { return array.count } public init() {} public subscript(key: KeyType) -> ValueType? { get { return dictionary[key] } set { if array.firstIndex(of: key) == nil { array.append(key) } dictionary[key] = newValue } } public subscript(index: Int) -> (KeyType, ValueType) { precondition(index < array.count, "index out of bounds") let key = array[index] let value = dictionary[key]! return (key, value) } @discardableResult public mutating func removeValue(forKey key: KeyType) -> ValueType? { if let index = array.firstIndex(of: key) { array.remove(at: index) } return dictionary.removeValue(forKey: key) } public mutating func removeAll(keepingCapacity: Bool = false) { dictionary.removeAll(keepingCapacity: keepingCapacity) array.removeAll(keepingCapacity: keepingCapacity) } } public extension OrderedDictionary { @discardableResult mutating func insert(_ value: ValueType, forKey key: KeyType, atIndex index: Int) -> ValueType? { precondition(index <= array.count, "index out of range") var adjustedIndex = index // If insert for key: b, at index 2 // // | // v // 0 1 2 // ["a", "b", "c"] // // Remove "b" // 0 1 // ["a", "c"] let existingValue = dictionary[key] if existingValue != nil { let existingIndex = array.firstIndex(of: key)! if existingIndex < index, index >= array.count { adjustedIndex -= 1 } array.remove(at: existingIndex) } array.insert(key, at: adjustedIndex) dictionary[key] = value return existingValue } @discardableResult mutating func remove(at index: Int) -> (KeyType, ValueType) { precondition(index < array.count, "index out of bounds") let key = array.remove(at: index) let value = dictionary.removeValue(forKey: key) return (key, value!) } }
27dd44bb8c293cab074a7b9a3dc812d1
23.054348
99
0.62901
false
false
false
false
teklabs/MyTabBarApp
refs/heads/master
MyTabBarApp/ItemListViewController.swift
gpl-3.0
1
// // ItemListViewController.swift // MyTabBarApp // // Created by teklabsco on 11/23/15. // Copyright © 2015 Teklabs, LLC. All rights reserved. // import UIKit //import Item var itemObjects:[String] = [String]() var currentItemIndex:Int = 0 var itemListView:ItemListViewController? var itemDetailViewController:ItemDetailViewController? let kItems:String = "items" let BLANK_ITEM_TITLE:String = "(New Item TITLE)" class ItemListViewController: UITableViewController { //@IBOutlet var addItemButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. itemListView = self load() self.navigationItem.leftBarButtonItem = self.editButtonItem() let addItemButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addItemButton } override func viewWillAppear(animated: Bool) { //self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed save() super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { if itemObjects.count == 0 { insertNewObject(self) } super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { if detailViewController?.detailDescriptionLabel.editable == false { return } if itemObjects.count == 0 || itemObjects[0] != BLANK_ITEM_TITLE { itemObjects.insert(BLANK_ITEM_TITLE, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } currentIndex = 0 self.performSegueWithIdentifier("showItemDetail", sender: self) } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemObjects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let itemObject = itemObjects[indexPath.row] cell.textLabel!.text = itemObject return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { itemObjects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated:animated) if editing { detailViewController?.detailDescriptionLabel.editable = false detailViewController?.detailDescriptionLabel.text = "" return } save() } override func tableView(tableView: UITableView, didEndEditingRowAtIndexPath indexPath: NSIndexPath) { detailViewController?.detailDescriptionLabel.editable = false detailViewController?.detailDescriptionLabel.text = "" save() } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { print("Made it to selection.") self.performSegueWithIdentifier("showItemDetail", sender: self) } func save() { NSUserDefaults.standardUserDefaults().setObject(itemObjects, forKey: kItems) NSUserDefaults.standardUserDefaults().synchronize() } func load() { if let loadedData = NSUserDefaults.standardUserDefaults().arrayForKey(kItems) as? [String] { itemObjects = loadedData } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { detailViewController?.detailDescriptionLabel.editable = true if segue.identifier == "showItemDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { currentIndex = indexPath.row } let itemObject = itemObjects[currentIndex] detailViewController?.detailItem = itemObject //detailItemViewController?.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() detailViewController?.navigationItem.leftItemsSupplementBackButton = true } } }
735169b7aa46ae03d6c900d238ec93f0
34.414474
157
0.666852
false
false
false
false
prasanth223344/celapp
refs/heads/master
Cgrams/CustomViews/CGButton.swift
mit
1
// // CGButton.swift // Cgrams // // Created by JH Lee on 04/03/2017. // Copyright © 2017 Widdit. All rights reserved. // import UIKit @IBDesignable class CGButton: UIButton { @IBInspectable var CornerRadius: CGFloat = 0 @IBInspectable var BorderWidth: CGFloat = 0 @IBInspectable var BorderColor: UIColor = UIColor.clear @IBInspectable var TitleLines: Int = 1 @IBInspectable var VerticalAlign: Bool = false override func draw(_ rect: CGRect) { // Drawing code titleLabel?.numberOfLines = TitleLines titleLabel?.lineBreakMode = .byWordWrapping titleLabel?.textAlignment = .center layer.masksToBounds = true layer.borderWidth = BorderWidth layer.borderColor = BorderColor.cgColor layer.cornerRadius = CornerRadius setLayout() } override func setImage(_ image: UIImage?, for state: UIControlState) { super.setImage(image, for: state) setLayout() } override func setTitle(_ title: String?, for state: UIControlState) { super.setTitle(title, for: state) setLayout() } func setLayout() { if(VerticalAlign) { let imageSize = imageView?.frame.size titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize!.width, -(imageSize!.height + 6.0), 0.0); // raise the image and push it right so it appears centered // above the text let titleSize = titleLabel?.frame.size; imageEdgeInsets = UIEdgeInsetsMake(-(titleSize!.height + 6.0), 0.0, 0.0, -titleSize!.width); } } }
e44efaa46115baf67fde31ff9753a3af
31.779661
74
0.527921
false
false
false
false
mottx/XCGLogger
refs/heads/master
Sources/XCGLogger/Destinations/FileDestination.swift
mit
1
// // FileDestination.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright © 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // import Foundation import Dispatch // MARK: - FileDestination /// A standard destination that outputs log details to a file open class FileDestination: BaseQueuedDestination { // MARK: - Properties /// Logger that owns the destination object open override var owner: XCGLogger? { didSet { if owner != nil { openFile() } else { closeFile() } } } /// FileURL of the file to log to open var writeToFileURL: URL? = nil { didSet { openFile() } } /// File handle for the log file internal var logFileHandle: FileHandle? = nil /// Option: whether or not to append to the log file if it already exists internal var shouldAppend: Bool /// Option: if appending to the log file, the string to output at the start to mark where the append took place internal var appendMarker: String? /// Option: Attributes to use when creating a new file internal var fileAttributes: [FileAttributeKey: Any]? = nil // MARK: - Life Cycle public init(owner: XCGLogger? = nil, writeToFile: Any, identifier: String = "", shouldAppend: Bool = false, appendMarker: String? = "-- ** ** ** --", attributes: [String: Any]? = nil) { self.shouldAppend = shouldAppend self.appendMarker = appendMarker if let attrKeys = attributes?.keys { fileAttributes = [FileAttributeKey: Any]() for key in attrKeys { if let val = attributes![key]{ let newKey = FileAttributeKey(key) fileAttributes?.updateValue(val, forKey: newKey) } } } if writeToFile is NSString { writeToFileURL = URL(fileURLWithPath: writeToFile as! String) } else if let writeToFile = writeToFile as? URL, writeToFile.isFileURL { writeToFileURL = writeToFile } else { writeToFileURL = nil } super.init(owner: owner, identifier: identifier) if owner != nil { openFile() } } deinit { // close file stream if open closeFile() } // MARK: - File Handling Methods /// Open the log file for writing. /// /// - Parameters: None /// /// - Returns: Nothing /// private func openFile() { guard let owner = owner else { return } if logFileHandle != nil { closeFile() } guard let writeToFileURL = writeToFileURL else { return } let fileManager: FileManager = FileManager.default let fileExists: Bool = fileManager.fileExists(atPath: writeToFileURL.path) if !shouldAppend || !fileExists { fileManager.createFile(atPath: writeToFileURL.path, contents: nil, attributes: self.fileAttributes) } do { logFileHandle = try FileHandle(forWritingTo: writeToFileURL) if fileExists && shouldAppend { logFileHandle?.seekToEndOfFile() if let appendMarker = appendMarker, let encodedData = "\(appendMarker)\n".data(using: String.Encoding.utf8) { _try({ self.logFileHandle?.write(encodedData) }, catch: { (exception: NSException) in print("Objective-C Exception occurred: \(exception)") }) } } } catch let error as NSError { owner._logln("Attempt to open log file for \(fileExists && shouldAppend ? "appending" : "writing") failed: \(error.localizedDescription)", level: .error, source: self) logFileHandle = nil return } owner.logAppDetails(selectedDestination: self) let logDetails = LogDetails(level: .info, date: Date(), message: "XCGLogger " + (fileExists && shouldAppend ? "appending" : "writing") + " log to: " + writeToFileURL.absoluteString, functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo) owner._logln(logDetails.message, level: logDetails.level, source: self) if owner.destination(withIdentifier: identifier) == nil { processInternal(logDetails: logDetails) } } /// Close the log file. /// /// - Parameters: None /// /// - Returns: Nothing /// private func closeFile() { logFileHandle?.synchronizeFile() logFileHandle?.closeFile() logFileHandle = nil } /// Force any buffered data to be written to the file. /// /// - Parameters: /// - closure: An optional closure to execute after the file has been rotated. /// /// - Returns: Nothing. /// open func flush(closure: (() -> Void)? = nil) { if let logQueue = logQueue { logQueue.async { self.logFileHandle?.synchronizeFile() closure?() } } else { logFileHandle?.synchronizeFile() closure?() } } /// Rotate the log file, storing the existing log file in the specified location. /// /// - Parameters: /// - archiveToFile: FileURL or path (as String) to where the existing log file should be rotated to. /// - closure: An optional closure to execute after the file has been rotated. /// /// - Returns: /// - true: Log file rotated successfully. /// - false: Error rotating the log file. /// @discardableResult open func rotateFile(to archiveToFile: Any, closure: ((_ success: Bool) -> Void)? = nil) -> Bool { var archiveToFileURL: URL? = nil if archiveToFile is NSString { archiveToFileURL = URL(fileURLWithPath: archiveToFile as! String) } else if let archiveToFile = archiveToFile as? URL, archiveToFile.isFileURL { archiveToFileURL = archiveToFile } else { closure?(false) return false } if let archiveToFileURL = archiveToFileURL, let writeToFileURL = writeToFileURL { let fileManager: FileManager = FileManager.default guard !fileManager.fileExists(atPath: archiveToFileURL.path) else { closure?(false); return false } closeFile() haveLoggedAppDetails = false do { try fileManager.moveItem(atPath: writeToFileURL.path, toPath: archiveToFileURL.path) } catch let error as NSError { openFile() owner?._logln("Unable to rotate file \(writeToFileURL.path) to \(archiveToFileURL.path): \(error.localizedDescription)", level: .error, source: self) closure?(false) return false } do { if let identifierData: Data = identifier.data(using: .utf8) { try archiveToFileURL.setExtendedAttribute(data: identifierData, forName: XCGLogger.Constants.extendedAttributeArchivedLogIdentifierKey) } if let timestampData: Data = "\(Date().timeIntervalSince1970)".data(using: .utf8) { try archiveToFileURL.setExtendedAttribute(data: timestampData, forName: XCGLogger.Constants.extendedAttributeArchivedLogTimestampKey) } } catch let error as NSError { owner?._logln("Unable to set extended file attributes on file \(archiveToFileURL.path): \(error.localizedDescription)", level: .error, source: self) } owner?._logln("Rotated file \(writeToFileURL.path) to \(archiveToFileURL.path)", level: .info, source: self) openFile() closure?(true) return true } closure?(false) return false } // MARK: - Overridden Methods /// Write the log to the log file. /// /// - Parameters: /// - message: Formatted/processed message ready for output. /// /// - Returns: Nothing /// open override func write(message: String) { if let encodedData = "\(message)\n".data(using: String.Encoding.utf8) { _try({ self.logFileHandle?.write(encodedData) }, catch: { (exception: NSException) in print("Objective-C Exception occurred: \(exception)") }) } } }
a0bc8d3bad628741b54c6dc03e234f7d
33.877953
284
0.57388
false
false
false
false
infobip/mobile-messaging-sdk-ios
refs/heads/master
Classes/Vendor/Kingsfisher/FormatIndicatedCacheSerializer.swift
apache-2.0
1
// // RequestModifier.swift // Kingfisher // // Created by Junyu Kuang on 5/28/17. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// `FormatIndicatedCacheSerializer` let you indicate an image format for serialized caches. /// /// It could serialize and deserialize PNG, JEPG and GIF images. For /// image other than these formats, a normalized `pngRepresentation` will be used. /// /// Example: /// ```` /// private let profileImageSize = CGSize(width: 44, height: 44) /// /// private let imageProcessor = RoundCornerImageProcessor( /// cornerRadius: profileImageSize.width / 2, targetSize: profileImageSize) /// /// private let optionsInfo: KingfisherOptionsInfo = [ /// .cacheSerializer(FormatIndicatedCacheSerializer.png), /// .backgroundDecode, .processor(imageProcessor), .scaleFactor(UIScreen.main.scale)] /// /// extension UIImageView { /// func setProfileImage(with url: URL) { /// // Image will always cached as PNG format to preserve alpha channel for round rect. /// _ = kf.setImage(with: url, options: optionsInfo) /// } ///} /// ```` internal struct FormatIndicatedCacheSerializer: CacheSerializer { internal static let png = FormatIndicatedCacheSerializer(imageFormat: .PNG) internal static let jpeg = FormatIndicatedCacheSerializer(imageFormat: .JPEG) internal static let gif = FormatIndicatedCacheSerializer(imageFormat: .GIF) /// The indicated image format. private let imageFormat: ImageFormat internal func data(with image: Image, original: Data?) -> Data? { func imageData(withFormat imageFormat: ImageFormat) -> Data? { switch imageFormat { case .PNG: return image.kf.pngRepresentation() case .JPEG: return image.kf.jpegRepresentation(compressionQuality: 1.0) case .GIF: return image.kf.gifRepresentation() case .unknown: return nil } } // generate data with indicated image format if let data = imageData(withFormat: imageFormat) { return data } let originalFormat = original?.kf.imageFormat ?? .unknown // generate data with original image's format if originalFormat != imageFormat, let data = imageData(withFormat: originalFormat) { return data } return original ?? image.kf.normalized.kf.pngRepresentation() } /// Same implementation as `DefaultCacheSerializer`. internal func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo return Kingfisher<Image>.image( data: data, scale: options.scaleFactor, preloadAllAnimationData: options.preloadAllAnimationData, onlyFirstFrame: options.onlyLoadFirstFrame) } }
0b7576186134d89b0c6c62de989d81e5
40.666667
94
0.6895
false
false
false
false
GrandCentralBoard/GrandCentralBoard
refs/heads/develop
GCBUtilities/Utilities/LabelWithSpacing.swift
gpl-3.0
2
// // Created by Oktawian Chojnacki on 08.09.2015. // Copyright (c) 2015 Macoscope. All rights reserved. // import UIKit public class LabelWithSpacing: UILabel { @IBInspectable public var kerning: Float = 1.0 { didSet { applyCustomAttributes() } } @IBInspectable public var lineSpace: CGFloat = 0.0 { didSet { applyCustomAttributes() } } public override var text: String? { didSet { applyCustomAttributes() } } public override func awakeFromNib() { super.awakeFromNib() applyCustomAttributes() } public func applyCustomAttributes() { guard let text = text else { attributedText = nil return } let attributedString = NSMutableAttributedString(string: text) attributedString.beginEditing() if lineSpace > 0.0 { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpace attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range: NSRange(location: 0, length: text.characters.count)) } attributedString.addAttribute(NSKernAttributeName, value: kerning, range: NSRange(location: 0, length: text.characters.count)) attributedString.endEditing() attributedText = attributedString sizeToFit() } }
e0838119ef6d1a27d935f9f5c866d594
28.77551
101
0.622344
false
false
false
false
mariopavlovic/advent-of-code
refs/heads/master
2015/advent-of-code/day2.playground/Contents.swift
mit
1
//let input = "20x3x11 " + // "15x27x5 " + // "6x29x7 " + // "30x15x9 " + // "19x29x21 " + // "10x4x15 " + // "1x26x4 " + // "1x5x18 " + // "10x15x23 " + // "10x14x20 " + // "3x5x18 " + // "29x23x30 " + // "7x4x10 " + // "22x24x29 " + // "30x1x2 " + // "19x2x5 " + // "11x9x22 " + // "23x15x10 " + // "11x11x10 " + // "30x28x5 " + // "22x5x4 " + // "6x26x20 " + // "16x12x30 " + // "10x20x5 " + // "25x14x24 " + // "16x17x22 " + // "11x28x26 " + // "1x11x10 " + // "1x24x15 " + // "13x17x21 " + // "30x3x13 " + // "20x25x17 " + // "22x12x5 " + // "22x20x24 " + // "9x2x14 " + // "6x18x8 " + // "27x28x24 " + // "11x17x1 " + // "1x4x12 " + // "5x20x13 " + // "24x23x23 " + // "22x1x25 " + // "18x19x5 " + // "5x23x13 " + // "8x16x4 " + // "20x21x9 " + // "1x7x11 " + // "8x30x17 " + // "3x30x9 " + // "6x16x18 " + // "22x25x27 " + // "9x20x26 " + // "16x21x23 " + // "5x24x17 " + // "15x17x15 " + // "26x15x10 " + // "22x16x3 " + // "20x24x24 " + // "8x18x10 " + // "23x19x16 " + // "1x21x24 " + // "23x23x9 " + // "14x20x6 " + // "25x5x5 " + // "16x3x1 " + // "29x29x20 " + // "11x4x26 " + // "10x23x24 " + // "29x25x16 " + // "27x27x22 " + // "9x7x22 " + // "6x21x18 " + // "25x11x19 " + // "14x13x3 " + // "15x28x17 " + // "14x3x12 " + // "29x8x19 " + // "30x14x20 " + // "20x23x4 " + // "8x16x5 " + // "4x11x18 " + // "20x8x24 " + // "21x13x21 " + // "14x26x29 " + // "27x4x17 " + // "27x4x25 " + // "5x28x6 " + // "23x24x11 " + // "29x22x5 " + // "30x20x6 " + // "23x2x10 " + // "11x4x7 " + // "27x23x6 " + // "10x20x19 " + // "8x20x22 " + // "5x29x22 " + // "16x13x2 " + // "2x11x14 " + // "6x12x4 " + // "3x13x6 " + // "16x5x18 " + // "25x3x28 " + // "21x1x5 " + // "20x16x19 " + // "28x30x27 " + // "26x7x18 " + // "25x27x24 " + // "11x19x7 " + // "21x19x17 " + // "2x12x27 " + // "20x5x14 " + // "8x5x8 " + // "6x24x8 " + // "7x28x20 " + // "3x20x28 " + // "5x20x30 " + // "13x29x1 " + // "26x29x5 " + // "19x28x25 " + // "5x19x11 " + // "11x20x22 " + // "4x23x1 " + // "19x25x12 " + // "3x10x6 " + // "3x14x10 " + // "28x16x12 " + // "23x12x2 " + // "23x12x19 " + // "20x28x10 " + // "9x10x25 " + // "16x21x16 " + // "1x18x20 " + // "9x4x26 " + // "3x25x8 " + // "17x16x28 " + // "9x28x16 " + // "27x3x12 " + // "17x24x12 " + // "13x21x10 " + // "7x17x13 " + // "6x10x9 " + // "7x29x25 " + // "11x19x30 " + // "1x24x5 " + // "20x16x23 " + // "24x28x21 " + // "6x29x19 " + // "25x2x19 " + // "12x5x26 " + // "25x29x12 " + // "16x28x22 " + // "26x26x15 " + // "9x13x5 " + // "10x29x7 " + // "1x24x16 " + // "22x2x2 " + // "6x16x13 " + // "3x12x28 " + // "4x12x13 " + // "14x27x21 " + // "14x23x26 " + // "7x5x18 " + // "8x30x27 " + // "15x9x18 " + // "26x16x5 " + // "3x29x17 " + // "19x7x18 " + // "16x18x1 " + // "26x15x30 " + // "24x30x21 " + // "13x20x7 " + // "4x12x10 " + // "27x20x11 " + // "28x29x21 " + // "20x14x30 " + // "28x12x3 " + // "19x1x8 " + // "4x8x6 " + // "21x14x2 " + // "27x19x21 " + // "17x24x14 " + // "15x18x11 " + // "18x7x26 " + // "25x28x29 " + // "27x26x9 " + // "18x12x17 " + // "24x28x25 " + // "13x24x14 " + // "26x9x28 " + // "9x3x30 " + // "9x2x9 " + // "8x1x29 " + // "18x30x10 " + // "18x14x5 " + // "26x8x30 " + // "12x1x1 " + // "30x5x28 " + // "26x17x21 " + // "10x10x10 " + // "20x7x27 " + // "13x17x6 " + // "21x13x17 " + // "2x16x8 " + // "7x9x9 " + // "15x26x4 " + // "11x28x25 " + // "10x6x19 " + // "21x6x29 " + // "15x5x6 " + // "28x9x16 " + // "14x3x10 " + // "12x29x5 " + // "22x19x19 " + // "25x15x22 " + // "30x6x28 " + // "11x23x13 " + // "20x25x14 " + // "26x1x13 " + // "6x14x15 " + // "16x25x17 " + // "28x4x13 " + // "10x24x25 " + // "4x13x10 " + // "9x15x16 " + // "15x24x6 " + // "22x9x19 " + // "11x11x8 " + // "4x19x12 " + // "24x5x4 " + // "27x12x13 " + // "7x27x16 " + // "2x6x9 " + // "29x27x15 " + // "18x26x23 " + // "19x16x15 " + // "14x5x25 " + // "9x16x30 " + // "4x6x4 " + // "13x10x10 " + // "1x8x29 " + // "23x5x17 " + // "19x20x20 " + // "11x27x24 " + // "27x15x5 " + // "15x11x12 " + // "21x11x3 " + // "1x13x22 " + // "17x8x8 " + // "13x14x14 " + // "17x22x7 " + // "9x5x8 " + // "2x6x3 " + // "25x9x15 " + // "11x8x13 " + // "9x25x12 " + // "3x16x12 " + // "12x16x8 " + // "16x24x17 " + // "4x6x26 " + // "22x29x11 " + // "14x17x19 " + // "28x2x27 " + // "24x22x19 " + // "22x20x30 " + // "23x28x4 " + // "16x12x14 " + // "22x24x22 " + // "29x1x28 " + // "26x29x16 " + // "3x25x30 " + // "27x3x13 " + // "22x24x26 " + // "25x3x2 " + // "7x24x2 " + // "10x5x3 " + // "28x8x29 " + // "25x6x4 " + // "12x17x14 " + // "24x3x5 " + // "23x27x7 " + // "26x23x30 " + // "11x10x19 " + // "23x7x11 " + // "26x14x15 " + // "14x3x25 " + // "12x24x14 " + // "2x14x12 " + // "9x12x16 " + // "9x2x28 " + // "3x8x2 " + // "22x6x9 " + // "2x30x2 " + // "25x1x9 " + // "20x11x2 " + // "14x11x12 " + // "7x14x12 " + // "24x8x26 " + // "13x21x23 " + // "18x17x23 " + // "13x6x17 " + // "20x20x19 " + // "13x17x29 " + // "7x24x24 " + // "23x8x6 " + // "19x10x28 " + // "3x8x21 " + // "15x20x18 " + // "11x27x1 " + // "11x24x28 " + // "13x20x11 " + // "18x19x22 " + // "27x22x12 " + // "28x3x2 " + // "13x4x29 " + // "26x5x6 " + // "14x29x25 " + // "7x4x7 " + // "5x17x7 " + // "2x8x1 " + // "22x30x24 " + // "22x21x28 " + // "1x28x13 " + // "11x20x4 " + // "25x29x19 " + // "9x23x4 " + // "30x6x11 " + // "25x18x10 " + // "28x10x24 " + // "3x5x20 " + // "19x28x10 " + // "27x19x2 " + // "26x20x4 " + // "19x21x6 " + // "2x12x30 " + // "8x26x27 " + // "11x27x10 " + // "14x13x17 " + // "4x3x21 " + // "2x20x21 " + // "22x30x3 " + // "2x23x2 " + // "3x16x12 " + // "22x28x22 " + // "3x23x29 " + // "8x25x15 " + // "9x30x4 " + // "10x11x1 " + // "24x8x20 " + // "10x7x27 " + // "7x22x4 " + // "27x13x17 " + // "5x28x5 " + // "30x15x13 " + // "10x8x17 " + // "8x21x5 " + // "8x17x26 " + // "25x16x4 " + // "9x7x25 " + // "13x11x20 " + // "6x30x9 " + // "15x14x12 " + // "30x1x23 " + // "5x20x24 " + // "22x7x6 " + // "26x11x23 " + // "29x7x5 " + // "13x24x28 " + // "22x20x10 " + // "18x3x1 " + // "15x19x23 " + // "28x28x20 " + // "7x26x2 " + // "9x12x20 " + // "15x4x6 " + // "1x17x21 " + // "3x22x17 " + // "9x4x20 " + // "25x19x5 " + // "9x11x22 " + // "14x1x17 " + // "14x5x16 " + // "30x5x18 " + // "19x6x12 " + // "28x16x22 " + // "13x4x25 " + // "29x23x18 " + // "1x27x3 " + // "12x14x4 " + // "10x25x19 " + // "15x19x30 " + // "11x30x4 " + // "11x22x26 " + // "13x25x2 " + // "17x13x27 " + // "11x30x24 " + // "15x1x14 " + // "17x18x4 " + // "26x11x3 " + // "16x22x28 " + // "13x20x9 " + // "1x18x3 " + // "25x11x12 " + // "20x21x1 " + // "22x27x4 " + // "8x28x23 " + // "7x13x27 " + // "17x9x26 " + // "27x27x20 " + // "11x20x12 " + // "26x21x11 " + // "29x14x12 " + // "27x25x1 " + // "28x29x25 " + // "21x23x28 " + // "5x18x18 " + // "19x5x4 " + // "7x6x30 " + // "27x8x11 " + // "12x24x12 " + // "16x25x22 " + // "26x11x29 " + // "25x22x17 " + // "15x23x23 " + // "17x9x6 " + // "30x10x16 " + // "21x3x5 " + // "18x27x2 " + // "28x21x14 " + // "16x18x17 " + // "4x18x2 " + // "9x1x14 " + // "9x1x9 " + // "5x27x12 " + // "8x16x30 " + // "3x19x19 " + // "16x26x24 " + // "1x6x9 " + // "15x14x3 " + // "11x7x19 " + // "8x19x3 " + // "17x26x26 " + // "6x18x11 " + // "19x12x4 " + // "29x20x16 " + // "20x17x23 " + // "6x6x5 " + // "20x30x19 " + // "18x25x18 " + // "2x26x2 " + // "3x1x1 " + // "14x25x18 " + // "3x1x6 " + // "11x14x18 " + // "17x23x27 " + // "25x29x9 " + // "6x25x20 " + // "20x10x9 " + // "17x5x18 " + // "29x14x8 " + // "14x25x26 " + // "10x15x29 " + // "23x19x11 " + // "22x2x2 " + // "4x5x5 " + // "13x23x25 " + // "19x13x19 " + // "20x18x6 " + // "30x7x28 " + // "26x18x17 " + // "29x18x10 " + // "30x29x1 " + // "12x26x24 " + // "18x17x26 " + // "29x28x15 " + // "3x12x20 " + // "24x10x8 " + // "30x15x6 " + // "28x23x15 " + // "14x28x11 " + // "10x27x19 " + // "14x8x21 " + // "24x1x23 " + // "1x3x27 " + // "6x15x6 " + // "8x25x26 " + // "13x10x25 " + // "6x9x8 " + // "10x29x29 " + // "26x23x5 " + // "14x24x1 " + // "25x6x22 " + // "17x11x18 " + // "1x27x26 " + // "18x25x23 " + // "20x15x6 " + // "2x21x28 " + // "2x10x13 " + // "12x25x14 " + // "2x14x23 " + // "30x5x23 " + // "29x19x21 " + // "29x10x25 " + // "14x22x16 " + // "17x11x26 " + // "12x17x30 " + // "8x17x7 " + // "20x25x28 " + // "20x11x30 " + // "15x1x12 " + // "13x3x24 " + // "16x23x23 " + // "27x3x3 " + // "26x3x27 " + // "18x5x12 " + // "12x26x7 " + // "19x27x12 " + // "20x10x28 " + // "30x12x25 " + // "3x14x10 " + // "21x26x1 " + // "24x26x26 " + // "7x21x30 " + // "3x29x12 " + // "29x28x5 " + // "5x20x7 " + // "27x11x2 " + // "15x20x4 " + // "16x15x15 " + // "19x13x7 " + // "7x17x15 " + // "27x24x15 " + // "9x17x28 " + // "20x21x14 " + // "14x29x29 " + // "23x26x13 " + // "27x23x21 " + // "18x13x6 " + // "26x16x21 " + // "18x26x27 " + // "9x3x12 " + // "30x18x24 " + // "12x11x29 " + // "5x15x1 " + // "1x16x3 " + // "14x28x11 " + // "2x18x1 " + // "19x18x19 " + // "18x28x21 " + // "2x3x14 " + // "22x16x5 " + // "28x18x28 " + // "24x16x18 " + // "7x4x10 " + // "19x26x19 " + // "24x17x7 " + // "25x9x6 " + // "25x17x7 " + // "20x22x20 " + // "3x3x7 " + // "23x19x15 " + // "21x27x21 " + // "1x23x11 " + // "9x19x4 " + // "22x4x18 " + // "6x15x5 " + // "15x25x2 " + // "23x11x20 " + // "27x16x6 " + // "27x8x5 " + // "10x10x19 " + // "22x14x1 " + // "7x1x29 " + // "8x11x17 " + // "27x9x27 " + // "28x9x24 " + // "17x7x3 " + // "26x23x8 " + // "7x6x30 " + // "25x28x2 " + // "1x30x25 " + // "3x18x18 " + // "28x27x15 " + // "14x14x1 " + // "10x25x29 " + // "18x12x9 " + // "20x28x16 " + // "26x27x22 " + // "8x26x1 " + // "21x2x12 " + // "25x16x14 " + // "21x19x5 " + // "12x9x22 " + // "16x5x4 " + // "5x4x16 " + // "25x29x3 " + // "4x29x13 " + // "15x16x29 " + // "8x11x24 " + // "30x11x20 " + // "17x21x14 " + // "12x24x10 " + // "10x12x6 " + // "3x26x30 " + // "15x14x25 " + // "20x12x21 " + // "13x11x16 " + // "15x13x3 " + // "5x17x29 " + // "6x3x23 " + // "9x26x11 " + // "30x1x8 " + // "14x10x30 " + // "18x30x10 " + // "13x19x19 " + // "16x19x17 " + // "28x7x10 " + // "28x29x4 " + // "3x21x10 " + // "4x28x24 " + // "7x28x9 " + // "2x4x9 " + // "25x27x13 " + // "6x12x15 " + // "4x18x20 " + // "20x1x16 " + // "5x13x24 " + // "11x11x10 " + // "12x9x23 " + // "1x9x30 " + // "17x28x24 " + // "9x5x27 " + // "21x15x16 " + // "17x4x14 " + // "8x14x4 " + // "13x10x7 " + // "17x12x14 " + // "9x19x19 " + // "2x7x21 " + // "8x24x23 " + // "19x5x12 " + // "11x23x21 " + // "13x3x1 " + // "5x27x15 " + // "12x25x25 " + // "13x21x16 " + // "9x17x11 " + // "1x15x21 " + // "4x26x17 " + // "11x5x15 " + // "23x10x15 " + // "12x17x21 " + // "27x15x1 " + // "4x29x14 " + // "5x24x25 " + // "10x10x12 " + // "18x12x9 " + // "11x24x23 " + // "24x23x3 " + // "28x12x15 " + // "29x9x14 " + // "11x25x8 " + // "5x12x2 " + // "26x26x29 " + // "9x21x2 " + // "8x8x25 " + // "1x16x30 " + // "17x29x20 " + // "9x22x13 " + // "7x18x16 " + // "3x3x23 " + // "26x25x30 " + // "15x23x24 " + // "20x23x5 " + // "20x16x10 " + // "23x7x8 " + // "20x18x26 " + // "8x27x6 " + // "30x23x23 " + // "7x7x24 " + // "21x11x15 " + // "1x30x25 " + // "26x27x22 " + // "30x28x13 " + // "20x13x13 " + // "3x1x15 " + // "16x7x1 " + // "7x25x15 " + // "12x7x18 " + // "16x9x23 " + // "16x12x18 " + // "29x5x2 " + // "17x7x7 " + // "21x17x5 " + // "9x9x17 " + // "26x16x10 " + // "29x29x23 " + // "17x26x10 " + // "5x19x17 " + // "1x10x1 " + // "14x21x20 " + // "13x6x4 " + // "13x13x3 " + // "23x4x18 " + // "4x16x3 " + // "16x30x11 " + // "2x11x2 " + // "15x30x15 " + // "20x30x22 " + // "18x12x16 " + // "23x5x16 " + // "6x14x15 " + // "9x4x11 " + // "30x23x21 " + // "20x7x12 " + // "7x18x6 " + // "15x6x5 " + // "18x22x19 " + // "16x10x22 " + // "26x20x25 " + // "9x25x25 " + // "29x21x10 " + // "9x21x24 " + // "7x18x21 " + // "14x3x15 " + // "18x19x19 " + // "4x29x17 " + // "14x10x9 " + // "2x26x14 " + // "13x3x24 " + // "4x4x17 " + // "6x27x24 " + // "2x18x3 " + // "14x25x2 " + // "30x14x17 " + // "11x6x14 " + // "4x10x18 " + // "15x4x2 " + // "27x7x10 " + // "13x24x1 " + // "7x12x6 " + // "25x22x26 " + // "19x2x18 " + // "23x29x2 " + // "2x15x4 " + // "12x6x9 " + // "16x14x29 " + // "9x17x3 " + // "21x9x12 " + // "23x18x22 " + // "10x8x4 " + // "29x2x7 " + // "19x27x15 " + // "4x24x27 " + // "25x20x14 " + // "8x23x19 " + // "1x24x19 " + // "6x20x10 " + // "15x8x5 " + // "18x28x5 " + // "17x23x22 " + // "9x16x13 " + // "30x24x4 " + // "26x3x13 " + // "12x22x18 " + // "29x17x29 " + // "26x4x16 " + // "15x7x20 " + // "9x15x30 " + // "12x7x18 " + // "28x19x18 " + // "11x23x23 " + // "24x20x1 " + // "20x3x24 " + // "1x26x1 " + // "14x10x6 " + // "5x27x24 " + // "13x21x12 " + // "20x20x5 " + // "6x28x9 " + // "11x26x11 " + // "26x29x12 " + // "21x4x11 " + // "20x11x17 " + // "22x27x20 " + // "19x11x21 " + // "2x11x11 " + // "13x5x7 " + // "12x10x25 " + // "21x28x1 " + // "15x30x17 " + // "28x19x1 " + // "4x19x12 " + // "11x4x12 " + // "4x10x30 " + // "11x18x5 " + // "22x20x12 " + // "3x7x27 " + // "20x26x4 " + // "13x27x26 " + // "23x14x13 " + // "4x19x7 " + // "26x27x16 " + // "20x5x20 " + // "18x5x8 " + // "19x21x1 " + // "22x8x1 " + // "29x4x1 " + // "24x10x15 " + // "24x9x20 " + // "10x3x8 " + // "29x30x3 " + // "2x8x24 " + // "16x7x18 " + // "2x11x23 " + // "23x15x16 " + // "21x12x6 " + // "24x28x9 " + // "6x1x13 " + // "14x29x20 " + // "27x24x13 " + // "16x26x8 " + // "5x6x17 " + // "21x8x1 " + // "28x19x21 " + // "1x14x16 " + // "18x2x9 " + // "29x28x10 " + // "22x26x27 " + // "18x26x23 " + // "22x24x2 " + // "28x26x1 " + // "27x29x12 " + // "30x13x11 " + // "1x25x5 " + // "13x30x18 " + // "3x13x22 " + // "22x10x11 " + // "2x7x7 " + // "18x17x8 " + // "9x22x26 " + // "30x18x16 " + // "10x2x3 " + // "7x27x13 " + // "3x20x16 " + // "9x21x16 " + // "1x18x15 " + // "21x30x30 " + // "4x25x23 " + // "3x11x7 " + // "5x6x12 " + // "27x1x20 " + // "13x15x24 " + // "23x29x2 " + // "13x5x24 " + // "22x16x15 " + // "28x14x3 " + // "29x24x9 " + // "2x20x4 " + // "30x10x4 " + // "23x7x20 " + // "22x12x21 " + // "3x19x11 " + // "4x28x28 " + // "5x4x7 " + // "28x12x25 " + // "2x16x26 " + // "23x20x7 " + // "5x21x29 " + // "9x21x16 " + // "9x6x10 " + // "9x6x4 " + // "24x14x29 " + // "28x11x6 " + // "10x22x1 " + // "21x30x20 " + // "13x17x8 " + // "2x25x24 " + // "19x21x3 " + // "28x8x14 " + // "6x29x28 " + // "27x10x28 " + // "30x11x12 " + // "17x2x10 " + // "14x19x17 " + // "2x11x4 " + // "26x1x2 " + // "13x4x4 " + // "23x20x18 " + // "2x17x21 " + // "28x7x15 " + // "3x3x27 " + // "24x17x30 " + // "28x28x20 " + // "21x5x29 " + // "13x12x19 " + // "24x29x29 " + // "19x10x6 " + // "19x12x14 " + // "21x4x17 " + // "27x16x1 " + // "4x17x30 " + // "23x23x18 " + // "23x15x27 " + // "26x2x11 " + // "12x8x8 " + // "15x23x26 " + // "30x17x15 " + // "17x17x15 " + // "24x4x30 " + // "9x9x10 " + // "14x25x20 " + // "25x11x19 " + // "20x7x1 " + // "9x21x3 " + // "7x19x9 " + // "10x6x19 " + // "26x12x30 " + // "21x9x20 " + // "15x11x6 " + // "30x21x9 " + // "10x18x17 " + // "22x9x8 " + // "8x30x26 " + // "28x12x27 " + // "17x17x7 " + // "11x13x8 " + // "5x3x21 " + // "24x1x29 " + // "1x28x2 " + // "18x28x10 " + // "8x29x14 " + // "26x26x27 " + // "17x10x25 " + // "22x30x3 " + // "27x9x13 " + // "21x21x4 " + // "30x29x16 " + // "22x7x20 " + // "24x10x2 " + // "16x29x17 " + // "28x15x17 " + // "19x19x22 " + // "9x8x6 " + // "26x23x24 " + // "25x4x27 " + // "16x12x2 " + // "11x6x18 " + // "19x14x8 " + // "9x29x13 " + // "23x30x19 " + // "10x16x1 " + // "4x21x28 " + // "23x25x25 " + // "19x9x16 " + // "30x11x12 " + // "24x3x9 " + // "28x19x4 " + // "18x12x9 " + // "7x1x25 " + // "28x7x1 " + // "24x3x12 " + // "30x24x22 " + // "27x24x26 " + // "9x30x30 " + // "29x10x8 " + // "4x6x18 " + // "10x1x15 " + // "10x4x26 " + // "23x20x16 " + // "6x3x14 " + // "30x8x16 " + // "25x14x20 " + // "11x9x3 " + // "15x23x25 " + // "8x30x22 " + // "22x19x18 " + // "25x1x12 " + // "27x25x7 " + // "25x23x3 " + // "13x20x8 " + // "5x30x7 " + // "18x19x27 " + // "20x23x3 " + // "1x17x21 " + // "21x21x27 " + // "13x1x24 " + // "7x30x20 " + // "21x9x18 " + // "23x26x6 " + // "22x9x29 " + // "17x6x21 " + // "28x28x29 " + // "19x25x26 " + // "9x27x21 " + // "5x26x8 " + // "11x19x1 " + // "10x1x18 " + // "29x4x8 " + // "21x2x22 " + // "14x12x8" let input = "1x1x10" struct Present { var length: Int var width: Int var height: Int func sideA() -> Int { return length * width } func sideB() -> Int { return width * height } func sideC() -> Int { return height * length } func volume() -> Int { return length * width * height } } func convertInputToDimensions(input: String) -> [Present] { let dimensionsRawArrayInput = input.characters.split { $0 == " " }.map(String.init) return dimensionsRawArrayInput.map({ (inputDimension) -> Present in let dimensions = inputDimension.characters.split { $0 == "x" }.map(String.init) return Present(length: Int(dimensions[0])!, width: Int(dimensions[1])!, height: Int(dimensions[2])!) }) } func paperNeededForPresent(present: Present) -> Int { let minSide = min(present.sideA(), present.sideB(), present.sideC()) //2*l*w + 2*w*h + 2*h*l + min_side //times 2 because we need square footage return 2 * (present.sideA() + present.sideB() + present.sideC()) + minSide } func ribbonNeededForPresent(present: Present) -> Int { //formula = shortest distance around presents sides + present volume //shortest distance around presents sides = circumference of two shortest sides let sortedDimensions = [present.length, present.height, present.width].sort() let minCircumference = 2 * (sortedDimensions[0] + sortedDimensions[1]) return present.volume() + minCircumference } let inputDimensions = convertInputToDimensions(input) let neededPaperForPresent = inputDimensions.reduce(0) { (total: Int, present) -> Int in total + paperNeededForPresent(present) } let neededPaperForRibbon = inputDimensions.reduce(0) { (total: Int, present) -> Int in total + ribbonNeededForPresent(present) } print("Elfs need \(neededPaperForPresent)^feet for present") print("Elfs need \(neededPaperForRibbon)^feet for ribbon")
6984ce5613ef2c78f7fe7a6dcfcf3ad4
18.863465
108
0.400427
false
false
false
false
OlegKetrar/NumberPad
refs/heads/master
Sources/ConvenienceExtensions.swift
mit
1
// // ConvenienceExtensions.swift // NumberPad // // Created by Oleg Ketrar on 28.11.16. // // import UIKit protocol Reusable: class { static var reuseIdentifier: String { get } static var nibName: String { get } } extension Reusable { static var reuseIdentifier: String { return String(describing: Self.self) } static var nibName: String { return String(describing: Self.self) } static var nib: UINib { return UINib(nibName: nibName, bundle: Bundle(for: self)) } } extension Reusable where Self: UIView { func replaceWithNib() { if let reusableView = Self.nib.instantiate(withOwner: self, options: nil)[0] as? UIView { reusableView.backgroundColor = UIColor.clear reusableView.isOpaque = false reusableView.clipsToBounds = true addSubview(reusableView) addPinConstraints(toSubview: reusableView) } } } extension UIView { func addPinConstraint(toSubview subview: UIView, attribute: NSLayoutAttribute, withSpacing spacing: CGFloat = 0) { subview.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: subview, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1.0, constant: spacing)) } func addPinConstraints(toSubview subview: UIView, withSpacing spacing: CGFloat = 0) { addPinConstraint(toSubview: subview, attribute: .left, withSpacing: spacing) addPinConstraint(toSubview: subview, attribute: .top, withSpacing: spacing) addPinConstraint(toSubview: subview, attribute: .right, withSpacing: -spacing) addPinConstraint(toSubview: subview, attribute: .bottom, withSpacing: -spacing) } /// pin current view to its superview with attribute func pinToSuperview(attribute: NSLayoutAttribute, spacing: CGFloat = 0) { translatesAutoresizingMaskIntoConstraints = false superview?.addPinConstraint(toSubview: self, attribute: attribute, withSpacing: spacing) } } extension UIImage { /// Creates image with specified color. /// - parameter color: specified color with alpha. /// - parameter size: image size, default 1x1. convenience init?(color: UIColor, size: CGSize = .init(width: 1, height: 1)) { let image: UIImage? = { defer { UIGraphicsEndImageContext() } UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(.init(origin: .zero, size: size)) return UIGraphicsGetImageFromCurrentImageContext() }() guard let createdImage = image, let patternImage = createdImage.cgImage else { return nil } self.init(cgImage: patternImage, scale: createdImage.scale, orientation: createdImage.imageOrientation) } }
bd5e7ab64297790f377d2cf985dadef0
35.822785
118
0.673427
false
false
false
false
airbnb/lottie-ios
refs/heads/master
Sources/Private/CoreAnimation/Layers/PreCompLayer.swift
apache-2.0
2
// Created by Cal Stephens on 12/14/21. // Copyright © 2021 Airbnb Inc. All rights reserved. import QuartzCore // MARK: - PreCompLayer /// The `CALayer` type responsible for rendering `PreCompLayerModel`s final class PreCompLayer: BaseCompositionLayer { // MARK: Lifecycle init(preCompLayer: PreCompLayerModel) { self.preCompLayer = preCompLayer super.init(layerModel: preCompLayer) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Called by CoreAnimation to create a shadow copy of this layer /// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init override init(layer: Any) { guard let typedLayer = layer as? Self else { fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))") } preCompLayer = typedLayer.preCompLayer timeRemappingInterpolator = typedLayer.timeRemappingInterpolator super.init(layer: typedLayer) } // MARK: Internal /// Post-init setup for `PreCompLayer`s. /// Should always be called after `PreCompLayer.init(preCompLayer:)`. /// /// This is a workaround for a hard-to-reproduce crash that was /// triggered when `PreCompLayer.init` was called reentantly. We didn't /// have any consistent repro steps for this crash (it happened 100% of /// the time for some testers, and 0% of the time for other testers), /// but moving this code out of `PreCompLayer.init` does seem to fix it. /// /// The stack trace looked like: /// - `_os_unfair_lock_recursive_abort` /// - `-[CALayerAccessibility__UIKit__QuartzCore dealloc]` /// - `PreCompLayer.__allocating_init(preCompLayer:context:)` <- reentrant init call /// - ... /// - `CALayer.setupLayerHierarchy(for:context:)` /// - `PreCompLayer.init(preCompLayer:context:)` /// func setup(context: LayerContext) throws { if let timeRemappingKeyframes = preCompLayer.timeRemapping { timeRemappingInterpolator = try .timeRemapping(keyframes: timeRemappingKeyframes, context: context) } else { timeRemappingInterpolator = nil } try setupLayerHierarchy( for: context.animation.assetLibrary?.precompAssets[preCompLayer.referenceID]?.layers ?? [], context: context) } override func setupAnimations(context: LayerAnimationContext) throws { var context = context context = context.addingKeypathComponent(preCompLayer.name) try setupLayerAnimations(context: context) // Precomp layers can adjust the local time of their child layers (relative to the // animation's global time) via `timeRemapping` or a custom `startTime` / `timeStretch` let contextForChildren = context.withTimeRemapping { [preCompLayer, timeRemappingInterpolator] layerLocalFrame in if let timeRemappingInterpolator = timeRemappingInterpolator { return timeRemappingInterpolator.value(frame: layerLocalFrame) as? AnimationFrameTime ?? layerLocalFrame } else { return (layerLocalFrame * AnimationFrameTime(preCompLayer.timeStretch)) + AnimationFrameTime(preCompLayer.startTime) } } try setupChildAnimations(context: contextForChildren) } // MARK: Private private let preCompLayer: PreCompLayerModel private var timeRemappingInterpolator: KeyframeInterpolator<AnimationFrameTime>? } // MARK: CustomLayoutLayer extension PreCompLayer: CustomLayoutLayer { func layout(superlayerBounds: CGRect) { anchorPoint = .zero // Pre-comp layers use a size specified in the layer model, // and clip the composition to that bounds bounds = CGRect( x: superlayerBounds.origin.x, y: superlayerBounds.origin.y, width: CGFloat(preCompLayer.width), height: CGFloat(preCompLayer.height)) masksToBounds = true } } extension KeyframeInterpolator where ValueType == AnimationFrameTime { /// A `KeyframeInterpolator` for the given `timeRemapping` keyframes static func timeRemapping( keyframes timeRemappingKeyframes: KeyframeGroup<LottieVector1D>, context: LayerContext) throws -> KeyframeInterpolator<AnimationFrameTime> { try context.logCompatibilityIssue(""" The Core Animation rendering engine partially supports time remapping keyframes, but this is somewhat experimental and has some known issues. Since it doesn't work in all cases, we have to fall back to using the main thread engine when using `RenderingEngineOption.automatic`. """) // `timeRemapping` is a mapping from the animation's global time to the layer's local time. // In the Core Animation engine, we need to perform the opposite calculation -- convert // the layer's local time into the animation's global time. We can get this by inverting // the time remapping, swapping the x axis (global time) and the y axis (local time). let localTimeToGlobalTimeMapping = timeRemappingKeyframes.keyframes.map { keyframe in Keyframe( value: keyframe.time, time: keyframe.value.cgFloatValue * CGFloat(context.animation.framerate), isHold: keyframe.isHold, inTangent: keyframe.inTangent, outTangent: keyframe.outTangent, spatialInTangent: keyframe.spatialInTangent, spatialOutTangent: keyframe.spatialOutTangent) } return KeyframeInterpolator(keyframes: .init(localTimeToGlobalTimeMapping)) } }
7d17925ee79d3f7eb171cbbd364d0bcc
37.769784
124
0.727222
false
false
false
false
aslanyanhaik/youtube-iOS
refs/heads/Master
YouTube/Supporting views/TabBarView.swift
mit
1
// MIT License // Copyright (c) 2017 Haik Aslanyan // 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 TabBarView: UIView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate { //MARK: Properties @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var whiteBar: UIView! @IBOutlet weak var whiteBarLeadingConstraint: NSLayoutConstraint! private let tabBarImages = ["home", "trending", "subscriptions", "account"] var selectedIndex = 0 //MARK: Methods func customization() { self.collectionView.delegate = self self.collectionView.dataSource = self self.backgroundColor = UIColor.rbg(r: 228, g: 34, b: 24) NotificationCenter.default.addObserver(self, selector: #selector(self.animateMenu(notification:)), name: Notification.Name.init(rawValue: "scrollMenu"), object: nil) } @objc func animateMenu(notification: Notification) { if let info = notification.userInfo { let userInfo = info as! [String: CGFloat] self.whiteBarLeadingConstraint.constant = self.whiteBar.bounds.width * userInfo["length"]! self.selectedIndex = Int(round(userInfo["length"]!)) self.layoutIfNeeded() self.collectionView.reloadData() } } //MARK: Delegates func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.tabBarImages.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! TabBarCellCollectionViewCell var imageName = self.tabBarImages[indexPath.row] if self.selectedIndex == indexPath.row { imageName += "Selected" } cell.icon.image = UIImage.init(named: imageName) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize.init(width: collectionView.bounds.width / 4, height: collectionView.bounds.height) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if self.selectedIndex != indexPath.row { self.selectedIndex = indexPath.row NotificationCenter.default.post(name: Notification.Name.init(rawValue: "didSelectMenu"), object: nil, userInfo: ["index": self.selectedIndex]) } } //MARK: View LifeCycle override func awakeFromNib() { super.awakeFromNib() self.customization() } deinit { NotificationCenter.default.removeObserver(self) } } //TabBarCell Class class TabBarCellCollectionViewCell: UICollectionViewCell { @IBOutlet weak var icon: UIImageView! }
3be2d6a2c5c311799aee1a1d0d3f9764
42.923913
173
0.71022
false
false
false
false
qvacua/vimr
refs/heads/master
VimR/VimR/MarkdownToolReducer.swift
mit
1
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Foundation final class MarkdownToolReducer: ReducerType { typealias StateType = MainWindow.State typealias ActionType = UuidAction<MarkdownTool.Action> init(baseServerUrl: URL) { self.baseServerUrl = baseServerUrl } func typedReduce(_ tuple: ReduceTuple) -> ReduceTuple { var state = tuple.state switch tuple.action.payload { case let .setAutomaticReverseSearch(to: value): state.previewTool.isReverseSearchAutomatically = value case let .setAutomaticForwardSearch(to: value): state.previewTool.isForwardSearchAutomatically = value case let .setRefreshOnWrite(to: value): state.previewTool.isRefreshOnWrite = value default: return tuple } return (state, tuple.action, true) } private let baseServerUrl: URL }
2f32a8d6b171ddf0c8cb1bf48edd21ea
22.459459
60
0.71659
false
false
false
false
mitchellporter/SAInboxViewController
refs/heads/master
SAInboxViewControllerSample/SAInboxViewControllerSample/DetailViewController.swift
mit
1
// // DetailViewController.swift // SAInboxViewControllerSample // // Created by Taiki Suzuki on 2015/08/15. // Copyright (c) 2015年 Taiki Suzuki. All rights reserved. // import UIKit import SAInboxViewController import QuartzCore class DetailViewController: SAInboxDetailViewController { var iconImage: UIImage? var text: String? var username: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.dataSource = self let nib = UINib(nibName: DetailViewCell.kCellIdentifier, bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: DetailViewCell.kCellIdentifier) title = username tableView.separatorInset = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.showsVerticalScrollIndicator = false let color = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1) appearance.barTintColor = .whiteColor() appearance.tintColor = color appearance.titleTextAttributes = [NSForegroundColorAttributeName : color] enabledViewControllerBasedAppearance = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) setNeedsStatusBarAppearanceUpdate() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .Default } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension DetailViewController: UITableViewDataSource { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(DetailViewCell.kCellIdentifier) as! UITableViewCell if let cell = cell as? DetailViewCell { cell.setIconImage(iconImage) cell.usernameLabel.text = username cell.textView.text = text } cell.layoutMargins = UIEdgeInsetsZero return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return CGRectGetHeight(tableView.frame) * 1.5 } }
249202feab5eb76227998df6d7c583f3
30.734177
114
0.67518
false
false
false
false
Hendrik44/pi-weather-app
refs/heads/master
Carthage/Checkouts/Charts/Source/Charts/Components/Description.swift
mit
1
// // Description.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if canImport(UIKit) import UIKit #endif #if canImport(Cocoa) import Cocoa #endif @objc(ChartDescription) open class Description: ComponentBase { public override init() { #if os(tvOS) // 23 is the smallest recommended font size on the TV font = .systemFont(ofSize: 23) #elseif os(OSX) font = .systemFont(ofSize: NSUIFont.systemFontSize) #else font = .systemFont(ofSize: 8.0) #endif super.init() } /// The text to be shown as the description. @objc open var text: String? /// Custom position for the description text in pixels on the screen. open var position: CGPoint? = nil /// The text alignment of the description text. Default RIGHT. @objc open var textAlign: NSTextAlignment = NSTextAlignment.right /// Font object used for drawing the description text. @objc open var font: NSUIFont /// Text color used for drawing the description text @objc open var textColor = NSUIColor.black }
5515bfadc8027b437f5428811397f065
23.222222
73
0.655963
false
false
false
false
JohnCoates/Aerial
refs/heads/master
Aerial/Source/Models/CustomVideoFolders+helpers.swift
mit
1
// // CustomVideoFolders+helpers.swift // Aerial // // Created by Guillaume Louel on 24/05/2019. // Copyright © 2019 John Coates. All rights reserved. // import Foundation // Helpers added on top of our generated json class extension CustomVideoFolders { func hasFolder(withUrl: String) -> Bool { for folder in folders where folder.url == withUrl { return true } return false } func getFolderIndex(withUrl: String) -> Int { var index = 0 for folder in folders { if folder.url == withUrl { return index } index += 1 } return -1 } func getFolder(withUrl: String) -> Folder? { for folder in folders where folder.url == withUrl { return folder } return nil } } extension Folder { func hasAsset(withUrl: String) -> Bool { for asset in assets where asset.url == withUrl { return true } return false } func getAssetIndex(withUrl: String) -> Int { var index = 0 for asset in assets { if asset.url == withUrl { return index } index += 1 } return -1 } }
b7e7fc9174ec2a359f3e1e7bff042823
20.559322
59
0.532233
false
false
false
false
lSlProject/master
refs/heads/master
lSl Project/lSl Project/RootViewController.swift
gpl-3.0
1
// // RootViewController.swift // lSl Project // // Created by crotel on 8/6/15. // Copyright (c) 2015 CROTEL©. All rights reserved. // import UIKit class RootViewController: UIViewController, UIPageViewControllerDelegate { var pageViewController: UIPageViewController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Configure the page view controller and add it as a child view controller. self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil) self.pageViewController!.delegate = self let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)! let viewControllers = [startingViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in }) self.pageViewController!.dataSource = self.modelController self.addChildViewController(self.pageViewController!) self.view.addSubview(self.pageViewController!.view) // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. var pageViewRect = self.view.bounds if UIDevice.currentDevice().userInterfaceIdiom == .Pad { pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0) } self.pageViewController!.view.frame = pageViewRect self.pageViewController!.didMoveToParentViewController(self) // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var modelController: ModelController { // Return the model controller object, creating it if necessary. // In more complex implementations, the model controller may be passed to the view controller. if _modelController == nil { _modelController = ModelController() } return _modelController! } var _modelController: ModelController? = nil // MARK: - UIPageViewController delegate methods func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation { if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) { // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here. let currentViewController = self.pageViewController!.viewControllers[0] as! UIViewController let viewControllers = [currentViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) self.pageViewController!.doubleSided = false return .Min } // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers. let currentViewController = self.pageViewController!.viewControllers[0] as! DataViewController var viewControllers: [AnyObject] let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController) if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) { let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfterViewController: currentViewController) viewControllers = [currentViewController, nextViewController!] } else { let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBeforeViewController: currentViewController) viewControllers = [previousViewController!, currentViewController] } self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) return .Mid } }
e03cd2d4154ff125fb3b5ccf42e5e4ab
51.483871
329
0.733047
false
false
false
false
bekin/issue-13-viper-swift
refs/heads/master
VIPER-SWIFT/Classes/Modules/Add/User Interface/Transition/AddDismissalTransition.swift
mit
5
// // AddDismissalTransition.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import UIKit class AddDismissalTransition : NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning!) -> NSTimeInterval { return 0.72 } func animateTransition(transitionContext: UIViewControllerContextTransitioning!) { let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as AddViewController let finalCenter = CGPointMake(160.0, (fromVC.view.bounds.size.height / 2) - 1000.0) let options = UIViewAnimationOptions.CurveEaseIn UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.64, initialSpringVelocity: 0.22, options: options, animations: { fromVC.view.center = finalCenter fromVC.transitioningBackgroundView.alpha = 0.0 }, completion: { finished in fromVC.view.removeFromSuperview() transitionContext.completeTransition(true) } ) } }
bb5f36cbe2f72000db6f90db57f302b2
32.55
122
0.659955
false
false
false
false
alblue/swift
refs/heads/master
validation-test/compiler_crashers_2_fixed/0119-rdar33613329.swift
apache-2.0
12
// RUN: %target-typecheck-verify-swift precedencegroup BindingPrecedence { higherThan: DefaultPrecedence } infix operator ~> infix operator ≈> : BindingPrecedence struct M<L : P, R> { let f: L let b: (inout L.B) -> R init(f: L, b: @escaping (inout L.B) -> R) { self.f = f self.b = b } } protocol P { associatedtype A associatedtype B func `in`<R>(_ a: inout A, apply body: (inout B) -> R) -> R static func ~> (_: A, _: Self) -> B } extension P { static func ≈> <R>(f: Self, b: @escaping (inout B) -> R) -> M<Self, R> {} // expected-note@-1 {{in call to operator '≈>'}} } extension WritableKeyPath : P { typealias A = Root typealias B = Value func `in`<R>(_ a: inout A, apply body: (inout B) -> R) -> R {} static func ~> (a: A, path: WritableKeyPath) -> B {} } struct X { var y: Int = 0 } var x = X() x ~> \X.y ≈> { a in a += 1; return 3 } // expected-error@-1 {{generic parameter 'R' could not be inferred}} // FIXME: Used to be better: "cannot convert call result type 'M<WritableKeyPath<X, Int>, _>' to expected type 'WritableKeyPath<_, _>'"
d31ca0e4c481a9b0648d42f5c6f3c244
22.297872
135
0.595434
false
false
false
false
SpeChen/SwiftDictModel
refs/heads/master
SwiftDictModel/02- 字典转模型/SwiftDictModel.swift
mit
2
// // SwiftDictModel.swift // 02- 字典转模型 // // Created by coderCSF on 15/3/13. // Copyright (c) 2015年 coderCSF. All rights reserved. // import Foundation /// 字典转模型自定义对象协议 @objc protocol DictModelProtocol { static func customClassMapping() -> [String: String] } class SwiftDictModel { /// 单例 static let sharedManager = SwiftDictModel() /// 讲字典转换成模型对象 /// :param: dict 数据字典 /// :param: cls 模型类 /// :returns: 类对象 func objectWithDictionary(dict: NSDictionary, cls: AnyClass) ->AnyObject?{ // 1. 取出模型字典 let dictInfo = fullModelInfo(cls) // 实例化对象 var obj: AnyObject = cls.alloc() // 2. 遍历模型字典, 有什么属性就设置什么属性 for (k, v) in dictInfo { // 取出字典中的内容 if let value: AnyObject? = dict[k] { // 判断是否是自定义类 if v.isEmpty && !(value === NSNull()){ obj.setValue(value, forKey: k) } else { let type = "\(value!.classForCoder)" println("\(type)") if type == "NSDictionary" { // 字典 /// 递归 if let subObj: AnyObject? = objectWithDictionary(value as! NSDictionary, cls: NSClassFromString(v)) { obj.setValue(subObj, forKey: k) } } else if type == "NSArray"{ // 数组 if let subObj: AnyObject? = objectWithArray(value as! NSArray, cls: NSClassFromString(v)) { obj.setValue(subObj, forKey: k) } } } } } return obj } /// 数组转换成模型字典 /// /// :param: array 数组的描述 /// :param: cls 模型类 /// /// :returns: 模型字典 func objectWithArray(array: NSArray, cls: AnyClass) -> [AnyObject]?{ var result = [AnyObject]() for value in array { println("遍历数组\(value)") let type = "\(value.classForCoder)" if type == "NSDictionary" { if let subObj: AnyObject? = objectWithDictionary(value as! NSDictionary, cls: cls) { result.append(subObj!) } else if type == "NSArray" { if let subObj:AnyObject? = objectWithArray(value as! NSArray, cls: cls) { result.append(subObj!) } } } } return result } /// 缓存字典 格式[类名: 模型字典, 类名2: 模型字典] var modelCache = [String: [String: String]]() /// 获取模型类的完整信息(包含父类信息) func fullModelInfo(cls:AnyClass) -> [String:String]{ // 判断类信息是否已经被缓存 if let cache = modelCache["\(cls)"] { return cache } // 循环查找父类 var currentCls: AnyClass = cls // 模型字典 var dictInfo = [String: String]() while let parent: AnyClass = currentCls.superclass() { // 取出并且合并字典, 最终获取自己的属性以及父类的属性 dictInfo.merge(modelInfo(currentCls)) // println("\(dictInfo)") currentCls = parent } // 将模型信息写入缓存 modelCache["\(cls)"] = dictInfo return dictInfo } // 获取给定类的信息 func modelInfo(cls:AnyClass) -> [String: String]{ var mapping:[String: String]? // 判断类信息是否已经被缓存 if let cache = modelCache["\(cls)"] { return cache } // 判断是否遵守协议, 遵守就执行方法 if cls.respondsToSelector("customClassMapping") { mapping = cls.customClassMapping() } var count: UInt32 = 0 let ivars = class_copyIvarList(cls, &count) // 定义一个类信息的字典 var dictInfo = [String: String]() // 获取每个属性的信息: 属性的名字, 类型 for i in 0..<count { let ivar = ivars[Int(i)] let cname = ivar_getName(ivar) let name = String.fromCString(cname)! println("\(name)") let type = mapping?[name] ?? "" dictInfo[name] = type } free(ivars) // 将模型信息写入缓存 modelCache["\(cls)"] = dictInfo return dictInfo } } extension Dictionary { /// 合并字典 /// mutating 表示函数操作的字典是可变类型的 /// 泛型(随便一个类型), 封装一些函数或者方法, 更加具有弹性 /// 任何两个 [key: value] 类型匹配字典, 都可以进行合并操作 mutating func merge<K, V>(dict:[K: V]) { for (k, v) in dict { // 字典的分类方法中, 如果要使用 updataValue 需要明确的指定类型 self.updateValue(v as! Value, forKey: k as! Key) } } }
f4ac59c0229a49c8cecde1139c781028
24.72043
125
0.469273
false
false
false
false
NicholasWon/algorithmStudy
refs/heads/master
Baekjun/2231.swift
mit
1
/* Brute Force * 문제: 어떤 자연수 N이 있을 때, 그 자연수 N의 분해합은 N과 N을 이루는 각 자리수의 합을 의미한다. * 어떤 자연수 M의 분해합이 N인 경우, M을 N의 생성자라 한다. * 예를 들어, 245의 분해합은 256(=245+2+4+5)이 된다. 따라서 245는 256의 생성자가 된다. * 물론, 어떤 자연수의 경우에는 생성자가 없을 수도 있다. 반대로, 생성자가 여러 개인 자연수도 있을 수 있다. * 자연수 N이 주어졌을 때, N의 가장 작은 생성자를 구해내는 프로그램을 작성하시오. * 첫째 줄에 답을 출력한다. 생성자가 없는 경우에는 0을 출력한다. * * 전략: (입력된 숫자 자릿수 - 1)*9 만큼이 검색하한이 되며, 그 이하의 숫자는 검색할 필요가 없다. * 예를들어, 1000000 -> 999999 -> 9*6 = 54이므로 (1000000-54) 이하의 숫자로는 1000000 을 못만든다는 뜻이 된다. * * 문제 링크: https://www.acmicpc.net/problem/2231 * 예제 입력: 216 * 예제 출력: 198 */ let input = readLine()! let N = Int(input)! // 1000000 let lowerN = N - (input.characters.map { String($0) }.count - 1)*9 // 999999 -> 9+9+9+9+9+9 -> 54가 검색하한이 된다. /* * 입력된 숫자의 분해합(Partial Summation) 계산 * 분해합 = 입력된 숫자(i) + 각 자리수 합 */ func getPS(from i: Int) -> Int { return "\(i)".characters.map { String($0) }.map { Int($0)! }.reduce(i) { $0 + $1 } } print(Array(lowerN...N).filter { getPS(from: $0) == N }.min() ?? 0) // 최소값이 없을 때는 0을 출력
494f7efd27600d52650cd0ed0202a4eb
35.607143
108
0.597073
false
false
false
false
mennovf/Swift-MathEagle
refs/heads/master
MathEagleTests/SequenceFunctionsTests.swift
mit
1
// // SequenceFunctionsTests.swift // MathEagle // // Created by Rugen Heidbuchel on 09/06/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Cocoa import XCTest import MathEagle class SequenceFunctionsTests: XCTestCase { // MARK: Sum func testSum() { var seq1 = [1, 2, 3, 4, 5, 6] XCTAssertEqual(21, sum(seq1)) let seq2: [UInt] = [1, 2, 3, 4, 5, 6] XCTAssertEqual(21 as UInt, sum(seq2)) seq1 = [] XCTAssertEqual(0, sum(seq1)) let seq3 = [1.0, -2.0, 3.0, -4.0, 5.0, -6.0] XCTAssertEqual(-3.0, sum(seq3)) } func testSumFloatVector() { let vector = Vector<Float>(randomWithLength: 10_000, intervals: -10.0...10.0) XCTAssertEqualWithAccuracy(vector.reduce(0, combine: +), sum(vector), accuracy: 1e-7) } func testSumFloatVectorPerformance() { let seq = Vector<Float>(randomWithLength: 10_000) compareBaseline(0.00408849716186523, title: "10_000 Sequence Sum (Float)", n: 10){ sum(seq) } } func testSumFloatVectorBenchmarking() { calculateBenchmarkingTimes(10, maxPower: 6, title: "Sequence Float Sum Benchmarking"){ let seq = Vector<Float>(randomWithLength: $0) return timeBlock(n: 10){ sum(seq) } } } func testSumDoubleVector() { let vector = Vector<Double>(randomWithLength: 10_000) XCTAssertEqual(vector.reduce(0, combine: +), sum(vector)) } func testSumDoubleVectorPerformance() { let seq = Vector<Double>(randomWithLength: 10_000) compareBaseline(0.00408849716186523, title: "10_000 Sequence Sum (Double)", n: 10){ sum(seq) } } func testSumDoubleVectorBenchmarking() { calculateBenchmarkingTimes(10, maxPower: 6, title: "Sequence Double Sum Benchmarking"){ let seq = Vector<Double>(randomWithLength: $0) return timeBlock(n: 10){ sum(seq) } } } // MARK: Product func testProduct() { var seq1 = [1, 2, 3, 4, 5, 6] XCTAssertEqual(720, product(seq1)) let seq2: [UInt] = [1, 2, 3, 4, 5, 6] XCTAssertEqual(720 as UInt, product(seq2)) seq1 = [] XCTAssertEqual(1, product(seq1)) let seq3 = [1.0, -2.0, 3.0, -4.0, 5.0, -6.0] XCTAssertEqual(-720.0, product(seq3)) } // MARK: Min func testMin() { let seq1 = [1, 4, 3, 2, 5, 6, 9, 8, 10] XCTAssertEqual(1, min(seq1)) let seq2: [UInt] = [4, 2, 1, 7, 6, 4, 2, 3, 8, 9, 0, 3, 2, 1] XCTAssertEqual(0, min(seq2)) let vector = Vector([4, 2, 1, 7, 6, 4, 2, 3, 8, 9, 0, 3, 2, 1]) XCTAssertEqual(0, min(vector)) } func testMinFloatVector() { let vector = Vector<Float>([1, 4, 3, 2, 5, 6, 9, 8, 10]) XCTAssertEqual(1, min(vector)) } func testMinFloatVectorPerformance() { let vector = Vector<Float>(randomWithLength: 10_000) compareBaseline(0.00356079936027527, title: "10_000 vector minimum (Float)", n: 10){ min(vector) } } func testMinFloatVectorBenchmarking() { calculateBenchmarkingTimes(10, maxPower: 6, title: "Sequence Float Min Benchmarking"){ let seq = Vector<Float>(randomWithLength: $0) return timeBlock(n: 10){ min(seq) } } } // MARK: Max func testMax() { let seq1 = [1, 4, 3, 2, 5, 6, 9, 8, 10] XCTAssertEqual(10, max(seq1)) let seq2: [UInt] = [4, 2, 1, 7, 6, 4, 2, 3, 8, 9, 0, 3, 2, 1] XCTAssertEqual(9, max(seq2)) let vector = Vector([4, 2, 1, 7, 6, 4, 2, 3, 8, 9, 0, 3, 2, 1]) XCTAssertEqual(9, max(vector)) } }
8ec7dfcfdaffafb2f419b17cd7196874
23.404494
95
0.486991
false
true
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/WalletPayload/Tests/WalletPayloadKitTests/Mocks/MockWalletEncoder.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation import WalletPayloadKit final class MockWalletEncoder: WalletEncodingAPI { var transformValue: AnyPublisher<EncodedWalletPayload, WalletEncodingError> = .failure( .genericFailure ) var transformWrapperCalled: Bool = false func transform(wrapper: Wrapper) -> AnyPublisher<EncodedWalletPayload, WalletEncodingError> { transformWrapperCalled = true return transformValue } var encodeValue: AnyPublisher<WalletCreationPayload, WalletEncodingError> = .failure( .genericFailure ) var encodePayloadCalled: Bool = false func encode( payload: EncodedWalletPayload, applyChecksum: @escaping (Data) -> String ) -> AnyPublisher<WalletCreationPayload, WalletEncodingError> { encodePayloadCalled = true return encodeValue } }
e70f4c29eb7ea7c87afbab32aa729cb4
28.741935
97
0.724512
false
false
false
false
JohnCoates/Aerial
refs/heads/master
Aerial/Source/Views/Sources/DescriptionCellView.swift
mit
1
// // DescriptionCellView.swift // Aerial // // Created by Guillaume Louel on 09/07/2020. // Copyright © 2020 Guillaume Louel. All rights reserved. // import Cocoa class DescriptionCellView: NSTableCellView { @IBOutlet weak var titleLabel: NSTextField! @IBOutlet weak var descriptionLabel: NSTextField! @IBOutlet weak var lastUpdatedLabel: NSTextField! @IBOutlet weak var videoCount: NSTextField! @IBOutlet weak var imageScene1: NSImageView! @IBOutlet weak var imageScene2: NSImageView! @IBOutlet weak var imageScene3: NSImageView! @IBOutlet weak var imageScene4: NSImageView! @IBOutlet weak var imageScene5: NSImageView! @IBOutlet weak var imageScene6: NSImageView! @IBOutlet weak var imageFilm: NSImageView! @IBOutlet weak var licenseButton: NSButton! @IBOutlet weak var moreButton: NSButton! @IBOutlet weak var refreshNowButton: NSButton! /// The item that represent the row in the outline view /// We may potentially use this cell for multiple outline views so let's make it generic var item: Any? /// The delegate of the cell // var delegate: CheckboxCellViewDelegate? override func awakeFromNib() { imageScene1.image = Aerial.helper.getMiniSymbol("flame") imageScene2.image = Aerial.helper.getMiniSymbol("tram.fill") imageScene3.image = Aerial.helper.getMiniSymbol("sparkles") imageScene4.image = Aerial.helper.getMiniSymbol("helm") imageScene5.image = Aerial.helper.getMiniSymbol("helm") imageScene6.image = Aerial.helper.getMiniSymbol("helm") imageFilm.image = Aerial.helper.getMiniSymbol("film") // imageScene1. // checkboxButton.target = self // checkboxButton.action = #selector(self.didChangeState(_:)) } /// Notify the delegate that the checkbox's state has changed @objc private func didChangeState(_ sender: NSObject) { // delegate?.checkboxCellView(self, didChangeState: checkboxButton.state) } @IBAction func licenseButtonClick(_ sender: NSButton) { if let source = item as? Source { let workspace = NSWorkspace.shared let url = URL(string: source.license)! workspace.open(url) } } @IBAction func moreButtonClick(_ sender: NSButton) { if let source = item as? Source { let workspace = NSWorkspace.shared let url = URL(string: source.more)! workspace.open(url) } } @IBAction func refreshNowButtonClick(_ sender: NSButton) { if let source = item as? Source { if source.isCachable { debugLog("Refreshing cacheable source") VideoList.instance.downloadSource(source: source) } else if source.type == .local { debugLog("Checking local directory") SourceList.updateLocalSource(source: source) } else { debugLog("Refreshing non-cacheable source") VideoList.instance.downloadSource(source: source) } } } }
8565ab5d49f543214517d0194289064b
35.916667
92
0.659142
false
false
false
false
Ramotion/showroom
refs/heads/master
Showroom/ViewControllers/AboutView/AboutView.swift
gpl-3.0
1
import UIKit import RxSwift import RxCocoa import EasyPeasy import NSObject_Rx private enum SocialNetwork: Int { case dribbble = 0 case facebook case twitter case github case instagram } class AboutView: UIView { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var infoText: UILabel! @IBOutlet weak var sharedView: UIView! @IBOutlet weak var sharedViewBottomConstraints: NSLayoutConstraint! @IBOutlet weak var sharedViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var learnMoreLabel: UIButton! @IBOutlet weak var learnMoreSpace: NSLayoutConstraint! @IBOutlet weak var learnMoreHeight: NSLayoutConstraint! @IBOutlet weak var infoTextHeightconstraint: NSLayoutConstraint! @IBOutlet weak var infoTextTopConstraint: NSLayoutConstraint! @IBOutlet weak var titleLabelHeight: NSLayoutConstraint! @IBOutlet weak var titleLabelTopConstraint: NSLayoutConstraint! @IBOutlet weak var titleLabel: UILabel! fileprivate var circleView: CircleView? @IBOutlet weak var topView: AboutTopView! @IBOutlet weak var topViewHeight: NSLayoutConstraint! var titleView: CarouselTitleView! let transperentView: UIView = .build(color: UIColor(red:0.16, green:0.23, blue:0.33, alpha:1.00), alpha: 0) } // MARK: Life Cycle extension AboutView { override func awakeFromNib() { super.awakeFromNib() configureInfoText() subscribeSeparatorAnimation() } } // MARK: Actions extension AboutView { @IBAction func socialNetworkHandler(_ sender: UIButton) { guard let item = SocialNetwork(rawValue: sender.tag) else { return } let urlString: String switch item { case .dribbble: urlString = "https://dribbble.com/ramotion/?utm_source=showroom&utm_medium=special&utm_campaign=socialbuton" case .facebook: urlString = "https://facebook.com/Ramotion" case .twitter: urlString = "https://twitter.com/ramotion" case .github: urlString = "https://github.com/ramotion" case .instagram: guard let url = URL(string: "instagram://user?username=ramotion") else { return } if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) return } urlString = "https://instagram.com/ramotion" } if let url = URL(string: urlString) { UIApplication.shared.open(url) } } @IBAction func LearnMoreHandler(_ sender: UIButton) { AppAnalytics.event(.google(name: "Buttons", parametr: "about")) let urlString = "https://dev.ramotion.com/" if let url = URL(string: urlString) { UIApplication.shared.open(url) } } } // MARK: Methods extension AboutView { func show(on view: UIView, completion: @escaping () -> Void) { if circleView == nil { circleView = .build(on: self, position: titleView.infoButton.center) } scrollView.alpha = 1 scrollView.contentOffset.y = 0 view.addSubview(self) self.easy.layout(Edges()) view.layoutIfNeeded() view.bringSubviewToFront(titleView) circleView?.show() topViewHeight.constant = titleView.bounds.size.height titleLabelTopConstraint.constant = titleView.bounds.size.height + 20 superview?.insertSubview(transperentView, belowSubview: self) transperentView.easy.layout(Edges()) transperentView.alpha = 0 transperentView.animate(duration: 0.4, [.alphaFrom(0, to: 0.4, removed: false)]) // move animations sharedView.pop_removeAllAnimations() sharedView.alpha = 0 sharedView.animate(duration: 0.001, delay: 0.4, [.alpha(to: 1)]) sharedView.animate(duration: 0.8, delay: 0.4, [ .layerPositionY(from: Showroom.screen.height + sharedViewHeightConstraint.constant / 2, to: Showroom.screen.height - sharedViewHeightConstraint.constant / 2) ], completion: completion) titleLabel.pop_removeAllAnimations() titleLabel.alpha = 0 titleLabel.animate(duration: 0.4, delay: 0.2, [.alphaFrom(0, to: 1, removed: false)]) let titleLabelAnimationFrom = titleLabelTopConstraint.constant + titleLabelHeight.constant / 2 + sharedViewHeightConstraint.constant / 2 let titleLabelAnimationTo = titleLabelTopConstraint.constant + titleLabelHeight.constant / 2 titleLabel.animate(duration: 0.6, delay: 0.2, [.layerPositionY(from: titleLabelAnimationFrom, to: titleLabelAnimationTo)]) infoText.pop_removeAllAnimations() infoText.alpha = 0 infoText.animate(duration: 0.5, delay: 0.3, [.alphaFrom(0, to: 1, removed: false)]) let titleLabelSummaryHeight = titleLabelTopConstraint.constant + titleLabelHeight.constant let infoTextSummaryHeight = infoText.bounds.size.height / 2 + infoTextTopConstraint.constant let infoTextAnimationFrom = titleLabelSummaryHeight + infoTextSummaryHeight + sharedViewHeightConstraint.constant / 2 infoText.animate(duration: 0.7, delay: 0.3, [.layerPositionY(from: infoTextAnimationFrom, to: infoTextAnimationFrom - sharedViewHeightConstraint.constant / 2)]) learnMoreLabel.pop_removeAllAnimations() learnMoreLabel.alpha = 0 learnMoreLabel.animate(duration: 0.5, delay: 0.3, [.alphaFrom(0, to: 1, removed: false)]) let infofrom = titleLabelTopConstraint.constant + titleLabelHeight.constant + infoText.bounds.size.height + infoTextTopConstraint.constant let lfrom = infofrom + learnMoreSpace.constant + learnMoreHeight.constant / 2 + sharedViewHeightConstraint.constant / 2 learnMoreLabel.animate(duration: 0.7, delay: 0.3, [.layerPositionY(from: lfrom, to: lfrom - sharedViewHeightConstraint.constant / 2)]) } func hide(on view: UIView, completion: @escaping () -> Void) { scrollView.animate(duration: 0.3, [.alpha(to: 0)], timing: .easyInEasyOut) transperentView.animate(duration: 0.4, [.alphaFrom(0.4, to: 0, removed: false)]) topView.animateSeparator(isShow: false) circleView?.hide() { [weak self] in self?.transperentView.removeFromSuperview() self?.removeFromSuperview() completion() } } } // MARK: RX private extension AboutView { func subscribeSeparatorAnimation() { _ = scrollView.rx.contentOffset .map { $0.y > 5 } .distinctUntilChanged() .subscribe { [weak self] in guard let topView = self?.topView else { return } if let isShow = $0.element { topView.animateSeparator(isShow: isShow) } } .disposed(by: rx.disposeBag) } } // MARK: Helpers private extension AboutView { func configureInfoText() { guard let text = infoText.text else { return } guard let font = UIFont(name: "Graphik-Regular", size: 16) else { return } let style = NSMutableParagraphStyle() style.lineSpacing = 7 let attributedText = text.withAttributes([ .paragraphStyle(style), .font(font)] ) infoText.attributedText = attributedText } }
5ecd8db17368eb3ccd20dcc148d5aeba
35.946809
164
0.701411
false
false
false
false
thesecretlab/ultimate-swift-video
refs/heads/master
UIDocuments/UIDocuments/FancyDocument.swift
mit
1
// // FancyDocument.swift // UIDocuments // // Created by Jon Manning on 21/11/2014. // Copyright (c) 2014 Secret Lab. All rights reserved. // import UIKit class FancyDocument: UIDocument { var number : Int = 0 override func loadFromContents(contents: AnyObject, ofType typeName: String, error outError: NSErrorPointer) -> Bool { let dataToLoad = contents as NSData let loadedString = NSString(data: dataToLoad, encoding: NSUTF8StringEncoding) number = loadedString?.integerValue ?? 0 return true } override func contentsForType(typeName: String, error outError: NSErrorPointer) -> AnyObject? { let numberAsString = "\(number)" let data = numberAsString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) return data } }
511e596479a8ba7c1ce695a233ae6cc8
24.305556
122
0.628979
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/preview-transition-master/PreviewTransitionDemo/ScreenShort/ScreenShot.swift
mit
1
// // ScreenShot.swift // PreviewTransitionDemo // // Created by Alex K. on 03/05/16. // Copyright © 2016 Alex K. All rights reserved. // import UIKit extension UIView { func makeScreenShotFromFrame(frame: CGRect) -> UIImage? { UIGraphicsBeginImageContextWithOptions(frame.size, false, 0.0) let context = UIGraphicsGetCurrentContext() context!.translateBy(x: frame.origin.x * -1, y: frame.origin.y * -1) guard let currentContext = UIGraphicsGetCurrentContext() else { return nil } layer.render(in: currentContext) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } extension UIImageView { func blurViewValue(value: CGFloat) { guard let image = self.image, let blurfilter = CIFilter(name: "CIGaussianBlur"), let imageToBlur = CIImage(image: image) else { return } blurfilter.setValue(value, forKey: kCIInputRadiusKey) blurfilter.setValue(imageToBlur, forKey: "inputImage") let resultImage = blurfilter.value(forKey: "outputImage") as! CIImage var blurredImage = UIImage(ciImage: resultImage) let cropped: CIImage = resultImage.cropped(to: CGRect(x: 0, y: 0, width: imageToBlur.extent.size.width, height: imageToBlur.extent.size.height)) blurredImage = UIImage(ciImage: cropped) self.image = blurredImage } }
8a3ed15912856109c4b53d47269dde5d
29.346939
152
0.657028
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Pods/AutoInch/Sources/Inch.swift
mit
1
// // Inch.swift // ┌─┐ ┌───────┐ ┌───────┐ // │ │ │ ┌─────┘ │ ┌─────┘ // │ │ │ └─────┐ │ └─────┐ // │ │ │ ┌─────┘ │ ┌─────┘ // │ └─────┐│ └─────┐ │ └─────┐ // └───────┘└───────┘ └───────┘ // // Created by lee on 2018/1/22. // Copyright © 2018年 lee. All rights reserved. // import Foundation #if os(iOS) import UIKit public enum Inch { typealias Number = CGFloat } extension Inch { public enum Phone: Int, CaseIterable { case unknown = -1 case i35 case i40 case i47 case i55 case i58Full case i61Full case i65Full var width: Number { switch self { case .unknown: return 0 case .i35: return 320 case .i40: return 320 case .i47: return 375 case .i55: return 414 case .i58Full: return 375 case .i61Full: return 414 case .i65Full: return 414 } } var height: Number { switch self { case .unknown: return 0 case .i35: return 480 case .i40: return 568 case .i47: return 667 case .i55: return 736 case .i58Full: return 812 case .i61Full: return 896 case .i65Full: return 896 } } var scale: CGFloat { switch self { case .unknown: return 0 case .i35: return 2 case .i40: return 2 case .i47: return 2 case .i55: return 3 case .i58Full: return 3 case .i61Full: return 2 case .i65Full: return 3 } } private var size: CGSize { return CGSize(width: width, height: height) } private var native: CGSize { return CGSize(width: width * scale, height: height * scale) } public static func type(size: CGSize = UIScreen.main.bounds.size, scale: CGFloat = UIScreen.main.scale) -> Phone { let width = min(size.width, size.height) * scale let height = max(size.width, size.height) * scale let size = CGSize(width: width, height: height) switch size { case Phone.i35.native: return .i35 case Phone.i40.native: return .i40 case Phone.i47.native: return .i47 case Phone.i55.native: return .i55 case Phone.i58Full.native: return .i58Full case Phone.i61Full.native: return .i61Full case Phone.i65Full.native: return .i65Full default: return .unknown } } public static let current: Phone = type() } } extension Inch.Phone: Equatable { public static func == (lhs: Inch.Phone, rhs: Inch.Phone) -> Bool { return lhs.rawValue == rhs.rawValue } } extension Inch.Phone: Comparable { public static func < (lhs: Inch.Phone, rhs: Inch.Phone) -> Bool { return lhs.rawValue < rhs.rawValue } } extension Int: Inchable {} extension Bool: Inchable {} extension Float: Inchable {} extension Double: Inchable {} extension String: Inchable {} extension CGRect: Inchable {} extension CGSize: Inchable {} extension CGFloat: Inchable {} extension CGPoint: Inchable {} extension UIImage: Inchable {} extension UIColor: Inchable {} extension UIFont: Inchable {} extension UIEdgeInsets: Inchable {} public protocol Inchable { func i35(_ value: Self) -> Self func i40(_ value: Self) -> Self func i47(_ value: Self) -> Self func i55(_ value: Self) -> Self func i58full(_ value: Self) -> Self func i61full(_ value: Self) -> Self func i65full(_ value: Self) -> Self func w320(_ value: Self) -> Self func w375(_ value: Self) -> Self func w414(_ value: Self) -> Self } extension Inchable { public func i35(_ value: Self) -> Self { return matching(type: .i35, value) } public func i40(_ value: Self) -> Self { return matching(type: .i40, value) } public func i47(_ value: Self) -> Self { return matching(type: .i47, value) } public func i55(_ value: Self) -> Self { return matching(type: .i55, value) } public func i58full(_ value: Self) -> Self { return matching(type: .i58Full, value) } public func i61full(_ value: Self) -> Self { return matching(type: .i61Full, value) } public func i65full(_ value: Self) -> Self { return matching(type: .i65Full, value) } public func ifull(_ value: Self) -> Self { return matching([.i58Full, .i61Full, .i65Full], value) } public func w320(_ value: Self) -> Self { return matching(width: 320, value) } public func w375(_ value: Self) -> Self { return matching(width: 375, value) } public func w414(_ value: Self) -> Self { return matching(width: 414, value) } private func matching(type: Inch.Phone, _ value: Self) -> Self { return Inch.Phone.current == type ? value : self } private func matching(width: Inch.Number, _ value: Self) -> Self { return Inch.Phone.current.width == width ? value : self } private func matching(_ types: [Inch.Phone], _ value: Self) -> Self { return types.contains(.current) ? value : self } private func matching(_ range: Range<Inch.Phone>, _ value: Self) -> Self { return range ~= .current ? value : self } private func matching(_ range: ClosedRange<Inch.Phone>, _ value: Self) -> Self { return range ~= .current ? value : self } } #endif
b83d36ef26a915d4410abf946349b637
28.729592
98
0.534066
false
false
false
false
JGiola/swift
refs/heads/main
test/IRGen/opaque_result_type.swift
apache-2.0
9
// RUN: %empty-directory(%t) // RUN: %{python} %utils/chex.py < %s > %t/opaque_result_type.swift // RUN: %target-swift-frontend -enable-experimental-named-opaque-types -enable-implicit-dynamic -disable-availability-checking -emit-ir %t/opaque_result_type.swift | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-NODEBUG %t/opaque_result_type.swift // rdar://76863553 // UNSUPPORTED: OS=watchos && CPU=x86_64 public protocol O { func bar() } public protocol O2 { func baz() } protocol P { associatedtype A: O func poo() -> A } protocol Q: AnyObject { associatedtype B: O, O2 func qoo() -> B } extension Int: O, O2 { public func bar() {} public func baz() {} } @_marker protocol Marker { } extension Int: Marker { } extension String: P { // CHECK-LABEL: @"$sSS18opaque_result_typeE3pooQryFQOMQ" = {{.*}}constant <{ {{.*}} }> <{ // -- header: opaque type context (0x4), generic (0x80), unique (0x40), two entries (0x2_0000) // CHECK-SAME: <i32 0x2_00c4>, // -- parent context: module, or anon context for function // CHECK-SAME: @"$s18opaque_result_typeMXM" // -- mangled underlying type // CHECK-SAME: @"symbolic Si" // -- conformance to O // CHECK-SAME: @"get_witness_table Si18opaque_result_type1OHpyHC // CHECK-SAME: }> func poo() -> some O { return 0 } // CHECK-LABEL: @"$sSS18opaque_result_typeE4propQrvpQOMQ" = {{.*}}constant public var prop: some O { return 0 } // CHECK-LABEL: @"$sSS18opaque_result_typeEQrycipQOMQ" = {{.*}}constant public subscript() -> some O { return 0 } } // CHECK-LABEL: @"$s18opaque_result_type10globalPropQrvpQOMQ" = {{.*}}constant public var globalProp: some O { return 0 } public class C: P, Q, Marker { // CHECK-LABEL: @"$s18opaque_result_type1CC3pooQryFQOMQ" = {{.*}} constant <{ {{.*}} }> <{ // -- header: opaque type context (0x4), generic (0x80), unique (0x40), two entries (0x2_0000) // CHECK-SAME: <i32 0x2_00c4> // -- parent context: module, or anon context for function // CHECK-SAME: @"$s18opaque_result_typeMXM" // -- mangled underlying type // CHECK-SAME: @"symbolic Si" // -- conformance to O // CHECK-SAME: @"get_witness_table Si18opaque_result_type1OHpyHC // CHECK-SAME: }> func poo() -> some O { return 0 } // CHECK-LABEL: @"$s18opaque_result_type1CC3qooQryFQOMQ" = {{.*}} constant <{ {{.*}} }> <{ // -- header: opaque type context (0x4), generic (0x80), unique (0x40), three entries (0x3_0000) // CHECK-SAME: <i32 0x3_00c4> // -- parent context: module, or anon context for function // CHECK-SAME: @"$s18opaque_result_typeMXM" // -- mangled underlying type // CHECK-SAME: @"symbolic Si" // -- conformance to O // CHECK-SAME: @"get_witness_table Si18opaque_result_type1OHpyHC // -- conformance to O2 // CHECK-SAME: @"get_witness_table Si18opaque_result_type2O2HpyHC // CHECK-SAME: }> func qoo() -> some O & O2 { return 0 } } // CHECK-LABEL: @"$s18opaque_result_type3foo1xQrSS_tFQOMQ" = {{.*}} constant <{ {{.*}} }> <{ // -- header: opaque type context (0x4), generic (0x80), unique (0x40), two entries (0x2_0000) // CHECK-SAME: <i32 0x2_00c4> // -- parent context: module, or anon context for function // CHECK-SAME: @"$s18opaque_result_typeMXM" // -- mangled underlying type // CHECK-SAME: @"symbolic SS" // -- conformance to P // CHECK-SAME: @"get_witness_table SS18opaque_result_type1PHpyHC // CHECK-SAME: }> func foo(x: String) -> some P { return x } // CHECK-LABEL: @"$s18opaque_result_type3bar1yQrAA1CC_tFQOMQ" = {{.*}} constant <{ {{.*}} }> <{ // -- header: opaque type context (0x4), generic (0x80), unique (0x40), two entries (0x2_0000) // CHECK-SAME: <i32 0x2_00c4> // -- parent context: module, or anon context for function // CHECK-SAME: @"$s18opaque_result_typeMXM" // -- mangled underlying type // CHECK-SAME: @"symbolic _____ 18opaque_result_type1CC" // -- conformance to Q // CHECK-SAME: @"get_witness_table 18opaque_result_type1CCAA1QHPyHC // CHECK-SAME: }> func bar(y: C) -> some Q { return y } // CHECK-LABEL: @"$s18opaque_result_type3baz1zQrx_tAA1PRzAA1QRzlFQOMQ" = {{.*}} constant <{ {{.*}} }> <{ // -- header: opaque type context (0x4), generic (0x80), unique (0x40), three entries (0x3_0000) // CHECK-SAME: <i32 0x3_00c4> // -- parent context: anon context for function // CHECK-SAME: @"$s18opaque_result_type3baz1zQrx_tAA1PRzAA1QRzlFMXX" // -- mangled underlying type // CHECK-SAME: @"symbolic x" // -- conformance to P // CHECK-SAME: @"get_witness_table 18opaque_result_type1PRzAA1QRzlxAaB // -- conformance to Q // CHECK-SAME: @"get_witness_table 18opaque_result_type1PRzAA1QRzlxAaC // CHECK-SAME: }> func baz<T: P & Q>(z: T) -> some P & Q { return z } // CHECK-LABEL: @"$s18opaque_result_type4fizz1zQrx_tAA6MarkerRzAA1PRzAA1QRzlFQOMQ" = {{.*}} constant <{ {{.*}} }> <{ // -- header: opaque type context (0x4), generic (0x80), unique (0x40), three entries (0x3_0000) // CHECK-SAME: <i32 0x3_00c4> // -- parent context: anon context for function // CHECK-SAME: @"$s18opaque_result_type4fizz1zQrx_tAA6MarkerRzAA1PRzAA1QRzlFMXX" // -- mangled underlying type // CHECK-SAME: @"symbolic x" // -- conformance to P // CHECK-SAME: @"get_witness_table 18opaque_result_type6MarkerRzAA1PRzAA1QRzlxAaCHD2_ // -- conformance to Q // CHECK-SAME: @"get_witness_table 18opaque_result_type6MarkerRzAA1PRzAA1QRzlxAaDHD3_ // CHECK-SAME: }> func fizz<T: P & Q & Marker>(z: T) -> some P & Q & Marker { return z } func bauble<T: P & Q & Marker, U: Q>(z: T, u: U) -> [(some P & Q & Marker, (some Q)?)] { return [(z, u)] } // Ensure the local type's opaque descriptor gets emitted. // CHECK-LABEL: @"$s18opaque_result_type11localOpaqueQryF0D0L_QryFQOMQ" = func localOpaque() -> some P { func local() -> some P { return "local" } return local() } public func useFoo(x: String, y: C) { let p = foo(x: x) let pa = p.poo() pa.bar() let q = bar(y: y) let qb = q.qoo() qb.bar() qb.baz() let pq = baz(z: y) let pqa = pq.poo() pqa.bar() let pqb = pq.qoo() pqb.bar() pqb.baz() let _ = bauble(z: y, u: y) } // CHECK-LABEL: define {{.*}} @"$s18opaque_result_type6bauble1z1uSayQr_QR_SgtGx_q_tAA6MarkerRzAA1PRzAA1QRzAaIR_r0_lF" // CHECK-LABEL: define {{.*}} @"$s18opaque_result_type6useFoo1x1yySS_AA1CCtF" // CHECK: [[OPAQUE:%.*]] = call {{.*}} @"$s18opaque_result_type3baz1zQrx_tAA1PRzAA1QRzlFQOMg" // CHECK: [[CONFORMANCE:%.*]] = call swiftcc i8** @swift_getOpaqueTypeConformance(i8* {{.*}}, %swift.type_descriptor* [[OPAQUE]], [[WORD:i32|i64]] 1) // CHECK: [[TYPE:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s18opaque_result_type3baz1zQrx_tAA1PRzAA1QRzlFQOyAA1CCQo_MD") // CHECK: call swiftcc i8** @swift_getAssociatedConformanceWitness(i8** [[CONFORMANCE]], %swift.type* [[TYPE]] // Make sure we can mangle named opaque result types struct Boom<T: P> { var prop1: Int = 5 var prop2: <U, V> (U, V) = ("hello", 5) } // CHECK-LABEL: define {{.*}} @"$s18opaque_result_type9gimmeBoomypyF // CHECK: call swiftcc void @"$s18opaque_result_type4BoomV5prop15prop2ACyxGSi_AcEQr_QR_tvpQOyx_Qo__AcEQr_QR_tvpQOyx_Qo0_ttcfcfA0_" public func gimmeBoom() -> Any { Boom<String>(prop1: 5) } // CHECK-LABEL: define {{.*}} @"$sSS18opaque_result_type1PAA1AAaBP_AA1OPWT" // CHECK: [[OPAQUE:%.*]] = call {{.*}} @"$sSS18opaque_result_typeE3pooQryFQOMg" // CHECK: call swiftcc i8** @swift_getOpaqueTypeConformance(i8* {{.*}}, %swift.type_descriptor* [[OPAQUE]], [[WORD]] 1) // rdar://problem/49585457 protocol R { associatedtype A: R func getA() -> A } struct Wrapper<T: R>: R { var wrapped: T func getA() -> some R { return wrapped.getA() } } struct X<T: R, U: R>: R { var t: T var u: U func getA() -> some R { return Wrapper(wrapped: u) } } var globalOProp: some O = 0 public struct OpaqueProps { static var staticOProp: some O = 0 var instanceOProp: some O = 0 } // Make sure we don't recurse indefinitely on recursive enums. public enum RecursiveEnum { case a(Int) case b(String) indirect case c(RecursiveEnum) } public enum EnumWithTupleWithOpaqueField { case a(Int) case b((OpaqueProps, String)) } // rdar://86800325 - Make sure we don't crash on result builders. @resultBuilder struct Builder { static func buildBlock(_: Any...) -> Int { 5 } } protocol P2 { associatedtype A: P2 @Builder var builder: A { get } } extension Int: P2 { var builder: some P2 { 5 } } struct UseBuilder: P2 { var builder: some P2 { let extractedExpr: some P2 = 5 } }
153d6b1b83ad5ba33ef1bc8a7999a532
30.577617
254
0.635075
false
false
false
false
zisko/swift
refs/heads/master
stdlib/public/core/ClosedRange.swift
apache-2.0
1
//===--- ClosedRange.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME: swift-3-indexing-model: Generalize all tests to check both // [Closed]Range. /// An interval from a lower bound up to, and including, an upper bound. /// /// You create a `ClosedRange` instance by using the closed range /// operator (`...`). /// /// let throughFive = 0...5 /// /// A `ClosedRange` instance contains both its lower bound and its /// upper bound. /// /// throughFive.contains(3) /// // true /// throughFive.contains(10) /// // false /// throughFive.contains(5) /// // true /// /// Because a closed range includes its upper bound, a closed range whose lower /// bound is equal to the upper bound contains that value. Therefore, a /// `ClosedRange` instance cannot represent an empty range. /// /// let zeroInclusive = 0...0 /// zeroInclusive.contains(0) /// // true /// zeroInclusive.isEmpty /// // false /// /// Using a Closed Range as a Collection of Consecutive Values /// ---------------------------------------------------------- /// /// When a closed range uses integers as its lower and upper bounds, or any /// other type that conforms to the `Strideable` protocol with an integer /// stride, you can use that range in a `for`-`in` loop or with any sequence or /// collection method. The elements of the range are the consecutive values /// from its lower bound up to, and including, its upper bound. /// /// for n in 3...5 { /// print(n) /// } /// // Prints "3" /// // Prints "4" /// // Prints "5" /// /// Because floating-point types such as `Float` and `Double` are their own /// `Stride` types, they cannot be used as the bounds of a countable range. If /// you need to iterate over consecutive floating-point values, see the /// `stride(from:through:by:)` function. @_fixed_layout public struct ClosedRange<Bound: Comparable> { /// The range's lower bound. public let lowerBound: Bound /// The range's upper bound. public let upperBound: Bound /// Creates an instance with the given bounds. /// /// Because this initializer does not perform any checks, it should be used /// as an optimization only when you are absolutely certain that `lower` is /// less than or equal to `upper`. Using the closed range operator (`...`) /// to form `ClosedRange` instances is preferred. /// /// - Parameter bounds: A tuple of the lower and upper bounds of the range. @_inlineable public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) { self.lowerBound = bounds.lower self.upperBound = bounds.upper } } // define isEmpty, which is available even on an uncountable ClosedRange extension ClosedRange { /// A Boolean value indicating whether the range contains no elements. /// /// Because a closed range cannot represent an empty range, this property is /// always `false`. @_inlineable public var isEmpty: Bool { return false } } extension ClosedRange: RangeExpression { @_inlineable // FIXME(sil-serialize-all) public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return Range( uncheckedBounds: ( lower: lowerBound, upper: collection.index(after: self.upperBound))) } /// Returns a Boolean value indicating whether the given element is contained /// within the range. /// /// A `ClosedRange` instance contains both its lower and upper bound. /// `element` is contained in the range if it is between the two bounds or /// equal to either bound. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range; otherwise, /// `false`. @_inlineable public func contains(_ element: Bound) -> Bool { return element >= self.lowerBound && element <= self.upperBound } } extension ClosedRange: Sequence where Bound: Strideable, Bound.Stride: SignedInteger { public typealias Element = Bound public typealias Iterator = IndexingIterator<ClosedRange<Bound>> } extension ClosedRange where Bound : Strideable, Bound.Stride : SignedInteger { public enum Index { case pastEnd case inRange(Bound) } } extension ClosedRange.Index : Comparable { @_inlineable public static func == ( lhs: ClosedRange<Bound>.Index, rhs: ClosedRange<Bound>.Index ) -> Bool { switch (lhs, rhs) { case (.inRange(let l), .inRange(let r)): return l == r case (.pastEnd, .pastEnd): return true default: return false } } @_inlineable public static func < ( lhs: ClosedRange<Bound>.Index, rhs: ClosedRange<Bound>.Index ) -> Bool { switch (lhs, rhs) { case (.inRange(let l), .inRange(let r)): return l < r case (.inRange(_), .pastEnd): return true default: return false } } } extension ClosedRange.Index: Hashable where Bound: Strideable, Bound.Stride: SignedInteger, Bound: Hashable { public var hashValue: Int { switch self { case .inRange(let value): return value.hashValue case .pastEnd: return .max } } } // FIXME: this should only be conformance to RandomAccessCollection but // the compiler balks without all 3 extension ClosedRange: Collection, BidirectionalCollection, RandomAccessCollection where Bound : Strideable, Bound.Stride : SignedInteger { // while a ClosedRange can't be empty, a _slice_ of a ClosedRange can, // so ClosedRange can't be its own self-slice unlike Range public typealias SubSequence = Slice<ClosedRange<Bound>> /// The position of the first element in the range. @_inlineable public var startIndex: Index { return .inRange(lowerBound) } /// The range's "past the end" position---that is, the position one greater /// than the last valid subscript argument. @_inlineable public var endIndex: Index { return .pastEnd } @_inlineable public func index(after i: Index) -> Index { switch i { case .inRange(let x): return x == upperBound ? .pastEnd : .inRange(x.advanced(by: 1)) case .pastEnd: _preconditionFailure("Incrementing past end index") } } @_inlineable public func index(before i: Index) -> Index { switch i { case .inRange(let x): _precondition(x > lowerBound, "Incrementing past start index") return .inRange(x.advanced(by: -1)) case .pastEnd: _precondition(upperBound >= lowerBound, "Incrementing past start index") return .inRange(upperBound) } } @_inlineable public func index(_ i: Index, offsetBy n: Int) -> Index { switch i { case .inRange(let x): let d = x.distance(to: upperBound) if n <= d { let newPosition = x.advanced(by: numericCast(n)) _precondition(newPosition >= lowerBound, "Advancing past start index") return .inRange(newPosition) } if d - -1 == n { return .pastEnd } _preconditionFailure("Advancing past end index") case .pastEnd: if n == 0 { return i } if n < 0 { return index(.inRange(upperBound), offsetBy: numericCast(n + 1)) } _preconditionFailure("Advancing past end index") } } @_inlineable public func distance(from start: Index, to end: Index) -> Int { switch (start, end) { case let (.inRange(left), .inRange(right)): // in range <--> in range return numericCast(left.distance(to: right)) case let (.inRange(left), .pastEnd): // in range --> end return numericCast(1 + left.distance(to: upperBound)) case let (.pastEnd, .inRange(right)): // in range <-- end return numericCast(upperBound.distance(to: right) - 1) case (.pastEnd, .pastEnd): // end <--> end return 0 } } /// Accesses the element at specified position. /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the range, and must not equal the range's end /// index. @_inlineable public subscript(position: Index) -> Bound { // FIXME: swift-3-indexing-model: range checks and tests. switch position { case .inRange(let x): return x case .pastEnd: _preconditionFailure("Index out of range") } } @_inlineable public subscript(bounds: Range<Index>) -> Slice<ClosedRange<Bound>> { return Slice(base: self, bounds: bounds) } @_inlineable public func _customContainsEquatableElement(_ element: Bound) -> Bool? { return lowerBound <= element && element <= upperBound } @_inlineable public func _customIndexOfEquatableElement(_ element: Bound) -> Index?? { return lowerBound <= element && element <= upperBound ? .inRange(element) : nil } } extension Comparable { /// Returns a closed range that contains both of its bounds. /// /// Use the closed range operator (`...`) to create a closed range of any type /// that conforms to the `Comparable` protocol. This example creates a /// `ClosedRange<Character>` from "a" up to, and including, "z". /// /// let lowercase = "a"..."z" /// print(lowercase.contains("z")) /// // Prints "true" /// /// - Parameters: /// - minimum: The lower bound for the range. /// - maximum: The upper bound for the range. @_inlineable // FIXME(sil-serialize-all) @_transparent public static func ... (minimum: Self, maximum: Self) -> ClosedRange<Self> { _precondition( minimum <= maximum, "Can't form Range with upperBound < lowerBound") return ClosedRange(uncheckedBounds: (lower: minimum, upper: maximum)) } } extension Strideable where Stride: SignedInteger { /// Returns a countable closed range that contains both of its bounds. /// /// Use the closed range operator (`...`) to create a closed range of any type /// that conforms to the `Strideable` protocol with an associated signed /// integer `Stride` type, such as any of the standard library's integer /// types. This example creates a `ClosedRange<Int>` from zero up to, /// and including, nine. /// /// let singleDigits = 0...9 /// print(singleDigits.contains(9)) /// // Prints "true" /// /// You can use sequence or collection methods on the `singleDigits` range. /// /// print(singleDigits.count) /// // Prints "10" /// print(singleDigits.last) /// // Prints "9" /// /// - Parameters:)`. /// - minimum: The lower bound for the range. /// - maximum: The upper bound for the range. @_inlineable // FIXME(sil-serialize-all) @_transparent public static func ... (minimum: Self, maximum: Self) -> ClosedRange<Self> { // FIXME: swift-3-indexing-model: tests for traps. _precondition( minimum <= maximum, "Can't form Range with upperBound < lowerBound") return ClosedRange(uncheckedBounds: (lower: minimum, upper: maximum)) } } extension ClosedRange: Equatable { /// Returns a Boolean value indicating whether two ranges are equal. /// /// Two ranges are equal when they have the same lower and upper bounds. /// /// let x: ClosedRange = 5...15 /// print(x == 5...15) /// // Prints "true" /// print(x == 10...20) /// // Prints "false" /// /// - Parameters: /// - lhs: A range to compare. /// - rhs: Another range to compare. @_inlineable public static func == ( lhs: ClosedRange<Bound>, rhs: ClosedRange<Bound> ) -> Bool { return lhs.lowerBound == rhs.lowerBound && lhs.upperBound == rhs.upperBound } } extension ClosedRange : CustomStringConvertible { /// A textual representation of the range. @_inlineable // FIXME(sil-serialize-all)...\( public var description: String { return "\(lowerBound)...\(upperBound)" } } extension ClosedRange : CustomDebugStringConvertible { /// A textual representation of the range, suitable for debugging. @_inlineable // FIXME(sil-serialize-all) public var debugDescription: String { return "ClosedRange(\(String(reflecting: lowerBound))" + "...\(String(reflecting: upperBound)))" } } extension ClosedRange : CustomReflectable { @_inlineable // FIXME(sil-serialize-all) public var customMirror: Mirror { return Mirror( self, children: ["lowerBound": lowerBound, "upperBound": upperBound]) } } extension ClosedRange { /// Returns a copy of this range clamped to the given limiting range. /// /// The bounds of the result are always limited to the bounds of `limits`. /// For example: /// /// let x: ClosedRange = 0...20 /// print(x.clamped(to: 10...1000)) /// // Prints "10...20" /// /// If the two ranges do not overlap, the result is a single-element range at /// the upper or lower bound of `limits`. /// /// let y: ClosedRange = 0...5 /// print(y.clamped(to: 10...1000)) /// // Prints "10...10" /// /// - Parameter limits: The range to clamp the bounds of this range. /// - Returns: A new range clamped to the bounds of `limits`. @_inlineable // FIXME(sil-serialize-all) @inline(__always) public func clamped(to limits: ClosedRange) -> ClosedRange { let lower = limits.lowerBound > self.lowerBound ? limits.lowerBound : limits.upperBound < self.lowerBound ? limits.upperBound : self.lowerBound let upper = limits.upperBound < self.upperBound ? limits.upperBound : limits.lowerBound > self.upperBound ? limits.lowerBound : self.upperBound return ClosedRange(uncheckedBounds: (lower: lower, upper: upper)) } } extension ClosedRange where Bound: Strideable, Bound.Stride : SignedInteger { /// Now that Range is conditionally a collection when Bound: Strideable, /// CountableRange is no longer needed. This is a deprecated initializer /// for any remaining uses of Range(countableRange). @available(*,deprecated: 4.2, message: "CountableRange is now Range. No need to convert any more.") public init(_ other: ClosedRange<Bound>) { self = other } /// Creates an instance equivalent to the given `Range`. /// /// - Parameter other: A `Range` to convert to a `ClosedRange` instance. /// /// An equivalent range must be representable as a closed range. /// For example, passing an empty range as `other` triggers a runtime error, /// because an empty range cannot be represented by a closed range instance. public init(_ other: Range<Bound>) { _precondition(!other.isEmpty, "Can't form an empty closed range") let upperBound = other.upperBound.advanced(by: -1) self.init(uncheckedBounds: (lower: other.lowerBound, upper: upperBound)) } } extension ClosedRange { @_inlineable public func overlaps(_ other: ClosedRange<Bound>) -> Bool { return self.contains(other.lowerBound) || other.contains(lowerBound) } @_inlineable public func overlaps(_ other: Range<Bound>) -> Bool { return other.overlaps(self) } } @available(*, deprecated, renamed: "ClosedRange.Index") public typealias ClosedRangeIndex<T> = ClosedRange<T>.Index where T: Strideable, T.Stride: SignedInteger @available(*, deprecated, renamed: "ClosedRange") public typealias CountableClosedRange<T: Comparable> = ClosedRange<T>
bfe5af13f93137a53733367e8d7b4739
32.141372
104
0.649959
false
false
false
false
justindhill/Facets
refs/heads/master
Facets/View Controllers/Issue Composer/OZLIssueComposerViewController.swift
mit
1
// // OZLIssueComposerViewController.swift // Facets // // Created by Justin Hill on 12/6/15. // Copyright © 2015 Justin Hill. All rights reserved. // import UIKit import JGProgressHUD private let CustomFieldUserInfoKey = "custom-field" class OZLIssueComposerViewController: OZLFormViewController { fileprivate let ProjectKeypath = "issue.project" fileprivate let TrackerKeypath = "issue.tracker" fileprivate let StatusKeypath = "issue.status" fileprivate let SubjectKeypath = "issue.subject" fileprivate let DescriptionKeypath = "issue.description" fileprivate let StartDateKeypath = "issue.start-date" fileprivate let DueDateKeypath = "issue.due-date" fileprivate let CommentKeypath = "issue.update-comment" fileprivate let TargetVersionKeypath = "issue.target-version" fileprivate let CategoryKeypath = "issue.category" fileprivate let AssigneeKeypath = "issue.assignee" fileprivate let TimeEstimationKeypath = "issue.estimated-time" fileprivate let PercentCompleteKeypath = "issue.percent-complete" fileprivate enum EditMode { case new case existing } var currentProject: OZLModelProject var projects = OZLModelProject.allObjects() var versions = OZLModelVersion.allObjects() var categories = OZLModelIssueCategory.allObjects() var issueStatuses = OZLModelIssueStatus.allObjects() var users = OZLModelUser.allObjects() var customFields: [OZLModelCustomField]? fileprivate var editMode: EditMode @NSCopying var issue: OZLModelIssue override func viewDidLoad() { super.viewDidLoad() if issue.index > 0 { self.title = "\(self.issue.tracker?.name ?? "") #\(self.issue.index)" } else { self.title = "New Issue" } self.refreshCustomFields() self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Submit", style: .plain, target: self, action: #selector(submitAction)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.presentingViewController != nil { self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismissAction)) } } func refreshCustomFields() { weak var weakSelf = self func completion(_ fields: [Any]?, error: Error?) { if let fields = fields as? [OZLModelCustomField] { weakSelf?.customFields = fields weakSelf?.reloadData() } } if self.issue.index > 0 { OZLNetwork.sharedInstance().getCustomFields(forIssue: self.issue.index, completion: completion) } else { OZLNetwork.sharedInstance().getCustomFields(forProject: self.currentProject.projectId, completion: completion) } } init(currentProjectID: Int) { guard let project = OZLModelProject(forPrimaryKey: currentProjectID) else { fatalError("Tried to instantiate an issue composer without a project.") } self.currentProject = project self.editMode = .new self.issue = OZLModelIssue() self.issue.modelDiffingEnabled = true super.init(style: .grouped) self.issue.projectId = project.projectId self.issue.tracker = project.trackers.firstObject() self.issue.status = self.issueStatuses.firstObject() as? OZLModelIssueStatus } init(issue: OZLModelIssue) { guard let project = OZLModelProject(forPrimaryKey: issue.projectId) else { fatalError("Project ID associated with passed issue is invalid") } self.issue = issue self.issue.modelDiffingEnabled = true self.currentProject = project self.editMode = .existing super.init(style: .grouped) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func definitionsForFields() -> [OZLFormSection] { var sections = [OZLFormSection]() if self.editMode == .existing { sections.append(OZLFormSection( title: "Update comment", fields: [ OZLTextViewFormField(keyPath: CommentKeypath, placeholder: "Comment", currentValue: nil) ])) } let generalSection = OZLFormSection(title: "General", fields: [ OZLEnumerationFormField(keyPath: ProjectKeypath, placeholder: "Project", currentValue: (self.changes[ProjectKeypath] as? OZLEnumerationFormFieldValue)?.stringValue() ?? self.currentProject.name, possibleRealmValues: self.projects), OZLEnumerationFormField( keyPath: TrackerKeypath, placeholder: "Tracker", currentValue: (self.changes[TrackerKeypath] as? OZLEnumerationFormFieldValue)?.stringValue() ?? self.issue.tracker?.name, possibleRealmValues: self.currentProject.trackers), OZLEnumerationFormField( keyPath: StatusKeypath, placeholder: "Status", currentValue: (self.changes[StatusKeypath] as? OZLEnumerationFormFieldValue)?.stringValue() ?? self.issue.status?.name, possibleRealmValues: self.issueStatuses), OZLEnumerationFormField( keyPath: CategoryKeypath, placeholder: "Category", currentValue: (self.changes[CategoryKeypath] as? OZLEnumerationFormFieldValue)?.stringValue() ?? self.issue.category?.name, possibleRealmValues: self.categories), OZLEnumerationFormField( keyPath: AssigneeKeypath, placeholder: "Assignee", currentValue: (self.changes[AssigneeKeypath] as? OZLEnumerationFormFieldValue)?.stringValue() ?? self.issue.assignedTo?.name, possibleRealmValues: self.users), OZLTextFormField( keyPath: SubjectKeypath, placeholder: "Subject", currentValue: self.changes[SubjectKeypath] as? String ?? self.issue.subject), OZLTextViewFormField( keyPath: DescriptionKeypath, placeholder: "Description", currentValue: self.changes[DescriptionKeypath] as? String ?? self.issue.issueDescription) ]) sections.append(generalSection) let schedulingSection = OZLFormSection(title: "Scheduling", fields: [ OZLEnumerationFormField( keyPath: TargetVersionKeypath, placeholder: "Target version", currentValue: (self.changes[TargetVersionKeypath] as? OZLEnumerationFormFieldValue)?.stringValue() ?? self.issue.targetVersion?.name, possibleRealmValues: self.versions), OZLTextFormField( keyPath: TimeEstimationKeypath, placeholder: "Estimated time (hours)", currentValue: (self.changes[TimeEstimationKeypath] as? String) ?? (self.issue.estimatedHours == nil ? "" : String(describing: self.issue.estimatedHours!))), OZLTextFormField( keyPath: PercentCompleteKeypath, placeholder: "Percent complete", currentValue: (self.changes[PercentCompleteKeypath] as? String ?? (self.issue.doneRatio == nil ? "" : String(describing: self.issue.doneRatio!)))), OZLDateFormField( keyPath: StartDateKeypath, placeholder: "Start date", currentValue: self.changes[StartDateKeypath] as? Date ?? self.issue.startDate), OZLDateFormField( keyPath: DueDateKeypath, placeholder: "Due date", currentValue: self.changes[DueDateKeypath] as? Date ?? self.issue.dueDate) ]) sections.append(schedulingSection) if let customFields = self.customFields, customFields.count > 0 { var fields = [OZLFormField]() for field in customFields { fields.append(field.createFormFieldForIssue(self.issue)) } sections.append(OZLFormSection(title: "Custom Fields", fields: fields)) self.tableView.tableFooterView = nil } else { let loadingView = OZLLoadingView(frame: CGRect(x: 0, y: 0, width: 320, height: 44)) loadingView.startLoading() loadingView.backgroundColor = UIColor.clear self.tableView.tableFooterView = loadingView } return sections } override func formFieldCell(_ formCell: OZLFormFieldCell, valueChangedFrom fromValue: AnyObject?, toValue: AnyObject?, atKeyPath keyPath: String, userInfo: [String : AnyObject]) { super.formFieldCell(formCell, valueChangedFrom:fromValue , toValue: toValue, atKeyPath: keyPath, userInfo: userInfo) let customField = userInfo[CustomFieldUserInfoKey] as? OZLModelCustomField if let toValue = toValue as? String { if keyPath == SubjectKeypath { self.issue.subject = toValue } else if keyPath == DescriptionKeypath { self.issue.issueDescription = toValue } else if keyPath == CommentKeypath { self.issue.setUpdateComment(toValue) } else if keyPath == TimeEstimationKeypath { if let toValue = Float(toValue) { self.issue.estimatedHours = Float(toValue) } } else if keyPath == PercentCompleteKeypath { if let toValue = Float(toValue) { self.issue.doneRatio = toValue } } else if let customField = customField { if let toValue = Float(toValue), customField.type == .float { self.issue.setValueOnDiff(toValue as AnyObject, forCustomFieldId: customField.fieldId) } else if let toValue = Int(toValue), customField.type == .integer { self.issue.setValueOnDiff(toValue as AnyObject, forCustomFieldId: customField.fieldId) } else { self.issue.setValueOnDiff(toValue as AnyObject, forCustomFieldId: customField.fieldId) } } } else if let toValue = toValue as? OZLModelTracker { if keyPath == TrackerKeypath { self.issue.tracker = toValue } } else if let toValue = toValue as? OZLModelProject { if keyPath == ProjectKeypath { self.issue.projectId = toValue.projectId } } else if let toValue = toValue as? OZLModelIssueStatus { if keyPath == StatusKeypath { self.issue.status = toValue } } else if let toValue = toValue as? OZLModelIssueCategory { if keyPath == CategoryKeypath { self.issue.category = toValue } } else if let toValue = toValue as? OZLModelVersion { if keyPath == TargetVersionKeypath { self.issue.targetVersion = toValue } else if let customField = customField { self.issue.setValueOnDiff(String(toValue.versionId) as AnyObject, forCustomFieldId: customField.fieldId) } } else if let toValue = toValue as? OZLModelUser { if keyPath == AssigneeKeypath { self.issue.assignedTo = toValue } } else if let toValue = toValue as? Date { if keyPath == DueDateKeypath { self.issue.dueDate = toValue } else if keyPath == StartDateKeypath { self.issue.startDate = toValue } else if let customField = customField { self.issue.setDateOnDiff(toValue, forCustomFieldId: customField.fieldId) } } else if let toValue = toValue as? OZLModelStringContainer, let value = toValue.value { if let customField = customField { self.issue.setValueOnDiff(value as AnyObject, forCustomFieldId: customField.fieldId) } } print("from: \(String(describing: fromValue)), to: \(String(describing: toValue)), keyPath: \(keyPath)") } @objc func submitAction() { self.tableView.endEditing(true) print(self.issue.changeDictionary as Any) let hud = JGProgressHUD(style: .dark) hud.show(in: self.view) weak var weakSelf = self func completion(_ success: Bool, error: Error?) { if let weakSelf = weakSelf { if success == false { hud.indicatorView = JGProgressHUDImageIndicatorView(imageInLibraryBundleNamed: "jg_hud_error", enableTinting: true) hud.dismiss(afterDelay: 1.5) } else { hud.indicatorView = JGProgressHUDImageIndicatorView(imageInLibraryBundleNamed: "jg_hud_success", enableTinting: true) weak var innerWeakSelf = weakSelf DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: { if let innerWeakSelf = innerWeakSelf { innerWeakSelf.presentingViewController?.dismiss(animated: true, completion: nil) } }) } } } if self.editMode == .new { OZLNetwork.sharedInstance().createIssue(self.issue, withParams: [:], completion: completion) } else if self.editMode == .existing { OZLNetwork.sharedInstance().update(self.issue, withParams: nil, completion: completion) } } @objc func dismissAction() { self.presentingViewController?.dismiss(animated: true, completion: nil) } } private extension JGProgressHUDImageIndicatorView { convenience init(image: UIImage!, enableTinting: Bool) { var image: UIImage = image if enableTinting { image = image.withRenderingMode(.alwaysTemplate) } self.init(image: image) } convenience init(imageInLibraryBundleNamed name: String, enableTinting: Bool) { let bundle = Bundle(path: Bundle(for: JGProgressHUD.self).path(forResource: "JGProgressHUD Resources", ofType: "bundle")!) let image = UIImage(named: name, in: bundle, compatibleWith: nil) self.init(image: image, enableTinting: enableTinting) } } private extension OZLModelCustomField { func createFormFieldForIssue(_ issue: OZLModelIssue) -> OZLFormField { let fieldName = self.name ?? "" let keyPath = "cf_\(self.fieldId)" var formField: OZLFormField! let stringValue = self.value as? String ?? "" switch self.type { case .boolean: formField = OZLEnumerationFormField( keyPath: keyPath, placeholder: fieldName, currentValue: stringValue == "0" ? "No" : stringValue == "1" ? "Yes" : nil, possibleValues: [ OZLModelStringContainer(string: "", value: ""), OZLModelStringContainer(string: "Yes", value: "1"), OZLModelStringContainer(string: "No", value: "0") ] ) case .date: formField = OZLDateFormField(keyPath: keyPath, placeholder: fieldName, currentValue: self.value as? Date) case .float: formField = OZLTextFormField(keyPath: keyPath, placeholder: fieldName, currentValue: stringValue) case .integer: formField = OZLTextFormField(keyPath: keyPath, placeholder: fieldName, currentValue: stringValue) case .link: formField = OZLTextFormField(keyPath: keyPath, placeholder: fieldName) case .list: formField = OZLEnumerationFormField(keyPath: keyPath, placeholder: fieldName, currentValue: stringValue, possibleRealmValues: self.options!) case .longText: formField = OZLTextViewFormField(keyPath: keyPath, placeholder: fieldName, currentValue: stringValue) case .text: formField = OZLTextFormField(keyPath: keyPath, placeholder: fieldName, currentValue: stringValue) case .user: formField = OZLEnumerationFormField(keyPath: keyPath, placeholder: fieldName, currentValue: stringValue, possibleRealmValues: self.options!) case .version: formField = OZLEnumerationFormField(keyPath: keyPath, placeholder: fieldName, currentValue: stringValue, possibleRealmValues: self.options!) default: // assertionFailure() formField = OZLFormField(keyPath: "", placeholder: "") } formField.userInfo[CustomFieldUserInfoKey] = self return formField } }
c30f4f1ca7d8b97e63417fb40b616db0
41.243781
183
0.622954
false
false
false
false
BluechipSystems/viper-module-generator
refs/heads/master
VIPERGenDemo/VIPERGenDemo/Libraries/Swifter/Swifter/SwifterFavorites.swift
mit
4
// // SwifterFavorites.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // 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 public extension Swifter { /* GET favorites/list Returns the 20 most recent Tweets favorited by the authenticating or specified user. If you do not provide either a user_id or screen_name to this method, it will assume you are requesting on behalf of the authenticating user. Specify one or the other for best results. */ public func getFavoritesListWithCount(count: Int?, sinceID: String?, maxID: String?, success: ((statuses: [JSONValue]?) -> Void)?, failure: FailureHandler?) { let path = "favorites/list.json" var parameters = Dictionary<String, AnyObject>() if count != nil { parameters["count"] = count! } if sinceID != nil { parameters["since_id"] = sinceID! } if maxID != nil { parameters["max_id"] = maxID! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(statuses: json.array) return }, failure: failure) } public func getFavoritesListWithUserID(userID: String, count: Int?, sinceID: String?, maxID: String?, success: ((statuses: [JSONValue]?) -> Void)?, failure: FailureHandler?) { let path = "favorites/list.json" var parameters = Dictionary<String, AnyObject>() parameters["user_id"] = userID if count != nil { parameters["count"] = count! } if sinceID != nil { parameters["since_id"] = sinceID! } if maxID != nil { parameters["max_id"] = maxID! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(statuses: json.array) return }, failure: failure) } public func getFavoritesListWithScreenName(screenName: String, count: Int?, sinceID: String?, maxID: String?, success: ((statuses: [JSONValue]?) -> Void)?, failure: FailureHandler?) { let path = "favorites/list.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if count != nil { parameters["count"] = count! } if sinceID != nil { parameters["since_id"] = sinceID! } if maxID != nil { parameters["max_id"] = maxID! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(statuses: json.array) return }, failure: failure) } /* POST favorites/destroy Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not. */ public func postDestroyFavoriteWithID(id: Int, includeEntities: Bool?, success: ((status: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "favorites/destroy.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if includeEntities != nil { parameters["include_entities"] = includeEntities! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(status: json.object) return }, failure: failure) } /* POST favorites/create Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful. This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not. */ public func postCreateFavoriteWithID(id: Int, includeEntities: Bool?, success: ((status: Dictionary<String, JSONValue>?) -> Void)?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "favorites/create.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if includeEntities != nil { parameters["include_entities"] = includeEntities! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(status: json.object) return }, failure: failure) } }
4a561453c304add4aae216d09eb8f3dd
37.67284
250
0.652035
false
false
false
false
groue/GRDB.swift
refs/heads/master
Tests/GRDBTests/DerivableRequestTests.swift
mit
1
import XCTest import GRDB private struct Author: FetchableRecord, PersistableRecord, Codable { var id: Int64 var firstName: String? var lastName: String? var country: String var fullName: String { [firstName, lastName] .compactMap { $0 } .joined(separator: " ") } static let databaseTableName = "author" static let books = hasMany(Book.self) var books: QueryInterfaceRequest<Book> { request(for: Author.books) } } private struct Book: FetchableRecord, PersistableRecord, Codable { var id: Int64 var authorId: Int64 var title: String static let databaseTableName = "book" static let author = belongsTo(Author.self) static let bookFts4 = hasOne(BookFts4.self, using: ForeignKey([.rowID])) #if SQLITE_ENABLE_FTS5 static let bookFts5 = hasOne(BookFts5.self, using: ForeignKey([.rowID])) #endif var author: QueryInterfaceRequest<Author> { request(for: Book.author) } } private struct BookFts4: TableRecord { } #if SQLITE_ENABLE_FTS5 private struct BookFts5: TableRecord { } #endif private var libraryMigrator: DatabaseMigrator = { var migrator = DatabaseMigrator() migrator.registerMigration("library") { db in try db.create(table: "author") { t in t.autoIncrementedPrimaryKey("id") t.column("firstName", .text) t.column("lastName", .text) t.column("country", .text).notNull() } try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") t.column("authorId", .integer).notNull().references("author") t.column("title", .text).notNull() } try db.create(virtualTable: "bookFts4", using: FTS4()) { t in t.synchronize(withTable: "book") t.column("title") } #if SQLITE_ENABLE_FTS5 try db.create(virtualTable: "bookFts5", using: FTS5()) { t in t.synchronize(withTable: "book") t.column("title") } #endif } migrator.registerMigration("fixture") { db in try Author(id: 1, firstName: "Herman", lastName: "Melville", country: "US").insert(db) try Author(id: 2, firstName: "Marcel", lastName: "Proust", country: "FR").insert(db) try Book(id: 1, authorId: 1, title: "Moby-Dick").insert(db) try Book(id: 2, authorId: 2, title: "Du côté de chez Swann").insert(db) } return migrator }() // Define DerivableRequest extensions extension DerivableRequest<Author> { // SelectionRequest func selectCountry() -> Self { select(Column("country")) } // FilteredRequest func filter(country: String) -> Self { filter(Column("country") == country) } // OrderedRequest func orderByFullName() -> Self { order( Column("lastName").collating(.localizedCaseInsensitiveCompare), Column("firstName").collating(.localizedCaseInsensitiveCompare)) } } extension DerivableRequest<Book> { // OrderedRequest func orderByTitle() -> Self { order(Column("title").collating(.localizedCaseInsensitiveCompare)) } // JoinableRequest func filter(authorCountry: String) -> Self { joining(required: Book.author.filter(country: authorCountry)) } // TableRequest & FilteredRequest func filter(id: Int) -> Self { filter(key: id) } // TableRequest & FilteredRequest func matchingFts4(_ pattern: FTS3Pattern?) -> Self { joining(required: Book.bookFts4.matching(pattern)) } #if SQLITE_ENABLE_FTS5 // TableRequest & FilteredRequest func matchingFts5(_ pattern: FTS3Pattern?) -> Self { joining(required: Book.bookFts5.matching(pattern)) } #endif // TableRequest & OrderedRequest func orderById() -> Self { orderByPrimaryKey() } } class DerivableRequestTests: GRDBTestCase { func testFilteredRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in // ... for two requests (1) let frenchAuthorNames = try Author.all() .filter(country: "FR") .fetchAll(db) .map(\.fullName) XCTAssertEqual(frenchAuthorNames, ["Marcel Proust"]) // ... for two requests (2) let frenchBookTitles = try Book .joining(required: Book.author.filter(country: "FR")) .order(Column("title")) .fetchAll(db) .map(\.title) XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann"]) } } func testOrderedRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in // ... for two requests (1) sqlQueries.removeAll() let authorNames = try Author.all() .orderByFullName() .fetchAll(db) .map(\.fullName) XCTAssertEqual(authorNames, ["Herman Melville", "Marcel Proust"]) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "author" \ ORDER BY "lastName" COLLATE swiftLocalizedCaseInsensitiveCompare, \ "firstName" COLLATE swiftLocalizedCaseInsensitiveCompare """) sqlQueries.removeAll() let reversedAuthorNames = try Author.all() .orderByFullName() .reversed() .fetchAll(db) .map(\.fullName) XCTAssertEqual(reversedAuthorNames, ["Marcel Proust", "Herman Melville"]) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "author" \ ORDER BY "lastName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC, \ "firstName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC """) sqlQueries.removeAll() _ /* unorderedAuthors */ = try Author.all() .orderByFullName() .unordered() .fetchAll(db) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "author" """) // ... for two requests (2) sqlQueries.removeAll() let bookTitles = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() .fetchAll(db) .map(\.title) XCTAssertEqual(bookTitles, ["Du côté de chez Swann", "Moby-Dick"]) XCTAssertEqual(lastSQLQuery, """ SELECT "book".* FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" \ ORDER BY \ "book"."title" COLLATE swiftLocalizedCaseInsensitiveCompare, \ "author"."lastName" COLLATE swiftLocalizedCaseInsensitiveCompare, \ "author"."firstName" COLLATE swiftLocalizedCaseInsensitiveCompare """) sqlQueries.removeAll() let reversedBookTitles = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() .reversed() .fetchAll(db) .map(\.title) XCTAssertEqual(reversedBookTitles, ["Moby-Dick", "Du côté de chez Swann"]) XCTAssertEqual(lastSQLQuery, """ SELECT "book".* FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" \ ORDER BY \ "book"."title" COLLATE swiftLocalizedCaseInsensitiveCompare DESC, \ "author"."lastName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC, \ "author"."firstName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC """) sqlQueries.removeAll() _ /* unorderedBooks */ = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() .unordered() .fetchAll(db) XCTAssertEqual(lastSQLQuery, """ SELECT "book".* FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" """) } } func testSelectionRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let request = Author.all().selectCountry() let authorCountries = try Set(String.fetchAll(db, request)) XCTAssertEqual(authorCountries, ["FR", "US"]) XCTAssertEqual(lastSQLQuery, """ SELECT "country" FROM "author" """) } do { sqlQueries.removeAll() let request = Book.including(required: Book.author.selectCountry()) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ SELECT "book".*, "author"."country" \ FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" """) } } } func testJoinableRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let frenchBookTitles = try Book.all() .filter(authorCountry: "FR") .order(Column("title")) .fetchAll(db) .map(\.title) XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann"]) XCTAssertEqual(lastSQLQuery, """ SELECT "book".* \ FROM "book" \ JOIN "author" ON ("author"."id" = "book"."authorId") AND ("author"."country" = 'FR') \ ORDER BY "book"."title" """) } do { sqlQueries.removeAll() let frenchAuthorFullNames = try Author .joining(required: Author.books.filter(authorCountry: "FR")) .order(Column("firstName")) .fetchAll(db) .map(\.fullName) XCTAssertEqual(frenchAuthorFullNames, ["Marcel Proust"]) XCTAssertEqual(lastSQLQuery, """ SELECT "author1".* \ FROM "author" "author1" \ JOIN "book" ON "book"."authorId" = "author1"."id" \ JOIN "author" "author2" ON ("author2"."id" = "book"."authorId") AND ("author2"."country" = 'FR') \ ORDER BY "author1"."firstName" """) } } } func testTableRequestFilteredRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in // filter(id:) do { let title = try Book.all() .filter(id: 2) .fetchOne(db) .map(\.title) XCTAssertEqual(title, "Du côté de chez Swann") XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "book" WHERE "id" = 2 """) let fullName = try Author .joining(required: Author.books.filter(id: 2)) .fetchOne(db) .map(\.fullName) XCTAssertEqual(fullName, "Marcel Proust") XCTAssertEqual(lastSQLQuery, """ SELECT "author".* FROM "author" \ JOIN "book" ON ("book"."authorId" = "author"."id") AND ("book"."id" = 2) \ LIMIT 1 """) } // matchingFts4 do { sqlQueries.removeAll() let title = try Book.all() .matchingFts4(FTS3Pattern(rawPattern: "moby dick")) .fetchOne(db) .map(\.title) XCTAssertEqual(title, "Moby-Dick") XCTAssert(sqlQueries.contains(""" SELECT "book".* FROM "book" \ JOIN "bookFts4" ON ("bookFts4"."rowid" = "book"."id") AND ("bookFts4" MATCH 'moby dick') \ LIMIT 1 """)) sqlQueries.removeAll() let fullName = try Author .joining(required: Author.books.matchingFts4(FTS3Pattern(rawPattern: "moby dick"))) .fetchOne(db) .map(\.fullName) XCTAssertEqual(fullName, "Herman Melville") XCTAssert(sqlQueries.contains(""" SELECT "author".* FROM "author" \ JOIN "book" ON "book"."authorId" = "author"."id" \ JOIN "bookFts4" ON ("bookFts4"."rowid" = "book"."id") AND ("bookFts4" MATCH 'moby dick') \ LIMIT 1 """)) } #if SQLITE_ENABLE_FTS5 // matchingFts5 do { sqlQueries.removeAll() let title = try Book.all() .matchingFts5(FTS3Pattern(rawPattern: "cote swann")) .fetchOne(db) .map(\.title) XCTAssertEqual(title, "Du côté de chez Swann") XCTAssert(sqlQueries.contains(""" SELECT "book".* FROM "book" \ JOIN "bookFts5" ON ("bookFts5"."rowid" = "book"."id") AND ("bookFts5" MATCH 'cote swann') \ LIMIT 1 """)) sqlQueries.removeAll() let fullName = try Author .joining(required: Author.books.matchingFts5(FTS3Pattern(rawPattern: "cote swann"))) .fetchOne(db) .map(\.fullName) XCTAssertEqual(fullName, "Marcel Proust") XCTAssert(sqlQueries.contains(""" SELECT "author".* FROM "author" \ JOIN "book" ON "book"."authorId" = "author"."id" \ JOIN "bookFts5" ON ("bookFts5"."rowid" = "book"."id") AND ("bookFts5" MATCH 'cote swann') \ LIMIT 1 """)) } #endif // orderById do { let titles = try Book.all() .orderById() .fetchAll(db) .map(\.title) XCTAssertEqual(titles, ["Moby-Dick", "Du côté de chez Swann"]) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "book" ORDER BY "id" """) let fullNames = try Author .joining(required: Author.books.orderById()) .fetchAll(db) .map(\.fullName) XCTAssertEqual(fullNames, ["Herman Melville", "Marcel Proust"]) XCTAssertEqual(lastSQLQuery, """ SELECT "author".* FROM "author" \ JOIN "book" ON "book"."authorId" = "author"."id" ORDER BY "book"."id" """) } } } }
dab6253a1f846fc3fd20bb044442d769
37.764706
118
0.504616
false
false
false
false
EstebanVallejo/sdk-ios
refs/heads/master
MercadoPagoSDK/MercadoPagoSDK/MerchantServer.swift
mit
3
// // MerchantServer.swift // MercadoPagoSDK // // Created by Matias Gualino on 31/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class MerchantServer : NSObject { public override init() { } public class func getCustomer(merchantBaseUrl : String, merchantGetCustomerUri : String, merchantAccessToken : String, success: (customer: Customer) -> Void, failure: ((error: NSError) -> Void)?) { let service : MerchantService = MerchantService(baseURL: merchantBaseUrl, getCustomerUri: merchantGetCustomerUri) service.getCustomer(merchant_access_token: merchantAccessToken, success: {(jsonResult: AnyObject?) -> Void in var cust : Customer? = nil if let custDic = jsonResult as? NSDictionary { if custDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.merchantServer.getCustomer", code: MercadoPago.ERROR_API_CODE, userInfo: custDic as [NSObject : AnyObject])) } } else { cust = Customer.fromJSON(custDic) success(customer: cust!) } } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.merchantServer.getCustomer", code: MercadoPago.ERROR_UNKNOWN_CODE, userInfo: ["message": "Response cannot be decoded"])) } } }, failure: failure) } public class func createPayment(merchantBaseUrl : String, merchantPaymentUri : String, payment : MerchantPayment, success: (payment: Payment) -> Void, failure: ((error: NSError) -> Void)?) { let service : MerchantService = MerchantService(baseURL: merchantBaseUrl, createPaymentUri: merchantPaymentUri) service.createPayment(payment: payment, success: {(jsonResult: AnyObject?) -> Void in var payment : Payment? = nil if let paymentDic = jsonResult as? NSDictionary { if paymentDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.merchantServer.createPayment", code: MercadoPago.ERROR_API_CODE, userInfo: paymentDic as [NSObject : AnyObject])) } } else { if paymentDic.allKeys.count > 0 { payment = Payment.fromJSON(paymentDic) success(payment: payment!) } else { failure!(error: NSError(domain: "mercadopago.sdk.merchantServer.createPayment", code: MercadoPago.ERROR_PAYMENT, userInfo: ["message": "PAYMENT_ERROR".localized])) } } } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.merchantServer.createPayment", code: MercadoPago.ERROR_UNKNOWN_CODE, userInfo: ["message": "Response cannot be decoded"])) } } }, failure: failure) } }
07b50412ded9118ebba34485b460bfe0
45.575758
202
0.601692
false
false
false
false
mownier/photostream
refs/heads/master
Photostream/Module Extensions/PostDiscoveryModuleExtension.swift
mit
1
// // PostDiscoveryModuleExtension.swift // Photostream // // Created by Mounir Ybanez on 20/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import DateTools extension PostDiscoveryModule { convenience init(sceneType: PostDiscoverySceneType = .grid) { let scene = PostDiscoveryViewController(type: sceneType) self.init(view: scene) } } extension PostDiscoveryScene { func isBackBarItemVisible(_ isVisible: Bool) { guard let controller = controller as? PostDiscoveryViewController else { return } controller.isBackBarItemVisible = isVisible } } extension PostDiscoveryWireframeInterface { func presentCommentController(from parent: UIViewController, delegate: CommentControllerDelegate?, postId: String, shouldComment: Bool = false) { let controller = CommentController(root: nil) controller.postId = postId controller.style = .push controller.shouldComment = shouldComment controller.delegate = delegate var property = WireframeEntryProperty() property.controller = controller property.parent = parent controller.enter(with: property) } func showPostDiscoveryAsList(from parent: UIViewController, posts: [PostDiscoveryData] = [PostDiscoveryData](), index: Int) { let module = PostDiscoveryModule(sceneType: .list) module.build( root: root, posts: posts, initialPostIndex: index ) module.view.isBackBarItemVisible(true) var property = WireframeEntryProperty() property.controller = module.view.controller property.parent = parent module.wireframe.style = .push module.wireframe.enter(with: property) } func showUserTimeline(from parent: UIViewController?, userId: String) { let userTimeline = UserTimelineViewController() userTimeline.root = root userTimeline.style = .push userTimeline.userId = userId var property = WireframeEntryProperty() property.parent = parent property.controller = userTimeline userTimeline.enter(with: property) } func showPostLikes(from parent: UIViewController?, postId: String) { let module = PostLikeModule() module.build(root: root, postId: postId) var property = WireframeEntryProperty() property.parent = parent property.controller = module.view.controller module.wireframe.style = .push module.wireframe.enter(with: property) } } extension PostDiscoveryModuleInterface { func presentCommentController(at index: Int, shouldComment: Bool = false) { guard let presenter = self as? PostDiscoveryPresenter, let parent = presenter.view.controller, let post = post(at: index) else { return } presenter.wireframe.presentCommentController(from: parent, delegate: presenter, postId: post.id, shouldComment: shouldComment) } func presentPostDiscoveryAsList(with index: Int) { guard let presenter = self as? PostDiscoveryPresenter, let parent = presenter.view.controller else { return } presenter.wireframe.showPostDiscoveryAsList( from: parent, posts: presenter.posts, index: index ) } func presentUserTimeline(at index: Int) { guard let presenter = self as? PostDiscoveryPresenter, let parent = presenter.view.controller, let post = post(at: index) else { return } presenter.wireframe.showUserTimeline(from: parent, userId: post.userId) } func presentPostLikes(at index: Int) { guard let presenter = self as? NewsFeedPresenter, let parent = presenter.view.controller, let post = post(at: index) else { return } presenter.wireframe.showPostLikes(from: parent, postId: post.id) } } extension PostDiscoveryPresenter: CommentControllerDelegate { func commentControllerDidWrite(with postId: String) { guard let index = indexOf(post: postId) else { return } var post = posts[index] post.comments += 1 posts[index] = post view.reloadView() } } extension PostDiscoveryDataItem: PostGridCollectionCellItem { } extension PostDiscoveryDataItem: PostListCollectionHeaderItem { } extension PostDiscoveryDataItem: PostListCollectionCellItem { var timeAgo: String { let date = NSDate(timeIntervalSince1970: timestamp) return date.timeAgoSinceNow() } var photoSize: CGSize { var size = CGSize.zero size.width = CGFloat(photoWidth) size.height = CGFloat(photoHeight) return size } var likesText: String { guard likes > 0 else { return "" } if likes > 1 { return "\(likes) likes" } else { return "1 like" } } var commentsText: String { guard comments > 0 else { return "" } if comments > 1 { return "View \(comments) comments" } else { return "View 1 comment" } } }
4e34c55750b4d4d6dbc052995d07c759
28.005208
149
0.608906
false
false
false
false
krzyzanowskim/ChorusBirdie
refs/heads/master
ChorusBirdie/UI/Scenes/SKPhysicsContactDelegate.swift
mit
1
// // SKPhysicsContactDelegate.swift // ChorusBirdie // // Created by Marcin Krzyzanowski on 16/11/14. // Copyright (c) 2014 SwiftCrunch. All rights reserved. // import SpriteKit import UIKit extension GameScene { func didBeginContact(contact: SKPhysicsContact) { if contact.bodyA == birdNode.physicsBody, contact.bodyB == cable1.physicsBody, birdNode.mode == .landing { birdNode.mode = .sitting enumerateChildNodes(withName: "bird", using: { (node, _) -> Void in if let bird = node as? FlyingBirdNode { bird.swinging = true } }) playChorus() } else if contact.bodyA == birdNode.physicsBody, birdNode.mode != .sitting { let crashStarNode = SKSpriteNode(imageNamed: "crash") crashStarNode.name = "crash" crashStarNode.position = contact.contactPoint addChild(crashStarNode) _ = gameOver(gameOver: true) } } }
9b35679fd7b9e020bec1afd33ff93292
27.5
110
0.66557
false
false
false
false
LoopKit/LoopKit
refs/heads/dev
LoopKit/DeviceManager/CGMManager.swift
mit
1
// // CGMManager.swift // Loop // // Copyright © 2017 LoopKit Authors. All rights reserved. // import HealthKit /// Describes the result of CGM manager operations to fetch and report sensor readings. /// /// - noData: No new data was available or retrieved /// - unreliableData: New glucose data was received, but is not reliable enough to use for therapy /// - newData: New glucose data was received and stored /// - error: An error occurred while receiving or store data public enum CGMReadingResult { case noData case unreliableData case newData([NewGlucoseSample]) case error(Error) } public struct CGMManagerStatus: Equatable { // Return false if no sensor active, or in a state where no future data is expected without user intervention public var hasValidSensorSession: Bool public var lastCommunicationDate: Date? public var device: HKDevice? public init(hasValidSensorSession: Bool, lastCommunicationDate: Date? = nil, device: HKDevice?) { self.hasValidSensorSession = hasValidSensorSession self.lastCommunicationDate = lastCommunicationDate self.device = device } } extension CGMManagerStatus: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.hasValidSensorSession = try container.decode(Bool.self, forKey: .hasValidSensorSession) self.lastCommunicationDate = try container.decodeIfPresent(Date.self, forKey: .lastCommunicationDate) self.device = try container.decodeIfPresent(CodableDevice.self, forKey: .device)?.device } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(hasValidSensorSession, forKey: .hasValidSensorSession) try container.encodeIfPresent(lastCommunicationDate, forKey: .lastCommunicationDate) try container.encodeIfPresent(device.map { CodableDevice($0) }, forKey: .device) } private enum CodingKeys: String, CodingKey { case hasValidSensorSession case lastCommunicationDate case device } } public protocol CGMManagerStatusObserver: AnyObject { /// Notifies observers of changes in CGMManagerStatus /// /// - Parameter manager: The manager instance /// - Parameter status: The new, updated status. Status includes properties associated with the manager, transmitter, or sensor, /// that are not part of an individual sensor reading. func cgmManager(_ manager: CGMManager, didUpdate status: CGMManagerStatus) } public protocol CGMManagerDelegate: DeviceManagerDelegate, CGMManagerStatusObserver { /// Asks the delegate for a date with which to filter incoming glucose data /// /// - Parameter manager: The manager instance /// - Returns: The date data occuring on or after which should be kept func startDateToFilterNewData(for manager: CGMManager) -> Date? /// Informs the delegate that the device has updated with a new result /// /// - Parameters: /// - manager: The manager instance /// - result: The result of the update func cgmManager(_ manager: CGMManager, hasNew readingResult: CGMReadingResult) -> Void /// Informs the delegate that the manager is deactivating and should be deleted /// /// - Parameter manager: The manager instance func cgmManagerWantsDeletion(_ manager: CGMManager) /// Informs the delegate that the manager has updated its state and should be persisted. /// /// - Parameter manager: The manager instance func cgmManagerDidUpdateState(_ manager: CGMManager) /// Asks the delegate for credential store prefix to avoid namespace conflicts /// /// - Parameter manager: The manager instance /// - Returns: The unique prefix for the credential store func credentialStoragePrefix(for manager: CGMManager) -> String } public protocol CGMManager: DeviceManager { var cgmManagerDelegate: CGMManagerDelegate? { get set } var appURL: URL? { get } /// Whether the device is capable of waking the app var providesBLEHeartbeat: Bool { get } /// The length of time to keep samples in HealthKit before removal. Return nil to never remove samples. var managedDataInterval: TimeInterval? { get } /// The length of time to delay until storing samples into HealthKit. Return 0 for no delay. static var healthKitStorageDelay: TimeInterval { get } var shouldSyncToRemoteService: Bool { get } var glucoseDisplay: GlucoseDisplayable? { get } /// The current status of the cgm manager var cgmManagerStatus: CGMManagerStatus { get } /// The queue on which CGMManagerDelegate methods are called /// Setting to nil resets to a default provided by the manager var delegateQueue: DispatchQueue! { get set } /// Implementations of this function must call the `completion` block, with the appropriate `CGMReadingResult` /// according to the current available data. /// - If there is new unreliable data, return `.unreliableData` /// - If there is no new data and the current data is unreliable, return `.unreliableData` /// - If there is new reliable data, return `.newData` with the data samples /// - If there is no new data and the current data is reliable, return `.noData` /// - If there is an error, return `.error` with the appropriate error. /// /// - Parameters: /// - completion: A closure called when operation has completed func fetchNewDataIfNeeded(_ completion: @escaping (CGMReadingResult) -> Void) -> Void /// Adds an observer of changes in CGMManagerStatus /// /// Observers are held by weak reference. /// /// - Parameters: /// - observer: The observing object /// - queue: The queue on which the observer methods should be called func addStatusObserver(_ observer: CGMManagerStatusObserver, queue: DispatchQueue) /// Removes an observer of changes in CGMManagerStatus /// /// Since observers are held weakly, calling this method is not required when the observer is deallocated /// /// - Parameter observer: The observing object func removeStatusObserver(_ observer: CGMManagerStatusObserver) /// Requests that the manager completes its deletion process /// /// - Parameter completion: Action to take after the CGM manager is deleted func delete(completion: @escaping () -> Void) } public extension CGMManager { var appURL: URL? { return nil } /// Default is no delay to store samples in HealthKit static var healthKitStorageDelay: TimeInterval { 0 } /// Convenience wrapper for notifying the delegate of deletion on the delegate queue /// /// - Parameters: /// - completion: A closure called from the delegate queue after the delegate is called func notifyDelegateOfDeletion(completion: @escaping () -> Void) { delegateQueue.async { self.cgmManagerDelegate?.cgmManagerWantsDeletion(self) completion() } } func addStatusObserver(_ observer: CGMManagerStatusObserver, queue: DispatchQueue) { // optional since a CGM manager may not support status observers } func removeStatusObserver(_ observer: CGMManagerStatusObserver) { // optional since a CGM manager may not support status observers } /// Override this default behaviour if the CGM Manager needs to complete tasks before being deleted func delete(completion: @escaping () -> Void) { notifyDelegateOfDeletion(completion: completion) } }
5298944902bd8d5e1d530de5befa2324
38.880829
132
0.706379
false
false
false
false
Dwarven/ShadowsocksX-NG
refs/heads/develop
MoyaRefreshToken/Pods/RxSwift/RxSwift/Observables/Deferred.swift
apache-2.0
4
// // Deferred.swift // RxSwift // // Created by Krunoslav Zaher on 4/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ public static func deferred(_ observableFactory: @escaping () throws -> Observable<E>) -> Observable<E> { return Deferred(observableFactory: observableFactory) } } final private class DeferredSink<S: ObservableType, O: ObserverType>: Sink<O>, ObserverType where S.E == O.E { typealias E = O.E private let _observableFactory: () throws -> S init(observableFactory: @escaping () throws -> S, observer: O, cancel: Cancelable) { self._observableFactory = observableFactory super.init(observer: observer, cancel: cancel) } func run() -> Disposable { do { let result = try self._observableFactory() return result.subscribe(self) } catch let e { self.forwardOn(.error(e)) self.dispose() return Disposables.create() } } func on(_ event: Event<E>) { self.forwardOn(event) switch event { case .next: break case .error: self.dispose() case .completed: self.dispose() } } } final private class Deferred<S: ObservableType>: Producer<S.E> { typealias Factory = () throws -> S private let _observableFactory : Factory init(observableFactory: @escaping Factory) { self._observableFactory = observableFactory } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { let sink = DeferredSink(observableFactory: self._observableFactory, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
2429848e24cce18e2589f1321de5ce58
31.72973
140
0.640793
false
false
false
false
tattn/SwiftRunner
refs/heads/master
Sources/SwiftProcess.swift
mit
1
// // SwiftProcess.swift // SwiftRunner // // Created by Tatsuya Tanaka on 2017/03/05. // // import Foundation import Result public class SwiftProcess { #if os(Linux) // see: http://stackoverflow.com/questions/39764801/how-to-use-process-in-swift-3-for-linux fileprivate let process = Task() #else fileprivate let process = Process() #endif fileprivate let pipes: (output: Pipe, error: Pipe) = (Pipe(), Pipe()) init(swiftPath: String = "/usr/bin/swift") { process.launchPath = swiftPath process.standardOutput = pipes.output process.standardError = pipes.error } public func launch(at path: URL) -> Result<StandardStream, SwiftRunnerError> { let absolutePath = path.absoluteString.replacingOccurrences(of: "file://", with: "") return launch(atFile: absolutePath) } public func launch(atFile path: String) -> Result<StandardStream, SwiftRunnerError> { process.arguments = ["run", path] process.launch() let outputData = pipes.output.fileHandleForReading.readDataToEndOfFile() let errorData = pipes.error.fileHandleForReading.readDataToEndOfFile() if let output = String(data: outputData, encoding: .utf8), let error = String(data: errorData, encoding: .utf8) { let stream = StandardStream(output: output, error: error) return .success(stream) } return .failure(SwiftRunnerError.unexpected) } }
dfab25387dc634ee7ac1ebf56516991f
28.88
95
0.658635
false
false
false
false
ewhitley/CDAKit
refs/heads/master
CDAKit/health-data-standards/lib/export/view_helper.swift
mit
1
// // view_helper.swift // CDAKit // // Created by Eric Whitley on 12/17/15. // Copyright © 2015 Eric Whitley. All rights reserved. // import Foundation class ViewHelper { //options = // {"tag_name"=>"value", "extra_content"=>"xsi:type=\"CD\"", "preferred_code_sets"=>["SNOMED-CT"]} // {"preferred_code_sets"=>["LOINC", "SNOMED-CT"]} // looks like the value of the dictionary can be a string or an array of values class func code_display(entry: CDAKEntry, var options:[String:Any] = [:]) -> String { if options["tag_name"] == nil { options["tag_name"] = "code" } if options["attribute"] == nil { options["attribute"] = "codes" } //note: original ruby uses :codes symbol var options_attribute: String = "" if let attr = options["attribute"] as? String { options_attribute = attr } var options_exclude_null_flavor = false if let opt = options["exclude_null_flavor"] as? Bool { options_exclude_null_flavor = opt } var code_string = "" //"nil" in original Ruby, but empty string works better for us //# allowing wild card matching of any code system for generic templates //# valueset filtering should filter out a decent code /* pcs will look like... ["LOINC", "SNOMED-CT"] */ var pcs: [String] = [] var preferred_code_sets : [String] = [] if let options = options["preferred_code_sets"] as? [String] { preferred_code_sets = options } if preferred_code_sets.count > 0 { if preferred_code_sets.contains("*") { //# all of the code_systems that we know about pcs = Array(Set(CDAKCodeSystemHelper.CODE_SYSTEMS.values).union(CDAKCodeSystemHelper.CODE_SYSTEM_ALIASES.keys)) // if options['preferred_code_sets'] && options['preferred_code_sets'].index("*") // options['preferred_code_sets'] can apparently take a wildcard "*" argument here // so we're saying "if we have code sets" - and if one of them is "wildcard" - give us everything // otherwise, only give us the preferred code sets we sent in //pcs = if options['preferred_code_sets'] && options['preferred_code_sets'].index("*") } else { pcs = preferred_code_sets } } var value_set_map: [CDAKCodedEntries] = [] if let vsm = options["value_set_map"] as? [CDAKCodedEntries] { value_set_map = vsm } let preferred_code = entry.preferred_code(pcs, codes_attribute: options_attribute, value_set_map: value_set_map) if let preferred_code = preferred_code { let pc = preferred_code.codeSystem let code_system_oid = CDAKCodeSystemHelper.oid_for_code_system(pc) let tag_name = options["tag_name"] as? String let code = preferred_code.code let extra_content = options["extra_content"] as? String let display = preferred_code.displayName != nil ? "displayName=\"\(preferred_code.displayName!)\"" : "" code_string = "<\(tag_name ?? "") code=\"\(code ?? "")\" codeSystemName=\"\(pc)\" codeSystem=\"\(code_system_oid ?? "")\" \(display) \(extra_content ?? "")>" } else { let tag_name = options["tag_name"] as? String let extra_content = options["extra_content"] as? String code_string = "<\(tag_name ?? "") " if !options_exclude_null_flavor { code_string += "nullFlavor=\"UNK\" " } code_string += "\(extra_content ?? "")>" } //if options["attribute"] == :codes && entry.respond_to?(:translation_codes) // we can't see if the method translation_codes is available, but... // the only class/protocol that uses this is ThingWithCodes, so we can test to see if // the entry is of type ThingWithCodes... but all entries at that, so.... if options_attribute == "codes" { code_string += "<originalText>\(CDAKCommonUtility.html_escape(entry.item_description))</originalText>" for (codeSystem, codes) in entry.translation_codes(preferred_code_sets, value_set_map: value_set_map) { for code in codes { let display = code.displayName != nil ? " displayName=\"\(code.displayName!)\"" : "" code_string += "<translation code=\"\(code.code)\" codeSystemName=\"\(codeSystem)\" codeSystem=\"\(CDAKCodeSystemHelper.oid_for_code_system(codeSystem))\"\(display)/>\n" } } } code_string += "</\(options["tag_name"]!)>" return code_string } class func status_code_for(entry: CDAKEntry) -> String? { if let status = entry.status { switch status.lowercaseString { case "active": return "55561003" case "inactive": return "73425007" case "resolved": return "413322009" default: return nil } } return nil } class func fulfillment_quantity(codes: CDAKCodedEntries, fulfillmentHistory: CDAKFulfillmentHistory, dose: CDAKValueAndUnit) -> String { if codes["RxNorm"]?.count > 0 { if let qty = fulfillmentHistory.quantity_dispensed.value, dose_value = dose.value { let doses = Int(qty / dose_value) return "value=\"\(doses)\"" } } let qty = fulfillmentHistory.quantity_dispensed.value != nil ? String(fulfillmentHistory.quantity_dispensed.value!) : "" let unit = fulfillmentHistory.quantity_dispensed.unit != nil ? String(fulfillmentHistory.quantity_dispensed.unit!) : "" return "value=\"\(qty)\" unit=\"\(unit)\"" } //take an Int representing time since 1970 -> format into date // using Ruby Time:: :number format ('%Y%m%d%H%M%S') // FIX_ME: - this isn't doing something right.. /* value_or_null_flavor(946702800) -> not right //Swift: 2000 12 31 23 00 00 //Ruby: "2000-01-01 05:00:00 +0000" value_or_null_flavor(-284061600) -> seems OK //Swift: 1960 12 31 00 00 00 //Ruby: 1960-12-31 00:00:00 -0600 */ class func value_or_null_flavor(time: Any?) -> String { if let time = time as? Double { //:number => '%Y%m%d%H%M%S' //return "value='#{Time.at(time).utc.to_formatted_s(:number)}'" let d = NSDate(timeIntervalSince1970: NSTimeInterval(time)) return "value=\"\(d.stringFormattedAsHDSDateNumber)\"" } else { return "nullFlavor='UNK'" } } class func dose_quantity(codes: CDAKCodedEntries, dose: [String:String]) -> String { if codes["RxNorm"]?.count > 0 { return "value = '1'" } else { let value = dose["value"] != nil ? dose["value"]! : "" let unit = dose["unit"] != nil ? dose["unit"]! : "" return "value=\"\(value)\" unit=\"\(unit)\"" } } class func time_if_not_nil(args: [Int?]?) -> NSDate? { if let args = args { return args.filter({$0 != nil}).map({t in NSDate(timeIntervalSince1970: NSTimeInterval(t!))}).first } else { return nil } } class func time_if_not_nil(args: Int?...) -> NSDate? { return args.filter({$0 != nil}).map({t in NSDate(timeIntervalSince1970: NSTimeInterval(t!))}).first } class func is_num(str: String?) -> Bool { if let str = str, _ = Double(str) { return true } return false } class func is_bool(str: String?) -> Bool { return ["true","false"].contains(str != nil ? str!.lowercaseString : "") } }
4f7e9c6914d47fce07315a3465a34389
37.795699
179
0.615939
false
false
false
false
asp2insp/CodePathFinalProject
refs/heads/master
Pretto/AddEventPhotoCell.swift
mit
1
// // AddEventPhotoCell.swift // Pretto // // Created by Francisco de la Pena on 6/14/15. // Copyright (c) 2015 Pretto. All rights reserved. // import UIKit @objc protocol AddEventPhotoCellDelegate { optional func addEventPhotoCell(addEventPhotoCell: AddEventPhotoCell, didTapOnEventPhoto photo: UIImageView) } class AddEventPhotoCell: UITableViewCell { @IBOutlet var eventPhoto: UIImageView! @IBOutlet var addPhotoLabel: UILabel! weak var delegate: AddEventPhotoCellDelegate? var eventImage: UIImage? { didSet { self.eventPhoto.image = eventImage self.eventPhoto.layer.borderWidth = 0 self.addPhotoLabel.hidden = true } } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCellSelectionStyle.None self.accessoryType = UITableViewCellAccessoryType.None addPhotoLabel.textColor = UIColor.prettoOrange() eventPhoto.userInteractionEnabled = true eventPhoto.layer.borderWidth = 1 eventPhoto.layer.borderColor = UIColor.lightGrayColor().CGColor eventPhoto.layer.cornerRadius = 35 eventPhoto.clipsToBounds = true eventPhoto.contentMode = UIViewContentMode.ScaleAspectFill var tapRecognizer = UITapGestureRecognizer(target: self, action: "didTapOnEventPhoto") eventPhoto.addGestureRecognizer(tapRecognizer) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func didTapOnEventPhoto() { delegate?.addEventPhotoCell!(self, didTapOnEventPhoto: self.eventPhoto) } }
34f29d1bd9989a7556fdd647ec2cbd94
29.035088
112
0.694509
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Frontend/Reader/ReaderMode.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import WebKit import SwiftyJSON let ReaderModeProfileKeyStyle = "readermode.style" enum ReaderModeMessageType: String { case StateChange = "ReaderModeStateChange" case PageEvent = "ReaderPageEvent" } enum ReaderPageEvent: String { case PageShow = "PageShow" } enum ReaderModeState: String { case Available = "Available" case Unavailable = "Unavailable" case Active = "Active" } enum ReaderModeTheme: String { case Light = "light" case Dark = "dark" case Sepia = "sepia" } enum ReaderModeFontType: String { case Serif = "serif" case SansSerif = "sans-serif" } enum ReaderModeFontSize: Int { case size1 = 1 case size2 = 2 case size3 = 3 case size4 = 4 case size5 = 5 case size6 = 6 case size7 = 7 case size8 = 8 case size9 = 9 case size10 = 10 case size11 = 11 case size12 = 12 case size13 = 13 func isSmallest() -> Bool { return self == ReaderModeFontSize.size1 } func smaller() -> ReaderModeFontSize { if isSmallest() { return self } else { return ReaderModeFontSize(rawValue: self.rawValue - 1)! } } func isLargest() -> Bool { return self == ReaderModeFontSize.size13 } static var defaultSize: ReaderModeFontSize { switch UIApplication.shared.preferredContentSizeCategory { case UIContentSizeCategory.extraSmall: return .size1 case UIContentSizeCategory.small: return .size3 case UIContentSizeCategory.medium: return .size5 case UIContentSizeCategory.large: return .size7 case UIContentSizeCategory.extraLarge: return .size9 case UIContentSizeCategory.extraExtraLarge: return .size11 case UIContentSizeCategory.extraExtraExtraLarge: return .size13 default: return .size5 } } func bigger() -> ReaderModeFontSize { if isLargest() { return self } else { return ReaderModeFontSize(rawValue: self.rawValue + 1)! } } } struct ReaderModeStyle { var theme: ReaderModeTheme var fontType: ReaderModeFontType var fontSize: ReaderModeFontSize /// Encode the style to a JSON dictionary that can be passed to ReaderMode.js func encode() -> String { return JSON(["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]).rawString(String.Encoding.utf8, options: [])! } /// Encode the style to a dictionary that can be stored in the profile func encodeAsDictionary() -> [String:Any] { return ["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue] } init(theme: ReaderModeTheme, fontType: ReaderModeFontType, fontSize: ReaderModeFontSize) { self.theme = theme self.fontType = fontType self.fontSize = fontSize } /// Initialize the style from a dictionary, taken from the profile. Returns nil if the object cannot be decoded. init?(dict: [String:Any]) { let themeRawValue = dict["theme"] as? String let fontTypeRawValue = dict["fontType"] as? String let fontSizeRawValue = dict["fontSize"] as? Int if themeRawValue == nil || fontTypeRawValue == nil || fontSizeRawValue == nil { return nil } let theme = ReaderModeTheme(rawValue: themeRawValue!) let fontType = ReaderModeFontType(rawValue: fontTypeRawValue!) let fontSize = ReaderModeFontSize(rawValue: fontSizeRawValue!) if theme == nil || fontType == nil || fontSize == nil { return nil } self.theme = theme! self.fontType = fontType! self.fontSize = fontSize! } } let DefaultReaderModeStyle = ReaderModeStyle(theme: .Light, fontType: .SansSerif, fontSize: ReaderModeFontSize.defaultSize) /// This struct captures the response from the Readability.js code. struct ReadabilityResult { var domain = "" var url = "" var content = "" var title = "" var credits = "" init?(object: AnyObject?) { if let dict = object as? NSDictionary { if let uri = dict["uri"] as? NSDictionary { if let url = uri["spec"] as? String { self.url = url } if let host = uri["host"] as? String { self.domain = host } } if let content = dict["content"] as? String { self.content = content } if let title = dict["title"] as? String { self.title = title } if let credits = dict["byline"] as? String { self.credits = credits } } else { return nil } } /// Initialize from a JSON encoded string init?(string: String) { let object = JSON(parseJSON: string) let domain = object["domain"].string let url = object["url"].string let content = object["content"].string let title = object["title"].string let credits = object["credits"].string if domain == nil || url == nil || content == nil || title == nil || credits == nil { return nil } self.domain = domain! self.url = url! self.content = content! self.title = title! self.credits = credits! } /// Encode to a dictionary, which can then for example be json encoded func encode() -> [String: Any] { return ["domain": domain as AnyObject, "url": url as AnyObject, "content": content as AnyObject, "title": title as AnyObject, "credits": credits as AnyObject] } /// Encode to a JSON encoded string func encode() -> String { return JSON(encode() as [String:Any]).rawString(String.Encoding.utf8, options: [])! } } /// Delegate that contains callbacks that we have added on top of the built-in WKWebViewDelegate protocol ReaderModeDelegate { func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab) func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab) } let ReaderModeNamespace = "_firefox_ReaderMode" class ReaderMode: TabHelper { var delegate: ReaderModeDelegate? fileprivate weak var tab: Tab? var state: ReaderModeState = ReaderModeState.Unavailable fileprivate var originalURL: URL? class func name() -> String { return "ReaderMode" } required init(tab: Tab) { self.tab = tab // This is a WKUserScript at the moment because webView.evaluateJavaScript() fails with an unspecified error. Possibly script size related. if let path = Bundle.main.path(forResource: "Readability", ofType: "js") { if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } // This is executed after a page has been loaded. It executes Readability and then fires a script message to let us know if the page is compatible with reader mode. if let path = Bundle.main.path(forResource: "ReaderMode", ofType: "js") { if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } } func scriptMessageHandlerName() -> String? { return "readerModeMessageHandler" } fileprivate func handleReaderPageEvent(_ readerPageEvent: ReaderPageEvent) { switch readerPageEvent { case .PageShow: if let tab = tab { delegate?.readerMode(self, didDisplayReaderizedContentForTab: tab) } } } fileprivate func handleReaderModeStateChange(_ state: ReaderModeState) { self.state = state delegate?.readerMode(self, didChangeReaderModeState: state, forTab: tab!) } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let msg = message.body as? Dictionary<String,String> { if let messageType = ReaderModeMessageType(rawValue: msg["Type"] ?? "") { switch messageType { case .PageEvent: if let readerPageEvent = ReaderPageEvent(rawValue: msg["Value"] ?? "Invalid") { handleReaderPageEvent(readerPageEvent) } break case .StateChange: if let readerModeState = ReaderModeState(rawValue: msg["Value"] ?? "Invalid") { handleReaderModeStateChange(readerModeState) } break } } } } var style: ReaderModeStyle = DefaultReaderModeStyle { didSet { if state == ReaderModeState.Active { tab!.webView?.evaluateJavaScript("\(ReaderModeNamespace).setStyle(\(style.encode()))", completionHandler: { (object, error) -> Void in return }) } } } }
190e549d5c8bf191470e89b86dc543cb
33.238908
172
0.61264
false
false
false
false
PrashantMangukiya/SwiftSimpleTaskList
refs/heads/master
Source-Xcode6/SwiftSimpleTaskList/SwiftSimpleTaskList/TaskAddViewController.swift
mit
1
// // TaskAddViewController.swift // SwiftSimpleTaskList // // Created by Prashant on 04/09/15. // Copyright (c) 2015 PrashantKumar Mangukiya. All rights reserved. // import UIKit import CoreData // Define global array for color , used within view controller whenever need var ARRAY_COLOR_LIST_TITLE: [String] = ["(( Choose Color ))", "Red", "Green", "Blue", "Yellow", "Pink", "Black"] var ARRAY_COLOR_LIST_VALUE: [String] = ["#FFFFFF", "#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF80BF", "#000000"] // define protocol for task function protocol TaskDelegate { // for new task added, newly added task object passed func taskDidAdd(newTask: Task) // for task updated, updated task object passed func taskDidUpdate(updatedTask: Task) } class TaskAddViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate { // task delegate variable var taskDelegate : TaskDelegate? // define color list array (used to fillup colorPicker) var colorListTitle: [String] = ARRAY_COLOR_LIST_TITLE var colorListValue: [String] = ARRAY_COLOR_LIST_VALUE // outlet and action - Cancel button @IBOutlet var cancelButton: UIBarButtonItem! @IBAction func cancelButtonClicked(sender: UIBarButtonItem) { self.goBack() } // outlet and action - Save button button @IBOutlet var saveButton: UIBarButtonItem! @IBAction func saveButtonClicked(sender: UIBarButtonItem) { self.saveRecord() } // outlet - task title @IBOutlet var taskTitle: UITextField! @IBAction func taskTitleEditingChanged(sender: UITextField) { self.validateInputData() } // outlet - colorPickerView @IBOutlet var colorPicker: UIPickerView! // outlet - task color preview circle @IBOutlet var colorPreview: UIView! // task color that stores color in hex var taskColor: String? { didSet{ // set preview color whenever taskColor value change self.colorPreview?.backgroundColor = UtilityManager.sharedInstance.convertHexToUIColor(hexColor: self.taskColor!) } } // MARK: - View functions override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // setup initial view self.setupInitialView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Textfield delegate // remove editing mode from text box and close keyboard when touched anywhere on a screen override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { self.view.endEditing(true) } func textFieldDidEndEditing(textField: UITextField) { self.validateInputData() } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false } // MARK: UIPicker View Delegate func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.colorListTitle.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return self.colorListTitle[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // close keyboard if open self.view.endEditing(true) // set task color self.taskColor = self.colorListValue[row] // if input not valid then disable save button. self.validateInputData() } // MARK: Utility function // setup initial view private func setupInitialView(){ // set text field delegate self.taskTitle.delegate = self // set colorPicker delegate and dataSource self.colorPicker.dataSource = self self.colorPicker.delegate = self // make color preview box circle self.colorPreview.layer.cornerRadius = self.colorPreview.frame.width/2 // set default value for colorPicker and task color self.taskColor = "#FFFFFF" // set white self.colorPicker.selectRow(0, inComponent: 0, animated: true) // select first row // disable save button if not valid input self.validateInputData() } // validate input data. // i.e. disable save button if task title and task color value not set. private func validateInputData() { var isValidData: Bool = true if self.taskTitle.text == "" { isValidData = false }else if self.taskColor == "" || self.taskColor == "#FFFFFF" { isValidData = false } if isValidData { self.saveButton.enabled = true }else{ self.saveButton.enabled = false } } // add record to core database and go to back screen private func saveRecord(){ // Step 1: get managed object context let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedObjectContext = appDelegate.managedObjectContext! // Step 2: Create entity for table let entityTask = NSEntityDescription.entityForName("Task", inManagedObjectContext: managedObjectContext) // Step 3: create empty Task record let taskRecord = Task(entity: entityTask!, insertIntoManagedObjectContext: managedObjectContext ) // Step 4: Set value within empty record taskRecord.title = self.taskTitle.text taskRecord.color = self.taskColor! taskRecord.dateAdded = NSDate() // i.e. current date // Step 5: Save data into database var error: NSError? managedObjectContext.save(&error) // Step 6: Show error if generated during save operation if let err = error { // show custom error message to user self.showAlertMessage(alertTitle: "Save Error", alertMessage: "Error while save, please try again.") }else{ // call task delegate function self.taskDelegate?.taskDidAdd(taskRecord) // Go to back screen self.goBack() } } // go to back scren private func goBack(){ self.navigationController?.popViewControllerAnimated(true) } // show alert message with OK button private func showAlertMessage( #alertTitle: String, alertMessage: String) { let myAlertVC = UIAlertController( title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) myAlertVC.addAction(okAction) self.presentViewController(myAlertVC, animated: true, completion: nil) } }
4e3a350eb3dc7ad0d3b1cfb8efb2826b
30.508621
130
0.633653
false
false
false
false
tomichj/dotfiles
refs/heads/master
bin/scres.swift
mit
1
#!/usr/bin/env xcrun -sdk macosx swift // // x2.swift // // // Created by john on 20/1/2020. // import Foundation import ApplicationServices import CoreVideo import OSAKit import IOKit class DisplayManager { let displayID:CGDirectDisplayID, displayInfo:[DisplayInfo], modes:[CGDisplayMode], modeIndex:Int init(_ _displayID:CGDirectDisplayID) { displayID = _displayID var modesArray:[CGDisplayMode]? if let modeList = CGDisplayCopyAllDisplayModes(displayID, [kCGDisplayShowDuplicateLowResolutionModes:kCFBooleanTrue] as CFDictionary) { modesArray = (modeList as! Array).filter { ($0 as CGDisplayMode).isUsableForDesktopGUI() } } else { print("Unable to get display modes") } modes = modesArray! displayInfo = modes.map { DisplayInfo(displayID:_displayID, mode:$0) } let mode = CGDisplayCopyDisplayMode(displayID)! modeIndex = modes.firstIndex(of:mode)! } private func _format(_ di:DisplayInfo, leadingString:String, trailingString:String) -> String { // We assume that 5 digits are enough to hold dimensions. // 100K monitor users will just have to live with a bit of formatting misalignment. return String( format:" %@ %5d x %4d @ %dx @ %dHz%@", leadingString, di.width, di.height, di.scale, di.frequency, trailingString ) } func printForOneDisplay(_ leadingString:String) { print(_format(displayInfo[modeIndex], leadingString:leadingString, trailingString:"")) } func printFormatForAllModes() { var i = 0 displayInfo.forEach { di in let bool = i == modeIndex print(_format(di, leadingString: bool ? "\u{001B}[0;33m⮕" : " ", trailingString: bool ? "\u{001B}[0;49m" : "")) i += 1 } } private func _set(_ mi:Int) { let mode:CGDisplayMode = modes[mi] print("Setting display mode") var config:CGDisplayConfigRef? let error:CGError = CGBeginDisplayConfiguration(&config) if error == .success { CGConfigureDisplayWithDisplayMode(config, displayID, mode, nil) let afterCheck = CGCompleteDisplayConfiguration(config, CGConfigureOption.permanently) if afterCheck != .success { CGCancelDisplayConfiguration(config) } } } func set(with setting: DisplayUserSetting) { if let mi = displayInfo.firstIndex(where: { setting ~= $0 }) { if mi != modeIndex { _set(mi) } } else { print("This mode is unavailable") } } } // return width, height and frequency info for corresponding displayID struct DisplayInfo { static let MAX_SCALE = 10 var width, height, scale, frequency:Int init(displayID:CGDirectDisplayID, mode:CGDisplayMode) { width = mode.width height = mode.height scale = mode.pixelWidth / mode.width; frequency = Int( mode.refreshRate ) if frequency == 0 { var link:CVDisplayLink? CVDisplayLinkCreateWithCGDisplay(displayID, &link) let time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link!) // timeValue is in fact already in Int64 let timeScale = Int64(time.timeScale) + time.timeValue / 2 frequency = Int( timeScale / time.timeValue ) } } static func ~= (lhs: Self, rhs: DisplayUserSetting) -> Bool { return rhs ~= lhs } } // Supported command calls: // 1 width => 2 // 2 id, width // 3 width, scale => 6 // 4 width, height => 5 // 5 id, width, height // 6 id, width, scale // 7 id, width, height, scale struct DisplayUserSetting { var displayIndex = 0, width = 0 var height, scale:Int? init(_ arr:[String]) { var args = arr.compactMap { Int($0) } if args.count < 1 { return } if args[0] > Screens.MAX_DISPLAYS { args.insert(0 /* displayIndex */, at:0) } if args.count < 2 { return } displayIndex = args[0] width = args[1] if args.count == 2 { return } if args[2] > DisplayInfo.MAX_SCALE { height = args[2] if args.count > 3 { scale = args[3] } } else { scale = args[2] if args.count > 3 { height = args[3] } } } // override a lesser-used operator to simplify diplay mode checks static func ~= (lhs: Self, rhs: DisplayInfo) -> Bool { var bool = lhs.width == rhs.width if lhs.height != nil { bool = bool && lhs.height == rhs.height } if lhs.scale != nil { bool = bool && lhs.scale == rhs.scale } return bool } } class Screens { // assume at most 8 display connected static let MAX_DISPLAYS = 8 var maxDisplays = MAX_DISPLAYS // actual number of display var displayCount:Int = 0 var dm = [DisplayManager]() init() { // actual number of display var displayCount32:UInt32 = 0 var displayIDs = [CGDirectDisplayID](arrayLiteral: 0) guard CGGetOnlineDisplayList(UInt32(maxDisplays), &displayIDs, &displayCount32) == .success else { print("Error on getting online display List.") return } displayCount = Int( displayCount32 ) dm = displayIDs.map { DisplayManager($0) } } // print a list of all displays // used by -l func listDisplays() { for (i, m) in dm.enumerated() { m.printForOneDisplay("Display \(i):") } } func listModes(_ displayIndex:Int) { dm[displayIndex].printFormatForAllModes() } func set(with setting:DisplayUserSetting) { dm[setting.displayIndex].set(with:setting) } } // darkMode toggle code with JXA ;-) // Method from Stackoverflow User: bacongravy // https://stackoverflow.com/questions/44209057 struct DarkMode { static let scriptString = """ pref = Application(\"System Events\").appearancePreferences pref.darkMode = !pref.darkMode() """ let script = OSAScript.init(source: scriptString, language: OSALanguage.init(forName: "JavaScript")) init() { var compileError: NSDictionary? script.compileAndReturnError(&compileError) } func toggle() { var scriptError: NSDictionary? if let result = script.executeAndReturnError(&scriptError)?.stringValue { print("Dark Mode:", result) } } } func sleepDisplay() { let r = IORegistryEntryFromPath(kIOMasterPortDefault, strdup("IOService:/IOResources/IODisplayWrangler")) IORegistryEntrySetCFProperty(r, ("IORequestIdle" as CFString), kCFBooleanTrue) IOObjectRelease(r) } func seeHelp() { print(""" Usage: screen-resolution-switcher [-h|--help] [-l|--list|list] [-m|--mode|mode displayIndex] [-s|--set|set displayIndex width scale] [-r|--set-retina|retina displayIndex width], Here are some examples: -h get help -l list displays -m 0 list all mode from a certain display -m shorthand for -m 0 -s 0 800 600 1 set resolution of display 0 to 800 x 600 @ 1x [@ 60Hz] -s 0 800 600 set resolution of display 0 to 800 x 600 @(highest scale factor) -s 0 800 1 set resolution of display 0 to 800 [x 600] @ 1x [@ 60Hz] -s 0 800 shorthand for -s 0 800 2 (highest scale factor) -s 800 shorthand for -s 0 800 2 (highest scale factor) -r 0 800 shorthand for -s 0 800 2 -r 800 shorthand for -s 0 800 2 -d toggle macOS Dark Mode -sl sleep display """) } func main() { let screens = Screens() let arguments = CommandLine.arguments let count = arguments.count guard count >= 2 else { seeHelp() return } switch arguments[1] { case "-l", "--list", "list": screens.listDisplays() case "-m", "--mode", "mode": var displayIndex = 0 if count > 2, let index = Int(arguments[2]) { displayIndex = index } if displayIndex < screens.displayCount { print("Supported Modes for Display \(displayIndex):") screens.listModes(displayIndex) } else { print("Display index not found. List all available displays by:\n screen-resolution-switcher -l") } case "-s", "--set", "set", "-r", "--set-retina", "retina": screens.set(with:DisplayUserSetting( arguments )) case "-d", "--toggle-dark-mode": DarkMode().toggle() case "-sl", "--sleep", "sleep": sleepDisplay() default: seeHelp() } } #if os(macOS) // run it main() #else print("This script currently only runs on macOS") #endif
837a034b97162941ee94aada2f3b3e77
30.097222
143
0.59301
false
false
false
false
MetalPetal/MetalPetal
refs/heads/master
MetalPetalExamples/Shared/MetalKitView.swift
mit
1
// // MetalKitView.swift // MetalPetalDemo // // Created by YuAo on 2021/4/3. // import Foundation import SwiftUI import MetalKit import MetalPetal #if os(iOS) fileprivate typealias ViewRepresentable = UIViewRepresentable #elseif os(macOS) fileprivate typealias ViewRepresentable = NSViewRepresentable #endif struct MetalKitView: ViewRepresentable { typealias ViewUpdater = (MTKView) -> Void private let viewUpdater: ViewUpdater private let device: MTLDevice init(device: MTLDevice, viewUpdater: @escaping ViewUpdater) { self.viewUpdater = viewUpdater self.device = device } func makeUIView(context: Context) -> MTKView { let mtkView = MTKView(frame: .zero, device: device) mtkView.delegate = context.coordinator mtkView.autoResizeDrawable = true mtkView.colorPixelFormat = .bgra8Unorm return mtkView } func updateUIView(_ uiView: MTKView, context: Context) { } func makeNSView(context: Context) -> MTKView { makeUIView(context: context) } func updateNSView(_ nsView: MTKView, context: Context) { updateUIView(nsView, context: context) } func makeCoordinator() -> Coordinator { Coordinator(viewUpdater: self.viewUpdater) } class Coordinator: NSObject, MTKViewDelegate { private let viewUpdater: ViewUpdater init(viewUpdater: @escaping ViewUpdater) { self.viewUpdater = viewUpdater } func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { } func draw(in view: MTKView) { viewUpdater(view) } } }
867cc889051bc6f9deb22c23067dd240
23.742857
76
0.639723
false
false
false
false
HTWDD/HTWDresden-iOS
refs/heads/master
HTWDD/Core/Extensions/UIView.swift
gpl-2.0
1
// // UIView.swift // HTWDD // // Created by Benjamin Herzog on 01.11.17. // Copyright © 2017 HTW Dresden. All rights reserved. // import UIKit extension UIView { var width: CGFloat { get { return self.bounds.size.width } set { self.bounds.size.width = newValue } } var height: CGFloat { get { return self.bounds.size.height } set { self.bounds.size.height = newValue } } var top: CGFloat { get { return self.frame.origin.y } set { self.frame.origin.y = newValue } } var bottom: CGFloat { get { return self.top + self.height } set { self.top = newValue - self.height } } var left: CGFloat { get { return self.frame.origin.x } set { self.frame.origin.x = newValue } } var right: CGFloat { get { return self.left + self.width } set { self.left = newValue - self.width } } func add(_ views: UIView..., transform: ((UIView) -> Void)? = nil) { views.forEach { self.addSubview($0) transform?($0) } } func layoutMatchingEdges(_ view: UIView?) { guard let view = view else { return } view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ view.leadingAnchor.constraint(equalTo: self.leadingAnchor), view.topAnchor.constraint(equalTo: self.htw.safeAreaLayoutGuide.topAnchor), view.trailingAnchor.constraint(equalTo: self.trailingAnchor), view.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) } } extension HTWNamespace where Base: UIView { var safeAreaInsets: UIEdgeInsets { if #available(iOS 11.0, *) { return self.base.safeAreaInsets } return .zero } var safeAreaLayoutGuide: LayoutGuide { if #available(iOS 11.0, *) { return self.base.safeAreaLayoutGuide } return self.base } } // MARK: - Confetti extension UIView { // https://github.com/sudeepag/SAConfettiView /// Emits confetti over the entire view for the given duration. func emitConfetti(duration: Double) { let colors = [UIColor(red: 0.95, green: 0.40, blue: 0.27, alpha: 1.0), UIColor(red: 1.00, green: 0.78, blue: 0.36, alpha: 1.0), UIColor(red: 0.48, green: 0.78, blue: 0.64, alpha: 1.0), UIColor(red: 0.30, green: 0.76, blue: 0.85, alpha: 1.0), UIColor(red: 0.58, green: 0.39, blue: 0.55, alpha: 1.0)] let emitter = CAEmitterLayer() emitter.emitterPosition = CGPoint(x: frame.size.width / 2.0, y: 0) emitter.emitterShape = CAEmitterLayerEmitterShape.line emitter.emitterSize = CGSize(width: frame.size.width, height: 1) emitter.beginTime = CACurrentMediaTime() var cells = [CAEmitterCell]() for color in colors { cells.append(confettiWithColor(color: color)) } emitter.emitterCells = cells layer.addSublayer(emitter) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) { emitter.birthRate = 0 } } } fileprivate func confettiWithColor(color: UIColor, intensity: CGFloat = 0.5) -> CAEmitterCell { let image = UIImage(named: "confetti.png") let confetti = CAEmitterCell() confetti.birthRate = Float(CGFloat(6.0 * intensity)) confetti.lifetime = Float(CGFloat(14.0 * intensity)) confetti.lifetimeRange = 0 confetti.color = color.cgColor confetti.velocity = CGFloat(350.0 * intensity) confetti.velocityRange = CGFloat(80.0 * intensity) confetti.emissionLongitude = CGFloat(Double.pi) confetti.emissionRange = CGFloat((Double.pi / 4)) confetti.spin = CGFloat(3.5 * intensity) confetti.spinRange = CGFloat(4.0 * intensity) confetti.scaleRange = CGFloat(intensity) confetti.scaleSpeed = CGFloat(-0.1 * intensity) confetti.contents = image?.cgImage return confetti } // MARK: - Dropshadow extension UIView { func dropShadow(scale: Bool = true) { layer.apply { $0.masksToBounds = false $0.shadowColor = UIColor.htw.shadow.cgColor $0.shadowOpacity = 0.35 $0.shadowOffset = .zero $0.shadowRadius = 3 $0.shouldRasterize = true $0.rasterizationScale = scale ? UIScreen.main.scale : 1 } } func removeDropShdow() { layer.shadowRadius = 0 } @IBInspectable var hasDropShadow: Bool { get { return layer.shadowRadius > 0 } set { if newValue { dropShadow() } else { removeDropShdow() } } } } // MARK: - CA Layers extension CALayer { func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) { let border = CALayer() switch edge { case .left: border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height) case .top: border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness) case .right: border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height) case .bottom: border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness) default: break } border.backgroundColor = color.cgColor addSublayer(border) } }
f318ec6005d2bbf38d624f46e140e7a7
28.699454
107
0.6092
false
false
false
false
sstanic/VirtualTourist
refs/heads/master
VirtualTourist/VirtualTourist/MapViewController.swift
mit
1
// // MapViewController.swift // VirtualTourist // // Created by Sascha Stanic on 06.06.16. // Copyright © 2016 Sascha Stanic. All rights reserved. // import UIKit import MapKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class MapViewController: UIViewController, MKMapViewDelegate { //# MARK: Outlets @IBOutlet weak var mapView: MKMapView! //# MARK: Attributes var newMapItem: MapItem? //# MARK: Overrides override func viewDidLoad() { super.viewDidLoad() initializeMap() initializePins() } override func viewWillAppear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = true } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = false } //# MARK: - Initialize fileprivate func initializeMap() { mapView.delegate = self let gestureRecognizerLongPress = UILongPressGestureRecognizer(target: self, action: #selector(createNewPin)) gestureRecognizerLongPress.minimumPressDuration = 0.5 mapView.addGestureRecognizer(gestureRecognizerLongPress) // init region let latitude = UserDefaults.standard.double(forKey: Constants.MapLatitude) let longitude = UserDefaults.standard.double(forKey: Constants.MapLongitude) let latitudeDelta = UserDefaults.standard.double(forKey: Constants.MapLatitudeDelta) let longitudeDelta = UserDefaults.standard.double(forKey: Constants.MapLongitudeDelta) let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let coordinateSpan = MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta) let region = MKCoordinateRegionMake(location, coordinateSpan) mapView.setRegion(region, animated: true) } fileprivate func initializePins() { DataStore.sharedInstance().loadPins() { (success, error) in if !success { print(error as Any) Utils.showAlert(self, alertMessage: "An error occured while loading map data from the data base.", completion: nil) } } for pin in DataStore.sharedInstance().pins { let location = CLLocationCoordinate2D(latitude: Double(pin.latitude!), longitude: Double(pin.longitude!)) let mapItem = MapItem(title: pin.title!, location: location) mapItem.pin = pin mapView.addAnnotation(mapItem) } } //# MARK: - Pin, Image, Geocode @objc func createNewPin(_ gestureRecognizer: UILongPressGestureRecognizer) { var touchPoint: CGPoint = gestureRecognizer.location(in: mapView) var touchMapCoordinate: CLLocationCoordinate2D = mapView.convert(touchPoint, toCoordinateFrom: mapView) switch gestureRecognizer.state { case .began: newMapItem = MapItem(title: "<...>", location: touchMapCoordinate) mapView.addAnnotation(newMapItem!) case .ended: geocodeMapItem(newMapItem!) { (success, error) in if success { let pin = DataStore.sharedInstance().createPin(touchMapCoordinate.latitude, longitude: touchMapCoordinate.longitude, title: self.newMapItem!.title!) self.newMapItem!.pin = pin self.showImages(pin) } else { print(error as Any) Utils.showAlert(self, alertMessage: "An error occured while creating a new pin.", completion: nil) } } case .changed: touchPoint = gestureRecognizer.location(in: mapView) touchMapCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView) mapView.removeAnnotation(newMapItem!) newMapItem = MapItem(title: ".", location: touchMapCoordinate) mapView.addAnnotation(newMapItem!) default: break } } fileprivate func showImages(_ pin: Pin) { let photoAlbumViewController = self.storyboard!.instantiateViewController(withIdentifier: "photoAlbumViewController") as! PhotoAlbumViewController photoAlbumViewController.pin = pin navigationController?.pushViewController(photoAlbumViewController, animated: true) } fileprivate func geocodeMapItem(_ mapItem: MapItem, geocodeCompletionHandler: @escaping (_ success: Bool, _ error: NSError?) -> Void) { var address = "" let location = CLLocation(latitude: mapItem.coordinate.latitude, longitude: mapItem.coordinate.longitude) CLGeocoder().reverseGeocodeLocation(location) { (placemark, error) in if error != nil { mapItem.title = "<unknown>" geocodeCompletionHandler(false, error! as NSError) return } else { if (placemark?.count > 0) { for al in placemark?.first!.addressDictionary?["FormattedAddressLines"] as! NSArray { if address == "" { address = address + (al as! String) } else { address = (address + " -- ") + (al as! String) } } } } mapItem.title = address geocodeCompletionHandler(true, nil) } } //# MARK: - MKMapViewDelegate func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } let identifier = "pin" var view: MKPinAnnotationView if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView { dequeuedView.annotation = annotation view = dequeuedView } else { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) view.canShowCallout = true view.calloutOffset = CGPoint(x: -5, y: 5) let btn = UIButton(type: .detailDisclosure) view.rightCalloutAccessoryView = btn as UIView view.isDraggable = true } return view } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { if let mapItem = view.annotation as? MapItem { if let pin = mapItem.pin { showImages(pin) } } } } //Remark: Removed navigation on click to be able to drag and drop the pin // func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { // if let mapItem = view.annotation as? MapItem { // if let pin = mapItem.pin { // showImages(pin) // } // } // } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { if newState == MKAnnotationViewDragState.ending { if let mapItem = view.annotation as? MapItem { Utils.GlobalBackgroundQueue.async { self.geocodeMapItem(mapItem) { (success, error) in if success { let pin = mapItem.pin pin?.latitude = mapItem.coordinate.latitude as NSNumber pin?.longitude = mapItem.coordinate.longitude as NSNumber pin?.title = mapItem.title pin?.imageSet = 1 DataStore.sharedInstance().loadImagesAfterPinMoved(pin!) { (success, results, error) in if !success { print(error as Any) Utils.showAlert(self, alertMessage: "An error occured while trying to load new images.", completion: nil) } } } else { print(error as Any) Utils.showAlert(self, alertMessage: "An error occured while dragging the map pin.", completion: nil) } } } } } } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { UserDefaults.standard.set(mapView.region.center.latitude, forKey: Constants.MapLatitude) UserDefaults.standard.set(mapView.region.center.longitude, forKey: Constants.MapLongitude) UserDefaults.standard.set(mapView.region.span.latitudeDelta, forKey: Constants.MapLatitudeDelta) UserDefaults.standard.set(mapView.region.span.longitudeDelta, forKey: Constants.MapLongitudeDelta) } }
c36b5252dc598805a9d807b63b8135e9
36.129496
176
0.570626
false
false
false
false
amraboelela/swift
refs/heads/master
test/SILOptimizer/existential_transform.swift
apache-2.0
3
// RUN: %target-swift-frontend -O -sil-existential-specializer -Xllvm -sil-disable-pass=GenericSpecializer -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xllvm -sil-disable-pass=SILCombine -emit-sil -sil-verify-all %s | %FileCheck %s internal protocol SomeProtocol : class { func foo() -> Int } internal class SomeClass: SomeProtocol { init() { } @inline(never) func foo() -> Int { return 10 } } @inline(never) internal func wrap_foo_cp(a:SomeProtocol ) -> Int{ return a.foo() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform2cpyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: alloc_ref // CHECK: debug_value // CHECK: init_existential_ref // CHECK: debug_value // CHECK: function_ref @$s21existential_transform11wrap_foo_cp1aSiAA12SomeProtocol_p_tFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : SomeProtocol> (@guaranteed τ_0_0) -> Int // CHECK: open_existential_ref // CHECK: apply // CHECK: set_deallocating // CHECK: debug_value // CHECK: debug_value // CHECK: dealloc_ref // CHECK: dealloc_ref // CHECK: tuple // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform2cpyyF' @inline(never) func cp() { let magic1:SomeProtocol = SomeClass() let _ = wrap_foo_cp(a:magic1) } /// Non Class Protocol internal protocol SomeNoClassProtocol { func foo() -> Int } internal class SomeNoClass: SomeNoClassProtocol { init() { } @inline(never) func foo() -> Int { return 10 } } @inline(never) internal func wrap_foo_ncp(a:SomeNoClassProtocol) -> Int{ return a.foo() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform3ncpyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: alloc_stack // CHECK: alloc_ref $SomeNoClass // CHECK: debug_value // CHECK: init_existential_addr // CHECK: store // CHECK: function_ref @$s21existential_transform12wrap_foo_ncp1aSiAA19SomeNoClassProtocol_p_tFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : SomeNoClassProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: open_existential_addr // CHECK: apply // CHECK: destroy_addr // CHECK: dealloc_stack // CHECK: tuple // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform3ncpyyF' @inline(never) func ncp() { let magic2:SomeNoClassProtocol = SomeNoClass() let _ = wrap_foo_ncp(a:magic2) } /// Class Protocol Composition internal protocol SomeClassProtocolComp : class { func foo() -> Int } internal protocol SomeOtherClassProtocolComp : class { func bar() -> Int } internal class SomeClassComp: SomeClassProtocolComp, SomeOtherClassProtocolComp { init() { } @inline(never) func foo() -> Int { return 10 } @inline(never) func bar() -> Int { return 20 } } @inline(never) internal func wrap_foo_bar_cpc(a:SomeClassProtocolComp & SomeOtherClassProtocolComp) -> Int{ return a.foo() + a.bar() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform3cpcyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: alloc_ref // CHECK: debug_value // CHECK: init_existential_ref // CHECK: debug_value // CHECK: function_ref @$s21existential_transform16wrap_foo_bar_cpc1aSiAA21SomeClassProtocolComp_AA0g5OtherhiJ0p_tFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : SomeClassProtocolComp, τ_0_0 : SomeOtherClassProtocolComp> (@guaranteed τ_0_0) -> Int // CHECK: open_existential_ref // CHECK: apply // CHECK: set_deallocating // CHECK: debug_value // CHECK: debug_value // CHECK: dealloc_ref // CHECK: dealloc_ref // CHECK: tuple // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform3cpcyyF' @inline(never) func cpc() { let magic3:SomeClassProtocolComp & SomeOtherClassProtocolComp = SomeClassComp() let _ = wrap_foo_bar_cpc(a:magic3) } /// Non Class Protocol Comp internal protocol SomeNoClassProtocolComp { func foo() -> Int } internal protocol SomeOtherNoClassProtocolComp { func bar() -> Int } internal class SomeNoClassComp: SomeNoClassProtocolComp, SomeOtherNoClassProtocolComp { init() { } @inline(never) func foo() -> Int { return 10 } @inline(never) func bar() -> Int { return 20 } } @inline(never) internal func wrap_no_foo_bar_comp_ncpc(a:SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp) -> Int{ return a.foo() + a.bar() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform4ncpcyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: alloc_stack // CHECK: alloc_ref // CHECK: debug_value // CHECK: init_existential_addr // CHECK: store // CHECK: function_ref @$s21existential_transform25wrap_no_foo_bar_comp_ncpc1aSiAA23SomeNoClassProtocolComp_AA0i5OtherjklM0p_tFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : SomeNoClassProtocolComp, τ_0_0 : SomeOtherNoClassProtocolComp> (@in_guaranteed τ_0_0) -> Int // CHECK: open_existential_addr // CHECK: apply // CHECK: destroy_addr // CHECK: dealloc_stack // CHECK: tuple // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform4ncpcyyF' @inline(never) func ncpc() { let magic4:SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp = SomeNoClassComp() let _ = wrap_no_foo_bar_comp_ncpc(a:magic4) } internal protocol P : class { func foo() -> Int } internal class K : P { init() { } @inline(never) func foo() -> Int { return 10 } } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform18do_not_optimize_cp1aSiAA1P_p_tF : $@convention(thin) (@guaranteed P) -> Int { // CHECK: bb0(%0 : $P): // CHECK: debug_value // CHECK: [[O1:%.*]] = open_existential_ref // CHECK: witness_method $@opened("{{.*}}") P, #P.foo!1 : <Self where Self : P> (Self) -> () -> Int, [[O1]] : $@opened("{{.*}}") P : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@guaranteed τ_0_0) -> Int // CHECK: apply // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform18do_not_optimize_cp1aSiAA1P_p_tF' @inline(never) internal func do_not_optimize_cp(a:P ) -> Int{ return a.foo() } internal protocol PP : class { func foo() -> Int } internal class KK : PP { init() { } @inline(never) func foo() -> Int { return 10 } } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform13wrap_inout_cp1aSiAA2PP_pz_tF : $@convention(thin) (@inout PP) -> Int { // CHECK: bb0(%0 : $*PP): // CHECK: debug_value_addr // CHECK: load // CHECK: [[O1:%.*]] = open_existential_ref // CHECK: witness_method $@opened("{{.*}}") PP, #PP.foo!1 : <Self where Self : PP> (Self) -> () -> Int, %3 : $@opened("{{.*}}PP : $@convention(witness_method: PP) <τ_0_0 where τ_0_0 : PP> (@guaranteed τ_0_0) -> Int // CHECK: apply // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform13wrap_inout_cp1aSiAA2PP_pz_tF' @inline(never) internal func wrap_inout_cp(a: inout PP ) -> Int{ return a.foo() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform24do_not_optimize_inout_cpyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: alloc_stack // CHECK: alloc_ref // CHECK: debug_value // CHECK: init_existential_ref // CHECK: store // CHECK: function_ref @$s21existential_transform13wrap_inout_cp1aSiAA2PP_pz_tF : $@convention(thin) (@inout PP) -> Int // CHECK: apply // CHECK: set_deallocating // CHECK: debug_value // CHECK: debug_value // CHECK: dealloc_ref // CHECK: dealloc_ref // CHECK: dealloc_stack // CHECK: tuple // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform24do_not_optimize_inout_cpyyF' @inline(never) func do_not_optimize_inout_cp() { var magic5:PP = KK() let _ = wrap_inout_cp(a: &magic5) } internal protocol PPP { func foo() -> Int } internal class KKKClass : PPP { init() { } @inline(never) func foo() -> Int { return 10 } } @inline(never) internal func wrap_inout_ncp(a: inout PPP ) -> Int{ return a.foo() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform9inout_ncpyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: alloc_stack // CHECK: alloc_ref // CHECK: debug_value // CHECK: init_existential_addr // CHECK: store // CHECK: function_ref @$s21existential_transform14wrap_inout_ncp1aSiAA3PPP_pz_tFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : PPP> (@inout τ_0_0) -> Int // CHECK: open_existential_addr // CHECK: apply // CHECK: destroy_addr // CHECK: dealloc_stack // CHECK: tuple // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform9inout_ncpyyF' @inline(never) func inout_ncp() { var magic6:PPP = KKKClass() let _ = wrap_inout_ncp(a: &magic6) } internal protocol PPPP { func foo() -> Int } internal struct SSSS : PPPP { init() { } @inline(never) func foo() -> Int { return 10 } } @inline(never) internal func wrap_struct_inout_ncp(a: inout PPPP ) -> Int{ return a.foo() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform16struct_inout_ncpyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: alloc_stack // CHECK: struct // CHECK: init_existential_addr // CHECK: store // CHECK: function_ref @$s21existential_transform21wrap_struct_inout_ncp1aSiAA4PPPP_pz_tFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : PPPP> (@inout τ_0_0) -> Int // CHECK: open_existential_addr // CHECK: apply // CHECK: destroy_addr // CHECK: dealloc_stack // CHECK: tuple // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform16struct_inout_ncpyyF' @inline(never) func struct_inout_ncp() { var magic7:PPPP = SSSS() let _ = wrap_struct_inout_ncp(a: &magic7) } protocol GP { func foo() -> Int } class GC: GP { @inline(never) func foo() ->Int { return 10 } } func wrap_gcp<T:GP>(_ a:T,_ b:GP) -> Int { return a.foo() + b.foo() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform3gcpySixAA2GPRzlF : $@convention(thin) <T where T : GP> (@in_guaranteed T) -> Int { // CHECK: bb0(%0 : $*T): // CHECK: debug_value_addr // CHECK: alloc_ref // CHECK: debug_value // CHECK: debug_value // CHECK: alloc_stack // CHECK: init_existential_addr // CHECK: store // CHECK: function_ref @$s21existential_transform8wrap_gcpySix_AA2GP_ptAaCRzlFTf4ne_n : $@convention(thin) <τ_0_0 where τ_0_0 : GP><τ_1_0 where τ_1_0 : GP> (@in_guaranteed τ_0_0, @in_guaranteed τ_1_0) -> Int // CHECK: open_existential_addr // CHECK: strong_retain // CHECK: apply // CHECK: destroy_addr // CHECK: dealloc_stack // CHECK: strong_release // CHECK: return // CHECK: } // end sil function '$s21existential_transform3gcpySixAA2GPRzlF' @inline(never) func gcp<T:GP>(_ a:T) -> Int { let k:GC = GC() return wrap_gcp(a, k) } func wrap_gcp_arch<T:GP>(_ a:T,_ b:GP, _ c:inout Array<T>) -> Int { return a.foo() + b.foo() + c[0].foo() } // CHECK-LABEL: sil hidden [noinline] @$s21existential_transform8gcp_archySix_SayxGztAA2GPRzlF : $@convention(thin) <T where T : GP> (@in_guaranteed T, @inout Array<T>) -> Int { // CHECK: bb0(%0 : $*T, %1 : $*Array<T>): // CHECK: debug_value_addr // CHECK: debug_value_addr // CHECK: alloc_ref // CHECK: debug_value // CHECK: debug_value // CHECK: alloc_stack // CHECK: init_existential_addr // CHECK: store // CHECK: function_ref @$s21existential_transform13wrap_gcp_archySix_AA2GP_pSayxGztAaCRzlFTf4nen_n : $@convention(thin) <τ_0_0 where τ_0_0 : GP><τ_1_0 where τ_1_0 : GP> (@in_guaranteed τ_0_0, @in_guaranteed τ_1_0, @inout Array<τ_0_0>) -> Int // CHECK: open_existential_addr // CHECK: strong_retain // CHECK: apply // CHECK: destroy_addr // CHECK: dealloc_stack // CHECK: strong_release // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform8gcp_archySix_SayxGztAA2GPRzlF' @inline(never) func gcp_arch<T:GP>(_ a:T, _ b:inout Array<T>) -> Int { let k:GC = GC() return wrap_gcp_arch(a, k, &b) } protocol Foo { var myName: String { get } } struct MyURL { } extension MyURL : Foo { var myName : String { return "MyURL" } } struct MyStruct : Foo { var myName : String { return "MyStruct" } } // CHECK-LABEL: sil shared [noinline] @$s21existential_transform7getNameySSAA3Foo_pFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : Foo> (@in_guaranteed τ_0_0) -> @owned String { // CHECK: bb0(%0 : $*τ_0_0): // CHECK: alloc_stack // CHECK: init_existential_addr // CHECK: copy_addr // CHECK: debug_value_addr // CHECK: open_existential_addr // CHECK: witness_method // CHECK: apply // CHECK: dealloc_stack // CHECK: return // CHECK-LABEL: } // end sil function '$s21existential_transform7getNameySSAA3Foo_pFTf4e_n' @inline(never) func getName(_ f: Foo) -> String { return f.myName } @inline(never) func getName_wrapper() -> Int32{ let u = MyURL() return getName(u) == "MyStruct" ? 0 : 1 } @_optimize(none) public func foo() -> Int { cp() ncp() cpc() ncpc() let p:P = K() let x:Int = do_not_optimize_cp(a:p) do_not_optimize_inout_cp() inout_ncp() struct_inout_ncp() let y:Int = gcp(GC()) var a:Array<GC> = [GC()] let z:Int = gcp_arch(GC(), &a) let zz:Int32 = getName_wrapper() return x + y + z + Int(zz) }
a45fe0979ff422059abbc941ae6836ba
30.259709
268
0.674897
false
false
false
false
tribalworldwidelondon/CassowarySwift
refs/heads/master
Sources/Cassowary/ConstraintOperatorsCGFloat.swift
bsd-3-clause
1
/* Copyright (c) 2017, Tribal Worldwide London Copyright (c) 2015, Alex Birkett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of kiwi-java nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation extension Term { convenience init(variable: Variable, coefficient: CGFloat) { self.init(variable: variable, coefficient: Double(coefficient)) } } extension Expression { convenience init(constant: CGFloat) { self.init(constant: Double(constant)) } } // MARK: - Variable *, /, and unary invert public func * (_ variable: Variable, _ coefficient: CGFloat) -> Term { return Term(variable: variable, coefficient: coefficient) .addingDebugDescription("\(variable.name) * \(coefficient)") } public func / (_ variable: Variable, _ denominator: CGFloat) -> Term { return (variable * (1.0 / denominator)) .addingDebugDescription("\(variable.name) / \(denominator)") } // Term *, /, and unary invert public func * (_ term: Term, _ coefficient: CGFloat) -> Term { return Term(variable: term.variable, coefficient: term.coefficient * Double(coefficient)) .addingDebugDescription("(\(term.debugDescription)) * \(coefficient)") } public func / (_ term: Term, _ denominator: CGFloat) -> Term { return (term * (1.0 / denominator)) .addingDebugDescription("(\(term.debugDescription)) / \(denominator)") } // MARK: - Expression *, /, and unary invert public func * (_ expression: Expression, _ coefficient: CGFloat) -> Expression { var terms = [Term]() for term in expression.terms { terms.append(term * coefficient) } // TODO: Do we need to make a copy of the term objects in the array? return Expression(terms: terms, constant: expression.constant * Double(coefficient)) .addingDebugDescription("(\(expression.debugDescription)) * \(coefficient)") } public func / (_ expression: Expression, _ denominator: CGFloat) -> Expression { return (expression * (1.0 / denominator)) .addingDebugDescription("(\(expression.debugDescription)) / \(denominator)") } // MARK: - CGFloat * public func * (_ coefficient: CGFloat, _ expression: Expression) -> Expression { return (expression * coefficient) .addingDebugDescription("(\(expression.debugDescription)) * \(coefficient)") } public func * (_ coefficient: CGFloat, _ term: Term) -> Term { return (term * coefficient) .addingDebugDescription("\(coefficient) * (\(term.debugDescription))") } public func * (_ coefficient: CGFloat, _ variable: Variable) -> Term { return (variable * coefficient) .addingDebugDescription("\(coefficient) * \(variable.name)") } public func + (_ expression: Expression, _ constant: CGFloat) -> Expression { return Expression(terms: expression.terms, constant: expression.constant + Double(constant)) .addingDebugDescription("(\(expression.debugDescription))¨ + \(constant)") } public func - (_ expression: Expression, _ constant: CGFloat) -> Expression{ return (expression + -constant) .addingDebugDescription("(\(expression.debugDescription)) - \(constant)") } public func + (_ term: Term, _ constant: CGFloat) -> Expression { return Expression(term: term, constant: Double(constant)) .addingDebugDescription("(\(term.debugDescription)) + \(constant)") } public func - (_ term: Term, _ constant: CGFloat) -> Expression { return (term + -constant) .addingDebugDescription("(\(term.debugDescription)) - \(constant)") } public func + (_ variable: Variable, _ constant: CGFloat) -> Expression { return (Term(variable: variable) + constant) .addingDebugDescription("\(variable.name) + \(constant)") } public func - (_ variable: Variable, _ constant: CGFloat) -> Expression { return (variable + -constant) .addingDebugDescription("\(variable.name) - \(constant)") } // MARK: - CGFloat + and - public func + (_ constant: CGFloat, _ expression: Expression) -> Expression { return (expression + constant) .addingDebugDescription("\(constant) + (\(expression.debugDescription))") } public func + (_ constant: CGFloat, _ term: Term) -> Expression { return (term + constant) .addingDebugDescription("\(constant) + (\(term.debugDescription))") } public func + (_ constant: CGFloat, _ variable: Variable) -> Expression { return (variable + constant) .addingDebugDescription("\(constant) + \(variable.name)") } public func - (_ constant: CGFloat, _ expression: Expression) -> Expression { return (-expression + constant) .addingDebugDescription("\(constant) - (\(expression.debugDescription))") } public func - (_ constant: CGFloat, _ term: Term) -> Expression { return (-term + constant) .addingDebugDescription("\(constant) - (\(term.debugDescription))") } public func - (_ constant: CGFloat, _ variable: Variable) -> Expression { return (-variable + constant) .addingDebugDescription("\(constant) - \(variable.name)") } public func == (_ expression: Expression, _ constant: CGFloat) -> Constraint { return (expression == Expression(constant: constant)) .addingDebugDescription("\(expression.debugDescription) == \(constant)") } public func <= (_ expression: Expression, _ constant: CGFloat) -> Constraint { return (expression <= Expression(constant: constant)) .addingDebugDescription("\(expression.debugDescription) <= \(constant)") } public func >= (_ expression: Expression, _ constant: CGFloat) -> Constraint { return (expression >= Expression(constant: constant)) .addingDebugDescription("\(expression.debugDescription) >= \(constant)") } public func == (_ term: Term, _ constant: CGFloat) -> Constraint { return (Expression(term: term) == constant) .addingDebugDescription("\(term.debugDescription) == \(constant)") } public func <= (_ term: Term, _ constant: CGFloat) -> Constraint { return (Expression(term: term) <= constant) .addingDebugDescription("\(term.debugDescription) <= \(constant))") } public func >= (_ term: Term, _ constant: CGFloat) -> Constraint { return (Expression(term: term) >= constant) .addingDebugDescription("\(term.debugDescription) >= \(constant)") } public func == (_ variable: Variable, _ constant: CGFloat) -> Constraint{ return (Term(variable: variable) == constant) .addingDebugDescription("\(variable.name) == \(constant)") } public func <= (_ variable: Variable, _ constant: CGFloat) -> Constraint { return (Term(variable: variable) <= constant) .addingDebugDescription("\(variable.name) <= \(constant)") } public func >= (_ variable: Variable, _ constant: CGFloat) -> Constraint { return (Term(variable: variable) >= constant) .addingDebugDescription("\(variable.name) >= \(constant)") } // MARK: - CGFloat relations public func == (_ constant: CGFloat, _ expression: Expression) -> Constraint { return (expression == constant) .addingDebugDescription("\(constant) == \(expression.debugDescription)") } public func == (_ constant: CGFloat, _ term: Term) -> Constraint { return (term == constant) .addingDebugDescription("\(constant) == \(term.debugDescription)") } public func == (_ constant: CGFloat, _ variable: Variable) -> Constraint { return (variable == constant) .addingDebugDescription("\(constant) == \(variable.name)") } public func <= (_ constant: CGFloat, _ expression: Expression) -> Constraint { return (Expression(constant: constant) <= expression) .addingDebugDescription("\(constant) <= \(expression.debugDescription)") } public func <= (_ constant: CGFloat, _ term: Term) -> Constraint { return (constant <= Expression(term: term)) .addingDebugDescription("\(constant) <= \(term.debugDescription)") } public func <= (_ constant: CGFloat, _ variable: Variable) -> Constraint { return (constant <= Term(variable: variable)) .addingDebugDescription("\(constant) <= \(variable.name)") } public func >= (_ constant: CGFloat, _ term: Term) -> Constraint { return (Expression(constant: constant) >= term) .addingDebugDescription("\(constant) >= \(term.debugDescription)") } public func >= (_ constant: CGFloat, _ variable: Variable) -> Constraint { return (constant >= Term(variable: variable)) .addingDebugDescription("\(constant) >= \(variable.name)") } // MARK: - Constraint strength modifier public func modifyStrength(_ constraint: Constraint, _ strength: CGFloat) -> Constraint { return Constraint(other: constraint, strength: Double(strength)) } public func modifyStrength(_ strength: CGFloat, _ constraint: Constraint) -> Constraint { return modifyStrength(constraint, strength) }
81e2fef7e74b050c4ccd978c662b2e42
37.934615
96
0.686951
false
false
false
false
shijinliang/KSMoney
refs/heads/master
Sources/App/Models/Account.swift
mit
1
// // Account.swift // KSMoney // // Created by niuhui on 2017/7/14. // // import Vapor import FluentProvider import Crypto final class Account: Model{ let storage = Storage() var name : String = "" var uuid : String = "" var create_at : Int = 0 var image : String = "" var type : Int = 0 //1现金 2储蓄卡 3信用卡 4虚拟 5债务 var balance : Float = 0 init(row: Row) throws { name = try row.get("name") create_at = try row.get("create_at") image = try row.get("image") type = try row.get("type") uuid = try row.get("uuid") balance = try row.get("balance") } init(uuid: String) { self.uuid = uuid } func makeRow() throws -> Row { var row = Row() try row.set("name", name) try row.set("create_at", create_at) try row.set("image", image) try row.set("type", type) try row.set("uuid", uuid) try row.set("balance", balance) return row } } extension Account: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { users in users.id() users.string("name") users.int("create_at") users.string("image") users.int("type") users.string("uuid") users.float("balance") } } static func revert(_ database: Database) throws { } } extension Account { func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id) try json.set("name", name) try json.set("create_at", create_at) try json.set("image", image) try json.set("type", type) try json.set("uuid", uuid) return json } } extension Account: NodeRepresentable { func makeNode(in context: Context?) throws -> Node { var node = Node(context) try node.set("id", id) try node.set("uuid", uuid) try node.set("create_at", create_at) try node.set("image", image) try node.set("type", type) try node.set("name", name) return node } } //添加字段 //struct addAccountHHHH: Preparation { // static func prepare(_ database: Database) throws { // try database.modify(Account.self, closure: { (bar) in // bar.string("HHHH") // }) // } // static func revert(_ database: Database) throws { // // } //}
cf28cd18af24f1b37a0739b07688d3dd
24.505155
63
0.533953
false
false
false
false
doctorn/hac-website
refs/heads/master
Sources/HaCTML/render.swift
mit
1
import HTMLString extension TextNode: Node { public func render() -> String { switch escapeLevel { case .preserveViewedCharacters: return text.addingUnicodeEntities case .unsafeRaw: return text } } } extension Fragment: Node { public func render() -> String { return self.nodes.map({ $0.render() }).joined() } } extension HTMLElement: Node { public func render() -> String { if self.tagName == "DOCTYPE" { return "<!DOCTYPE html>" } let attributeString = renderAttributeMap(self.attributes).map({ " " + $0 }) ?? "" let elementBody = self.tagName + attributeString if self.selfClosing { if self.child != nil { print("Not rendering children of self closing element \(self.tagName)") } return "<\(elementBody) />" } return "<\(elementBody)>\(self.child.map({ $0.render() }) ?? "")</\(self.tagName)>" } } func renderAttributeMap(_ attributes: AttributeMap) -> String? { guard !attributes.isEmpty else { return nil } return attributes.renderedValues.flatMap(renderAttribute).joined(separator: " ") } func renderAttribute(_ attribute: AppliedAttribute) -> String? { switch attribute.value { case .noValue: return attribute.keyName case .text(let text): return "\(attribute.keyName)=\"\(text.addingUnicodeEntities)\"" case .removeAttribute: return nil } }
b866cdaee754e45da44b511448023097
23.051724
87
0.648746
false
false
false
false
kasei/kineo
refs/heads/master
Sources/Kineo/SimpleParser/QueryParser.swift
mit
1
// // QueryParser.swift // Kineo // // Created by Gregory Todd Williams on 5/10/18. // import Foundation import SPARQLSyntax // swiftlint:disable:next type_body_length open class QueryParser<T: LineReadable> { let reader: T var stack: [Algebra] public init(reader: T) { self.reader = reader self.stack = [] } // swiftlint:disable:next cyclomatic_complexity func parse(line: String) throws -> Algebra? { let parts = line.components(separatedBy: " ").filter { $0 != "" && !$0.hasPrefix("\t") } guard parts.count > 0 else { return nil } if parts[0].hasPrefix("#") { return nil } let rest = parts.suffix(from: 1).joined(separator: " ") let op = parts[0] if op == "project" { guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") } let vars = Array(parts.suffix(from: 1)) guard vars.count > 0 else { throw QueryError.parseError("No projection variables supplied") } return .project(child, Set(vars)) } else if op == "join" { guard stack.count >= 2 else { throw QueryError.parseError("Not enough operands for \(op)") } guard let rhs = stack.popLast() else { return nil } guard let lhs = stack.popLast() else { return nil } return .innerJoin(lhs, rhs) } else if op == "union" { guard stack.count >= 2 else { throw QueryError.parseError("Not enough operands for \(op)") } guard let rhs = stack.popLast() else { return nil } guard let lhs = stack.popLast() else { return nil } return .union(lhs, rhs) } else if op == "leftjoin" { guard stack.count >= 2 else { throw QueryError.parseError("Not enough operands for \(op)") } guard let rhs = stack.popLast() else { return nil } guard let lhs = stack.popLast() else { return nil } return .leftOuterJoin(lhs, rhs, .node(.bound(Term.trueValue))) } else if op == "quad" { let parser = NTriplesPatternParser(reader: "") guard let pattern = parser.parseQuadPattern(line: rest) else { return nil } return .quad(pattern) } else if op == "triple" { let parser = NTriplesPatternParser(reader: "") guard let pattern = parser.parseTriplePattern(line: rest) else { return nil } return .triple(pattern) } else if op == "nps" { let parser = NTriplesPatternParser(reader: "") let view = AnyIterator(rest.unicodeScalars.makeIterator()) var chars = PeekableIterator(generator: view) guard let nodes = parser.parseNodes(chars: &chars, count: 2) else { return nil } guard nodes.count == 2 else { return nil } let iriStrings = chars.elements().map { String($0) }.joined(separator: "").components(separatedBy: " ") let iris = iriStrings.map { Term(value: $0, type: .iri) } return .path(nodes[0], .nps(iris), nodes[1]) } else if op == "path" { let parser = NTriplesPatternParser(reader: "") let view = AnyIterator(rest.unicodeScalars.makeIterator()) var chars = PeekableIterator(generator: view) guard let nodes = parser.parseNodes(chars: &chars, count: 2) else { return nil } guard nodes.count == 2 else { return nil } let rest = chars.elements().map { String($0) }.joined(separator: "").components(separatedBy: " ") guard let pp = try parsePropertyPath(rest) else { throw QueryError.parseError("Failed to parse property path") } return .path(nodes[0], pp, nodes[1]) } else if op == "agg" { // (SUM(?skey) AS ?sresult) (AVG(?akey) AS ?aresult) ... GROUP BY ?x ?y ?z --> "agg sum sresult ?skey , avg aresult ?akey ; ?x , ?y , ?z" let pair = parts.suffix(from: 1).split(separator: ";") guard pair.count >= 1 else { throw QueryError.parseError("Bad syntax for agg operation") } let aggs = pair[0].split(separator: ",") guard aggs.count > 0 else { throw QueryError.parseError("Bad syntax for agg operation") } let groupby = pair.count == 2 ? pair[1].split(separator: ",") : [] var aggregates = [Algebra.AggregationMapping]() for a in aggs { let strings = Array(a) guard strings.count >= 3 else { throw QueryError.parseError("Failed to parse aggregate expression") } let op = strings[0] let name = strings[1] var expr: Expression! if op != "countall" { guard let e = try ExpressionParser.parseExpression(Array(strings.suffix(from: 2))) else { throw QueryError.parseError("Failed to parse aggregate expression") } expr = e } var agg: Aggregation switch op { case "avg": agg = .avg(expr, false) case "sum": agg = .sum(expr, false) case "count": agg = .count(expr, false) case "countall": agg = .countAll default: throw QueryError.parseError("Unexpected aggregation operation: \(op)") } let aggMap = Algebra.AggregationMapping(aggregation: agg, variableName: name) aggregates.append(aggMap) } let groups = try groupby.map { (gstrings) -> Expression in guard let e = try ExpressionParser.parseExpression(Array(gstrings)) else { throw QueryError.parseError("Failed to parse aggregate expression") } return e } guard let child = stack.popLast() else { return nil } return .aggregate(child, groups, Set(aggregates)) } else if op == "window" { // window row rowresult , rank rankresult ; ?x , ?y , ?z" let pair = parts.suffix(from: 1).split(separator: ";") guard pair.count >= 1 else { throw QueryError.parseError("Bad syntax for window operation") } let w = pair[0].split(separator: ",") guard w.count > 0 else { throw QueryError.parseError("Bad syntax for window operation") } let groupby = pair.count == 2 ? pair[1].split(separator: ",") : [] let groups = try groupby.map { (gstrings) -> Expression in guard let e = try ExpressionParser.parseExpression(Array(gstrings)) else { throw QueryError.parseError("Failed to parse aggregate expression") } return e } var windows: [Algebra.WindowFunctionMapping] = [] for a in w { let strings = Array(a) guard strings.count >= 2 else { throw QueryError.parseError("Failed to parse window expression") } let op = strings[0] let name = strings[1] // var expr: Expression! var f: WindowFunction switch op { case "rank": f = .rank case "row": f = .rowNumber default: throw QueryError.parseError("Unexpected window operation: \(op)") } let frame = WindowFrame(type: .rows, from: .unbound, to: .unbound) let windowApp = WindowApplication(windowFunction: f, comparators: [], partition: groups, frame: frame) let windowMap = Algebra.WindowFunctionMapping(windowApplication: windowApp, variableName: name) windows.append(windowMap) } guard let child = stack.popLast() else { return nil } return .window(child, windows) } else if op == "avg" { // (AVG(?key) AS ?name) ... GROUP BY ?x ?y ?z --> "avg key name x y z" guard parts.count > 2 else { return nil } let key = parts[1] let name = parts[2] let groups = parts.suffix(from: 3).map { (name) -> Expression in .node(.variable(name, binding: true)) } guard let child = stack.popLast() else { return nil } let aggMap = Algebra.AggregationMapping(aggregation: .avg(.node(.variable(key, binding: true)), false), variableName: name) return .aggregate(child, groups, [aggMap]) } else if op == "sum" { // (SUM(?key) AS ?name) ... GROUP BY ?x ?y ?z --> "sum key name x y z" guard parts.count > 2 else { throw QueryError.parseError("Not enough arguments for \(op)") } let key = parts[1] let name = parts[2] let groups = parts.suffix(from: 3).map { (name) -> Expression in .node(.variable(name, binding: true)) } guard let child = stack.popLast() else { return nil } let aggMap = Algebra.AggregationMapping(aggregation: .sum(.node(.variable(key, binding: true)), false), variableName: name) return .aggregate(child, groups, [aggMap]) } else if op == "count" { // (COUNT(?key) AS ?name) ... GROUP BY ?x ?y ?z --> "count key name x y z" guard parts.count > 2 else { throw QueryError.parseError("Not enough arguments for \(op)") } let key = parts[1] let name = parts[2] let groups = parts.suffix(from: 3).map { (name) -> Expression in .node(.variable(name, binding: true)) } guard let child = stack.popLast() else { return nil } let aggMap = Algebra.AggregationMapping(aggregation: .count(.node(.variable(key, binding: true)), false), variableName: name) return .aggregate(child, groups, [aggMap]) } else if op == "countall" { // (COUNT(*) AS ?name) ... GROUP BY ?x ?y ?z --> "count name x y z" guard parts.count > 1 else { throw QueryError.parseError("Not enough arguments for \(op)") } let name = parts[1] let groups = parts.suffix(from: 2).map { (name) -> Expression in .node(.variable(name, binding: true)) } guard let child = stack.popLast() else { return nil } let aggMap = Algebra.AggregationMapping(aggregation: .countAll, variableName: name) return .aggregate(child, groups, [aggMap]) } else if op == "limit" { guard let count = Int(rest) else { return nil } guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") } return .slice(child, 0, count) } else if op == "graph" { let parser = NTriplesPatternParser(reader: "") guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") } guard let graph = parser.parseNode(line: rest) else { return nil } return .namedGraph(child, graph) } else if op == "extend" { guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") } let name = parts[1] guard parts.count > 2 else { return nil } do { if let expr = try ExpressionParser.parseExpression(Array(parts.suffix(from: 2))) { return .extend(child, expr, name) } } catch {} fatalError("Failed to parse filter expression: \(parts)") } else if op == "filter" { guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") } do { if let expr = try ExpressionParser.parseExpression(Array(parts.suffix(from: 1))) { return .filter(child, expr) } } catch {} fatalError("Failed to parse filter expression: \(parts)") } else if op == "sort" { let comparators = try parts.suffix(from: 1).split(separator: ",").map { (stack) -> Algebra.SortComparator in guard let expr = try ExpressionParser.parseExpression(Array(stack)) else { throw QueryError.parseError("Failed to parse ORDER expression") } let c = Algebra.SortComparator(ascending: true, expression: expr) return c } guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") } return .order(child, comparators) } else if op == "distinct" { guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") } return .distinct(child) } else if op == "reduced" { guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") } return .reduced(child) } warn("Cannot parse query line: \(line)") return nil } func parsePropertyPath(_ parts: [String]) throws -> PropertyPath? { var stack = [PropertyPath]() var i = parts.makeIterator() let parser = NTriplesPatternParser(reader: "") while let s = i.next() { switch s { case "|": guard stack.count >= 2 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") } let rhs = stack.popLast()! let lhs = stack.popLast()! stack.append(.alt(lhs, rhs)) case "/": guard stack.count >= 2 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") } let rhs = stack.popLast()! let lhs = stack.popLast()! stack.append(.seq(lhs, rhs)) case "^": guard stack.count >= 1 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") } let lhs = stack.popLast()! stack.append(.inv(lhs)) case "+": guard stack.count >= 1 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") } let lhs = stack.popLast()! stack.append(.plus(lhs)) case "*": guard stack.count >= 1 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") } let lhs = stack.popLast()! stack.append(.star(lhs)) case "nps": guard let c = i.next() else { throw QueryError.parseError("No count argument given for property path operation: \(s)") } guard let count = Int(c) else { throw QueryError.parseError("Failed to parse count argument for property path operation: \(s)") } guard stack.count >= count else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") } var iris = [Term]() for _ in 0..<count { let link = stack.popLast()! guard case .link(let term) = link else { throw QueryError.parseError("Not an IRI for \(s)") } iris.append(term) } stack.append(.nps(iris)) default: guard let n = parser.parseNode(line: s) else { throw QueryError.parseError("Failed to parse property path: \(parts.joined(separator: " "))") } guard case .bound(let term) = n else { throw QueryError.parseError("Failed to parse property path: \(parts.joined(separator: " "))") } stack.append(.link(term)) } } return stack.popLast() } public func parse() throws -> Query? { let lines = try self.reader.lines() for line in lines { guard let algebra = try self.parse(line: line) else { continue } stack.append(algebra) } guard let algebra = stack.popLast() else { return nil } let proj = Array(algebra.projectableVariables) return try Query(form: .select(.variables(proj)), algebra: algebra, dataset: nil) } }
b30e837995de3adaf87b99dfd6a4cbe4
55.117647
179
0.557652
false
false
false
false
boostcode/tori
refs/heads/master
Sources/tori/Core/Authentication.swift
apache-2.0
1
/** * Copyright boostco.de 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 Foundation import Kitura import KituraSys import KituraNet import SwiftyJSON import MongoKitten // logger import HeliumLogger import LoggerAPI func routerAuth() { let userCollection = db["User"] // MARK: - Login router.all("/api/log*", middleware: AllRemoteOriginMiddleware()) router.all("/api/log*", middleware: BodyParser()) router.all("/api/log*", middleware: CheckRequestIsValidJson()) router.post("/api/login") { req, res, next in guard case let .Json(json) = req.body! else { res.error(withMsg: "request is not in json format") return } guard let userName = json["username"].string else { res.error(withMsg: "missing username value") return } guard let userPassword = json["password"].string else { res.error(withMsg: "missing password value") return } let passwordMD5 = "\(userPassword.md5())" guard let user = try! userCollection.findOne(matching: "username" == userName && "password" == passwordMD5) else { res.error(withMsg: "wrong user or password provided") return } // generate an unique token let userToken = NSUUID().uuidString var newUser = user newUser["token"] = .string(userToken) // add new token try! userCollection.update(matching: user, to: newUser) let responseJson = JSON([ "status": "ok", "token": userToken, "user": userName]) res.json(withJson: responseJson) } // MARK: - Registration // TODO: implement registration, figure out how to manage default role // MARK: - Logout router.all("/api/logout", middleware: TokenAuthentication()) router.get("/api/logout") { req, res, next in guard let userName = req.userInfo["Tori-User"] as? String else { res.error(withMsg: "missing Tori-User") return } guard let userToken = req.userInfo["Tori-Token"] as? String else { res.error(withMsg: "missing Tori-Token") return } guard let user = try! userCollection.findOne(matching: "username" == userName && "token" == userToken) else { res.error(withMsg: "user not found") return } var newUser = user newUser["token"] = .null // remove token try! userCollection.update(matching: user, to: newUser) let responseJson = JSON([ "status": "ok", "action": "logout"]) res.json(withJson: responseJson) } }
9575632a0ce47fe2c0fe64d29d4852c0
27.057851
122
0.586156
false
false
false
false
cheeyi/ProjectSora
refs/heads/master
ProjectSora/OnboardViewController.swift
mit
1
// // OnboardViewController.swift // ProjectSora // // Created by Chee Yi Ong on 11/29/15. // Copyright © 2015 Expedia MSP. All rights reserved. // import Foundation import Onboard class OnboardViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().statusBarStyle = .LightContent // Hardcode this first to see onboarding every time NSUserDefaults.standardUserDefaults().setBool(false, forKey: "kUserHasOnboardedKey") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let userHasOnboarded = NSUserDefaults.standardUserDefaults().boolForKey("kUserHasOnboardedKey") if !userHasOnboarded { // Handle onboarding // Set up onboarding content pages let firstPage = OnboardingContentViewController(title: "Welcome", body: "This app is going to rock your world", image: UIImage(named: "umbrella-icon"), buttonText: nil) { () -> Void in // Do something here when users press the button, like ask for location services permissions, register for push notifications } let secondPage = OnboardingContentViewController(title: "Getting to Know You", body: "We'll start by asking you some questions. Be honest!", image: UIImage(named: "umbrella-icon"), buttonText: nil) { () -> Void in } let thirdPage = OnboardingContentViewController(title: "Understanding You", body: "The app learns and understands what you like", image: UIImage(named: "umbrella-icon"), buttonText: nil) { () -> Void in } let fourthPage = OnboardingContentViewController(title: "Assisting You", body: "We then suggest full holiday packages based on your interests", image: UIImage(named: "umbrella-icon"), buttonText: "Let's get started!") { () -> Void in NSUserDefaults.standardUserDefaults().setBool(true, forKey: "kUserHasOnboardedKey") // Perform segue to survey questions } // Set up onboarding view controller let onboardingVC = OnboardingViewController(backgroundImage: UIImage(named: "haystack"), contents: [firstPage, secondPage, thirdPage, fourthPage]) onboardingVC.allowSkipping = true onboardingVC.skipHandler = {() -> Void in // Copy completion block from last onboarding content VC's button completion above, and put it under the completion block below NSUserDefaults.standardUserDefaults().setBool(true, forKey: "kUserHasOnboardedKey") self.dismissViewControllerAnimated(true, completion: nil) } // Present onboarding view controller modally self.modalTransitionStyle = UIModalTransitionStyle.CoverVertical self.modalPresentationStyle = .CurrentContext self.presentViewController(onboardingVC, animated: true, completion: nil) } NSUserDefaults.standardUserDefaults().synchronize() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
05ed152f9a8a79eb1dd77591d0b5bcf7
47.617647
245
0.658396
false
false
false
false
jkereako/LoginView
refs/heads/master
Source/LoginTableViewController.swift
mit
1
// // LoginController.swift // LoginView // // Created by Jeff Kereakoglow on 2/11/16. // Copyright © 2016 Alexis Digital. All rights reserved. // import UIKit final class LoginTableViewController: UITableViewController { @IBOutlet private(set) weak var usernameField: UITextField! @IBOutlet private(set) weak var passwordField: UITextField! @IBOutlet private(set) weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 64 tableView.rowHeight = UITableView.automaticDimension } } // MARK: - Actions extension LoginTableViewController { // This is triggered before `shouldPerformSegueWithIdentifier` @IBAction func loginAction(sender: UIButton) { let password = Keychain.password(forAccount: usernameField.text ?? "") if passwordField.text == password { return } // Indicate failed login ShakeAnimator(view: usernameField).shake() ShakeAnimator(view: passwordField).shake() ShakeAnimator(view: loginButton).shake() } } // MARK: - Navigation extension LoginTableViewController { override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { guard identifier == "login", let username = usernameField.text, !username.isEmpty, let suppliedPassword = passwordField.text, !suppliedPassword.isEmpty else { return false } let actualPassword = Keychain.password(forAccount: username) // Make sure the passwords match and that `Keychain.password()` has returned a non-empty string if suppliedPassword == actualPassword { return true } return false } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: self) segue.destination.transitioningDelegate = self segue.destination.modalPresentationStyle = .custom } } // MARK: - UITextFieldDelegate extension LoginTableViewController: UITextFieldDelegate { func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() // Move on to the password field automatically if textField === usernameField { passwordField.becomeFirstResponder() } return true } } // MARK: - UIViewControllerTransitioningDelegate extension LoginTableViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController( presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { // Find the center of `loginButton` in the container view's coordinate system let origin = loginButton.convert(loginButton.center, to: view) // Match the transition color to the background color of the presented view return BubblePresentationAnimator( origin: origin, backgroundColor: presented.view.backgroundColor! ) } }
d709e8b7dbc2c5a619683e6303fc0757
31.990196
103
0.669539
false
false
false
false
shams-ahmed/SAStickyHeader
refs/heads/master
Example/SAStickyHeaderExample/ViewController.swift
mit
1
// // ViewController.swift // SAStickyHeaderExample // // Created by shams ahmed on 18/10/2015. // Copyright © 2015 SA. All rights reserved. // import UIKit /** Github example images from: https://octodex.github.com */ enum GithubImage: String { case example1 = "Example1" // Gracehoppertocat case example2 = "Example2" // Hipster case example3 = "Example3" // Mountietocat case example4 = "Example4" // Octoliberty case example5 = "Example5" // ProfessortocatV2 } /// Example View Controller class ViewController: UITableViewController { // list of github images, for Demo purposes i've loaded everything first but can easily be inserted with 'images.append()' private let images = [ UIImage(named: GithubImage.example1.rawValue), UIImage(named: GithubImage.example2.rawValue), UIImage(named: GithubImage.example3.rawValue), UIImage(named: GithubImage.example4.rawValue), UIImage(named: GithubImage.example5.rawValue) ] // MARK: // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() // setupView() } // MARK: // MARK: TableViewDelegate // EXAMPLE 2: Using Delegate override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return SAStickyHeaderView(tableView, with: 400, using: images) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "Cell1" return tableView.dequeueReusableCell(withIdentifier: identifier) ?? UITableViewCell(style: .default, reuseIdentifier: identifier) } // MARK: // MARK: Setup func setupView() { // EXAMPLE 1: SAStickyHeaderView with a frame and optional image array. let stickyHeaderView = SAStickyHeaderView(tableView, with: 400, using: images) tableView.tableHeaderView = stickyHeaderView } }
b90c669cdbc73afd4772371989d72db3
29.323944
126
0.664654
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/public/SDK/Intents/INGetCarLockStatusIntentResponse.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation #if os(iOS) || os(watchOS) @available(iOS 10.3, watchOS 3.2, *) extension INGetCarLockStatusIntentResponse { @nonobjc public final var locked: Bool? { get { return __locked?.boolValue } set(newLocked) { __locked = newLocked.map { NSNumber(value: $0) } } } } #endif
9f899ca06e4d3a7afabad8c7e08779ff
29.965517
80
0.54343
false
false
false
false
KanChen2015/DRCRegistrationKit
refs/heads/master
DRCRegistrationKit/DRCRegistrationKit/DRRSignUpStep1.swift
mit
1
// // DRRSignUpStep1.swift // DRCRegistrationKit // // Created by Kan Chen on 6/8/16. // Copyright © 2016 drchrono. All rights reserved. // import UIKit class DRRSignUpStep1: UIViewController, UITextFieldDelegate { @IBOutlet weak var nameTextField: CustomTextField! @IBOutlet weak var phoneNumberTextField: CustomTextField! @IBOutlet weak var emailTextField: CustomTextField! @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var inputContainerView: UIView! private var viewModel = DRRSignUpViewModel() private let step2SegueId = "gotoStepTwo" override func viewDidLoad() { super.viewDidLoad() inputContainerView.addBorderForInputContainerStyle() } @IBAction func nextButtonClicked(sender: AnyObject) { var parameters: [String: AnyObject] = [:] parameters[kDRRSignupFullNameKey] = nameTextField.text parameters[kDRRSignupPhoneKey] = phoneNumberTextField.text parameters[kDRRSignupEmailKey] = emailTextField.text spinner.startAnimating() viewModel.signupStep1WithInfo(parameters) { (success, errorMsg) in dispatch_async(dispatch_get_main_queue()) { self.spinner.stopAnimating() if success { self.performSegueWithIdentifier(self.step2SegueId, sender: self) } else { let alert = UIAlertController(title: nil, message: errorMsg, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: false, completion: nil) } } } } @IBAction func cancelButtonClicked(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) view.endEditing(true) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == step2SegueId { (segue.destinationViewController as? DRRSignUpStep2)?.viewModel = viewModel } } // MARK: - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { switch textField { case nameTextField: phoneNumberTextField.becomeFirstResponder() case phoneNumberTextField: emailTextField.becomeFirstResponder() default: textField.resignFirstResponder() } return true } }
5778f9a5cf675701576521887ac2a17c
37
106
0.667628
false
false
false
false
tectijuana/patrones
refs/heads/master
Bloque1SwiftArchivado/PracticasSwift/FernandoPreciado/Practica #4.swift
gpl-3.0
1
// Alumno: Fernando Preciado Salman // Numero de Control: 12211415 // Patrones de diseño // Practica: 34 capitulo 4 // Realizar un programa que realize la operacion A2 + B2 = C2 con todos los valores que c2 de menor a 50 import Foundation var i = 1.0 var z = 0.0 var a = 1.0 var b = 1.0 var index = 1 while index < 8 { var a2 = pow(a ,2.0) var b2 = pow(b, 2.0) var c = a2 + b2 if c <= 50{ b = b + 1.0 print(c) } else { a = (a + 1.0) b = 1.0 index = (index + 1) } }
8e9644113c75d162e617463cd97e5060
14.6875
107
0.544944
false
false
false
false
digices-llc/paqure-ios-framework
refs/heads/master
Paqure/User/UserManager.swift
bsd-3-clause
1
// // UserManager.swift // Paqure // // Created by Linguri Technology on 7/21/16. // Copyright © 2016 Digices. All rights reserved. // import UIKit protocol UserManagerDelegate { func userObjectSynced(success: Bool) } public class UserManager { public static var sharedInstance : UserManager = UserManager() var controller : UserManagerDelegate? var object : User = User() // var collection : [User] = [] var source : Source = Source.DEFAULT let url = NSURL(string: "https://www.digices.com/api/user.php") private init() { if self.pullFromLocal() == true { self.source = Source.LOCAL } else { self.saveToLocal() } self.pushToRemote() } func setController(controller: UserManagerDelegate) { self.controller = controller } func pullFromLocal() -> Bool { let storedObject = defaults.objectForKey("user") if let retrievedObject = storedObject as? NSData { if let unarchivedObject = NSKeyedUnarchiver.unarchiveObjectWithData(retrievedObject) { if let user = unarchivedObject as? User { self.object = user return true } else { return false } } else { return false } } else { return false } } func pushToRemote() { let request = NSMutableURLRequest(URL: self.url!) request.HTTPMethod = "POST" request.HTTPBody = self.object.encodedPostBody() let task = session.dataTaskWithRequest(request, completionHandler: receiveReply) task.resume() } func receiveReply(data : NSData?, response: NSURLResponse?, error: NSError?) { if let error = error { print(error.description) } // initialize parameter to pass to delegate var success : Bool = false if let data = data { do { let parsedObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) if let parsedUser = parsedObject["user"] { if let user = parsedUser as? NSDictionary { let remoteUser = User(dict: user) if remoteUser.id > 0 { self.object = remoteUser self.source = Source.REMOTE self.saveToLocal() self.source = Source.SYNCED success = true } } else { print("object did not evaluate") } } else { print("key \"user\" does not exist in data") } } catch { print("serialization failed") } } else { print("no data received") } NSOperationQueue.mainQueue().addOperationWithBlock({ if success == true { self.source = Source.SYNCED self.controller?.userObjectSynced(true) } else { self.controller?.userObjectSynced(false) } }) } func saveToLocal() { let data = NSKeyedArchiver.archivedDataWithRootObject(self.object) defaults.setObject(data, forKey: "user") self.source = Source.LOCAL } }
c5b3562b0d69941db2655f8c24ed4380
28.064
109
0.505507
false
false
false
false
dasdom/SlideControl
refs/heads/master
SlideControlDemo/ViewController.swift
mit
1
// // ViewController.swift // SlideControlDemo // // Created by dasdom on 11.09.15. // Copyright © 2015 Dominik Hauser. All rights reserved. // import UIKit class ViewController: UIViewController { var label: UILabel? let titles = ["1st Option", "2nd Option", "3rd Option", "4th Option"] override func viewDidLoad() { super.viewDidLoad() let slideControl = DHSlideControl(titles: titles) slideControl.translatesAutoresizingMaskIntoConstraints = false slideControl.addTarget(self, action: "didChange:", forControlEvents: .ValueChanged) slideControl.color = UIColor(hue: 0.6, saturation: 0.9, brightness: 0.65, alpha: 1.0) slideControl.layer.cornerRadius = 10 label = UILabel() label?.translatesAutoresizingMaskIntoConstraints = false label?.text = titles.first label?.textAlignment = .Center view.addSubview(slideControl) view.addSubview(label!) let views = ["slide": slideControl, "label": label!] var layoutConstraints = [NSLayoutConstraint]() layoutConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|-20-[slide]-20-|", options: [], metrics: nil, views: views) layoutConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-50-[slide(80)]-50-[label]", options: [.AlignAllLeading, .AlignAllTrailing], metrics: nil, views: views) NSLayoutConstraint.activateConstraints(layoutConstraints) } func didChange(sender: DHSlideControl) { print(sender.selectedIndex) label?.text = titles[sender.selectedIndex] } }
8171d53bdf0f2b789465c14d2d9d2f1f
32.106383
180
0.713368
false
false
false
false
DikeyKing/WeCenterMobile-iOS
refs/heads/master
WeCenterMobile/Model/DataObject/Question.swift
gpl-2.0
1
// // Question.swift // WeCenterMobile // // Created by Darren Liu on 14/10/7. // Copyright (c) 2014年 ifLab. All rights reserved. // import AFNetworking import CoreData import Foundation class Question: DataObject { @NSManaged var attachmentKey: String? @NSManaged var body: String? @NSManaged var date: NSDate? @NSManaged var viewCount: NSNumber? @NSManaged var focusCount: NSNumber? @NSManaged var title: String? @NSManaged var updatedDate: NSDate? @NSManaged var answers: Set<Answer> @NSManaged var featuredObject: FeaturedQuestionAnswer? @NSManaged var questionFocusingActions: Set<QuestionFocusingAction> @NSManaged var questionPublishmentActions: Set<QuestionPublishmentAction> @NSManaged var topics: Set<Topic> @NSManaged var user: User? var focusing: Bool? = nil class func fetch(#ID: NSNumber, success: ((Question) -> Void)?, failure: ((NSError) -> Void)?) { let question = Question.cachedObjectWithID(ID) NetworkManager.defaultManager!.GET("Question Detail", parameters: [ "id": ID ], success: { data in let value = data["question_info"] as! NSDictionary question.id = Int(msr_object: value["question_id"])! question.title = value["question_content"] as? String question.body = value["question_detail"] as? String question.focusCount = Int(msr_object: value["focus_count"]) question.focusing = (Int(msr_object: value["has_focus"]) == 1) for (key, value) in data["answers"] as? [String: NSDictionary] ?? [:] { let answerID = value["answer_id"] as! NSNumber var answer: Answer! = filter(question.answers) { $0.id == answerID }.first if answer == nil { answer = Answer.cachedObjectWithID(answerID) question.answers.insert(answer) } answer.question = question answer.body = value["answer_content"] as? String answer.agreementCount = value["agree_count"] as? NSNumber if answer.user == nil { answer.user = User.cachedObjectWithID(Int(msr_object: value["uid"])!) } answer.user!.name = value["user_name"] as? String answer.user!.avatarURI = value["avatar_file"] as? String } for value in data["question_topics"] as! [NSDictionary] { let topicID = value["topic_id"] as! NSNumber let topic = Topic.cachedObjectWithID(topicID) topic.title = value["topic_title"] as? String question.topics.insert(topic) } success?(question) }, failure: failure) } func toggleFocus(#success: (() -> Void)?, failure: ((NSError) -> Void)?) { NetworkManager.defaultManager!.GET("Focus Question", parameters: [ "question_id": id ], success: { [weak self] data in if let self_ = self { self_.focusing = (data["type"] as! String == "add") if self_.focusCount != nil { self_.focusCount = self_.focusCount!.integerValue + (self!.focusing! ? 1 : -1) } } success?() }, failure: failure) } func uploadImageWithJPEGData(jpegData: NSData, success: ((Int) -> Void)?, failure: ((NSError) -> Void)?) -> AFHTTPRequestOperation { return NetworkManager.defaultManager!.request("Upload Attachment", GETParameters: [ "id": "question", "attach_access_key": attachmentKey!], POSTParameters: nil, constructingBodyWithBlock: { data in data?.appendPartWithFileData(jpegData, name: "qqfile", fileName: "image.jpg", mimeType: "image/jpeg") return }, success: { data in success?(Int(msr_object: data["attach_id"])!) return }, failure: failure)! } func post(#success: (() -> Void)?, failure: ((NSError) -> Void)?) { let topics = [Topic](self.topics) var topicsParameter = "" if topics.count == 1 { topicsParameter = topics[0].title! } else if topics.count > 1 { topicsParameter = join(",", map(topics, { $0.title! })) } let title = self.title! let body = self.body! NetworkManager.defaultManager!.POST("Post Question", parameters: [ "question_content": title, "question_detail": body, "attach_access_key": attachmentKey!, "topics": topicsParameter ], success: { [weak self] data in success?() return }, failure: failure) } }
ed63fd389917221a48adc826010b078b
38.328358
136
0.519545
false
false
false
false
pbunting/OHTreesStorageManagerKit
refs/heads/master
OHTreesStorageManagerApp/MasterViewController.swift
gpl-3.0
1
// // MasterViewController.swift // OHTreesStorageManagerApp // // Created by Paul Bunting on 4/10/16. // Copyright © 2016 Paul Bunting. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(MasterViewController.insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
c918b2d505ed78d3860ab4e83b17d11d
37.489362
157
0.696241
false
false
false
false
banxi1988/BXViewPager
refs/heads/master
Pod/Classes/BXTabLayout.swift
mit
1
// BXTab 将支持两种显示模式,一种是Tab 栏本身是可滚动的. // 比如 Android Google Play 中的顶栏就是可滚动的. 国内众多 的新闻客户端 Tab 栏也是可滚动的. // 可滚动的 Tab 栏可以指定可见的 Tab 数量,为了更灵活的控制,可见 Tab 数量可以指定为小数 public enum BXTabLayoutMode{ case scrollable(visibleItems:CGFloat) case fixed var isFixed:Bool{ switch self{ case .fixed: return true default: return false } } } public struct BXTabLayoutOptions{ public var minimumInteritemSpacing:CGFloat = 8 public static let defaultOptions = BXTabLayoutOptions() } public let BX_TAB_REUSE_IDENTIFIER = "bx_tabCell" // Build for target uimodel //locale (None, None) import UIKit import PinAuto // -BXTabLayout:v // _[hor0,t0,b0]:c // shadow[hor0,h1,b0]:v // indicator[w60,h2,b0]:v open class BXTabLayout : UIView,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource { lazy var collectionView :UICollectionView = { [unowned self] in return UICollectionView(frame: CGRect.zero, collectionViewLayout: self.flowLayout) }() fileprivate lazy var flowLayout:UICollectionViewFlowLayout = { let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumInteritemSpacing = 10 flowLayout.itemSize = CGSize(width:100,height:100) flowLayout.minimumLineSpacing = 0 flowLayout.sectionInset = UIEdgeInsets.zero flowLayout.scrollDirection = .vertical return flowLayout }() let shadowView = UIView(frame:CGRect.zero) let indicatorView = UIView(frame:CGRect.zero) open dynamic var showIndicator:Bool { get{ return !indicatorView.isHidden }set{ indicatorView.isHidden = !newValue } } open dynamic var showShadow:Bool{ get{ return !shadowView.isHidden }set{ shadowView.isHidden = !newValue } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func awakeFromNib() { super.awakeFromNib() commonInit() } var allOutlets :[UIView]{ return [collectionView,shadowView,indicatorView] } var allUICollectionViewOutlets :[UICollectionView]{ return [collectionView] } var allUIViewOutlets :[UIView]{ return [shadowView,indicatorView] } func commonInit(){ for childView in allOutlets{ addSubview(childView) childView.translatesAutoresizingMaskIntoConstraints = false } installConstaints() setupAttrs() } func installConstaints(){ collectionView.pac_vertical(0) collectionView.pac_horizontal(0) shadowView.pa_height.eq(1).install() shadowView.pa_bottom.eq(0).install() shadowView.pac_horizontal(0) indicatorView.pa_height.eq(2).install() indicatorView.pa_bottom.eq(0).install() indicatorView.pa_width.eq(60).install() } func setupAttrs(){ self.backgroundColor = UIColor(white: 0.912, alpha: 1.0) // 注意: 当 scrollDirection 为 .Horizontal 时,Item 之间的间距其实是 minmumLineSpacing flowLayout.minimumInteritemSpacing = options.minimumInteritemSpacing flowLayout.minimumLineSpacing = options.minimumInteritemSpacing flowLayout.scrollDirection = .horizontal collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.isScrollEnabled = true collectionView.backgroundColor = .white collectionView.delegate = self collectionView.dataSource = self registerClass(BXTabView.self) indicatorView.backgroundColor = self.tintColor } // MARK: Indicator View Support // 使用 dynamic 以便可以支付 appearance 的设置 open dynamic var indicatorColor:UIColor?{ get{ NSLog("get indicatorColor") return indicatorView.backgroundColor } set{ NSLog("set indicatorColor") indicatorView.backgroundColor = newValue } } open override func tintColorDidChange() { super.tintColorDidChange() if indicatorColor == nil{ indicatorView.backgroundColor = self.tintColor } } func reloadData(){ collectionView.reloadData() } open var mode:BXTabLayoutMode = .fixed{ didSet{ if collectionView.dataSource != nil{ itemSize = CGSize.zero reloadData() } } } fileprivate var tabs:[BXTab] = [] open var didSelectedTab: ( (BXTab) -> Void )? open var options:BXTabLayoutOptions = BXTabLayoutOptions.defaultOptions{ didSet{ itemSize = CGSize.zero flowLayout.minimumInteritemSpacing = options.minimumInteritemSpacing flowLayout.minimumLineSpacing = options.minimumInteritemSpacing // } } open func registerClass(_ cellClass: AnyClass?) { collectionView.register(cellClass, forCellWithReuseIdentifier: BX_TAB_REUSE_IDENTIFIER) } open func registerNib(_ nib: UINib?) { collectionView.register(nib, forCellWithReuseIdentifier: BX_TAB_REUSE_IDENTIFIER) } open func addTab(_ tab:BXTab,index:Int = 0,setSelected:Bool = false){ tabs.insert(tab, at: index) reloadData() if(setSelected){ selectTabAtIndex(index) } } open func updateTabs(_ tabs:[BXTab]){ self.tabs.removeAll() self.tabs.append(contentsOf: tabs) reloadData() if tabs.count > 0 { if let indexPaths = collectionView.indexPathsForSelectedItems , indexPaths.isEmpty{ collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .centeredHorizontally) } } } open func bx_delay(_ delay:TimeInterval,block:@escaping ()->()){ DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) , execute: block) } open func selectTabAtIndex(_ index:Int){ let indexPath = IndexPath(item: index, section: 0) collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally) if mode.isFixed{ self.onSelectedTabChanged() }else{ flowLayout.invalidateLayout() bx_delay(0.3){ self.onSelectedTabChanged() } } } open func tabAtIndexPath(_ indexPath:IndexPath) -> BXTab{ return tabs[(indexPath as NSIndexPath).item] } func onSelectedTabChanged(){ updateIndicatorView() } func updateIndicatorView(){ guard let indexPath = collectionView.indexPathsForSelectedItems?.first else{ return } if mode.isFixed{ let itemSize = flowLayout.itemSize let item = CGFloat((indexPath as NSIndexPath).item) let originX = collectionView.bounds.origin.x + (itemSize.width * item) + (flowLayout.minimumLineSpacing * item) let centerX = originX + itemSize.width * 0.5 UIView.animate(withDuration: 0.3, animations: { self.indicatorView.center.x = centerX }) }else{ guard let attrs = flowLayout.layoutAttributesForItem(at: indexPath) else{ return } NSLog("Current Selected Item Attrs:\(attrs)") let originX = attrs.frame.minX - collectionView.bounds.origin.x let centerX = originX + attrs.frame.width * 0.5 UIView.animate(withDuration: 0.3, animations: { self.indicatorView.center.x = centerX }) } } open override func layoutSubviews() { super.layoutSubviews() updateItemSize() updateIndicatorView() NSLog("\(#function)") } open override func didMoveToWindow() { super.didMoveToWindow() NSLog("\(#function)") } open var numberOfTabs:Int{ return tabs.count } // 自由类中实现中才可以被继承的子类重写,所以放在同一个类中 //MARK: UICollectionViewDataSource open func numberOfSections(in collectionView: UICollectionView) -> Int{ return 1 } open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return numberOfTabs } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let tab = tabAtIndexPath(indexPath) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BX_TAB_REUSE_IDENTIFIER, for: indexPath) as! BXTabViewCell cell.bind(tab) return cell } // MARK: UICollectionViewDelegate open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let tab = tabAtIndexPath(indexPath) tab.position = (indexPath as NSIndexPath).row didSelectedTab?(tab) onSelectedTabChanged() } fileprivate var itemSize:CGSize = CGSize.zero fileprivate func calculateItemWidth() -> CGFloat{ if collectionView.bounds.width < 1{ return 0 } let tabCount:CGFloat = CGFloat(numberOfTabs) var visibleTabCount = tabCount switch mode{ case .scrollable(let visibleItems): visibleTabCount = visibleItems default:break } let spaceCount :CGFloat = visibleTabCount - 1 let itemSpace = flowLayout.scrollDirection == .horizontal ? flowLayout.minimumLineSpacing: flowLayout.minimumInteritemSpacing let totalWidth = collectionView.bounds.width - itemSpace * spaceCount - flowLayout.sectionInset.left - flowLayout.sectionInset.right let itemWidth = totalWidth / visibleTabCount return itemWidth } fileprivate func calculateItemHeight() -> CGFloat{ if collectionView.bounds.height < 1{ return 0 } let height = collectionView.bounds.height - flowLayout.sectionInset.top - flowLayout.sectionInset.bottom return height } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if itemSize == CGSize.zero{ itemSize = CGSize(width: calculateItemWidth(),height: calculateItemHeight()) } return itemSize } func updateItemSize(){ itemSize = CGSize(width: calculateItemWidth(),height: calculateItemHeight()) flowLayout.itemSize = itemSize } }
b1feaa4ab5ae8077c6004772833a4b38
26.351499
163
0.697848
false
false
false
false
PeteShearer/SwiftNinja
refs/heads/master
028-TableView Actions/MasterDetail/MasterDetail/MasterViewController.swift
bsd-2-clause
1
// // MasterViewController.swift // MasterDetail // // Created by Peter Shearer on 12/12/16. // Copyright © 2016 Peter Shearer. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var objects = [Episode]() var selectedEpisode = Episode( episodeTitle: "", writerName: "", doctorName: "", episodeNumber: "", synopsis: "") override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. objects = EpisodeRepository.getEpisodeList() } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { (segue.destination as! DetailViewController).detailItem = selectedEpisode } } // MARK: - Table View func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // You need to declare this method or else you can't swipe } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in self.objects.remove(at: indexPath.row) self.tableView.reloadData() } let selectToView = UITableViewRowAction(style: .normal, title: "Select") { (action, indexPath) in self.selectedEpisode = self.objects[indexPath.row] self.performSegue(withIdentifier: "showDetail", sender: nil) } selectToView.backgroundColor = UIColor.blue return [delete, selectToView] } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell let episode = objects[indexPath.row] cell.textLabel?.text = episode.episodeTitle cell.detailTextLabel?.text = episode.episodeNumber return cell } }
1ccf5c7e4797a0621e67e4614b027abe
32.654321
148
0.647102
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/public/core/Builtin.swift
apache-2.0
3
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // Definitions that make elements of Builtin usable in real code // without gobs of boilerplate. @available(*, unavailable, message: "use MemoryLayout<T>.size instead.") public func sizeof<T>(_:T.Type) -> Int { Builtin.unreachable() } @available(*, unavailable, renamed: "MemoryLayout.size(ofValue:)") public func sizeofValue<T>(_:T) -> Int { Builtin.unreachable() } @available(*, unavailable, message: "use MemoryLayout<T>.alignment instead.") public func alignof<T>(_:T.Type) -> Int { Builtin.unreachable() } @available(*, unavailable, renamed: "MemoryLayout.alignment(ofValue:)") public func alignofValue<T>(_:T) -> Int { Builtin.unreachable() } @available(*, unavailable, message: "use MemoryLayout<T>.stride instead.") public func strideof<T>(_:T.Type) -> Int { Builtin.unreachable() } @available(*, unavailable, renamed: "MemoryLayout.stride(ofValue:)") public func strideofValue<T>(_:T) -> Int { Builtin.unreachable() } // This function is the implementation of the `_roundUp` overload set. It is // marked `@inline(__always)` to make primary `_roundUp` entry points seem // cheap enough for the inliner. @_versioned @inline(__always) internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt { _sanityCheck(alignment > 0) _sanityCheck(_isPowerOf2(alignment)) // Note, given that offset is >= 0, and alignment > 0, we don't // need to underflow check the -1, as it can never underflow. let x = offset + UInt(bitPattern: alignment) &- 1 // Note, as alignment is a power of 2, we'll use masking to efficiently // get the aligned value return x & ~(UInt(bitPattern: alignment) &- 1) } @_versioned internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt { return _roundUpImpl(offset, toAlignment: alignment) } @_versioned internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int { _sanityCheck(offset >= 0) return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment)) } /// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe. @_transparent public // @testable func _canBeClass<T>(_: T.Type) -> Int8 { return Int8(Builtin.canBeClass(T.self)) } /// Returns the bits of the given instance, interpreted as having the specified /// type. /// /// Only use this function to convert the instance passed as `x` to a /// layout-compatible type when the conversion is not possible through other /// means. Common conversions that are supported by the standard library /// include the following: /// /// - To convert an integer value from one type to another, use an initializer /// or the `numericCast(_:)` function. /// - To perform a bitwise conversion of an integer value to a different type, /// use an `init(bitPattern:)` or `init(truncatingBitPattern:)` initializer. /// - To convert between a pointer and an integer value with that bit pattern, /// or vice versa, use the `init(bitPattern:)` initializer for the /// destination type. /// - To perform a reference cast, use the casting operators (`as`, `as!`, or /// `as?`) or the `unsafeDowncast(_:to:)` function. Do not use /// `unsafeBitCast(_:to:)` with class or pointer types; doing so may /// introduce undefined behavior. /// /// - Warning: Calling this function breaks the guarantees of Swift's type /// system; use with extreme care. /// /// - Parameters: /// - x: The instance to cast to `type`. /// - type: The type to cast `x` to. `type` and the type of `x` must have the /// same size of memory representation and compatible memory layout. /// - Returns: A new instance of type `U`, cast from `x`. @_transparent public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { _precondition(MemoryLayout<T>.size == MemoryLayout<U>.size, "can't unsafeBitCast between types of different sizes") return Builtin.reinterpretCast(x) } /// `unsafeBitCast` something to `AnyObject`. @_transparent internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject { return unsafeBitCast(x, to: AnyObject.self) } @_transparent func == (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @_transparent func != (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool { return !(lhs == rhs) } @_transparent func == (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @_transparent func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return !(lhs == rhs) } /// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both /// `nil` or they both represent the same type. public func == (t0: Any.Type?, t1: Any.Type?) -> Bool { return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self) } /// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both /// `nil` or they both represent the same type. public func != (t0: Any.Type?, t1: Any.Type?) -> Bool { return !(t0 == t1) } /// Tell the optimizer that this code is unreachable if condition is /// known at compile-time to be true. If condition is false, or true /// but not a compile-time constant, this call has no effect. @_transparent internal func _unreachable(_ condition: Bool = true) { if condition { // FIXME: use a parameterized version of Builtin.unreachable when // <rdar://problem/16806232> is closed. Builtin.unreachable() } } /// Tell the optimizer that this code is unreachable if this builtin is /// reachable after constant folding build configuration builtins. @_versioned @_transparent internal func _conditionallyUnreachable() -> Never { Builtin.conditionallyUnreachable() } @_versioned @_silgen_name("_swift_isClassOrObjCExistentialType") func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool /// Returns `true` iff `T` is a class type or an `@objc` existential such as /// `AnyObject`. @_versioned @inline(__always) internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool { switch _canBeClass(x) { // Is not a class. case 0: return false // Is a class. case 1: return true // Maybe a class. default: return _swift_isClassOrObjCExistentialType(x) } } /// Returns an `UnsafePointer` to the storage used for `object`. There's /// not much you can do with this other than use it to identify the /// object. @available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.") public func unsafeAddress(of object: AnyObject) -> UnsafeRawPointer { Builtin.unreachable() } @available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.") public func unsafeAddressOf(_ object: AnyObject) -> UnsafeRawPointer { Builtin.unreachable() } /// Converts a reference of type `T` to a reference of type `U` after /// unwrapping one level of Optional. /// /// Unwrapped `T` and `U` must be convertible to AnyObject. They may /// be either a class or a class protocol. Either T, U, or both may be /// optional references. @_transparent public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } /// - returns: `x as T`. /// /// - Precondition: `x is T`. In particular, in -O builds, no test is /// performed to ensure that `x` actually has dynamic type `T`. /// /// - Warning: Trades safety for performance. Use `unsafeDowncast` /// only when `x as! T` has proven to be a performance problem and you /// are confident that, always, `x is T`. It is better than an /// `unsafeBitCast` because it's more restrictive, and because /// checking is still performed in debug builds. @_transparent public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to: T.Type) -> T { _debugPrecondition(x is T, "invalid unsafeDowncast") return Builtin.castReference(x) } @inline(__always) public func _getUnsafePointerToStoredProperties(_ x: AnyObject) -> UnsafeMutableRawPointer { let storedPropertyOffset = _roundUp( MemoryLayout<_HeapObject>.size, toAlignment: MemoryLayout<Optional<AnyObject>>.alignment) return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) + storedPropertyOffset } //===----------------------------------------------------------------------===// // Branch hints //===----------------------------------------------------------------------===// // Use @_semantics to indicate that the optimizer recognizes the // semantics of these function calls. This won't be necessary with // mandatory generic inlining. @_versioned @_transparent @_semantics("branchhint") internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool { return Bool(Builtin.int_expect_Int1(actual._value, expected._value)) } /// Optimizer hint that `x` is expected to be `true`. @_transparent @_semantics("fastpath") public func _fastPath(_ x: Bool) -> Bool { return _branchHint(x, expected: true) } /// Optimizer hint that `x` is expected to be `false`. @_transparent @_semantics("slowpath") public func _slowPath(_ x: Bool) -> Bool { return _branchHint(x, expected: false) } /// Optimizer hint that the code where this function is called is on the fast /// path. @_transparent public func _onFastPath() { Builtin.onFastPath() } //===--- Runtime shim wrappers --------------------------------------------===// /// Returns `true` iff the class indicated by `theClass` uses native /// Swift reference-counting. #if _runtime(_ObjC) // Declare it here instead of RuntimeShims.h, because we need to specify // the type of argument to be AnyClass. This is currently not possible // when using RuntimeShims.h @_versioned @_silgen_name("swift_objc_class_usesNativeSwiftReferenceCounting") func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool #else @_versioned @inline(__always) func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool { return true } #endif @_silgen_name("swift_class_getInstanceExtents") func swift_class_getInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) @_silgen_name("swift_objc_class_unknownGetInstanceExtents") func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) /// - Returns: @inline(__always) internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int { #if _runtime(_ObjC) return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive) #else return Int(swift_class_getInstanceExtents(theClass).positive) #endif } //===--- Builtin.BridgeObject ---------------------------------------------===// #if arch(i386) || arch(arm) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0003 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0002 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #elseif arch(x86_64) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x7F00_0000_0000_0006 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 1 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0x8000_0000_0000_0001 } } #elseif arch(arm64) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x7F00_0000_0000_0007 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0x8000_0000_0000_0000 } } #elseif arch(powerpc64) || arch(powerpc64le) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0000_0000_0007 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0000_0000_0002 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #elseif arch(s390x) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0000_0000_0007 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0000_0000_0002 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #endif /// Extract the raw bits of `x`. @_versioned @inline(__always) internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt { return UInt(Builtin.castBitPatternFromBridgeObject(x)) } /// Extract the raw spare bits of `x`. @_versioned @inline(__always) internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt { return _bitPattern(x) & _objectPointerSpareBits } @_versioned @inline(__always) internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool { return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0 } /// Create a `BridgeObject` around the given `nativeObject` with the /// given spare bits. /// /// Reference-counting and other operations on this /// object will have access to the knowledge that it is native. /// /// - Precondition: `bits & _objectPointerIsObjCBit == 0`, /// `bits & _objectPointerSpareBits == bits`. @_versioned @inline(__always) internal func _makeNativeBridgeObject( _ nativeObject: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _sanityCheck( (bits & _objectPointerIsObjCBit) == 0, "BridgeObject is treated as non-native when ObjC bit is set" ) return _makeBridgeObject(nativeObject, bits) } /// Create a `BridgeObject` around the given `objCObject`. @inline(__always) public // @testable func _makeObjCBridgeObject( _ objCObject: AnyObject ) -> Builtin.BridgeObject { return _makeBridgeObject( objCObject, _isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit) } /// Create a `BridgeObject` around the given `object` with the /// given spare bits. /// /// - Precondition: /// /// 1. `bits & _objectPointerSpareBits == bits` /// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise, /// `object` is either a native object, or `bits == /// _objectPointerIsObjCBit`. @_versioned @inline(__always) internal func _makeBridgeObject( _ object: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _sanityCheck(!_isObjCTaggedPointer(object) || bits == 0, "Tagged pointers cannot be combined with bits") _sanityCheck( _isObjCTaggedPointer(object) || _usesNativeSwiftReferenceCounting(type(of: object)) || bits == _objectPointerIsObjCBit, "All spare bits must be set in non-native, non-tagged bridge objects" ) _sanityCheck( bits & _objectPointerSpareBits == bits, "Can't store non-spare bits into Builtin.BridgeObject") return Builtin.castToBridgeObject( object, bits._builtinWordValue ) } @_versioned @_silgen_name("_swift_class_getSuperclass") internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass? /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// a root class or class protocol. @inline(__always) public // @testable func _getSuperclass(_ t: AnyClass) -> AnyClass? { return _swift_class_getSuperclass(t) } /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// not a class, is a root class, or is a class protocol. @inline(__always) public // @testable func _getSuperclass(_ t: Any.Type) -> AnyClass? { return (t as? AnyClass).flatMap { _getSuperclass($0) } } //===--- Builtin.IsUnique -------------------------------------------------===// // _isUnique functions must take an inout object because they rely on // Builtin.isUnique which requires an inout reference to preserve // source-level copies in the presence of ARC optimization. // // Taking an inout object makes sense for two additional reasons: // // 1. You should only call it when about to mutate the object. // Doing so otherwise implies a race condition if the buffer is // shared across threads. // // 2. When it is not an inout function, self is passed by // value... thus bumping the reference count and disturbing the // result we are trying to observe, Dr. Heisenberg! // // _isUnique and _isUniquePinned cannot be made public or the compiler // will attempt to generate generic code for the transparent function // and type checking will fail. /// Returns `true` if `object` is uniquely referenced. @_versioned @_transparent internal func _isUnique<T>(_ object: inout T) -> Bool { return Bool(Builtin.isUnique(&object)) } /// Returns `true` if `object` is uniquely referenced or pinned. @_versioned @_transparent internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool { return Bool(Builtin.isUniqueOrPinned(&object)) } /// Returns `true` if `object` is uniquely referenced. /// This provides sanity checks on top of the Builtin. @_transparent public // @testable func _isUnique_native<T>(_ object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero, so // force cast it to BridgeObject and check the spare bits. _sanityCheck( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _sanityCheck(_usesNativeSwiftReferenceCounting( type(of: Builtin.reinterpretCast(object) as AnyObject))) return Bool(Builtin.isUnique_native(&object)) } /// Returns `true` if `object` is uniquely referenced or pinned. /// This provides sanity checks on top of the Builtin. @_transparent public // @testable func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero. _sanityCheck( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _sanityCheck(_usesNativeSwiftReferenceCounting( type(of: Builtin.reinterpretCast(object) as AnyObject))) return Bool(Builtin.isUniqueOrPinned_native(&object)) } /// Returns `true` if type is a POD type. A POD type is a type that does not /// require any special handling on copying or destruction. @_transparent public // @testable func _isPOD<T>(_ type: T.Type) -> Bool { return Bool(Builtin.ispod(type)) } /// Returns `true` if type is nominally an Optional type. @_transparent public // @testable func _isOptional<T>(_ type: T.Type) -> Bool { return Bool(Builtin.isOptional(type)) } @available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.") public func unsafeUnwrap<T>(_ nonEmpty: T?) -> T { Builtin.unreachable() } /// Extract an object reference from an Any known to contain an object. internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject { _sanityCheck(type(of: any) is AnyObject.Type || type(of: any) is AnyObject.Protocol, "Any expected to contain object reference") // With a SIL instruction, we could more efficiently grab the object reference // out of the Any's inline storage. // On Linux, bridging isn't supported, so this is a force cast. #if _runtime(_ObjC) return any as AnyObject #else return any as! AnyObject #endif } // Game the SIL diagnostic pipeline by inlining this into the transparent // definitions below after the stdlib's diagnostic passes run, so that the // `staticReport`s don't fire while building the standard library, but do // fire if they ever show up in code that uses the standard library. @inline(__always) public // internal with availability func _trueAfterDiagnostics() -> Builtin.Int1 { return true._value } /// Returns the dynamic type of a value. /// /// - Parameter of: The value to take the dynamic type of. /// - Returns: The dynamic type, which will be a value of metatype type. /// /// - Remark: If the parameter is statically of a protocol or protocol /// composition type, the result will be an *existential metatype* /// (`P.Type` for a protocol `P`), and will represent the type of the value /// inside the existential container with the same protocol conformances /// as the value. Otherwise, the result will be a *concrete metatype* /// (`T.Type` for a non-protocol type `T`, or `P.Protocol` for a protocol /// `P`). Normally, this will do what you mean, but one wart to be aware /// of is when you use `type(of:)` in a generic context with a type /// parameter bound to a protocol type: /// /// ``` /// func foo<T>(x: T) -> T.Type { /// return type(of: x) /// } /// protocol P {} /// func bar(x: P) { /// foo(x: x) // Call foo with T == P /// } /// ``` /// /// since the call to `type(of:)` inside `foo` only sees `T` as a concrete /// type, foo will end up returning `P.self` instead of the dynamic type /// inside `x`. This can be worked around by writing `type(of: x as Any)` /// to get the dynamic type inside `x` as an `Any.Type`. @_transparent @_semantics("typechecker.type(of:)") public func type<Type, Metatype>(of: Type) -> Metatype { // This implementation is never used, since calls to `Swift.type(of:)` are // resolved as a special case by the type checker. Builtin.staticReport(_trueAfterDiagnostics(), true._value, ("internal consistency error: 'type(of:)' operation failed to resolve" as StaticString).utf8Start._rawValue) Builtin.unreachable() } /// Allows a nonescaping closure to temporarily be used as if it were /// allowed to escape. /// /// This is useful when you need to pass a closure to an API that can't /// statically guarantee the closure won't escape when used in a way that /// won't allow it to escape in practice, such as in a lazy collection /// view: /// /// ``` /// func allValues(in array: [Int], matchPredicate: (Int) -> Bool) -> Bool { /// // Error because `lazy.filter` may escape the closure if the `lazy` /// // collection is persisted; however, in this case, we discard the /// // lazy collection immediately before returning. /// return array.lazy.filter { !matchPredicate($0) }.isEmpty /// } /// ``` /// /// or with `async`: /// /// ``` /// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void, /// on queue: DispatchQueue) { /// // Error: `async` normally escapes the closure, but in this case /// // we explicitly barrier before the closure would escape /// queue.async(f) /// queue.async(g) /// queue.sync(flags: .barrier) {} /// } /// ``` /// /// `withoutActuallyEscaping` provides a temporarily-escapable copy of the /// closure that can be used in these situations: /// /// ``` /// func allValues(in array: [Int], matchPredicate: (Int) -> Bool) -> Bool { /// return withoutActuallyEscaping(matchPredicate) { escapablePredicate in /// array.lazy.filter { !escapableMatchPredicate($0) }.isEmpty /// } /// } /// /// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void, /// on queue: DispatchQueue) { /// withoutActuallyEscaping(f) { escapableF in /// withoutActuallyEscaping(g) { escapableG in /// queue.async(escapableF) /// queue.async(escapableG) /// queue.sync(flags: .barrier) {} /// } /// } /// } /// ``` /// /// - Parameter closure: A non-escaping closure value that will be made /// escapable for the duration of the execution of the `do` block. /// - Parameter do: A code block that will be immediately executed, receiving /// an escapable copy of `closure` as an argument. /// - Returns: the forwarded return value from the `do` block. /// - Remark: It is undefined behavior for the escapable closure to be stored, /// referenced, or executed after `withoutActuallyEscaping` returns. A /// future version of Swift will introduce a dynamic check to trap if /// the escapable closure is still referenced at the point /// `withoutActuallyEscaping` returns. @_transparent @_semantics("typechecker.withoutActuallyEscaping(_:do:)") public func withoutActuallyEscaping<ClosureType, ResultType>( _ closure: ClosureType, do: (_ escapingClosure: ClosureType) throws -> ResultType ) rethrows -> ResultType { // This implementation is never used, since calls to // `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by // the type checker. Builtin.staticReport(_trueAfterDiagnostics(), true._value, ("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve" as StaticString).utf8Start._rawValue) Builtin.unreachable() }
247770a6b0716c5ceced6ad9fd80dbde
33.556757
110
0.690286
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Frontend/Browser/OpenInHelper.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import PassKit import WebKit import SnapKit import Shared import XCGLogger private let log = Logger.browserLogger struct OpenInViewUX { static let ViewHeight: CGFloat = 40.0 static let TextFont = UIFont.systemFont(ofSize: 16) static let TextColor = UIColor(red: 74.0/255.0, green: 144.0/255.0, blue: 226.0/255.0, alpha: 1.0) static let TextOffset = -15 static let OpenInString = NSLocalizedString("Open in…", comment: "String indicating that the file can be opened in another application on the device") } enum MimeType: String { case PDF = "application/pdf" case PASS = "application/vnd.apple.pkpass" } protocol OpenInHelper { init?(response: URLResponse) var openInView: OpenInView? { get } func open() } struct OpenIn { static let helpers: [OpenInHelper.Type] = [OpenPdfInHelper.self, OpenPassBookHelper.self, ShareFileHelper.self] static func helperForResponse(response: URLResponse) -> OpenInHelper? { return helpers.flatMap { $0.init(response: response) }.first } } class ShareFileHelper: NSObject, OpenInHelper { let openInView: OpenInView? = nil private var url: URL var pathExtension: String? required init?(response: URLResponse) { guard let MIMEType = response.mimeType, !(MIMEType == MimeType.PASS.rawValue || MIMEType == MimeType.PDF.rawValue), let responseURL = response.url else { return nil } url = responseURL super.init() } func open() { let alertController = UIAlertController( title: Strings.OpenInDownloadHelperAlertTitle, message: Strings.OpenInDownloadHelperAlertMessage, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction( UIAlertAction(title: Strings.OpenInDownloadHelperAlertCancel, style: .cancel, handler: nil)) alertController.addAction(UIAlertAction(title: Strings.OpenInDownloadHelperAlertConfirm, style: .default){ (action) in let objectsToShare = [self.url] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) UIApplication.shared.keyWindow?.rootViewController?.present(activityVC, animated: true, completion: nil) }) UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil) } } class OpenPassBookHelper: NSObject, OpenInHelper { let openInView: OpenInView? = nil private var url: URL required init?(response: URLResponse) { guard let MIMEType = response.mimeType, MIMEType == MimeType.PASS.rawValue && PKAddPassesViewController.canAddPasses(), let responseURL = response.url else { return nil } url = responseURL super.init() } func open() { let passData = try? Data(contentsOf: url) var error: NSError? = nil let pass = PKPass(data: passData!, error: &error) if let _ = error { // display an error let alertController = UIAlertController( title: Strings.UnableToAddPassErrorTitle, message: Strings.UnableToAddPassErrorMessage, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction( UIAlertAction(title: Strings.UnableToAddPassErrorDismiss, style: .cancel) { (action) in // Do nothing. }) UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil) return } let passLibrary = PKPassLibrary() if passLibrary.containsPass(pass) { UIApplication.shared.openURL(pass.passURL!) } else { let addController = PKAddPassesViewController(pass: pass) UIApplication.shared.keyWindow?.rootViewController?.present(addController, animated: true, completion: nil) } } } class OpenPdfInHelper: NSObject, OpenInHelper, UIDocumentInteractionControllerDelegate { private var url: URL private var docController: UIDocumentInteractionController? = nil private var openInURL: URL? lazy var openInView: OpenInView? = getOpenInView(self)() lazy var documentDirectory: URL = { return URL(string: NSTemporaryDirectory())!.appendingPathComponent("pdfs") }() private var filepath: URL? required init?(response: URLResponse) { guard let MIMEType = response.mimeType, MIMEType == MimeType.PDF.rawValue && UIApplication.shared.canOpenURL(URL(string: "itms-books:")!), let responseURL = response.url else { return nil } url = responseURL super.init() setFilePath(response.suggestedFilename ?? url.lastPathComponent ?? "file.pdf") } private func setFilePath(_ suggestedFilename: String) { var filename = suggestedFilename let pathExtension = filename.asURL?.pathExtension if pathExtension == nil { filename.append(".pdf") } filepath = documentDirectory.appendingPathComponent(filename) } deinit { guard let url = openInURL else { return } let fileManager = FileManager.default do { try fileManager.removeItem(at: url) } catch { log.error("failed to delete file at \(url): \(error)") } } func getOpenInView() -> OpenInView { let overlayView = OpenInView() overlayView.openInButton.addTarget(self, action: #selector(OpenPdfInHelper.open), for: .touchUpInside) return overlayView } func createDocumentControllerForURL(_ url: URL) { docController = UIDocumentInteractionController(url: url) docController?.delegate = self self.openInURL = url } func createLocalCopyOfPDF() { guard let filePath = filepath else { log.error("failed to create proper URL") return } if docController == nil{ // if we already have a URL but no document controller, just create the document controller if let url = openInURL { createDocumentControllerForURL(url) return } let contentsOfFile = try? Data(contentsOf: url) let fileManager = FileManager.default do { try fileManager.createDirectory(atPath: documentDirectory.absoluteString, withIntermediateDirectories: true, attributes: nil) if fileManager.createFile(atPath: filePath.absoluteString, contents: contentsOfFile, attributes: nil) { let openInURL = URL(fileURLWithPath: filePath.absoluteString) createDocumentControllerForURL(openInURL) } else { log.error("Unable to create local version of PDF file at \(filePath)") } } catch { log.error("Error on creating directory at \(self.documentDirectory)") } } } func open() { createLocalCopyOfPDF() guard let _parentView = self.openInView!.superview, let docController = self.docController else { log.error("view doesn't have a superview so can't open anything"); return } // iBooks should be installed by default on all devices we care about, so regardless of whether or not there are other pdf-capable // apps on this device, if we can open in iBooks we can open this PDF // simulators do not have iBooks so the open in view will not work on the simulator if UIApplication.shared.canOpenURL(URL(string: "itms-books:")!) { log.info("iBooks installed: attempting to open pdf") docController.presentOpenInMenu(from: .zero, in: _parentView, animated: true) } else { log.info("iBooks is not installed") } } } class OpenInView: UIView { let openInButton = UIButton() init() { super.init(frame: .zero) openInButton.setTitleColor(OpenInViewUX.TextColor, for: UIControlState.normal) openInButton.setTitle(OpenInViewUX.OpenInString, for: UIControlState.normal) openInButton.titleLabel?.font = OpenInViewUX.TextFont openInButton.sizeToFit() self.addSubview(openInButton) openInButton.snp_makeConstraints { make in make.centerY.equalTo(self) make.height.equalTo(self) make.trailing.equalTo(self).offset(OpenInViewUX.TextOffset) } self.backgroundColor = UIColor.white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
9beed789de6bed8de243898f4ed5203c
38.185022
181
0.659472
false
false
false
false
Wolkabout/WolkSense-Hexiwear-
refs/heads/master
iOS/Hexiwear/ForgotPasswordViewController.swift
gpl-3.0
1
// // Hexiwear application is used to pair with Hexiwear BLE devices // and send sensor readings to WolkSense sensor data cloud // // Copyright (C) 2016 WolkAbout Technology s.r.o. // // Hexiwear is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Hexiwear is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // // ForgotPasswordViewController.swift // import UIKit protocol ForgotPasswordDelegate { func didFinishResettingPassword() } class ForgotPasswordViewController: SingleTextViewController { var forgotPasswordDelegate: ForgotPasswordDelegate? @IBOutlet weak var emailText: UITextField! @IBOutlet weak var errorLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() skipButton.title = "Done" actionButton.title = "Reset" emailText.delegate = self emailText.text = "" title = "Reset password" errorLabel.isHidden = true } override func toggleActivateButtonEnabled() { if let em = emailText.text, isValidEmailAddress(em) { actionButton.isEnabled = true } else { actionButton.isEnabled = false } } override func actionButtonAction() { dataStore.resetPasswordForUserEmail(emailText.text!, onFailure: handleResetFail(reason:), onSuccess: { showSimpleAlertWithTitle(applicationTitle, message: "Check your email for new password.", viewController: self, OKhandler: { _ in self.forgotPasswordDelegate?.didFinishResettingPassword() }) } ) } func handleResetFail(reason: Reason) { switch reason { case .noSuccessStatusCode(let statusCode, _): guard statusCode != BAD_REQUEST && statusCode != NOT_AUTHORIZED else { DispatchQueue.main.async { showSimpleAlertWithTitle(applicationTitle, message: "There is no account registered with provided email.", viewController: self) self.view.setNeedsDisplay() } return } fallthrough default: DispatchQueue.main.async { showSimpleAlertWithTitle(applicationTitle, message: "There was a problem resetting your password. Please try again or contact our support.", viewController: self) self.view.setNeedsDisplay() } } } override func skipButtonAction() { forgotPasswordDelegate?.didFinishResettingPassword() } @IBAction func emailChanged(_ sender: UITextField) { toggleActivateButtonEnabled() errorLabel.isHidden = true self.view.setNeedsDisplay() } } extension ForgotPasswordViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
fb985053aa9d2a2070a06bbf7e9f27d3
34.106796
235
0.628595
false
false
false
false
igormatyushkin014/Verbose
refs/heads/master
Source/Verbose.swift
mit
1
// // Verbose.swift // Verbose // // Created by Igor Matyushkin on 07.11.15. // Copyright © 2015 Igor Matyushkin. All rights reserved. // import UIKit public class Verbose: NSObject { // MARK: Class variables & properties // MARK: Class methods /** Generates text with required length. - Parameters: - type: Type of text. - length: Required length of generated text. - replaceLastThreeSymbolsWithDots: Defines whether last three symbols in generated text should be replaced with dots. - returns: Text with required length. */ public class func textOfType(type: VerboseTextType, withLength length: Int, replaceLastThreeSymbolsWithDots: Bool) -> String { let unitText = type.text let resultText = generateTextWithUnit(unitText, length: length, replaceLastThreeSymbolsWithDots: replaceLastThreeSymbolsWithDots) return resultText } /** Generates text with required length. - Parameters: - textUnit: Unit of text that will be repeated in result string as many times as needed to fit required text length. - length: Required length of generated text. - replaceLastThreeSymbolsWithDots: Defines whether last three symbols in generated text should be replaced with dots. - returns: Text with required length. */ private class func generateTextWithUnit(textUnit: String, length: Int, replaceLastThreeSymbolsWithDots: Bool) -> String { // Create result text variable var resultText = "" // Fill result text with text unit until its length become bigger than required while resultText.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) < length { if resultText.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 { resultText += " " } resultText += textUnit } // Remove text which goes beyond of required length let lengthOfResultText = resultText.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) let resultTextIsBiggerThanRequiredLength = lengthOfResultText > length if resultTextIsBiggerThanRequiredLength { resultText = (resultText as NSString).substringToIndex(length) } // Replace last three symbols with dots if needed if replaceLastThreeSymbolsWithDots { // Obtain string with maximum possible number of dots between zero and three depending on length of result string var dots = "" for var i = 0; i < length; i++ { if i == 3 { break } dots += "." } // Replace end of result text with dots let indexWhereDotsBegin = length - dots.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) let resultTextBeforeDots = (resultText as NSString).substringToIndex(indexWhereDotsBegin) resultText = resultTextBeforeDots + dots } // Return result return resultText } // MARK: Initializers // MARK: Deinitializer deinit { } // MARK: Variables & properties // MARK: Public methods // MARK: Private methods // MARK: Protocol methods }
2c571ff3f267fd4ffa05a3839bc40154
27.728
137
0.59482
false
false
false
false
beauhankins/rhok-thankbank-ios
refs/heads/master
ThankBank/MainController.swift
mit
1
// // ViewController.swift // ThankBank // // Created by Beau Hankins on 13/06/2015. // Copyright (c) 2015 Beau Hankins. All rights reserved. // import Foundation import UIKit class MainController: UIViewController { let manager = AFHTTPRequestOperationManager() var fbUserId: String? lazy var coinImage: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = UIImage(named: "falling-coin") return imageView }() lazy var vaultImage: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = UIImage(named: "vault") return imageView }() lazy var checkInButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setBackgroundImage(UIImage(named: "check-in"), forState: .Normal) button.setBackgroundImage(UIImage(named: "check-in-pressed"), forState: .Highlighted) button.addTarget(self, action: "checkInController", forControlEvents: .TouchUpInside) return button }() lazy var profileButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Profile", forState: .Normal) button.setTitleColor(Colors().Black, forState: .Normal) button.addTarget(self, action: "profileController", forControlEvents: .TouchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() layoutInterface() } // MARK: - Interface override func prefersStatusBarHidden() -> Bool { return true } func layoutInterface() { UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: .Slide) view.backgroundColor = Colors().BackgroundDark view.addSubview(vaultImage) view.addSubview(coinImage) view.addSubview(checkInButton) view.addConstraint(NSLayoutConstraint(item: vaultImage, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: vaultImage, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: vaultImage, attribute: .Width, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 265.0)) view.addConstraint(NSLayoutConstraint(item: vaultImage, attribute: .Height, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 161.0)) view.addConstraint(NSLayoutConstraint(item: coinImage, attribute: .Bottom, relatedBy: .Equal, toItem: vaultImage, attribute: .Top, multiplier: 1, constant: -20)) view.addConstraint(NSLayoutConstraint(item: coinImage, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: coinImage, attribute: .Width, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 95.0)) view.addConstraint(NSLayoutConstraint(item: coinImage, attribute: .Height, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 135.0)) view.addConstraint(NSLayoutConstraint(item: checkInButton, attribute: .Top, relatedBy: .Equal, toItem: vaultImage, attribute: .Bottom, multiplier: 1, constant: 40)) view.addConstraint(NSLayoutConstraint(item: checkInButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: checkInButton, attribute: .Width, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 265.0)) view.addConstraint(NSLayoutConstraint(item: checkInButton, attribute: .Height, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 47.0)) } // MARK: - Navigation func checkInController() { if FBSDKAccessToken.currentAccessToken() != nil { self.getUserFBDetailsAsync() let checkInController = CheckInController() self.navigationController?.pushViewController(checkInController, animated: true) } else { let checkInAlert = UIAlertController(title: "Please connect with facebook to win and share your prizes", message: nil, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "No Thanks", style: .Cancel, handler: { (action: UIAlertAction!) -> Void in }) let okAction = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) -> Void in let login = FBSDKLoginManager() login.logInWithReadPermissions(["email"]) { (result: FBSDKLoginManagerLoginResult!, error: NSError!) -> Void in if error != nil { // Process error } else if result.isCancelled { // Handle cancellations } else { let checkInController = CheckInController() self.navigationController?.pushViewController(checkInController, animated: true) self.getUserFBDetailsAsync() } } }) checkInAlert.addAction(cancelAction) checkInAlert.addAction(okAction) presentViewController(checkInAlert, animated: true, completion: nil) } } func getUserFBDetailsAsync() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,first_name,last_name,email"]).startWithCompletionHandler({ (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in if error != nil { print(error?.description) } else { print("Fetched facebook user: \(result)") self.fbUserId = result["id"] as? String let fbFirstName = result["first_name"] as! String let fbLastName = result["last_name"] as! String let fbEmail = result["email"] as! String let fbAvatarUrl = "https://graph.facebook.com/\(self.fbUserId!)/picture?type=large&return_ssl_resources=1" self.manager.requestSerializer.setValue("aaiu73nklx0hhb0imn05ipz4dztbnlgonlnhmfjx", forHTTPHeaderField: "X-Auth-Token") let userParameters = [ "user": ["facebook_uid":self.fbUserId!, "email":fbEmail, "first_name":fbFirstName, "last_name":fbLastName, "avatar_url":fbAvatarUrl] ] print(userParameters) self.manager.POST( "http://brisbane-thank-bank.herokuapp.com/api/v1/users", parameters: userParameters, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in print("JSON: \(responseObject)") self.saveDefaults() }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in print("Error: \(error.localizedDescription)") }) } }) } } func profileController() { let checkInController = ProfileController() navigationController?.pushViewController(checkInController, animated: true) } // MARK: - NSUserDefaults func saveDefaults() { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(fbUserId, forKey: "checkin_facebook_uid") } }
10561ff33120e1e363d75ccd8a7016ea
42.819767
216
0.686969
false
false
false
false
Keenan144/SpaceKase
refs/heads/master
SpaceKase/GameScene.swift
mit
1
// // GameScene.swift // SpaceKase // // Created by Keenan Sturtevant on 5/29/16. // Copyright (c) 2016 Keenan Sturtevant. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { let shipCategory: UInt32 = 0x1 << 1 let rockCategory: UInt32 = 0x1 << 2 let boundaryCategory: UInt32 = 0x1 << 3 let healthCategory: UInt32 = 0x2 << 4 var score = NSInteger() var label = SKLabelNode(fontNamed: "Arial") var ship = SKSpriteNode() var rock = SKSpriteNode() var health = SKSpriteNode() var boosterRateTimer = NSTimer() var rockRateTimer = NSTimer() var healthRateTimer = NSTimer() var scoreLabel = SKLabelNode(fontNamed: "Arial") var exitLabel = SKLabelNode(fontNamed: "Arial") var invincibleLabel = SKLabelNode() var invincibilityTimer = Int32() var invincibilityNSTimer = NSTimer() var boundary = SKSpriteNode() var boundaryColor = UIColor.yellowColor() var backgroundColorCustom = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0) var touchLocation = CGPoint() override func didMoveToView(view: SKView) { view.showsPhysics = false physicsWorld.contactDelegate = self self.backgroundColor = backgroundColorCustom setBoundaries() spawnShip() start() } func setBoundaries() { setBottomBoundary() setLeftSideBoundry() setRightSideBoundry() } func start() { score = 0 Helper.toggleRun(true) showExitButton() showScore() rockTimer() healthTimer() boosterTimer() } func spawnShip(){ ship = SpaceShip.spawn(shipCategory, rockCategory: rockCategory, frame: self.frame) SpaceShip.setShipHealth(Helper.setShipHealth()) showHealth() self.addChild(ship) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches{ touchLocation = touch.locationInNode(self) let pos = touch.locationInNode(self) let node = self.nodeAtPoint(pos) if node == exitLabel { stopRocks() endGame() } else { touchLocation = touch.locationInNode(self) ship.position.x = touchLocation.x print(ship.position.x) } } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches{ touchLocation = touch.locationInNode(self) ship.position.x = touchLocation.x } } func didBeginContact(contact: SKPhysicsContact) { if (contact.bodyA.categoryBitMask == boundaryCategory) { contact.bodyB.node?.removeFromParent() print("GAMESCENE: scoreIncresed") increaseScore() refreshScoreView() } if (contact.bodyA.categoryBitMask == shipCategory) { contact.bodyB.node?.physicsBody?.collisionBitMask = 0 if (contact.bodyB.node?.name == "Health") { contact.bodyB.node?.removeFromParent() increaseHealth() } else if (contact.bodyB.node?.name == "ScoreBump") { contact.bodyB.node?.removeFromParent() bumpScore() } else if (contact.bodyB.node?.name == "Invincibility") { contact.bodyB.node?.removeFromParent() makeInvincible() showInvincibleLabel() } else if (contact.bodyB.node?.name == "Rock") { if Helper.isInvincible() == false { SpaceShip.deductHealth(Helper.deductHealth()) if SpaceShip.dead() { stopRocks() endGame() } } } refreshHealthView() } } func increaseHealth() { if Helper.canRun() { SpaceShip.health = SpaceShip.health + 5 } } func bumpScore() { if Helper.canRun() { score = score + 50 } } func increaseScore() { if Helper.canRun() { score = score + 5 } } func spawnRock() { if Helper.canRun() { rock = Rock.spawn() rock.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: frame.maxY) self.addChild(rock) } } func spawnHealth() { if Helper.canRun() { health = Health.spawn() health.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: frame.maxY) self.addChild(health) } } func randomSpawn() { if Helper.canRun() { if Helper.randomSpawn() == 1 { let boost = Boost.spawnInvincibility() boost.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: self.frame.maxY) self.addChild(boost) } else { let boost = Boost.spawnScoreBump() boost.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: self.frame.maxY) self.addChild(boost) } } } func boosterTimer() { boosterRateTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: ("randomSpawn"), userInfo: nil, repeats: true) } func rockTimer() { rockRateTimer = NSTimer.scheduledTimerWithTimeInterval(Helper.rockSpawnRate(), target: self, selector: ("spawnRock"), userInfo: nil, repeats: true) } func healthTimer() { healthRateTimer = NSTimer.scheduledTimerWithTimeInterval(5.3, target: self, selector: ("spawnHealth"), userInfo: nil, repeats: true) } func stopRocks() { Helper.toggleRun(false) } private func showHighScores() { Helper.setLastScore(score) } private func setBottomBoundary() { let boundary = Boundary.setBottomBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame) self.addChild(boundary) } private func setRightSideBoundry() { let boundary = Boundary.setRightSideBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame) self.addChild(boundary) } private func setLeftSideBoundry() { let boundary = Boundary.setLeftSideBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame) self.addChild(boundary) } private func showHealth() { let health = Health.showHealth(label) health.fontSize = 20 health.position = CGPoint(x: self.frame.minX + 55 , y: self.frame.maxY - 40) self.addChild(health) } func showInvincibleLabel() { if 15 - invincibilityTimer > 0 { invincibleLabel.removeFromParent() let invLabel = invincibleLabel invLabel.text = "Invincible: \(15 - invincibilityTimer)" invLabel.fontColor = UIColor.yellowColor() invLabel.fontSize = 20 invLabel.position = CGPoint(x: self.frame.minX + 55 , y: self.frame.maxY - 65) self.addChild(invLabel) } else { invincibleLabel.removeFromParent() } } private func showScore() { scoreLabel.text = "Score: \(score)" scoreLabel.fontSize = 20 scoreLabel.position = CGPoint(x: self.frame.maxX - 75 , y: self.frame.maxY - 40) self.addChild(scoreLabel) } func showExitButton() { if Helper.canRun() { exitLabel.text = "exit" exitLabel.fontSize = 20 exitLabel.position = CGPoint(x: self.frame.maxX - 55, y: self.frame.maxY - 80) self.addChild(exitLabel) } } private func refreshHealthView() { label.removeFromParent() showHealth() print("GAMESCENE: refreshHealthView") } private func refreshScoreView() { scoreLabel.removeFromParent() showScore() print("GAMESCENE: refreshScoreView") } private func endGame() { showHighScores() ship.removeAllActions() rock.removeAllActions() invincibleLabel.removeAllActions() let skView = self.view as SKView!; let gameScene = EndScene(size: (skView?.bounds.size)!) let transition = SKTransition.fadeWithDuration (2.0) boosterRateTimer.invalidate() rockRateTimer.invalidate() healthRateTimer.invalidate() view!.presentScene(gameScene, transition: transition) } private func makeInvincible() { if Helper.invincible == false { Helper.toggleInvincibility(true) invincibilityTimer = 1 startInvincibilityTimer() print("GAMESCENE: makeInvincible") } } @objc private func incrementInvincibilityTimer() { invincibilityTimer = invincibilityTimer + 1 showInvincibleLabel() if invincibilityTimer >= 15 { invincibilityNSTimer.invalidate() Helper.toggleInvincibility(false) print("GAMESCENE: incrementInvincibilityTimer") } } private func returnInvincibilityTime() -> Int32 { return invincibilityTimer } private func startInvincibilityTimer() { invincibilityNSTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: (#selector(GameScene.incrementInvincibilityTimer)), userInfo: nil, repeats: true) print("GAMESCENE: startInvincibilityTimer") } }
1ee1da34752c2f13dc23fc9a751cdb62
30.790997
179
0.585213
false
false
false
false
IndisputableLabs/Swifthereum
refs/heads/master
Examples/MacOS/MacEtherScan/MacEtherScan/ViewController.swift
mit
1
// // ViewController.swift // MacEtherScan // // Created by Ronald Mannak on 10/18/17. // Copyright © 2017 Indisputable Labs. All rights reserved. // import Cocoa import Swifthereum import BigInt // geth --rpc // testrpc // infura class ViewController: NSViewController { // let swifthereum = Swifthereum(provider: .web3(server: Server(domain: "https://mainnet.infura.io/mwHd0j5tlQUZ9zx3Lkv5"))) let swifthereum = Swifthereum(provider: .web3(server: Server())) override func viewDidLoad() { super.viewDidLoad() // getBalance() // getTransaction() // getAccounts() // testParameters() gasPrice() } func getBalance() { let address = Address(hex:"0x3914bff975ef35e8d3403e1ea953bf886b0e8fea")! print(address) address.balance(swifthereum: swifthereum) { result in switch result { case .data(let balance): break //print(BigInt(balance.remove0xPrefix(), radix: 16)!) default: break } } } func getTransaction() { let transaction = TransactionHash(hex: "0x7f853aea006cf7eb1f06b6aefcb1049a48a49bd93a0ae70e7e85b7b284d7662b")! transaction.transaction(swifthereum: swifthereum) { result in print(result) } } func gasPrice() { self.swifthereum.gasPrice(completion: { (result) in switch result { case .data(let weiString): let gasPrice = BigInt(weiString)! print(gasPrice) // let estTransaction = NewTransaction(from: firstAccount, to: secondAccount, gasPrice: gasPrice) // // self.swifthereum.estimateGas(for: <#T##NewTransaction#>, completion: <#T##(Result<String>) -> ()#>) default: fatalError() } }) } func getAccounts() { swifthereum.accounts { result in switch result { case .data(let accounts): guard let firstAccount = accounts.first else { fatalError() } let secondAccount = accounts[2] self.swifthereum.gasPrice(completion: { (result) in switch result { case .data(let weiString): let gasPrice = BigInt(weiString)! print(gasPrice) // let estTransaction = NewTransaction(from: firstAccount, to: secondAccount, gasPrice: gasPrice) // // self.swifthereum.estimateGas(for: <#T##NewTransaction#>, completion: <#T##(Result<String>) -> ()#>) default: fatalError() } }) // let transaction = NewTransaction( // public let from: Address? // public let to: Address // public let gas: Wei? // public let gasPrice: Wei? // public let value: HashString? // public let data: String? // public let nonce: Int? // ) // print("Account: \(firstAccount)") // default: fatalError() } } } func testParameters() { swifthereum.balance(for: Address(hex: "0xb81df5747f39bfd5ce9410f1be9b02851b0cbd6e")!) { result in print("result") } /* case .balance(let address, let defaultBlock): return [String(describing: address), defaultBlock.value] case .storage(let address, let defaultBlock): return [String(describing: address), defaultBlock.value] case .transactionCount(let address, let defaultBlock): return [String(describing: address), defaultBlock.value] case .blockTransactionCount(let blockHash): return String(describing: blockHash) case .blockTransactionCountByNumber(let number): return "\(number)" case .uncleCount(let blockHash): return String(describing: blockHash) case .uncleCountByBlockNumber(let number): return "\(number)" */ } }
e8f425e97b6e4d00aa724f04a13ed01f
31.42963
137
0.533805
false
false
false
false
mabels/ipaddress
refs/heads/main
swift/Sources/IpAddress/prefix128.swift
mit
1
//import Prefix from './prefix'; //import IpBits from './ip_bits'; public class Prefix128 { // #[derive(Ord,PartialOrd,Eq,PartialEq,Debug,Copy,Clone)] // pub struct Prefix128 { // } // // impl Prefix128 { // // Creates a new prefix object for 128 bits IPv6 addresses // // prefix = IPAddressPrefix128.new 64 // // => 64 // //#[allow(unused_comparisons)] public class func create(_ num: UInt8) -> Prefix? { if (num <= 128) { let ip_bits = IpBits.v6(); let bits = ip_bits.bits; return Prefix( num: num, ip_bits: ip_bits, net_mask: Prefix.new_netmask(num, bits), vt_from: Prefix128.from // vt_to_ip_str: _TO_IP_STR ); } return nil; } public class func from(_ my: Prefix, _ num: UInt8) -> Prefix? { return Prefix128.create(num); } }
b0600d74958559f41944ada2d98e7f86
22.583333
65
0.570082
false
false
false
false
Adlai-Holler/Bond
refs/heads/master
Bond/Bond+NSTextView.swift
mit
12
// // The MIT License (MIT) // // Copyright (c) 2015 Tony Arnold (@tonyarnold) // // 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 Cocoa var stringDynamicHandleNSTextView: UInt8 = 0; extension NSTextView: Dynamical, Bondable { public var designatedDynamic: Dynamic<String> { return self.dynString } public var designatedBond: Bond<String> { return self.designatedDynamic.valueBond } public var dynString: Dynamic<String> { if let d: AnyObject = objc_getAssociatedObject(self, &stringDynamicHandleNSTextView) { return (d as? Dynamic<String>)! } else { let d: InternalDynamic<String> = dynamicObservableFor(NSTextViewDidChangeTypingAttributesNotification, object: self) { notification -> String in if let textView = notification.object as? NSTextView { return textView.string ?? "" } else { return "" } } let bond = Bond<String>() { [weak d] v in // NSTextView cannot be referenced weakly if let d = d where !d.updatingFromSelf { self.string = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &stringDynamicHandleNSTextView, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return d } } } public func ->> (left: NSTextView, right: Bond<String>) { left.designatedDynamic ->> right } public func ->> <U: Bondable where U.BondType == String>(left: NSTextView, right: U) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: NSTextView, right: NSTextView) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: NSTextView, right: NSTextField) { left.designatedDynamic ->> right.designatedBond } public func ->> <T: Dynamical where T.DynamicType == String>(left: T, right: NSTextView) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: Dynamic<String>, right: NSTextView) { left ->> right.designatedBond } public func <->> (left: NSTextView, right: NSTextView) { left.designatedDynamic <->> right.designatedDynamic } public func <->> (left: Dynamic<String>, right: NSTextView) { left <->> right.designatedDynamic } public func <->> (left: NSTextView, right: Dynamic<String>) { left.designatedDynamic <->> right } public func <->> (left: NSTextView, right: NSTextField) { left.designatedDynamic <->> right.designatedDynamic }
7b161cd680b1d792a8c5ab459dc611cc
34.161905
136
0.666576
false
false
false
false
cactis/SwiftEasyKit
refs/heads/master
Source/Development.swift
mit
1
// // Development.swift // SwiftEasyKit // // Created by ctslin on 7/28/16. // Copyright © 2016 airfont. All rights reserved. // import Foundation public struct Development { // static var simulator = true public static var setDeviceAsSimulator = false public static var setSimulatorAsDevice = false public static var mode = "UI Design" // public static var mode = "API Implement" public static var developer = "All" public static var user = "" public static var password = "" public static var delayed: Double = 2000 public static var autoRun = true public static var prompt = true public static var uiTestMode = false { didSet { if uiTestMode { autoRun = false // prompt = true } } } public struct Log { public struct API { public static var request = true public static var response = true public static var statusCode = true public static var processInfo = false public static var header = true public static var parameters = true } } }
44e694024af7b2949a5d87ad652865a3
22.195652
50
0.660731
false
false
false
false
omaralbeik/SwifterSwift
refs/heads/master
Examples/Examples.playground/Pages/01-SwiftStdlibExtensions.xcplaygroundpage/Contents.swift
mit
1
//: [Table of Contents](00-ToC) //: [Previous](@previous) import SwifterSwift //: ## SwiftStdlib extensions //: ### Array extensions // Remove duplicates from an array var array = ["h", "e", "l", "l", "o"] array.removeDuplicates() //: ### Dictionary extensions var dict: [String: Any] = ["id": 1, "Product-Name": "SwifterSwift"] // Check if key exists in dictionary. dict.has(key: "id") // Lowercase all keys in dictionary. dict.lowercaseAllKeys() // Create JSON Data and string from a dictionary let json = dict.jsonString(prettify: true) //: ### Int extensions // Return square root of a number √9 // Return square power of a number 5 ** 2 // Return a number plus or minus another number 5 ± 2 // Return roman numeral for a number 134.romanNumeral //: ### Random Access Collection extensions // Return all indices of specified item ["h", "e", "l", "l", "o"].indices(of: "l") //: ### String extensions // Return count of substring in string "hello world".count(of: "", caseSensitive: false) // Return string with no spaces or new lines in beginning and end "\n Hello ".trimmed // Return most common character in string "swifterSwift is making swift more swifty".mostCommonCharacter() // Returns CamelCase of string "Some variable nAme".camelCased // Check if string is in valid email format "[email protected]".isEmail // Check if string contains at least one letter and one number "123abc".isAlphaNumeric // Reverse string var str1 = "123abc" str1.reverse() // Return latinized string var str2 = "Hèllö Wórld!" str2.latinize() // Create random string of length String.random(ofLength: 10) // Check if string contains one or more instance of substring "Hello World!".contains("o", caseSensitive: false) // Check if string contains one or more emojis "string👨‍with😍emojis✊🏿".containEmoji // Subscript strings easily "Hello"[safe: 2] // Slice strings let str = "Hello world" str.slicing(from: 6, length: 5) // Convert string to numbers "12.12".double // Encode and decode URLs "it's easy to encode strings".urlEncoded "it's%20easy%20to%20encode%20strings".urlDecoded // Encode and decode base64 "Hello World!".base64Encoded "SGVsbG8gV29ybGQh".base64Decoded // Truncate strings with a trailing "This is a very long sentence".truncated(toLength: 14, trailing: "...") // Repeat a string n times "s" * 5 // NSString has never been easier let boldString = "this is string".bold.colored(with: .red) //: [Next](@next)
0d8951441f8cb008b69d957be30e74d5
21.126126
71
0.712541
false
false
false
false
DeveloperLx/LxProjectTemplate
refs/heads/master
Carthage/Checkouts/PromiseKit/Categories/StoreKit/SKRequest+Promise.swift
mit
4
import StoreKit #if !COCOAPODS import PromiseKit #endif /** To import the `SKRequest` category: use_frameworks! pod "PromiseKit/StoreKit" And then in your sources: import PromiseKit */ extension SKRequest { public func promise() -> Promise<SKProductsResponse> { let proxy = SKDelegate() delegate = proxy proxy.retainCycle = proxy start() return proxy.promise } } private class SKDelegate: NSObject, SKProductsRequestDelegate { let (promise, fulfill, reject) = Promise<SKProductsResponse>.pendingPromise() var retainCycle: SKDelegate? #if os(iOS) @objc func request(request: SKRequest, didFailWithError error: NSError) { reject(error) retainCycle = nil } #else @objc func request(request: SKRequest, didFailWithError error: NSError?) { reject(error!) retainCycle = nil } #endif @objc func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) { fulfill(response) retainCycle = nil } @objc override class func initialize() { //FIXME Swift can’t see SKError, so can't do CancellableErrorType NSError.registerCancelledErrorDomain(SKErrorDomain, code: SKErrorPaymentCancelled) } }
c699937f70994f31ca5f560fa1bf4c8e
23.807692
109
0.683721
false
false
false
false
Ivacker/swift
refs/heads/master
test/Constraints/subscript.swift
apache-2.0
7
// RUN: %target-parse-verify-swift // Simple subscript of arrays: func simpleSubscript(array: [Float], x: Int) -> Float { _ = array[x] return array[x] } // Subscript of archetype. protocol IntToStringSubscript { subscript (i : Int) -> String { get } } class LameDictionary { subscript (i : Int) -> String { get { return String(i) } } } func archetypeSubscript<T : IntToStringSubscript, U : LameDictionary>(t: T, u: U) -> String { // Subscript an archetype. if false { return t[17] } // Subscript an archetype for which the subscript operator is in a base class. return u[17] } // Subscript of existential type. func existentialSubscript(a: IntToStringSubscript) -> String { return a[17] } class MyDictionary<Key, Value> { subscript (key : Key) -> Value { get {} } } class MyStringToInt<T> : MyDictionary<String, Int> { } // Subscript of generic type. func genericSubscript<T>(t: T, array: Array<Int>, i2i: MyDictionary<Int, Int>, t2i: MyDictionary<T, Int>, s2i: MyStringToInt<()>) -> Int { if true { return array[5] } if true { return i2i[5] } if true { return t2i[t] } return s2i["hello"] } // <rdar://problem/21364448> QoI: Poor error message for ambiguous subscript call extension String { func number() -> Int { } // expected-note {{found this candidate}} func number() -> Double { } // expected-note {{found this candidate}} } let _ = "a".number // expected-error {{ambiguous use of 'number()'}} extension Int { subscript(key: String) -> Int { get {} } // expected-note {{found this candidate}} subscript(key: String) -> Double { get {} } // expected-note {{found this candidate}} } let _ = 1["1"] // expected-error {{ambiguous use of 'subscript'}} // rdar://17687826 - QoI: error message when reducing to an untyped dictionary isn't helpful let squares = [ 1, 2, 3 ].reduce([:]) { (dict, n) in // expected-error {{cannot invoke 'reduce' with an argument list of type '([_ : _], @noescape (_, Int) throws -> _)'}} // expected-note @-1 {{expected an argument list of type '(T, combine: @noescape (T, Int) throws -> T)'}} var dict = dict // expected-error {{type of expression is ambiguous without more context}} dict[n] = n * n return dict }
bab87a3fe8f5ea176d665350d799cbb6
27.385542
171
0.617572
false
false
false
false
Explora-codepath/explora
refs/heads/master
Explora/LoginViewController.swift
mit
1
// // LoginViewController.swift // Explora // // Created by admin on 10/21/15. // Copyright © 2015 explora-codepath. All rights reserved. // import UIKit import ParseFacebookUtilsV4 import FBSDKCoreKit protocol LoginDelegate: class { func handleLoginSuccess(user: PFUser) } class LoginViewController: UIViewController { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! weak var delegate: LoginDelegate?; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. PFUser.logOut() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loginToFacebook() { PFFacebookUtils.logInInBackgroundWithReadPermissions(nil) { (user: PFUser?, error: NSError?) -> Void in if let user = user { user.getUserInfo() let message = "You've successfully logged in!" print(message) let alertController = UIAlertController(title: "Facebook Signin", message: message, preferredStyle: UIAlertControllerStyle.Alert) let button = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction) -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in self.delegate?.handleLoginSuccess(user) }) }) alertController.addAction(button) self.presentViewController(alertController, animated: true, completion: nil) } else { let message = "Uh oh. There was an error logging in through Facebook." print(message) let alertController = UIAlertController(title: "Facebook Signin", message: message, preferredStyle: UIAlertControllerStyle.Alert) let button = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(button) self.presentViewController(alertController, animated: true, completion: nil) } } } @IBAction func loginButtonPressed(sender: AnyObject) { let username = usernameField.text!; let password = passwordField.text!; PFUser.logInWithUsernameInBackground(username, password: password) { (user: PFUser?, error: NSError?) -> Void in if let user = user { // Do stuff after successful login. print(user) self.dismissViewControllerAnimated(true, completion: { () -> Void in self.delegate?.handleLoginSuccess(user) }) } else { // The login failed. Check error to see why. print(error) } } } @IBAction func cancelButtonPressed(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func facebookSignInButtonPressed(sender: AnyObject) { loginToFacebook() } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "SignUp" { if let signupVC = segue.destinationViewController as? SignUpViewController { signupVC.delegate = self.delegate } } } }
343ffd0fe4f1a4e6c618fca7a861e849
36.333333
145
0.615546
false
false
false
false
lambdaacademy/2015.01_swift
refs/heads/master
VoterApp/Voter/VoteUploader.swift
apache-2.0
1
// // VoteUploader.swift // Voter // // Created by Wojciech Nagrodzki on 22/02/15. // Copyright (c) 2015 Lambda Academy. All rights reserved. // import Foundation let updateURL = "http://voting.erlang-solutions.com/talk_api/update" let talksURL = "http://voting.erlang-solutions.com/talk_api/index" class VoteUploader: NSObject { func submitVotes(_ votes: NSDictionary, succeded: (() -> Void)?, failed: ((_ error: NSError?) -> Void)? = nil ) { print("Votes: \(votes)") var request = URLRequest(url: URL(string: updateURL)!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") print("Request: \(request)") let bodyData: Data? do { bodyData = try JSONSerialization.data(withJSONObject: votes, options: JSONSerialization.WritingOptions(rawValue: 0)) } catch let error as NSError { // TODO failed bodyData = nil } print("string: \(NSString(data: bodyData!, encoding: String.Encoding.utf8.rawValue))") request.httpBody = bodyData print("bodyData: \(bodyData)") print("headers: \(request.allHTTPHeaderFields)") let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in let httpResp = response as? HTTPURLResponse print("Response: \(response)") if let data = data { let strData = NSString(data: data, encoding: String.Encoding.utf8.rawValue) print("Body: \(strData)") } // var err: NSError? // var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) if (httpResp?.statusCode == 200) { if let s = succeded { s() } } else { failed?(error as NSError?) } }) task.resume() } func getTalks(_ succeded: ((NSArray) -> Void)?, failed: ((_ error: NSError?) -> Void)? = nil ) { var request = URLRequest(url: URL(string: talksURL)!) request.httpMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Content-Type") print("Request: \(request)") let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in print("Response: \(response)") print("Error: \(error)") if let httpResp = response as? HTTPURLResponse { let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) print("Body: \(strData)") do { let json: NSDictionary! = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSDictionary if (httpResp.statusCode == 200 && json != nil) { if let s = succeded { s(json["talks"] as! NSArray!) } } else { failed?(error as NSError?) } } catch { failed?(error as NSError?) } } }) task.resume() } }
b7115307c07ec3f76d54df01dc5168e1
34.876289
133
0.528161
false
false
false
false
LeonClover/DouYu
refs/heads/master
DouYuZB/DouYuZB/Classes/Tools/NetworkTools.swift
mit
1
// // NetworkTools.swift // Alamofire // // Created by 1 on 16/9/19. // Copyright © 2016年 小码哥. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) { // 1.获取类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post // 2.发送网络请求 Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in // 3.获取结果 guard let result = response.result.value else { print(response.result.error ?? "") return } // 4.将结果回调出去 finishedCallback(result) } } }
18d8e7dabc2757b550a43a96194fa2f3
23.75
159
0.548822
false
false
false
false
hoorace/Swift-Font-Awesome
refs/heads/master
Source/FontAwesome+UILabel.swift
mit
1
// // FontAwesome+UILabel.swift // Swift-Font-Awesome // // Created by longhao on 15/7/7. // Copyright (c) 2015年 longhao. All rights reserved. // import UIKit public extension UILabel { public var fa: Fa? { get { if let txt = text { //only support FaTextAlignment.Left if let index = FontContentArray.indexOf(txt.substringToIndex(txt.startIndex.advancedBy(1))) { return Fa(rawValue: index)! } } return nil } set { if let value = newValue { FontAwesome.sharedManager.registerFont() font = UIFont.fa(self.font.pointSize) if let txt = text { if let align = faTextAlignment { switch align { case .Left: text = value.text! + txt break case .Right: text = txt + value.text! break } } }else{ text = value.text! } } } } public var faTextAlignment: FaTextAlignment? { get { if let _align = align { return _align }else { return FaTextAlignment.Left } } set { align = newValue } } }
2dbc2392818e37e434168dbe14db6599
25.824561
110
0.405494
false
false
false
false
tlax/looper
refs/heads/master
looper/View/Loops/VLoopsFooter.swift
mit
1
import UIKit class VLoopsFooter:UICollectionReusableView { private weak var controller:CLoops? private weak var button:UIButton! private weak var layoutButtonLeft:NSLayoutConstraint! private let kButtonSize:CGFloat = 80 private let kButtonTop:CGFloat = 20 override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear let button:UIButton = UIButton() button.isUserInteractionEnabled = false button.translatesAutoresizingMaskIntoConstraints = false button.setImage( #imageLiteral(resourceName: "assetLoopsHelp").withRenderingMode(UIImageRenderingMode.alwaysOriginal), for:UIControlState.normal) button.setImage( #imageLiteral(resourceName: "assetLoopsHelp").withRenderingMode(UIImageRenderingMode.alwaysTemplate), for:UIControlState.highlighted) button.imageView!.tintColor = UIColor(white:0.97, alpha:1) button.imageView!.clipsToBounds = true button.imageView!.contentMode = UIViewContentMode.center button.addTarget( self, action:#selector(actionHelp(sender:)), for:UIControlEvents.touchUpInside) self.button = button addSubview(button) NSLayoutConstraint.topToTop( view:button, toView:self, constant:kButtonTop) NSLayoutConstraint.size( view:button, constant:kButtonSize) layoutButtonLeft = NSLayoutConstraint.leftToLeft( view:button, toView:self) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let remain:CGFloat = width - kButtonSize let margin:CGFloat = remain / 2.0 layoutButtonLeft.constant = margin super.layoutSubviews() } //MARK: actions func actionHelp(sender button:UIButton) { button.isUserInteractionEnabled = false controller?.help() } //MARK: public func config(controller:CLoops) { self.controller = controller button.isUserInteractionEnabled = true } }
14618104f05e88fdc5a63f262020b024
28.43038
113
0.630538
false
false
false
false
mahuiying0126/MDemo
refs/heads/master
BangDemo/BangDemo/Define/Comment/MThirdPartyDefinition.swift
mit
1
// // MThirdPartyDefinition.swift // BangDemo // // Created by yizhilu on 2017/8/21. // Copyright © 2017年 Magic. All rights reserved. // import Foundation public let UMENG_APIKEY = "54797a46fd98c53ad700125b" public let WeChatAppID = "wxaf676dee667d4f80" public let WeChatAppSecrect = "7e59a11bb58f8d2a4050bdfca1158586" public let QQAppID = "101070993" public let QQAppKEY = "fe145071ee22b561b19a475ce4404d60"
51112c97f3b1b9c87583704c4bbbd8cf
26.666667
64
0.780723
false
false
false
false
loudnate/Loop
refs/heads/master
WatchApp Extension/Controllers/HUDInterfaceController.swift
apache-2.0
1
// // HUDInterfaceController.swift // WatchApp Extension // // Created by Bharat Mediratta on 6/29/18. // Copyright © 2018 LoopKit Authors. All rights reserved. // import WatchKit class HUDInterfaceController: WKInterfaceController { private var activeContextObserver: NSObjectProtocol? @IBOutlet weak var loopHUDImage: WKInterfaceImage! @IBOutlet weak var glucoseLabel: WKInterfaceLabel! @IBOutlet weak var eventualGlucoseLabel: WKInterfaceLabel! var loopManager = ExtensionDelegate.shared().loopManager override func willActivate() { super.willActivate() update() if activeContextObserver == nil { activeContextObserver = NotificationCenter.default.addObserver(forName: LoopDataManager.didUpdateContextNotification, object: loopManager, queue: nil) { [weak self] _ in DispatchQueue.main.async { self?.update() } } } loopManager.requestGlucoseBackfillIfNecessary() } override func didDeactivate() { super.didDeactivate() if let observer = activeContextObserver { NotificationCenter.default.removeObserver(observer) } activeContextObserver = nil } func update() { guard let activeContext = loopManager.activeContext, let date = activeContext.loopLastRunDate else { loopHUDImage.setLoopImage(.unknown) return } glucoseLabel.setText("---") glucoseLabel.setHidden(false) eventualGlucoseLabel.setHidden(true) if let glucose = activeContext.glucose, let glucoseDate = activeContext.glucoseDate, let unit = activeContext.preferredGlucoseUnit, glucoseDate.timeIntervalSinceNow > -loopManager.settings.inputDataRecencyInterval { let formatter = NumberFormatter.glucoseFormatter(for: unit) if let glucoseValue = formatter.string(from: glucose.doubleValue(for: unit)) { let trend = activeContext.glucoseTrend?.symbol ?? "" glucoseLabel.setText(glucoseValue + trend) } if let eventualGlucose = activeContext.eventualGlucose { let glucoseValue = formatter.string(from: eventualGlucose.doubleValue(for: unit)) eventualGlucoseLabel.setText(glucoseValue) eventualGlucoseLabel.setHidden(false) } } loopHUDImage.setLoopImage({ switch date.timeIntervalSinceNow { case let t where t > .minutes(-6): return .fresh case let t where t > .minutes(-20): return .aging default: return .stale } }()) } @IBAction func addCarbs() { presentController(withName: AddCarbsInterfaceController.className, context: nil) } @IBAction func setBolus() { presentController(withName: BolusInterfaceController.className, context: loopManager.activeContext) } }
c9b4a2a7528507ff4397753bd0177202
32.505495
223
0.642178
false
false
false
false
thelvis4/Troublemaker
refs/heads/master
TroublemakerTests/IssueDataTests.swift
mit
1
// // IssueDataTests.swift // Troublemaker // // Created by Andrei Raifura on 11/23/15. // Copyright © 2015 Andrei Raifura. All rights reserved. // import Quick import Nimble @testable import Troublemaker class IssueDataTests : QuickSpec { override func spec() { describe("IssueData") { let title = "Test title" let filePath = "/Path/to/test/file.txt" let line: UInt = 1 let column: UInt? = nil let comparedData = IssueData(title: title, filePath: filePath, line: line, column: column) it("should be equal to a similar data") { let similatData = IssueData(title: title, filePath: filePath, line: line, column: column) expect(comparedData).to(equal(similatData)) } it("should not be equal to a different data") { let differentTitleData = IssueData(title: "bla bla", filePath: filePath, line: line, column: column) expect(comparedData).notTo(equal(differentTitleData)) let differentFilePathData = IssueData(title: title, filePath: "wrongPath", line: line, column: column) expect(comparedData).notTo(equal(differentFilePathData)) let differentLineData = IssueData(title: title, filePath: filePath, line: 3, column: column) expect(comparedData).notTo(equal(differentLineData)) let differentColumnData = IssueData(title: title, filePath: filePath, line: line, column: 3) expect(comparedData).notTo(equal(differentColumnData)) } } } }
6212edb0e92208ab609ad4f7ab7d43d2
38.651163
118
0.594135
false
true
false
false
cuzv/TinyCoordinator
refs/heads/master
Sample/UITableViewSample/TableViewFooterView.swift
mit
1
// // TableViewFooterView.swift // Copyright (c) 2016 Red Rain (https://github.com/cuzv). // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import TinyCoordinator import SnapKit class TableViewFooterView: UITableViewHeaderFooterView, TCReusableViewSupport { let descLabel: UILabel = { let label = UILabel() label.textColor = UIColor.black label.lineBreakMode = .byCharWrapping label.numberOfLines = 0 return label }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { contentView.backgroundColor = UIColor.yellow contentView.addSubview(descLabel) descLabel.snp.makeConstraints { (make) -> Void in make.edges.equalTo(contentView).inset(UIEdgeInsetsMake(8, 8, 8, 8)) } } var text: String = "" { didSet { descLabel.text = text } } override func layoutSubviews() { super.layoutSubviews() descLabel.preferredMaxLayoutWidth = descLabel.bounds.width } func populate(data: TCDataType) { if let data = data as? String { text = data } } }
38a6ceba16b712f06d1e1c3f2c0e578a
32.694444
81
0.671888
false
false
false
false
balitm/Sherpany
refs/heads/master
Sherpany/AppDelegate.swift
mit
1
// // AppDelegate.swift // Sherpany // // Created by Balázs Kilvády on 3/3/16. // Copyright © 2016 kil-dev. All rights reserved. // import UIKit import DATAStack @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // Model object of the application. var _model: Model! = nil override init() { super.init() let config = Config() _model = Model(config: config, dataStack: self.dataStack) } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if let navController = window?.rootViewController as? UINavigationController { let usersController = navController.topViewController as? UsersTableViewController // Set the network event indicator delegate of the model. _model.indicatorDelegate = self // Set the model for the "main"/users controller. usersController?.model = _model usersController?.dataStack = dataStack } UINavigationBar.appearance().barTintColor = UIColor(red: 75.0/255.0, green: 195.0/255.0, blue: 123.0/255.0, alpha: 1.0) UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { self.dataStack.persistWithCompletion(nil) } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { self.dataStack.persistWithCompletion(nil) } // MARK: - DATA stack lazy var dataStack: DATAStack = { let dataStack = DATAStack(modelName: "Sherpany") return dataStack }() } // MARK: - ModelNetworkIndicatorDelegate extension. extension AppDelegate: ModelNetworkIndicatorDelegate { func show() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func hide() { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } }
a66305fa0740155d1b6e88d03948f08e
36.270588
285
0.711399
false
false
false
false
IngmarStein/swift
refs/heads/master
test/SIL/Serialization/Inputs/def_generic_marker.swift
apache-2.0
32
public protocol mmGeneratorType { associatedtype Element } public protocol mmSequenceType { associatedtype Generator : mmGeneratorType } public protocol mmCollectionType : mmSequenceType { mutating func extend< S : mmSequenceType where S.Generator.Element == Self.Generator.Element > (_ seq: S) } public func test< EC1 : mmCollectionType, EC2 : mmCollectionType where EC1.Generator.Element == EC2.Generator.Element > (_ lhs: EC1, _ rhs: EC2) -> EC1 { var lhs = lhs lhs.extend(rhs) return lhs }
d8ee68f5950d5da76b6bdd1a1a144afc
20.875
55
0.721905
false
false
false
false
tonystone/tracelog
refs/heads/master
Sources/TraceLog/Internal/Utilities/Streams/RawOutputStream.swift
apache-2.0
1
/// /// RawOutputStream.swift /// /// Copyright 2019 Tony Stone /// /// 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. /// /// Created by Tony Stone on 1/27/19. /// import Foundation #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif internal class RawOutputStream { /// Designated initializer for this class. /// /// - Parameters: /// - fileDescriptor: The file descriptor associated with this OutputStream. /// - closeFd: Should we close this file descriptor on deinit and on request or not. If this is system stream such as stdout, then you don't want to close it so pass false. /// internal /* @testable and for use with Standard only */ init(fileDescriptor: Int32, closeFd: Bool) { self.fd = fileDescriptor self.closeFd = closeFd } deinit { self.close() } /// Close the file. /// func close() { if self.fd >= 0 && closeFd { self.close(self.fd) self.fd = -1 } } /// The file descriptor associated with this OutputStream. /// internal var fd: Int32 /// Should we close this file descriptor on deinit and on request or not. /// private let closeFd: Bool } /// OutputStream conformance for FileOutputStream. /// extension RawOutputStream: OutputStream { /// Writes the byte block to the File. /// /// - Note: We are forgoing locking of the file here since we write the data /// nearly 100% of the time in a single write() call. POSIX guarantees that /// if the file is opened in append mode, individual write() operations will /// be atomic. Partial writes are the only time that we can't write in a /// single call but with the minimal write sizes that are written, these /// will be almost non-existent. /// \ /// Per the [POSIX standard](http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html): /// \ /// "If the O_APPEND flag of the file status flags is set, the file offset /// shall be set to the end of the file prior to each write and no intervening /// file modification operation shall occur between changing the file offset /// and the write operation." /// func write(_ bytes: [UInt8]) -> Result<Int, OutputStreamError> { return bytes.withUnsafeBytes { (bufferPointer) -> Result<Int, OutputStreamError> in guard var buffer = bufferPointer.baseAddress else { return .failure(.invalidArgument("byte buffer empty, can not write.")) } var length = bufferPointer.count var written: Int = 0 /// Handle partial writes. /// repeat { written = self.write(self.fd, buffer, length) if written == -1 { if errno == EINTR { /// Always retry if interrupted. continue } return .failure(OutputStreamError.error(for: errno)) } length -= written buffer += written /// Exit if there are no more bytes (length != 0) or /// we wrote zero bytes (written != 0) /// } while (length != 0 && written != 0) return .success(written) } } } /// Private extension to work around Swifts confusion around similar function names. /// internal extension RawOutputStream { @inline(__always) func write(_ fd: Int32, _ buffer: UnsafeRawPointer, _ nbytes: Int) -> Int { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) return Darwin.write(fd, buffer, nbytes) #elseif os(Linux) || CYGWIN return Glibc.write(fd, buffer, nbytes) #endif } @inline(__always) func close(_ fd: Int32) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) Darwin.close(fd) #elseif os(Linux) || CYGWIN Glibc.close(fd) #endif } }
9362fa5c1ddc8b585933bd95fb2d8397
32.571429
180
0.586596
false
false
false
false
CrossWaterBridge/Attributed
refs/heads/master
Attributed/Modifier.swift
mit
1
// // Copyright (c) 2015 Hilton Campbell // // 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 public struct State { public var mutableAttributedString: NSMutableAttributedString public var range: NSRange public var stack: [MarkupElement] public var startElement: MarkupElement? public var endElement: MarkupElement? } public typealias Modifier = (_ state: State) -> Void public func modifierWithBaseAttributes(_ attributes: [NSAttributedString.Key: Any], modifiers: [Modifier]) -> Modifier { return { state in state.mutableAttributedString.addAttributes(attributes, range: state.range) for count in 0...state.stack.count { let localStack = Array(state.stack[0..<count]) for modifier in modifiers { var newState = state newState.stack = localStack modifier(newState) } } } } public typealias Map = (NSAttributedString) -> NSAttributedString public func selectMap(_ selector: String, _ map: @escaping Map) -> Modifier { return { state in guard let element = state.stack.last, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: map(attributedString)) } } public func selectMapBefore(_ selector: String, _ map: @escaping Map) -> Modifier { return { state in guard let element = state.startElement, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: map(attributedString)) } } public func selectMapAfter(_ selector: String, _ map: @escaping Map) -> Modifier { return { state in guard let element = state.endElement, state.stack.isEmpty, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: map(attributedString)) } } public typealias MapWithContext = (NSAttributedString, NSAttributedString) -> NSAttributedString public func selectMap(_ selector: String, _ mapWithContext: @escaping MapWithContext) -> Modifier { return { state in guard let element = state.stack.last, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: mapWithContext(state.mutableAttributedString, attributedString)) } } public func selectMapBefore(_ selector: String, _ mapWithContext: @escaping MapWithContext) -> Modifier { return { state in guard let element = state.startElement, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: mapWithContext(state.mutableAttributedString, attributedString)) } } public func selectMapAfter(_ selector: String, _ mapWithContext: @escaping MapWithContext) -> Modifier { return { state in guard let element = state.endElement, state.stack.isEmpty, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: mapWithContext(state.mutableAttributedString, attributedString)) } } public typealias MapWithElement = (MarkupElement, NSAttributedString) -> NSAttributedString public func selectMap(_ selector: String, _ mapWithElement: @escaping MapWithElement) -> Modifier { return { state in guard let element = state.stack.last, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: mapWithElement(element, attributedString)) } } public func selectMapBefore(_ selector: String, _ mapWithElement: @escaping MapWithElement) -> Modifier { return { state in guard let element = state.startElement, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: mapWithElement(element, attributedString)) } } public func selectMapAfter(_ selector: String, _ mapWithElement: @escaping MapWithElement) -> Modifier { return { state in guard let element = state.endElement, state.stack.isEmpty, selector ~= element else { return } let attributedString = state.mutableAttributedString.attributedSubstring(from: state.range) state.mutableAttributedString.replaceCharacters(in: state.range, with: mapWithElement(element, attributedString)) } }
ed87351aa37319247bbba16d7bfd4534
44.792593
143
0.737302
false
false
false
false
wesj/Project105
refs/heads/master
Project105/ReadingList.swift
mpl-2.0
1
// // ReadingList.swift // Project105 // // Created by Wes Johnston on 10/15/14. // Copyright (c) 2014 Wes Johnston. All rights reserved. // import UIKit public struct ReadingList { public static func getAll() -> [NSURL] { var list : [NSURL] = []; if (self.createDB()) { let (rows, err) = SD.executeQuery("SELECT * FROM Urls") if (err == nil) { println("Found \(rows.count) rows") for row in rows as [SwiftData.SDRow] { let url : String = row.values["Url"]?.value as String list.append(NSURL(string: url)!) } } } return list } public static func printToConsole() { if (self.createDB()) { let (rows, err) = SD.executeQuery("SELECT * FROM Urls") if (err == nil) { println("Found \(rows.count) rows") for row in rows as [SwiftData.SDRow] { let url = row.values["Url"] println("Found row \(url?.value)") } } else { println("Error in query \(err)") } } } private static func createDB() -> Bool { var tables = SD.existingTables() if (!contains(tables.result, "Urls")) { let err = SD.createTable("Urls", withColumnNamesAndTypes: ["Url": .StringVal]) if (err != nil) { println("Err creating db \(err)"); return false; } } return true; } public static func add(url : NSURL) { var urlString : NSString = url.absoluteString! if (!self.createDB()) { println("Couldn't create db"); return; } let err = SD.executeChange("INSERT INTO Urls (Url) VALUES (?)", withArgs: [urlString]) if (err != nil) { println("Err inserting in db \(err)"); } else { println("inserted \(url)") } } }
ecbea988de9316cb828db8816716be80
28.797101
94
0.474708
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/ABTestsController.swift
mit
1
import Foundation @objc public protocol ABTestsPersisting: AnyObject { func libraryValue(for key: String) -> NSCoding? func setLibraryValue(_ value: NSCoding?, for key: String) } @objc(WMFABTestsController) public class ABTestsController: NSObject { enum ABTestsError: Error { case invalidPercentage } struct ExperimentConfig { let experiment: Experiment let percentageKey: PercentageKey let bucketKey: BucketKey let bucketValueControl: BucketValue let bucketValueTest: BucketValue } public enum Experiment { case articleAsLivingDoc var config: ExperimentConfig { switch self { case .articleAsLivingDoc: return ABTestsController.articleAsLivingDocConfig } } } public enum PercentageKey: String { case articleAsLivingDocPercentKey } enum BucketKey: String { case articleAsLivingDocBucketKey } public enum BucketValue: String { case articleAsLivingDocTest = "LivingDoc_Test" case articleAsLivingDocControl = "LivingDoc_Control" } private static let articleAsLivingDocConfig = ExperimentConfig(experiment: .articleAsLivingDoc, percentageKey: .articleAsLivingDocPercentKey, bucketKey: .articleAsLivingDocBucketKey, bucketValueControl: .articleAsLivingDocControl, bucketValueTest: .articleAsLivingDocTest) private let persistanceService: ABTestsPersisting @objc public init(persistanceService: ABTestsPersisting) { self.persistanceService = persistanceService super.init() } // this will only generate a new bucket as needed (i.e. if the percentage is different than the last time bucket was generated) @discardableResult func determineBucketForExperiment(_ experiment: Experiment, withPercentage percentage: NSNumber) throws -> BucketValue { guard percentage.intValue >= 0 && percentage.intValue <= 100 else { throw ABTestsError.invalidPercentage } // if we have previously generated a bucket with the same percentage, return that value let maybeOldPercentage = percentageForExperiment(experiment) let maybeOldBucket = bucketForExperiment(experiment) if let oldPercentage = maybeOldPercentage, let oldBucket = maybeOldBucket, oldPercentage == percentage { return oldBucket } // otherwise generate new bucket let randomInt = Int.random(in: 1...100) let isInTest = randomInt <= percentage.intValue let bucket: BucketValue switch experiment { case .articleAsLivingDoc: bucket = isInTest ? .articleAsLivingDocTest : .articleAsLivingDocControl } setBucket(bucket, forExperiment: experiment) try setPercentage(percentage, forExperiment: experiment) return bucket } // MARK: Persistence setters/getters func percentageForExperiment(_ experiment: Experiment) -> NSNumber? { let key = experiment.config.percentageKey.rawValue return persistanceService.libraryValue(for: key) as? NSNumber } func setPercentage(_ percentage: NSNumber, forExperiment experiment: Experiment) throws { guard percentage.intValue >= 0 && percentage.intValue <= 100 else { throw ABTestsError.invalidPercentage } let key = experiment.config.percentageKey.rawValue persistanceService.setLibraryValue(percentage, for: key) } public func bucketForExperiment(_ experiment: Experiment) -> BucketValue? { let key = experiment.config.bucketKey.rawValue guard let rawValue = persistanceService.libraryValue(for: key) as? String else { return nil } return BucketValue(rawValue: rawValue) } func setBucket(_ bucket: BucketValue, forExperiment experiment: Experiment) { let key = experiment.config.bucketKey.rawValue persistanceService.setLibraryValue((bucket.rawValue as NSString), for: key) } }
a062b2503a361f49f6da56b61f1e96fa
33.634146
276
0.663615
false
true
false
false
ahmadbaraka/SwiftLayoutConstraints
refs/heads/master
SwiftLayoutConstraints/Classes/GreaterThan.swift
mit
1
// // GreaterThan.swift // Pods // // Created by Ahmad Baraka on 7/17/16. // // import Foundation infix operator ~>= { associativity right precedence 93 } /// Initializes and *activates* `NSLayoutConstraint` with `NSLayoutRelation.GreaterThanOrEqual` relation. public func ~>= <Value1: AnyObject, Value2: AnyObject, L2: LayoutConstraintType where L2.Value == Value2>(lhs: LhsLayoutConstraint<Value1>, rhs: L2) -> NSLayoutConstraint { return lhs ~>= RhsLayoutConstraint(constraint: rhs) } /// Initializes and *activates* `NSLayoutConstraint` with `NSLayoutRelation.GreaterThanOrEqual` relation. public func ~>= <Value1: AnyObject, Value2: AnyObject, L2: LayoutConstraintType where L2.Value == Value2?>(lhs: LhsLayoutConstraint<Value1>, rhs: L2) -> NSLayoutConstraint { return NSLayoutConstraint(lhs: lhs, rhs: rhs, relation: NSLayoutRelation.GreaterThanOrEqual) } /// Initializes and **activates* `NSLayoutConstraint` with `lhs` and `rhs` with nil object /// and `rhs` constant. /// /// e.g: `object.height ~>= 500` public func ~>= <Value: AnyObject>(lhs: LhsLayoutConstraint<Value>, rhs: CGFloat) -> NSLayoutConstraint { return lhs ~>= RhsLayoutConstraint<Value>(constant: rhs) } /// Initializes an **activates** `NSLayoutConstraint` array, where `rhs` values are taken from /// `lhs.` /// /// This is a shortcut to create for example: `object1.top | left | right ~>= object2.top | left | right.` public func ~>= <Value1: AnyObject, Value2: AnyObject>(lhs: [LhsLayoutConstraint<Value1>], rhs: Value2) -> [NSLayoutConstraint] { let right = lhs.map { RhsLayoutConstraint(rhs, constraint: $0) } return lhs ~>= right } /// Initializes an **activates** `NSLayoutConstraint` array, where `lhs` values are taken from /// `rhs.` /// /// This is a shortcut to create for example: `object1.top | left | right ~>= object2.top | left | right.` public func ~>= <Value1: AnyObject, Value2: AnyObject, L: LayoutConstraintType where L.Value == Value2>(lhs: Value1, rhs: [L]) -> [NSLayoutConstraint] { let left = rhs.map { LhsLayoutConstraint(lhs, constraint: $0) } return left ~>= rhs } /// Initializes an **activates** `NSLayoutConstraint` array, where `lhs` values are taken from /// `rhs.` /// /// This is a shortcut to create for example: `object1.top | left | right ~>= object2.top | left | right.` public func ~>= <Value1: AnyObject, Value2: AnyObject, L: LayoutConstraintType where L.Value == Value2?>(lhs: Value1, rhs: [L]) -> [NSLayoutConstraint] { let left = rhs.map { LhsLayoutConstraint(lhs, constraint: $0) } return left ~>= rhs } /// Initializes an **activates** `NSLayoutConstraint` array, /// applying `~>=` for each element in `lhs` to each element in `rhs.` public func ~>= <Value1: AnyObject, Value2: AnyObject, L: LayoutConstraintType where L.Value == Value2>(lhs: [LhsLayoutConstraint<Value1>], rhs: [L]) -> [NSLayoutConstraint] { return lhs ~>= rhs.map { RhsLayoutConstraint(constraint: $0) } } /// Initializes an **activates** `NSLayoutConstraint` array, /// applying `~>=` for each element in `lhs` to each element in `rhs.` public func ~>= <Value1: AnyObject, Value2: AnyObject, L: LayoutConstraintType where L.Value == Value2?>(lhs: [LhsLayoutConstraint<Value1>], rhs: [L]) -> [NSLayoutConstraint] { precondition(lhs.count == rhs.count) var constraints = [NSLayoutConstraint]() for i in 0..<lhs.count { constraints.append(lhs[i] ~>= rhs[i]) } return constraints }
a4fffd67e329ccf67966f99a9387e8dc
42.873418
176
0.694661
false
false
false
false
CharlinFeng/Reflect
refs/heads/master
Reflect/Convert3.swift
mit
2
// // Convert3.swift // Reflect // // Created by 成林 on 15/8/23. // Copyright (c) 2015年 冯成林. All rights reserved. // import Foundation /** 属性值为数组的转换 */ class Person3: Reflect { var name: String! var score: [Int]! var bags: [Bag]! class func convert(){ let person3 = Person3() person3.name = "jack" person3.score = [98,87,95] let bag1 = Bag(color: "red", price: 12) let bag2 = Bag(color: "blue", price: 15.8) person3.bags = [bag1,bag2] let dict = person3.toDict() print(dict) } }
4dcbfcfa10b2ecafffcd17b2e973fc66
15.384615
50
0.496088
false
false
false
false
getstalkr/stalkr-cloud
refs/heads/master
Sources/StalkrCloud/Extensions/String+Extensions.swift
mit
1
// // String+Hashed.swift // stalkr-cloud // // Created by Matheus Martins on 6/20/17. // // import Foundation import Vapor extension String { func hashed(by drop: Droplet) throws -> String { return try drop.hash.make(self.makeBytes()).makeString() } } struct RandomStringOptions: OptionSet { var rawValue: Set<Character> static let lowercase = RandomStringOptions.string("abcdefghijklmnopqrstuvwxyz") static let uppercase = RandomStringOptions.string("ABCDEFGHIJKLMONPQRSTUVWXYZ") static let numbers = RandomStringOptions.string("0123456789") static func string(_ string: String) -> RandomStringOptions { return RandomStringOptions(rawValue: Set<Character>(string.characters)) } init(rawValue: Set<Character>) { self.rawValue = rawValue } init() { self.rawValue = Set<Character>() } mutating func formUnion(_ other: RandomStringOptions) { self.rawValue.formUnion(other.rawValue) } mutating func formIntersection(_ other: RandomStringOptions) { self.rawValue.formIntersection(other.rawValue) } mutating func formSymmetricDifference(_ other: RandomStringOptions) { self.rawValue.formSymmetricDifference(other.rawValue) } } extension String { static func random(length: Int, options: RandomStringOptions) -> String { var randomString = "" let letters = options.rawValue for _ in 1...length { let randomIndex = Int(arc4random_uniform(UInt32(letters.count))) let a = letters.index(letters.startIndex, offsetBy: randomIndex) randomString += String(letters[a]) } return randomString } }
037a8bb16cacb8b858c9dcb3473d8107
26.857143
83
0.658689
false
false
false
false
jayrparro/iOS11-Examples
refs/heads/master
CoreML/WhatPic/WhatPic/ImageChooser.swift
mit
4
// // ImageChooser.swift // FaceDetection // // Created by Leonardo Parro on 27/7/17. // Copyright © 2017 Leonardo Parro. All rights reserved. // import Foundation import UIKit protocol ImageChooserDelegate { func didSelect(image: UIImage) } class ImageChooser: NSObject, UINavigationControllerDelegate { var vc: UIViewController? var delegate: ImageChooserDelegate? func choose(viewController vc: UIViewController) { let dialog = UIAlertController(title: "", message: "Choose image", preferredStyle: .actionSheet) //dialog.addAction(UIAlertAction(title: "Take picture", style: .default, handler: self.showCamera)) dialog.addAction(UIAlertAction(title: "Choose from photo library", style: .default, handler: self.chooseFromPhotoLibrary)) dialog.addAction(UIAlertAction(title: "Cancel", style: .cancel)) self.vc = vc vc.present(dialog, animated: true) } private func showCamera(action: UIAlertAction){ debugPrint("show camera") if UIImagePickerController.isSourceTypeAvailable(.camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .camera self.vc?.present(imagePicker, animated: true) } } private func chooseFromPhotoLibrary(action: UIAlertAction){ debugPrint("choose from photo library") if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .photoLibrary self.vc?.present(imagePicker, animated: true) } } } // MARK: - UIImagePickerControllerDelegate extension ImageChooser: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let anImage = info[UIImagePickerControllerOriginalImage] as? UIImage { delegate?.didSelect(image: anImage) } vc?.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { // do nothing... vc?.dismiss(animated: true, completion: nil) } }
ad9f75dfbecfa492ffb75049cf67daa2
33.955224
130
0.677199
false
false
false
false