repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringlengths
1
3
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jshultz/ios9-swift2-memorable-places
memorable-places/MapViewController.swift
1
9305
// // ViewController.swift // memorable-places // // Created by Jason Shultz on 10/15/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit import CoreData import CoreLocation import MapKit class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { var place: Places? = nil @IBOutlet weak var map: MKMapView! @IBAction func refreshLocation(sender: AnyObject) { locationManager.startUpdatingLocation() } var locationManager = CLLocationManager() override func viewDidLoad() { print("place", place) // Do any additional setup after loading the view, typically from a nib. locationManager.delegate = self locationManager.requestWhenInUseAuthorization() if activePlace == -1 { } else { let latitude = NSString(string: (place?.lat)!).doubleValue let longitude = NSString(string: (place?.lon!)!).doubleValue let latDelta:CLLocationDegrees = 0.01 // must use type CLLocationDegrees let lonDelta:CLLocationDegrees = 0.01 // must use type CLLocationDegrees let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) // Combination of two Delta Degrees let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) // Combination of the latitude and longitude variables let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) // takes span and location and uses those to set the region. self.map.setRegion(region, animated: false) // Take all that stuff and make a map! let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = place?.title annotation.subtitle = place?.user_description self.map.addAnnotation(annotation) } // Get Location locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.pausesLocationUpdatesAutomatically = true // Ending // User adds an annotation let uilpgr = UILongPressGestureRecognizer(target: self, action: "action:") uilpgr.minimumPressDuration = 2 map.addGestureRecognizer(uilpgr) // Ending } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let userLocation:CLLocation = locations[0] print("UserLocation: ", userLocation) let latitude:CLLocationDegrees = userLocation.coordinate.latitude let longitude:CLLocationDegrees = userLocation.coordinate.longitude let latDelta:CLLocationDegrees = 0.05 // must use type CLLocationDegrees let lonDelta:CLLocationDegrees = 0.05 // must use type CLLocationDegrees let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) // Combination of two Delta Degrees let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) // Combination of the latitude and longitude variables let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) // takes span and location and uses those to set the region. map.setRegion(region, animated: false) // Take all that stuff and make a map! locationManager.stopUpdatingLocation() } func action(gestureRecognizer:UIGestureRecognizer){ let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext if gestureRecognizer.state == UIGestureRecognizerState.Began { // Setup Connection // Bleh print("Gesture Recognized") var title = "" var subThoroughfare:String = "" var thoroughfare:String = "" var street:String = "" var locality:String = "" var region:String = "" var country:String = "" var administrativeArea:String = "" let touchPoint = gestureRecognizer.locationInView(self.map) let newCoordinate: CLLocationCoordinate2D = self.map.convertPoint(touchPoint, toCoordinateFromView: self.map) let location = CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude) CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in if (error == nil) { if let p = placemarks?[0] { print("name: ", p.name) print("p.subThoroughfare: ", p.subThoroughfare) print("p.thoroughfare", p.thoroughfare) if p.subThoroughfare != nil { subThoroughfare = String(p.subThoroughfare!) } else { subThoroughfare = "" } if p.thoroughfare != nil { thoroughfare = String(p.thoroughfare!) } else { thoroughfare = "" } if p.locality != nil { locality = String(p.locality!) } else { locality = "" } if p.region != nil { region = String(p.region!) } else { region = "" } if p.country != nil { country = String(p.country!) } else { country = "" } if p.administrativeArea != nil { administrativeArea = String(p.administrativeArea!) } else { administrativeArea = "" } if (p.name != "") { title = String(p.name!) } else { title = "\(subThoroughfare) \(thoroughfare)" } street = "\(subThoroughfare) \(thoroughfare)" } } if title == " " { title = "Added \(NSDate())" } let annotation = MKPointAnnotation() annotation.coordinate = newCoordinate annotation.title = title annotation.subtitle = "If you were here you would know it." self.map.addAnnotation(annotation) do { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let entityDescripition = NSEntityDescription.entityForName("Places", inManagedObjectContext: managedObjectContext) let place = Places(entity: entityDescripition!, insertIntoManagedObjectContext: managedObjectContext) place.setValue(String(title), forKey: "title") place.setValue(String(street), forKey: "street") place.setValue(String(locality), forKey: "locality") place.setValue(String(region), forKey: "region") place.setValue(String(country), forKey: "country") place.setValue(String(newCoordinate.latitude), forKey: "lat") place.setValue(String(newCoordinate.longitude), forKey: "lon") place.setValue(String(administrativeArea), forKey: "administrativeArea") do { print("place", place) try managedObjectContext.save() } catch { print("something went wrong") } } }) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { print("i am here") if segue.identifier == "newPlace" { print("in this spot") activePlace = -1 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
9cbc10f80ad8475b761c02c35789bee6
37.605809
152
0.508276
6.708003
false
false
false
false
xiaomudegithub/viossvc
viossvc/Scenes/Order/CustomView/SkillWidthLayout.swift
1
4851
// // SkillWidthLayout.swift // HappyTravel // // Created by J-bb on 16/11/5. // Copyright © 2016年 J-bb. All rights reserved. // import UIKit protocol SkillWidthLayoutDelegate : NSObjectProtocol { func autoLayout(layout:SkillWidthLayout, atIndexPath:NSIndexPath)->Float } class SkillWidthLayout: UICollectionViewFlowLayout { /** 默认属性 可外部修改 */ var columnMargin:CGFloat = 0.0 var rowMargin:CGFloat = 6.0 var skillSectionInset = UIEdgeInsetsMake(16.0, 16.0, 16.0, 16.0) var itemHeight:CGFloat = 24.0 var finalHeight:Float = 0.0 /* 需实现代理方法获取width */ weak var delegate:SkillWidthLayoutDelegate? var isLayouted = false private var currentX:Float = 0.0 private var currentY:Float = 0.0 private var currentMaxX:Float = 0.0 private var attributedAry:Array<UICollectionViewLayoutAttributes>? override init() { super.init() columnMargin = 10.0 rowMargin = 10.0 skillSectionInset = UIEdgeInsetsMake(10.0, 16.0, 16.0, 16.0) itemHeight = 30.0 attributedAry = Array() } required init?(coder aDecoder: NSCoder) { columnMargin = 10.0 rowMargin = 10.0 skillSectionInset = UIEdgeInsetsMake(10.0, 16.0, 16.0, 16.0) itemHeight = 24.0 attributedAry = Array() fatalError("init(coder:) has not been implemented") } override func prepareLayout() { currentX = Float(skillSectionInset.left) currentY = Float(skillSectionInset.top) currentMaxX = currentX attributedAry?.removeAll() if let count = collectionView?.numberOfItemsInSection(0) { for index in 0..<count { let atr = layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) attributedAry?.append(atr!) if index == count - 1 { isLayouted = true /** 在最后一个layout结束后 发送通知 或者下面👇这个方法里发通知 **** override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool ****** */ NSNotificationCenter.defaultCenter().postNotificationName("LayoutStop", object: nil, userInfo: nil) } } } } /** 判断是否需要重新计算layout 这里只需layout一次 */ override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return !isLayouted } /** 计算collectionView的Contensize - returns: */ override func collectionViewContentSize() -> CGSize { if let atr = attributedAry?.last { let frame = atr.frame let height = CGRectGetMaxY(frame) + skillSectionInset.bottom return CGSizeMake(0, height) } return CGSizeMake(0, 0) } /** 返回每个cell的UICollectionViewLayoutAttributes 逐个计算 - parameter indexPath: cell 所在的IndexPath - returns: 返回计算好的UICollectionViewLayoutAttributes */ override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { // storyBoard宽度 在layout的时候是在storyboard文件上的宽度,所以这里用屏幕宽度 // let maxWidth = collectionView?.frame.size.width let maxWidth = UIScreen.mainScreen().bounds.width let itemW = delegate!.autoLayout(self, atIndexPath:indexPath) let atr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) atr.frame = CGRectMake(CGFloat(currentX), CGFloat(currentY), CGFloat(itemW), itemHeight) currentMaxX = currentX + itemW + Float(skillSectionInset.right) if currentMaxX - Float(maxWidth) > 0 { currentX = Float(skillSectionInset.left) currentY = currentY + Float(itemHeight) + Float(rowMargin) atr.frame = CGRectMake(CGFloat(currentX), CGFloat(currentY), CGFloat(itemW), itemHeight) currentX = currentX + itemW + Float(columnMargin) } else { currentX = currentX + itemW + Float(columnMargin) } finalHeight = currentY + Float(itemHeight) + Float(skillSectionInset.bottom) return atr } /** layout数据源 - parameter rect: - returns: */ override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return attributedAry } }
apache-2.0
8f26cf05ddc3f1bbbeac7329b99ab14f
27.598765
119
0.599611
4.976369
false
false
false
false
SvenTiigi/PerfectAPIClient
Sources/PerfectAPIClient/APIClientProtocolExtension.swift
1
10721
// // APIClientProtocolExtension.swift // PerfectAPIClient // // Created by Sven Tiigi on 29.10.17. // import PerfectHTTP import PerfectCURL import ObjectMapper // MARK: Default implementation public extension APIClient { /// The current environment. Default case: .default /// - `default`: The default environment. Performs real network requests /// - tests: The tests environment uses mockedResult if available static var environment: APIClientEnvironment { get { // Return Environment from APIClientEnvironmentManager for APIClient return APIClientEnvironmentManager.shared.get(forAPIClient: self) } set(newValue) { // Set the Environment for the APIClient on APIClientEnvironmentManager APIClientEnvironmentManager.shared.set(newValue, forAPIClient: self) } } /// Get request URL by concatenating baseURL and current path /// /// - Returns: The request URL func getRequestURL() -> String { // Initialize baseUrl var baseUrl = self.baseURL // Initialize path var path = self.path // Check if baseUrl last character is not slash if baseUrl.last != "/" && !path.isEmpty { // Add a slash baseUrl += "/" } // Check if first character is slash if path.first == "/" { // Chop first character path = String(path.dropFirst()) } // Initialize request url var requestURL = baseUrl + path // Invoke modifyRequestURL self.modify(requestURL: &requestURL) // Return request url return requestURL } /// Modify the request url that is used to perform the API request /// /// - Parameter requestURL: The request url func modify(requestURL: inout String) {} /// Request the API endpoint to retrieve CURLResponse /// /// - Parameter completion: completion closure with APIClientResult func request(completion: ((APIClientResult<APIClientResponse>) -> Void)?) { // Initialize APIClientRequest for APIClient let request = APIClientRequest(apiClient: self) // Invoke will perform request self.willPerformRequest(request: request) // Perform API request with url and options and handle requestCompletion result self.performRequest(request) { (result: APIClientResult<APIClientResponse>) in // Invoke didRetrieveResponse with result self.didRetrieveResponse(request: request, result: result) // Unwrap completion clousre guard let completion = completion else { // No completion closure return out of function return } // Invoke completion with result completion(result) } } /// Request the API endpoint to retrieve response as mappable object /// /// - Parameters: /// - mappable: The mappable object type /// - completion: The completion closure with APIClientresult func request<T: BaseMappable>(mappable: T.Type, completion: @escaping (APIClientResult<T>) -> Void) { // Perform request to retrieve response self.request { (result: APIClientResult<APIClientResponse>) in // Analysis request result result.analysis(success: { (response: APIClientResponse) in // Unwrap payload JSON guard var json = response.getPayloadJSON() else { // Payload isn't a valid JSON let error = APIClientError.mappingFailed( reason: "Response payload isn't a valid JSON", response: response ) completion(.failure(error)) // Return out of function return } // Invoke modify responseJSON self.modify(responseJSON: &json, mappable: mappable) // Try to map response via mapped response type guard let mappedResponse = Mapper<T>().map(JSON: json) else { // Unable to map response let error = APIClientError.mappingFailed( reason: "Unable to map response for type: \(mappable)", response: response ) completion(.failure(error)) // Return out of function return } // Mapping succeded complete with success completion(.success(mappedResponse)) }, failure: { (error: APIClientError) in // Complete with error completion(.failure(error)) }) } } /// Request the API endpoint to retrieve response as mappable object array /// /// - Parameters: /// - mappable: The mappable object type /// - completion: The completion closure with APIClientResult func request<T: BaseMappable>(mappable: T.Type, completion: @escaping (APIClientResult<[T]>) -> Void) { // Perform request to retrieve response self.request { (result: APIClientResult<APIClientResponse>) in // Analysis request result result.analysis(success: { (response: APIClientResponse) in // Unwrap payload JSON guard var jsonArray = response.getPayloadJSONArray() else { // Payload isn't a valid JSON let error = APIClientError.mappingFailed( reason: "Response payload isn't a valid JSON Array", response: response ) completion(.failure(error)) // Return out of function return } // Invoke modify responseJSONArray self.modify(responseJSONArray: &jsonArray, mappable: mappable) // Map JSON Array to Mappable Object Array let mappedResponseArray = Mapper<T>().mapArray(JSONArray: jsonArray) // Check if ObjectMapper mapped the json array to given type if jsonArray.count != mappedResponseArray.count { // Unable to map response let error = APIClientError.mappingFailed( reason: "Unable to map response array for type: \(mappable)", response: response ) completion(.failure(error)) // Return out of function return } // Mapping succeded complete with success completion(.success(mappedResponseArray)) }, failure: { (error: APIClientError) in // Complete with error completion(.failure(error)) }) } } /// Modify response payload for mappable /// /// - Parameters: /// - responseJSON: The response JSON /// - mappable: The mappable object type that should be mapped to func modify(responseJSON: inout [String: Any], mappable: BaseMappable.Type) {} /// Modify response payload array for mappable /// /// - Parameters: /// - responseJSONArray: The response JSON array /// - mappable: The mappable object type that should be mapped to func modify(responseJSONArray: inout [[String: Any]], mappable: BaseMappable.Type) {} /// Indicating if the APIClient should return an error /// On a bad response code >= 300 and < 200 func shouldFailOnBadResponseStatus() -> Bool { // Default implementation return true return true } /// Will perform request to API endpoint /// /// - Parameters: /// - request: The APIClientRequest func willPerformRequest(request: APIClientRequest) {} /// Did retrieve response after request has initiated /// /// - Parameters: /// - request: The APIClientRequest /// - result: The APIClientResult func didRetrieveResponse(request: APIClientRequest, result: APIClientResult<APIClientResponse>) {} } // MARK: Perform Request Extension fileprivate extension APIClient { /// Perform API request which evaluates if a network request or a mocked response /// result should be returned via the request completion closure /// /// - Parameters: /// - url: The request url /// - options: The request options /// - requestCompletion: The request completion closure after result has been retrieved func performRequest(_ request: APIClientRequest, requestCompletion: @escaping (APIClientResult<APIClientResponse>) -> Void) { // Check if a mockedResult object is available and environment is under unit test conditions if let mockedResult = self.mockedResult, Self.environment == .tests { // Invoke requestCompletion with mockedResult requestCompletion(mockedResult) // Return out of function return } // Perform network request for url and options CURLRequest(request.url, options: request.options).perform { (curlResponse: () throws -> CURLResponse) in do { // Try to retrieve CURLResponse and construct APIClientResponse let response = APIClientResponse( request: request, curlResponse: try curlResponse() ) // Initialize result with success and response var result: APIClientResult<APIClientResponse> = .success(response) // Check if APIClient should fail on bad response status // and response isn't successful if self.shouldFailOnBadResponseStatus() && !response.isSuccessful { // Initialize APIClientError let error = APIClientError.badResponseStatus(response: response) // Override result with failure result = .failure(error) } // Invoke request completion with result requestCompletion(result) } catch { // Invoke requestCompletion with failure and error let connectionError = APIClientError.connectionFailed( error: error, request: request ) requestCompletion(.failure(connectionError)) } } } }
mit
952decc05b80a87a6dd148df620d1dfa
40.554264
113
0.580823
5.763978
false
false
false
false
naoyashiga/CatsForInstagram
Nekobu/SettingCollectionViewController+SNS.swift
1
1530
// // SettingCollectionViewController+SNS.swift // Nekobu // // Created by naoyashiga on 2015/08/23. // Copyright (c) 2015年 naoyashiga. All rights reserved. // import Foundation import Social extension SettingCollectionViewController { func openAppStore(urlStr:String){ let url = NSURL(string:urlStr) UIApplication.sharedApplication().openURL(url!) } func transitionToOtherAppPage() { let otherAppURL = NSLocalizedString("otherAppURL", tableName: "Setting", value: AppConstraints.otherAppURLString, comment: "") openAppStore(otherAppURL) } func transitionToReviewPage() { let reviewVC = ReviewViewController(nibName: "ReviewViewController", bundle: nil) reviewVC.modalPresentationStyle = .Custom reviewVC.transitioningDelegate = self view.window?.rootViewController?.presentViewController(reviewVC, animated: true, completion: nil) } func postToTwitter(){ let vc = SLComposeViewController(forServiceType: SLServiceTypeTwitter) vc.setInitialText(shareText) presentViewController(vc,animated:true,completion:nil) } func postToLINE(){ let encodedText = shareText.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! let shareURL = NSURL(string: "line://msg/text/" + encodedText) if UIApplication.sharedApplication().canOpenURL(shareURL!) { UIApplication.sharedApplication().openURL(shareURL!) } } }
mit
30154e4e5e876e8820e52f09415b918a
32.23913
134
0.693717
5.197279
false
false
false
false
TorIsHere/SwiftyProgressBar
SwiftyProgressBar/CircularProgressBar.swift
1
2172
// // CircularProgressBar.swift // SwiftyProgressBar // // Created by Kittikorn Ariyasuk on 2016/12/12. // Copyright © 2016 TorIsHere. All rights reserved. // import UIKit @IBDesignable open class CircularProgressBar: BaseCircleView { open var isAnimate: Bool = true open var withPercentage: Bool = true private var _label: UILabel? private var _labelText: String = "" open var labelText: String { get { return self._labelText } set(newText) { self._labelText = newText setNeedsDisplay() } } private var _progress: CGFloat = 0.0 open var cuurentProgress: CGFloat { get { return self._progress } set(newProgress) { var _newProgress = min(newProgress, 1.0) _newProgress = max(_newProgress, 0.0) self._progress = _newProgress setNeedsDisplay() } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ override open func draw(_ rect: CGRect) { if isAnimate { super.drawProgressBarWithAnimate(frame: bounds, progress: self._progress, fgColor: self.fgColor, bgColor: self.bgColor, callback: nil) } else { super.drawProgressBar(frame: bounds, progress: self._progress, fgColor: self.fgColor, bgColor: self.bgColor) } if withPercentage { if _label == nil { _label = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)) let center = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) _label!.center = center _label!.textAlignment = .center _label!.textColor = self.fgColor self.addSubview(_label!) } if let label = _label { label.text = "\(Int(_progress * 100)) %" } } } }
apache-2.0
38e209b238da2312e0422dcd72107de0
29.152778
146
0.561492
4.476289
false
false
false
false
bastienFalcou/SoundWave
Example/SoundWave/SoundWave+Helpers.swift
1
2157
// // SoundWave+Helpers.swift // SoundWave // // Created by Bastien Falcou on 12/6/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit extension URL { static func checkPath(_ path: String) -> Bool { let isFileExist = FileManager.default.fileExists(atPath: path) return isFileExist } static func documentsPath(forFileName fileName: String) -> URL? { let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let writePath = URL(string: documents)!.appendingPathComponent(fileName) var directory: ObjCBool = ObjCBool(false) if FileManager.default.fileExists(atPath: documents, isDirectory:&directory) { return directory.boolValue ? writePath : nil } return nil } } extension UIViewController { func showAlert(with error: Error) { let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in alertController.dismiss(animated: true, completion: nil) }) DispatchQueue.main.async { self.present(alertController, animated: true, completion: nil) } } } extension UIColor { static var mainBackgroundPurple: UIColor { return UIColor(red: 61.0 / 255.0, green: 28.0 / 255.0, blue: 105.0 / 255.0, alpha: 1.0) } static var audioVisualizationPurpleGradientStart: UIColor { return UIColor(red: 76.0 / 255.0, green: 62.0 / 255.0, blue: 127.0 / 255.0, alpha: 1.0) } static var audioVisualizationPurpleGradientEnd: UIColor { return UIColor(red: 133.0 / 255.0, green: 112.0 / 255.0, blue: 190.0 / 255.0, alpha: 1.0) } static var mainBackgroundGray: UIColor { return UIColor(red: 193.0 / 255.0, green: 188.0 / 255.0, blue: 167.0 / 255.0, alpha: 1.0) } static var audioVisualizationGrayGradientStart: UIColor { return UIColor(red: 130.0 / 255.0, green: 135.0 / 255.0, blue: 115.0 / 255.0, alpha: 1.0) } static var audioVisualizationGrayGradientEnd: UIColor { return UIColor(red: 83.0 / 255.0, green: 85.0 / 255.0, blue: 71.0 / 255.0, alpha: 1.0) } }
mit
be08c2c352811adc3fd20afbd0e715be
31.666667
118
0.697588
3.384615
false
false
false
false
Tim77277/WizardUIKit
WizardUIKit/WizardUIKit.swift
1
34103
/********************************************************** MIT License WizardUIKit Copyright (c) 2016 Wei-Ting Lin 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 public enum AlertStatus { case success case warning case error } public enum AlertAction { case delete case add case save case overwrite case download } public enum ProgressAlertStyle { case activityIndicator case horizontalProgressBar } public class Wizard { open static let UIKit = Wizard() open var statusAlert: WizardStatusAlert open var actionAlert: WizardActionAlert open var imageActionAlert: WizardImageActionAlert open var textFieldAlert: WizardTextFieldAlert open var namePicker: WizardNamePickerAlert open var datePicker: WizardDatePickerAlert open var progressAlert: WizardProgressAlert open var indicator: WizardIndicatorAlert public init(statusAlert: WizardStatusAlert = WizardStatusAlert(), actionAlert: WizardActionAlert = WizardActionAlert(), imageActionAlert: WizardImageActionAlert = WizardImageActionAlert(), textFieldAlert: WizardTextFieldAlert = WizardTextFieldAlert(), namePicker: WizardNamePickerAlert = WizardNamePickerAlert(), datePicker: WizardDatePickerAlert = WizardDatePickerAlert(), progressAlert: WizardProgressAlert = WizardProgressAlert(), indicator: WizardIndicatorAlert = WizardIndicatorAlert()) { self.statusAlert = statusAlert self.actionAlert = actionAlert self.imageActionAlert = imageActionAlert self.textFieldAlert = textFieldAlert self.namePicker = namePicker self.datePicker = datePicker self.progressAlert = progressAlert self.indicator = indicator } public class func showStatusAlert(alert: WizardStatusAlert, status: AlertStatus, title: String, message: String, viewController: UIViewController, completion: (() -> Void)?) { var statusOptions: WizardStatus! switch status { case .success: statusOptions = alert.successStatus statusOptions.titleLabel.text = title statusOptions.contentLabel.text = message case .warning: statusOptions = alert.warningStatus statusOptions.titleLabel.text = title statusOptions.contentLabel.text = message case .error: statusOptions = alert.errorStatus statusOptions.titleLabel.text = title statusOptions.contentLabel.text = message } let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "StatusAlertViewController") as! StatusAlertViewController vc.statusAlert = alert vc.statusOptions = statusOptions vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didConfim = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public func showStatusAlert(withStatus status: AlertStatus, title: String, message: String, viewController: UIViewController, completion: (() -> Void)?) { var statusOptions: WizardStatus! switch status { case .success: statusOptions = statusAlert.successStatus statusOptions.titleLabel.text = title statusOptions.contentLabel.text = message case .warning: statusOptions = statusAlert.warningStatus statusOptions.titleLabel.text = title statusOptions.contentLabel.text = message case .error: statusOptions = statusAlert.errorStatus statusOptions.titleLabel.text = title statusOptions.contentLabel.text = message } let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "StatusAlertViewController") as! StatusAlertViewController vc.statusAlert = statusAlert vc.statusOptions = statusOptions vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didConfim = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public class func showActionAlert(alert: WizardActionAlert, message: String, actionStyle: AlertAction, viewController: UIViewController, completion: (() -> Void)?) { var actionAlert = alert actionAlert.contentLabel.text = message switch actionStyle { case .save: actionAlert.titleLabel.text = "Save" actionAlert.actionButton?.backgroundColor = UIColor.WizardGreenColor() actionAlert.actionButton?.text = "Save" case .add: actionAlert.titleLabel.text = "Add" actionAlert.actionButton?.backgroundColor = UIColor.WizardGreenColor() actionAlert.actionButton?.text = "Add" case .download: actionAlert.titleLabel.text = "Download" actionAlert.actionButton?.backgroundColor = UIColor.WizardGreenColor() actionAlert.actionButton?.text = "Download" case .overwrite: actionAlert.titleLabel.text = "Overwrite" actionAlert.actionButton?.backgroundColor = UIColor.WizardRedColor() actionAlert.actionButton?.text = "Overwrite" case .delete: actionAlert.titleLabel.text = "Delete" actionAlert.actionButton?.backgroundColor = UIColor.WizardRedColor() actionAlert.actionButton?.text = "Delete" } let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ActionAlertViewController") as! ActionAlertViewController vc.actionAlert = actionAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirmAction = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public class func showActionAlert(alert: WizardActionAlert, title: String, message: String, viewController: UIViewController, completion: (() -> Void)?) { var actionAlert = alert actionAlert.titleLabel.text = title actionAlert.contentLabel.text = message let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ActionAlertViewController") as! ActionAlertViewController vc.actionAlert = actionAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirmAction = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public func showActionAlert(message: String, actionStyle: AlertAction, viewController: UIViewController, completion: (() -> Void)?) { var actionAlert = self.actionAlert actionAlert.contentLabel.text = message switch actionStyle { case .save: actionAlert.titleLabel.text = "Save" actionAlert.actionButton?.backgroundColor = UIColor.WizardGreenColor() actionAlert.actionButton?.text = "Save" case .add: actionAlert.titleLabel.text = "Add" actionAlert.actionButton?.backgroundColor = UIColor.WizardGreenColor() actionAlert.actionButton?.text = "Add" case .download: actionAlert.titleLabel.text = "Download" actionAlert.actionButton?.backgroundColor = UIColor.WizardGreenColor() actionAlert.actionButton?.text = "Download" case .overwrite: actionAlert.titleLabel.text = "Overwrite" actionAlert.actionButton?.backgroundColor = UIColor.WizardRedColor() actionAlert.actionButton?.text = "Overwrite" case .delete: actionAlert.titleLabel.text = "Delete" actionAlert.actionButton?.backgroundColor = UIColor.WizardRedColor() actionAlert.actionButton?.text = "Delete" } let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ActionAlertViewController") as! ActionAlertViewController vc.actionAlert = actionAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirmAction = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public func showActionAlert(withTitle title: String, message: String, viewController: UIViewController, completion: (() -> Void)?) { var actionAlert = self.actionAlert actionAlert.titleLabel.text = title actionAlert.contentLabel.text = message let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ActionAlertViewController") as! ActionAlertViewController vc.actionAlert = actionAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirmAction = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public class func showImageActionAlert(alert: WizardImageActionAlert, image: UIImage, message: String, viewController: UIViewController, completion: (() -> Void)?) { var imageActionAlert = alert imageActionAlert.image = image imageActionAlert.contentLabel.text = message let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ImageActionAlertViewController") as! ImageActionAlertViewController vc.imageActionAlert = imageActionAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirmAction = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public class func showImageActionAlert(alert: WizardImageActionAlert, message: String, action: AlertAction, viewController: UIViewController, completion: (() -> Void)?) { var imageActionAlert = alert imageActionAlert.contentLabel.text = message switch action { case .save: imageActionAlert.image = UIImage(named: "save", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardGreenColor() imageActionAlert.actionButton.text = "Save" case .add: imageActionAlert.image = UIImage(named: "add", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardGreenColor() imageActionAlert.actionButton.text = "Add" case .download: imageActionAlert.image = UIImage(named: "download", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardBlueColor() imageActionAlert.actionButton.text = "Download" case .overwrite: imageActionAlert.image = UIImage(named: "overwrite", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardRedColor() imageActionAlert.actionButton.text = "Overwrite" case .delete: imageActionAlert.image = UIImage(named: "delete", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardRedColor() imageActionAlert.actionButton.text = "Delete" } let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ImageActionAlertViewController") as! ImageActionAlertViewController vc.imageActionAlert = imageActionAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirmAction = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public func showImageActionAlert(withImage image: UIImage, message: String, viewController: UIViewController, completion: (() -> Void)?) { var imageActionAlert = self.imageActionAlert imageActionAlert.image = image imageActionAlert.contentLabel.text = message let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ImageActionAlertViewController") as! ImageActionAlertViewController vc.imageActionAlert = imageActionAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirmAction = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public func showImageActionAlert(message: String, action: AlertAction, viewController: UIViewController, completion: (() -> Void)?) { var imageActionAlert = self.imageActionAlert imageActionAlert.contentLabel.text = message switch action { case .save: imageActionAlert.image = UIImage(named: "save", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardGreenColor() imageActionAlert.actionButton.text = "Save" case .add: imageActionAlert.image = UIImage(named: "add", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardGreenColor() imageActionAlert.actionButton.text = "Add" case .download: imageActionAlert.image = UIImage(named: "download", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardBlueColor() imageActionAlert.actionButton.text = "Download" case .overwrite: imageActionAlert.image = UIImage(named: "overwrite", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardRedColor() imageActionAlert.actionButton.text = "Overwrite" case .delete: imageActionAlert.image = UIImage(named: "delete", in: kWizardBundle, compatibleWith: nil)! imageActionAlert.actionButton.backgroundColor = UIColor.WizardRedColor() imageActionAlert.actionButton.text = "Delete" } let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ImageActionAlertViewController") as! ImageActionAlertViewController vc.imageActionAlert = imageActionAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirmAction = { viewController.dismiss(animated: true, completion: nil) if completion != nil { completion!() } } viewController.present(vc, animated: true, completion: nil) } public class func showTextFieldAlert(alert: WizardTextFieldAlert, title: String, placeholder: String, viewController: UIViewController, completion: @escaping ((String)-> Void)) { var textFieldAlert = alert textFieldAlert.titleLabel.text = title textFieldAlert.textField.placeholder = placeholder let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "TextFieldAlertViewController") as! TextFieldAlertViewController vc.textFieldAlert = textFieldAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirm = { text in viewController.dismiss(animated: true, completion: nil) completion(text) } viewController.present(vc, animated: true, completion: nil) } public func showTextFieldAlert(title: String, placeholder: String, viewController: UIViewController, completion: @escaping ((String)-> Void)) { var textFieldAlert = self.textFieldAlert textFieldAlert.titleLabel.text = title textFieldAlert.textField.placeholder = placeholder let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "TextFieldAlertViewController") as! TextFieldAlertViewController vc.textFieldAlert = textFieldAlert vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } vc.didConfirm = { text in viewController.dismiss(animated: true, completion: nil) completion(text) } viewController.present(vc, animated: true, completion: nil) } public class func showNamePicker(picker: WizardNamePickerAlert,title: String, stringsForComponents:[[String]], selectedStringsForComponents:[String] = [], viewController: UIViewController, completion: @escaping ((([String], [Int]))-> Void)) { if Wizard.isNamePickerValid(stringsForComponents: stringsForComponents, selectedStringsForComponents: selectedStringsForComponents) { var namePicker = picker namePicker.titleLabel.text = title let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "NamePickerViewController") as! NamePickerViewController vc.stringsForComponents = stringsForComponents vc.selectedStringsForComponents = selectedStringsForComponents vc.namePicker = namePicker vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didPick = { (strings, indices) in viewController.dismiss(animated: true, completion: nil) completion((strings, indices)) } vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } viewController.present(vc, animated: true, completion: nil) } } public func showNamePicker(title: String, stringsForComponents:[[String]], selectedStringsForComponents:[String] = [], viewController: UIViewController, completion: @escaping ((([String], [Int]))-> Void)) { if isNamePickerValid(stringsForComponents: stringsForComponents, selectedStringsForComponents: selectedStringsForComponents) { var namePicker = self.namePicker namePicker.titleLabel.text = title let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "NamePickerViewController") as! NamePickerViewController vc.stringsForComponents = stringsForComponents vc.selectedStringsForComponents = selectedStringsForComponents vc.namePicker = namePicker vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didPick = { (strings, indices) in viewController.dismiss(animated: true, completion: nil) completion((strings, indices)) } vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } viewController.present(vc, animated: true, completion: nil) } } public class func showDatePicker(picker: WizardDatePickerAlert,title: String, datePickerMode: UIDatePickerMode, viewController: UIViewController, completion: @escaping (Date) -> ()) { var datePicker = picker datePicker.titleLabel.text = title datePicker.picker.mode = datePickerMode let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "DatePickerViewController") as! DatePickerViewController vc.datePicker = datePicker vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didPick = { selectedDate in viewController.dismiss(animated: true, completion: nil) completion(selectedDate) } vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } viewController.present(vc, animated: true, completion: nil) } public func showDatePicker(title: String, datePickerMode: UIDatePickerMode, viewController: UIViewController, completion: @escaping (Date) -> ()) { var datePicker = self.datePicker datePicker.titleLabel.text = title datePicker.picker.mode = datePickerMode let vc = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "DatePickerViewController") as! DatePickerViewController vc.datePicker = datePicker vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.didPick = { selectedDate in viewController.dismiss(animated: true, completion: nil) completion(selectedDate) } vc.didCancel = { viewController.dismiss(animated: true, completion: nil) } viewController.present(vc, animated: true, completion: nil) } public class func showProgressAlert(alert: WizardProgressAlert, viewController: UIViewController) { let progressAlert = alert classProgressViewController = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ProgressViewController") as! ProgressViewController classProgressViewController.progressAlert = progressAlert classProgressViewController.modalPresentationStyle = .overCurrentContext classProgressViewController.modalTransitionStyle = .crossDissolve viewController.present(classProgressViewController, animated: true, completion: nil) } public class func setProgress(progress: Float) { DispatchQueue.main.async { if classProgressViewController != nil { classProgressViewController.progressView.progress = progress } } } public class func hideProgressAlert() { if classProgressViewController != nil { DispatchQueue.main.async { classProgressViewController.dismiss(animated: true, completion: nil) classProgressViewController = nil } } } private var progressViewController: ProgressViewController! public func showProgressAlert(viewController: UIViewController) { let progressAlert = self.progressAlert progressViewController = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ProgressViewController") as! ProgressViewController progressViewController.progressAlert = progressAlert progressViewController.modalPresentationStyle = .overCurrentContext progressViewController.modalTransitionStyle = .crossDissolve viewController.present(progressViewController, animated: true, completion: nil) } public func setProgress(progress: Float) { DispatchQueue.main.async { if self.progressViewController != nil { self.progressViewController.progressView.progress = progress } } } public func hideProgressAlert() { if self.progressViewController != nil { DispatchQueue.main.async { self.progressViewController.dismiss(animated: true, completion: nil) self.progressViewController = nil } } } public class func showIndicator(indicator: WizardIndicatorAlert,withStyle style: IndicatorStyle, viewController: UIViewController) { var indicator = indicator switch style { case .white: indicator.color = UIColor.WizardBlueColor() indicator.backgroundColor = .white indicator.dimColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) case .black: indicator.color = .white indicator.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) indicator.dimColor = .clear } classIndicatorViewController = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ActivityIndicatorAlertViewController") as! ActivityIndicatorAlertViewController classIndicatorViewController.indicator = indicator classIndicatorViewController.modalPresentationStyle = .overCurrentContext classIndicatorViewController.modalTransitionStyle = .crossDissolve viewController.present(classIndicatorViewController, animated: true, completion: nil) } public class func showIndicator(indicator: WizardIndicatorAlert, viewController: UIViewController) { classIndicatorViewController = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ActivityIndicatorAlertViewController") as! ActivityIndicatorAlertViewController classIndicatorViewController.indicator = indicator classIndicatorViewController.modalPresentationStyle = .overCurrentContext classIndicatorViewController.modalTransitionStyle = .crossDissolve viewController.present(classIndicatorViewController, animated: true, completion: nil) } public class func hideIndicator() { if classIndicatorViewController != nil { DispatchQueue.main.async { classIndicatorViewController.dismiss(animated: true, completion: nil) classIndicatorViewController = nil } } } private var indicatorViewController: ActivityIndicatorAlertViewController! public func showIndicator(withStyle style: IndicatorStyle, viewController: UIViewController) { var indicator = self.indicator switch style { case .white: indicator.color = UIColor.WizardBlueColor() indicator.backgroundColor = .white indicator.dimColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) case .black: indicator.color = .white indicator.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) indicator.dimColor = .clear } indicatorViewController = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ActivityIndicatorAlertViewController") as! ActivityIndicatorAlertViewController indicatorViewController.indicator = indicator indicatorViewController.modalPresentationStyle = .overCurrentContext indicatorViewController.modalTransitionStyle = .crossDissolve viewController.present(indicatorViewController, animated: true, completion: nil) } public func showIndicator(viewController: UIViewController) { indicatorViewController = UIStoryboard(name: "Wizard", bundle: kWizardBundle).instantiateViewController(withIdentifier: "ActivityIndicatorAlertViewController") as! ActivityIndicatorAlertViewController indicatorViewController.indicator = indicator indicatorViewController.modalPresentationStyle = .overCurrentContext indicatorViewController.modalTransitionStyle = .crossDissolve viewController.present(indicatorViewController, animated: true, completion: nil) } public func hideIndicator() { if self.indicatorViewController != nil { DispatchQueue.main.async { self.indicatorViewController.dismiss(animated: true, completion: nil) self.indicatorViewController = nil } } } private class func isNamePickerValid(stringsForComponents:[[String]], selectedStringsForComponents:[String] = []) -> Bool { if stringsForComponents.count != selectedStringsForComponents.count && !selectedStringsForComponents.isEmpty { print("-- Failed to show name picker because stringsForComponents.count doesn't match to selectedStringsForComponents.count") return false } for stringsForComponent in stringsForComponents { if stringsForComponent.isEmpty { print("-- Failed to show name picker because each string array in stringsForComponents must have at least one item") return false } } return true } private func isNamePickerValid(stringsForComponents:[[String]], selectedStringsForComponents:[String] = []) -> Bool { if stringsForComponents.count != selectedStringsForComponents.count && !selectedStringsForComponents.isEmpty { print("-- Failed to show name picker because stringsForComponents.count doesn't match to selectedStringsForComponents.count") return false } for stringsForComponent in stringsForComponents { if stringsForComponent.isEmpty { print("-- Failed to show name picker because each string array in stringsForComponents must have at least one item") return false } } return true } }
mit
49fe9288a1a5338ec0030aaa6e9ab47d
46.365278
497
0.650031
5.804766
false
false
false
false
dictav/SwiftLint
Source/SwiftLintFramework/Extensions/File+Cache.swift
1
1186
// // File+Cache.swift // SwiftLint // // Created by Nikolaj Schumacher on 2015-05-26. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework private var structureCache = Cache({file in Structure(file: file)}) private var syntaxMapCache = Cache({file in SyntaxMap(file: file)}) private struct Cache<T> { private var values = [String: T]() private var factory: File -> T private init(_ factory: File -> T) { self.factory = factory } private mutating func get(file: File) -> T { guard let path = file.path else { return factory(file) } if let value = values[path] { return value } let value = factory(file) values[path] = value return value } private mutating func clear() { values.removeAll(keepCapacity: false) } } public extension File { public var structure: Structure { return structureCache.get(self) } public var syntaxMap: SyntaxMap { return syntaxMapCache.get(self) } public static func clearCaches() { structureCache.clear() syntaxMapCache.clear() } }
mit
a98e4f82bb769c47ca187a9947a433d5
20.962963
67
0.612985
4.205674
false
false
false
false
Yummypets/YPImagePicker
Source/Helpers/Extensions/AVAsset+Extensions.swift
1
2533
// // AVAsset+Extensions.swift // YPImagePicker // // Created by Nik Kov on 23.04.2018. // Copyright © 2018 Yummypets. All rights reserved. // import AVFoundation // MARK: Trim extension AVAsset { func assetByTrimming(startTime: CMTime, endTime: CMTime) throws -> AVAsset { let timeRange = CMTimeRangeFromTimeToTime(start: startTime, end: endTime) let composition = AVMutableComposition() do { for track in tracks { let compositionTrack = composition.addMutableTrack(withMediaType: track.mediaType, preferredTrackID: track.trackID) try compositionTrack?.insertTimeRange(timeRange, of: track, at: CMTime.zero) } } catch let error { throw YPTrimError("Error during composition", underlyingError: error) } // Reaply correct transform to keep original orientation. if let videoTrack = self.tracks(withMediaType: .video).last, let compositionTrack = composition.tracks(withMediaType: .video).last { compositionTrack.preferredTransform = videoTrack.preferredTransform } return composition } /// Export the video /// /// - Parameters: /// - destination: The url to export /// - videoComposition: video composition settings, for example like crop /// - removeOldFile: remove old video /// - completion: resulting export closure /// - Throws: YPTrimError with description func export(to destination: URL, videoComposition: AVVideoComposition? = nil, removeOldFile: Bool = false, completion: @escaping (_ exportSession: AVAssetExportSession) -> Void) -> AVAssetExportSession? { guard let exportSession = AVAssetExportSession(asset: self, presetName: YPConfig.video.compression) else { ypLog("AVAsset -> Could not create an export session.") return nil } exportSession.outputURL = destination exportSession.outputFileType = YPConfig.video.fileType exportSession.shouldOptimizeForNetworkUse = true exportSession.videoComposition = videoComposition if removeOldFile { try? FileManager.default.removeFileIfNecessary(at: destination) } exportSession.exportAsynchronously(completionHandler: { completion(exportSession) }) return exportSession } }
mit
0f57f07e78b6e6bbed71a987e74a74bb
37.363636
114
0.634281
5.528384
false
false
false
false
davecom/SwiftGraph
Tests/SwiftGraphTests/UniqueElementsGraph/UniqueElementsGraphHashableInitTests.swift
2
19403
// // UnweightedUniqueElementsGraphHashableInitTests.swift // SwiftGraphTests // // Copyright (c) 2018 Ferran Pujol Camins // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import SwiftGraph class UnweightedUniqueElementsGraphHashableInitTests: XCTestCase { func testPathInitializerUndirected() { let g0Path = UnweightedUniqueElementsGraph<String>.withPath([]) XCTAssertEqual(g0Path.vertexCount, 0, "g0Path: Expected empty graph") XCTAssertEqual(g0Path.edgeCount, 0, "g0Path: Expected empty graph") let g1Path = UnweightedUniqueElementsGraph.withPath(["Atlanta"]) XCTAssertEqual(g1Path.vertices, ["Atlanta"], "g1Path: Expected only Atlanta vertex") XCTAssertEqual(g1Path.edgeCount, 0, "g1Path: Expected no edges") let g2Path = UnweightedUniqueElementsGraph.withPath(["Atlanta", "Boston"]) XCTAssertEqual(g2Path.vertices, ["Atlanta", "Boston"], "g2Path: Expected vertices to be Atlanta and Boston") XCTAssertEqual(g2Path.edgeCount, 2, "g2Path: Expected exactly 2 edges") XCTAssertTrue(g2Path.edgeExists(from: "Atlanta", to: "Boston"), "g2Path: Expected an edge from Atlanta to Boston") XCTAssertTrue(g2Path.edgeExists(from: "Boston", to: "Atlanta"), "g2Path: Expected an edge from Boston to Atlanta") let g3Path = UnweightedUniqueElementsGraph.withPath(["Atlanta", "Boston", "Chicago"]) XCTAssertEqual(g3Path.vertices, ["Atlanta", "Boston", "Chicago"], "g3Path: Expected vertices to be Atlanta, Boston and Chicago") XCTAssertEqual(g3Path.edgeCount, 4, "g3Path: Expected exactly 4 edges") XCTAssertTrue(g3Path.edgeExists(from: "Atlanta", to: "Boston"), "g3Path: Expected an edge from Atlanta to Boston") XCTAssertTrue(g3Path.edgeExists(from: "Boston", to: "Atlanta"), "g3Path: Expected an edge from Boston to Atlanta") XCTAssertTrue(g3Path.edgeExists(from: "Boston", to: "Chicago"), "g3Path: Expected an edge from Boston to Chicago") XCTAssertTrue(g3Path.edgeExists(from: "Chicago", to: "Boston"), "g3Path: Expected an edge from Chicago to Boston") let g4Path = UnweightedUniqueElementsGraph.withPath(["Atlanta", "Boston", "Atlanta"]) XCTAssertEqual(g4Path.vertices, ["Atlanta", "Boston"], "g4Path: Expected vertices to be Atlanta and Boston.") XCTAssertEqual(g4Path.edgeCount, 2, "g4Path: Expected exactly 2 edges") XCTAssertTrue(g4Path.edgeExists(from: "Atlanta", to: "Boston"), "g4Path: Expected an edge from Atlanta to Boston") XCTAssertTrue(g4Path.edgeExists(from: "Boston", to: "Atlanta"), "g4Path: Expected an edge from Boston to Atlanta") let g5Path = UnweightedUniqueElementsGraph.withPath(["Atlanta", "Boston", "Chicago", "Atlanta", "Denver", "Chicago", "Atlanta"]) XCTAssertEqual(g5Path.vertices, ["Atlanta", "Boston", "Chicago", "Denver"], "g5Path: Expected vertices to be Atlanta, Boston, Chiicago and Denver.") XCTAssertEqual(g5Path.edgeCount, 10, "g5Path: Expected exactly 10 edges") XCTAssertTrue(g5Path.edgeExists(from: "Atlanta", to: "Boston"), "g5Path: Expected an edge from Atlanta to Boston") XCTAssertTrue(g5Path.edgeExists(from: "Boston", to: "Atlanta"), "g5Path: Expected an edge from Boston to Atlanta") XCTAssertTrue(g5Path.edgeExists(from: "Boston", to: "Chicago"), "g5Path: Expected an edge from Boston to Chicago") XCTAssertTrue(g5Path.edgeExists(from: "Chicago", to: "Boston"), "g5Path: Expected an edge from Chicago to Boston") XCTAssertTrue(g5Path.edgeExists(from: "Chicago", to: "Atlanta"), "g5Path: Expected an edge from Chicago to Atlanta") XCTAssertTrue(g5Path.edgeExists(from: "Atlanta", to: "Chicago"), "g5Path: Expected an edge from Atlanta to Chicago") XCTAssertTrue(g5Path.edgeExists(from: "Atlanta", to: "Denver"), "g5Path: Expected an edge from Atlanta to Denver") XCTAssertTrue(g5Path.edgeExists(from: "Denver", to: "Atlanta"), "g5Path: Expected an edge from Denver to Atlanta") XCTAssertTrue(g5Path.edgeExists(from: "Denver", to: "Chicago"), "g5Path: Expected an edge from Denver to Chicago") XCTAssertTrue(g5Path.edgeExists(from: "Chicago", to: "Denver"), "g5Path: Expected an edge from Chicago to Denver") } func testPathInitializerDirected() { let g0Path = UnweightedUniqueElementsGraph<String>.withPath([], directed: true) XCTAssertEqual(g0Path.vertexCount, 0, "g0Path: Expected empty graph") XCTAssertEqual(g0Path.edgeCount, 0, "g0Path: Expected empty graph") let g1Path = UnweightedUniqueElementsGraph.withPath(["Atlanta"], directed: true) XCTAssertEqual(g1Path.vertices, ["Atlanta"], "g1Path: Expected only Atlanta vertex") XCTAssertEqual(g1Path.edgeCount, 0, "g1Path: Expected no edges") let g2Path = UnweightedUniqueElementsGraph.withPath(["Atlanta", "Boston"], directed: true) XCTAssertEqual(g2Path.vertices, ["Atlanta", "Boston"], "g2Path: Expected vertices to be Atlanta and Boston") XCTAssertEqual(g2Path.edgeCount, 1, "g2Path: Expected exactly 1 edges") XCTAssertTrue(g2Path.edgeExists(from: "Atlanta", to: "Boston"), "g2Path: Expected an edge from Atlanta to Boston") let g3Path = UnweightedUniqueElementsGraph.withPath(["Atlanta", "Boston", "Chicago"], directed: true) XCTAssertEqual(g3Path.vertices, ["Atlanta", "Boston", "Chicago"], "g3Path: Expected vertices to be Atlanta, Boston and Chicago") XCTAssertEqual(g3Path.edgeCount, 2, "g3Path: Expected exactly 2 edges") XCTAssertTrue(g3Path.edgeExists(from: "Atlanta", to: "Boston"), "g3Path: Expected an edge from Atlanta to Boston") XCTAssertTrue(g3Path.edgeExists(from: "Boston", to: "Chicago"), "g3Path: Expected an edge from Boston to Chicago") let g4Path = UnweightedUniqueElementsGraph.withPath(["Atlanta", "Boston", "Atlanta"], directed: true) XCTAssertEqual(g4Path.vertices, ["Atlanta", "Boston"], "g4Path: Expected vertices to be Atlanta and Boston.") XCTAssertEqual(g4Path.edgeCount, 2, "g4Path: Expected exactly 2 edges") XCTAssertTrue(g4Path.edgeExists(from: "Atlanta", to: "Boston"), "g4Path: Expected an edge from Atlanta to Boston") XCTAssertTrue(g4Path.edgeExists(from: "Boston", to: "Atlanta"), "g4Path: Expected an edge from Boston to Atlanta") let g5Path = UnweightedUniqueElementsGraph.withPath(["Atlanta", "Boston", "Chicago", "Atlanta", "Denver", "Chicago", "Atlanta"], directed: true) XCTAssertEqual(g5Path.vertices, ["Atlanta", "Boston", "Chicago", "Denver"], "g4Path: Expected vertices to be Atlanta, Boston, Chiicago and Denver.") XCTAssertEqual(g5Path.edgeCount, 5, "g5Path: Expected exactly 5 edges") XCTAssertTrue(g5Path.edgeExists(from: "Atlanta", to: "Boston"), "g5Path: Expected an edge from Atlanta to Boston") XCTAssertTrue(g5Path.edgeExists(from: "Boston", to: "Chicago"), "g5Path: Expected an edge from Boston to Chicago") XCTAssertTrue(g5Path.edgeExists(from: "Chicago", to: "Atlanta"), "g5Path: Expected an edge from Chicago to Atlanta") XCTAssertTrue(g5Path.edgeExists(from: "Atlanta", to: "Denver"), "g5Path: Expected an edge from Atlanta to Denver") XCTAssertTrue(g5Path.edgeExists(from: "Denver", to: "Chicago"), "g5Path: Expected an edge from Denver to Chicago") } func testCycleInitializerUndirected() { let g0Cycle = UnweightedUniqueElementsGraph<String>.withCycle([]) XCTAssertEqual(g0Cycle.vertexCount, 0, "g0Cycle: Expected empty graph") XCTAssertEqual(g0Cycle.edgeCount, 0, "g0Cycle: Expected empty graph") let g1Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta"]) XCTAssertEqual(g1Cycle.vertices, ["Atlanta"], "g1Cycle: Expected only Atlanta vertex") XCTAssertEqual(g1Cycle.edgeCount, 1, "g1Cycle: Expected 1 edges") XCTAssertTrue(g1Cycle.edgeExists(from: "Atlanta", to: "Atlanta"), "g1Cycle: Expected an edge from Atlanta to Atlanta") let g2Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston"]) XCTAssertEqual(g2Cycle.vertices, ["Atlanta", "Boston"], "g2Cycle: Expected vertices to be Atlanta and Boston") XCTAssertEqual(g2Cycle.edgeCount, 2, "g2Cycle: Expected exactly 2 edges") XCTAssertTrue(g2Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g2Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g2Cycle.edgeExists(from: "Boston", to: "Atlanta"), "g2Cycle: Expected an edge from Boston to Atlanta") let g3Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston", "Chicago"]) XCTAssertEqual(g3Cycle.vertices, ["Atlanta", "Boston", "Chicago"], "g3Cycle: Expected vertices to be Atlanta, Boston and Chicago") XCTAssertEqual(g3Cycle.edgeCount, 6, "g3Path: Expected exactly 6 edges") XCTAssertTrue(g3Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g3Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g3Cycle.edgeExists(from: "Boston", to: "Atlanta"), "g3Cycle: Expected an edge from Boston to Atlanta") XCTAssertTrue(g3Cycle.edgeExists(from: "Boston", to: "Chicago"), "g3Cycle: Expected an edge from Boston to Chicago") XCTAssertTrue(g3Cycle.edgeExists(from: "Chicago", to: "Boston"), "g3Cycle: Expected an edge from Chicago to Boston") XCTAssertTrue(g3Cycle.edgeExists(from: "Chicago", to: "Atlanta"), "g3Cycle: Expected an edge from Chicago to Atlanta") XCTAssertTrue(g3Cycle.edgeExists(from: "Atlanta", to: "Chicago"), "g3Cycle: Expected an edge from Atlanta to Chicago") let g4Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston", "Atlanta"]) XCTAssertEqual(g4Cycle.vertices, ["Atlanta", "Boston"], "g4Cycle: Expected vertices to be Atlanta and Boston.") XCTAssertEqual(g4Cycle.edgeCount, 3, "g4Cycle: Expected exactly 3 edges") XCTAssertTrue(g4Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g4Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g4Cycle.edgeExists(from: "Boston", to: "Atlanta"), "g4Cycle: Expected an edge from Boston to Atlanta") XCTAssertTrue(g4Cycle.edgeExists(from: "Atlanta", to: "Atlanta"), "g4Cycle: Expected an edge from Atlanta to Boston") let g5Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston", "Chicago", "Atlanta", "Denver", "Chicago", "Atlanta"]) XCTAssertEqual(g5Cycle.vertices, ["Atlanta", "Boston", "Chicago", "Denver"], "g5Cycle: Expected vertices to be Atlanta, Boston, Chiicago and Denver.") XCTAssertEqual(g5Cycle.edgeCount, 11, "g5Path: Expected exactly 11 edges") XCTAssertTrue(g5Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g5Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g5Cycle.edgeExists(from: "Boston", to: "Atlanta"), "g5Cycle: Expected an edge from Boston to Atlanta") XCTAssertTrue(g5Cycle.edgeExists(from: "Boston", to: "Chicago"), "g5Cycle: Expected an edge from Boston to Chicago") XCTAssertTrue(g5Cycle.edgeExists(from: "Chicago", to: "Boston"), "g5Cycle: Expected an edge from Chicago to Boston") XCTAssertTrue(g5Cycle.edgeExists(from: "Chicago", to: "Atlanta"), "g5Cycle: Expected an edge from Chicago to Atlanta") XCTAssertTrue(g5Cycle.edgeExists(from: "Atlanta", to: "Chicago"), "g5Cycle: Expected an edge from Atlanta to Chicago") XCTAssertTrue(g5Cycle.edgeExists(from: "Atlanta", to: "Denver"), "g5Cycle: Expected an edge from Atlanta to Denver") XCTAssertTrue(g5Cycle.edgeExists(from: "Denver", to: "Atlanta"), "g5Cycle: Expected an edge from Denver to Atlanta") XCTAssertTrue(g5Cycle.edgeExists(from: "Denver", to: "Chicago"), "g5Cycle: Expected an edge from Denver to Chicago") XCTAssertTrue(g5Cycle.edgeExists(from: "Chicago", to: "Denver"), "g5Cycle: Expected an edge from Chicago to Denver") XCTAssertTrue(g5Cycle.edgeExists(from: "Atlanta", to: "Atlanta"), "g5Cycle: Expected an edge from Atlanta to Boston") let g6Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston", "Chicago", "Denver", "Boston", "Eugene"]) XCTAssertEqual(g6Cycle.vertices, ["Atlanta", "Boston", "Chicago", "Denver", "Eugene"], "g6Cycle: Expected vertices to be Atlanta, Boston, Chiicago and Denver.") XCTAssertEqual(g6Cycle.edgeCount, 12, "g6Cycle: Expected exactly 12 edges") XCTAssertTrue(g6Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g6Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g6Cycle.edgeExists(from: "Boston", to: "Atlanta"), "g6Cycle: Expected an edge from Boston to Atlanta") XCTAssertTrue(g6Cycle.edgeExists(from: "Boston", to: "Chicago"), "g6Cycle: Expected an edge from Boston to Chicago") XCTAssertTrue(g6Cycle.edgeExists(from: "Chicago", to: "Boston"), "g6Cycle: Expected an edge from Chicago to Boston") XCTAssertTrue(g6Cycle.edgeExists(from: "Chicago", to: "Denver"), "g6Cycle: Expected an edge from Chicago to Denver") XCTAssertTrue(g6Cycle.edgeExists(from: "Denver", to: "Chicago"), "g6Cycle: Expected an edge from Denver to Chicago") XCTAssertTrue(g6Cycle.edgeExists(from: "Denver", to: "Boston"), "g6Cycle: Expected an edge from Denver to Boston") XCTAssertTrue(g6Cycle.edgeExists(from: "Boston", to: "Denver"), "g6Cycle: Expected an edge from Boston to Denver") XCTAssertTrue(g6Cycle.edgeExists(from: "Boston", to: "Eugene"), "g6Cycle: Expected an edge from Boston to Eugene") XCTAssertTrue(g6Cycle.edgeExists(from: "Eugene", to: "Boston"), "g6Cycle: Expected an edge from Eugene to Boston") XCTAssertTrue(g6Cycle.edgeExists(from: "Eugene", to: "Atlanta"), "g6Cycle: Expected an edge from Eugene to Atlanta") XCTAssertTrue(g6Cycle.edgeExists(from: "Atlanta", to: "Eugene"), "g6Cycle: Expected an edge from Atlanta to Eugene") } func testCycleInitializerDirected() { let g0Cycle = UnweightedUniqueElementsGraph<String>.withCycle([], directed: true) XCTAssertEqual(g0Cycle.vertexCount, 0, "g0Cycle: Expected empty graph") XCTAssertEqual(g0Cycle.edgeCount, 0, "g0Cycle: Expected empty graph") let g1Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta"], directed: true) XCTAssertEqual(g1Cycle.vertices, ["Atlanta"], "g1Cycle: Expected only Atlanta vertex") XCTAssertEqual(g1Cycle.edgeCount, 1, "g1Cycle: Expected 1 edge") XCTAssertTrue(g1Cycle.edgeExists(from: "Atlanta", to: "Atlanta"), "g1Cycle: Expected an edge from Atlanta to Atlanta") let g2Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston"], directed: true) XCTAssertEqual(g2Cycle.vertices, ["Atlanta", "Boston"], "g2Cycle: Expected vertices to be Atlanta and Boston") XCTAssertEqual(g2Cycle.edgeCount, 2, "g2Cycle: Expected exactly 2 edges") XCTAssertTrue(g2Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g2Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g2Cycle.edgeExists(from: "Boston", to: "Atlanta"), "g2Cycle: Expected an edge from Atlanta to Boston") let g3Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston", "Chicago"], directed: true) XCTAssertEqual(g3Cycle.vertices, ["Atlanta", "Boston", "Chicago"], "g3Cycle: Expected vertices to be Atlanta, Boston and Chicago") XCTAssertEqual(g3Cycle.edgeCount, 3, "g3Cycle: Expected exactly 4 edges") XCTAssertTrue(g3Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g3Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g3Cycle.edgeExists(from: "Boston", to: "Chicago"), "g3Cycle: Expected an edge from Boston to Chicago") XCTAssertTrue(g3Cycle.edgeExists(from: "Chicago", to: "Atlanta"), "g3Cycle: Expected an edge from Chicago to Atlanta") let g4Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston", "Atlanta"], directed: true) XCTAssertEqual(g4Cycle.vertices, ["Atlanta", "Boston"], "g4Cycle: Expected vertices to be Atlanta and Boston.") XCTAssertEqual(g4Cycle.edgeCount, 3, "g4Cycle: Expected exactly 3 edges") XCTAssertTrue(g4Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g4Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g4Cycle.edgeExists(from: "Boston", to: "Atlanta"), "g4Cycle: Expected an edge from Boston to Atlanta") XCTAssertTrue(g4Cycle.edgeExists(from: "Atlanta", to: "Atlanta"), "g4Cycle: Expected an edge from Atlanta to Boston") let g5Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston", "Chicago", "Atlanta", "Denver", "Chicago", "Atlanta"], directed: true) XCTAssertEqual(g5Cycle.vertices, ["Atlanta", "Boston", "Chicago", "Denver"], "g5Cycle: Expected vertices to be Atlanta, Boston, Chiicago and Denver.") XCTAssertEqual(g5Cycle.edgeCount, 6, "g5Path: Expected exactly 6 edges") XCTAssertTrue(g5Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g5Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g5Cycle.edgeExists(from: "Boston", to: "Chicago"), "g5Cycle: Expected an edge from Boston to Chicago") XCTAssertTrue(g5Cycle.edgeExists(from: "Chicago", to: "Atlanta"), "g5Cycle: Expected an edge from Chicago to Atlanta") XCTAssertTrue(g5Cycle.edgeExists(from: "Atlanta", to: "Denver"), "g5Cycle: Expected an edge from Atlanta to Denver") XCTAssertTrue(g5Cycle.edgeExists(from: "Denver", to: "Chicago"), "g5Cycle: Expected an edge from Denver to Chicago") XCTAssertTrue(g5Cycle.edgeExists(from: "Atlanta", to: "Atlanta"), "g5Cycle: Expected an edge from Atlanta to Boston") let g6Cycle = UnweightedUniqueElementsGraph.withCycle(["Atlanta", "Boston", "Chicago", "Denver", "Boston", "Eugene"], directed: true) XCTAssertEqual(g6Cycle.vertices, ["Atlanta", "Boston", "Chicago", "Denver", "Eugene"], "g6Cycle: Expected vertices to be Atlanta, Boston, Chiicago and Denver.") XCTAssertEqual(g6Cycle.edgeCount, 6, "g6Cycle: Expected exactly 6 edges") XCTAssertTrue(g6Cycle.edgeExists(from: "Atlanta", to: "Boston"), "g6Cycle: Expected an edge from Atlanta to Boston") XCTAssertTrue(g6Cycle.edgeExists(from: "Boston", to: "Chicago"), "g6Cycle: Expected an edge from Boston to Chicago") XCTAssertTrue(g6Cycle.edgeExists(from: "Chicago", to: "Denver"), "g6Cycle: Expected an edge from Chicago to Denver") XCTAssertTrue(g6Cycle.edgeExists(from: "Denver", to: "Boston"), "g6Cycle: Expected an edge from Denver to Boston") XCTAssertTrue(g6Cycle.edgeExists(from: "Boston", to: "Eugene"), "g6Cycle: Expected an edge from Boston to Eugene") XCTAssertTrue(g6Cycle.edgeExists(from: "Eugene", to: "Atlanta"), "g6Cycle: Expected an edge from Eugene to Atlanta") } }
apache-2.0
aee0750dec393380816340bdca3d161d
87.195455
168
0.711024
4.026354
false
false
false
false
felixjendrusch/Matryoshka
MatryoshkaPlayground/MatryoshkaPlayground/Networking/HTTPParameterEncoding.swift
1
7575
// 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 /** Used to specify the way in which a set of parameters are applied to a URL request. */ public enum HTTPParameterEncoding: Equatable { /** 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`. 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`). */ case URL /** 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`. */ case JSON /** 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`. */ case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) /** Creates a URL request by encoding parameters and applying them onto an existing request. :param: URLRequest The request to have parameters applied :param: 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: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) { if parameters == nil { return (URLRequest, nil) } var mutableURLRequest: NSMutableURLRequest! = URLRequest.mutableCopy() as! NSMutableURLRequest var error: NSError? = nil switch self { case .URL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in sorted(Array(parameters.keys), <) { let value: AnyObject! = parameters[key] components += self.queryComponents(key, value) } return join("&", components.map{"\($0)=\($1)"} as [String]) } func encodesParametersInURL(method: HTTPMethod) -> Bool { switch method { case .GET, .HEAD, .DELETE: return true default: return false } } let method = HTTPMethod(rawValue: mutableURLRequest.HTTPMethod) if method != nil && encodesParametersInURL(method!) { if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!) mutableURLRequest.URL = URLComponents.URL } } else { if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") } mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) } case .JSON: let options = NSJSONWritingOptions.allZeros if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) { mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } case .PropertyList(let (format, options)): if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) { mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } } return (mutableURLRequest, error) } 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.extend([(escape(key), escape("\(value)"))]) } return components } func escape(string: String) -> String { let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*" return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } } private func == (lhs: [String: AnyObject]?, rhs: [String: AnyObject]?) -> Bool { switch (lhs, rhs) { case let (.Some(lhs), .Some(rhs)): return (lhs as NSDictionary).isEqual(rhs as NSDictionary) case (nil, nil): return true default: return false } } public func == (lhs: HTTPParameterEncoding, rhs: HTTPParameterEncoding) -> Bool { switch (lhs, rhs) { case (.URL, .URL): return true case (.JSON, .JSON): return true case let (.PropertyList(format1, writeOptions1), .PropertyList(format2, writeOptions2)): return format1 == format2 && writeOptions1 == writeOptions2 default: return false } } extension HTTPParameterEncoding: Printable { public var description: String { switch self { case .URL: return "URL" case .JSON: return "JSON" case let .PropertyList(format, writeOptions): return "PropertyList(format: \(format), writeOptions: \(writeOptions))" } } }
mit
6769286900e6a03e42a1be3e6dd76aa3
45.176829
555
0.645979
5.1031
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/PXItem/PXItemRenderer.swift
1
8404
import Foundation struct PXItemRenderer { let CONTENT_WIDTH_PERCENT: CGFloat = 86.0 // Image static let IMAGE_WIDTH: CGFloat = 48.0 static let IMAGE_HEIGHT: CGFloat = 48.0 // Font sizes static let TITLE_FONT_SIZE = PXLayout.M_FONT static let DESCRIPTION_FONT_SIZE = PXLayout.XXS_FONT static let QUANTITY_FONT_SIZE = PXLayout.XS_FONT static let AMOUNT_FONT_SIZE = PXLayout.XS_FONT func render(_ itemComponent: PXItemComponent) -> PXItemContainerView { let itemView = PXItemContainerView() itemView.backgroundColor = itemComponent.props.backgroundColor itemView.translatesAutoresizingMaskIntoConstraints = false let (imageUrl, imageObj) = buildItemImageUrl(imageURL: itemComponent.props.imageURL, collectorImage: itemComponent.props.collectorImage) itemView.itemImage = UIImageView() // Item icon if let itemImage = itemView.itemImage { if let url = imageUrl { buildCircle(targetImageView: itemImage) itemImage.backgroundColor = ThemeManager.shared.placeHolderColor() Utils().loadImageWithCache(withUrl: url, targetImageView: itemImage, placeholderImage: nil, fallbackImage: imageObj) } else { itemImage.image = imageObj } itemView.addSubview(itemImage) PXLayout.centerHorizontally(view: itemImage).isActive = true PXLayout.setHeight(owner: itemImage, height: PXItemRenderer.IMAGE_HEIGHT).isActive = true PXLayout.setWidth(owner: itemImage, width: PXItemRenderer.IMAGE_WIDTH).isActive = true PXLayout.pinTop(view: itemImage, withMargin: PXLayout.L_MARGIN).isActive = true } // Item Title if itemComponent.shouldShowTitle() { itemView.itemTitle = buildTitle(with: itemComponent.getTitle(), labelColor: itemComponent.props.boldLabelColor) } if let itemTitle = itemView.itemTitle { itemView.addSubviewToBottom(itemTitle, withMargin: PXLayout.S_MARGIN) PXLayout.centerHorizontally(view: itemTitle).isActive = true PXLayout.matchWidth(ofView: itemTitle, withPercentage: CONTENT_WIDTH_PERCENT).isActive = true } // Item description if itemComponent.shouldShowDescription() { itemView.itemDescription = buildDescription(with: itemComponent.getDescription(), labelColor: itemComponent.props.lightLabelColor) } if let itemDescription = itemView.itemDescription { itemView.addSubviewToBottom(itemDescription, withMargin: PXLayout.XS_MARGIN) PXLayout.centerHorizontally(view: itemDescription).isActive = true PXLayout.matchWidth(ofView: itemDescription, withPercentage: CONTENT_WIDTH_PERCENT).isActive = true } // Item quantity if itemComponent.shouldShowQuantity() { itemView.itemQuantity = buildQuantity(with: itemComponent.getQuantity(), labelColor: itemComponent.props.lightLabelColor) } if let itemQuantity = itemView.itemQuantity { itemView.addSubviewToBottom(itemQuantity, withMargin: PXLayout.XS_MARGIN) PXLayout.centerHorizontally(view: itemQuantity).isActive = true PXLayout.matchWidth(ofView: itemQuantity, withPercentage: CONTENT_WIDTH_PERCENT).isActive = true } // Item amount if itemComponent.shouldShowUnitAmount() { itemView.itemAmount = buildItemAmount(with: itemComponent.getUnitAmountPrice(), title: itemComponent.getUnitAmountTitle(), labelColor: itemComponent.props.lightLabelColor) } if let itemAmount = itemView.itemAmount { let margin = itemView.itemQuantity == nil ? PXLayout.XS_MARGIN : PXLayout.XXXS_MARGIN itemView.addSubviewToBottom(itemAmount, withMargin: margin) PXLayout.centerHorizontally(view: itemAmount).isActive = true PXLayout.matchWidth(ofView: itemAmount, withPercentage: CONTENT_WIDTH_PERCENT).isActive = true } itemView.pinLastSubviewToBottom(withMargin: PXLayout.L_MARGIN)?.isActive = true return itemView } } extension PXItemRenderer { fileprivate func buildItemImageUrl(imageURL: String?, collectorImage: UIImage? = nil) -> (String?, UIImage?) { if imageURL != nil { return (imageURL, collectorImage ?? ResourceManager.shared.getImage("MPSDK_review_iconoCarrito")) } else if let image = collectorImage { return (nil, image) } else { return (nil, ResourceManager.shared.getImage("MPSDK_review_iconoCarrito")) } } fileprivate func buildTitle(with text: String?, labelColor: UIColor) -> UILabel? { guard let text = text else { return nil } let font = Utils.getFont(size: PXItemRenderer.TITLE_FONT_SIZE) return buildLabel(text: text, color: labelColor, font: font) } fileprivate func buildDescription(with text: String?, labelColor: UIColor) -> UILabel? { guard let text = text else { return nil } let font = Utils.getFont(size: PXItemRenderer.DESCRIPTION_FONT_SIZE) return buildLabel(text: text, color: labelColor, font: font) } func buildQuantity(with text: String?, labelColor: UIColor) -> UILabel? { guard let text = text else { return nil } let font = Utils.getFont(size: PXItemRenderer.QUANTITY_FONT_SIZE) return buildLabel(text: text, color: labelColor, font: font) } fileprivate func buildItemAmount(with amount: Double?, title: String?, labelColor: UIColor) -> UILabel? { guard let title = title, let amount = amount else { return nil } let font = Utils.getFont(size: PXItemRenderer.AMOUNT_FONT_SIZE) let unitPrice = buildAttributedUnitAmount(amount: amount, color: labelColor, fontSize: font.pointSize) let unitPriceTitle = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font: font]) unitPriceTitle.append(unitPrice) return buildLabel(attributedText: unitPriceTitle, color: labelColor, font: font) } fileprivate func buildAttributedUnitAmount(amount: Double, color: UIColor, fontSize: CGFloat) -> NSAttributedString { let currency = SiteManager.shared.getCurrency() return Utils.getAmountFormatted(amount: amount, thousandSeparator: currency.getThousandsSeparatorOrDefault(), decimalSeparator: currency.getDecimalSeparatorOrDefault(), addingCurrencySymbol: currency.getCurrencySymbolOrDefault()).toAttributedString() } fileprivate func buildLabel(text: String, color: UIColor, font: UIFont) -> UILabel { let label = UILabel() label.textAlignment = .center label.text = text label.textColor = color label.lineBreakMode = .byTruncatingTail label.numberOfLines = 2 label.font = font let screenWidth = PXLayout.getScreenWidth(applyingMarginFactor: CONTENT_WIDTH_PERCENT) let height = UILabel.requiredHeight(forText: text, withFont: font, inNumberOfLines: 3, inWidth: screenWidth) PXLayout.setHeight(owner: label, height: height).isActive = true return label } fileprivate func buildLabel(attributedText: NSAttributedString, color: UIColor, font: UIFont) -> UILabel { let label = UILabel() label.textAlignment = .center label.textColor = color label.attributedText = attributedText label.lineBreakMode = .byTruncatingTail label.numberOfLines = 2 label.font = font let screenWidth = PXLayout.getScreenWidth(applyingMarginFactor: CONTENT_WIDTH_PERCENT) let height = UILabel.requiredHeight(forAttributedText: attributedText, withFont: font, inNumberOfLines: 3, inWidth: screenWidth) PXLayout.setHeight(owner: label, height: height).isActive = true return label } fileprivate func buildCircle(targetImageView: UIImageView?) { targetImageView?.layer.masksToBounds = false targetImageView?.layer.cornerRadius = PXItemRenderer.IMAGE_HEIGHT / 2 targetImageView?.clipsToBounds = true targetImageView?.translatesAutoresizingMaskIntoConstraints = false targetImageView?.contentMode = .scaleAspectFill } }
mit
70df0ad88f3d358a726285b430f593bc
45.949721
258
0.688125
4.894584
false
false
false
false
buttacciot/Hiragana
Hiragana/PracticeController.swift
1
7929
// // PracticeViewController.swift // Hiragana // // Created by Travis Buttaccio on 6/13/16. // Copyright © 2016 LangueMatch. All rights reserved. // import AVFoundation import SideMenu import STPopup class PracticeController: UIViewController { // MARK: - Constants lazy private var menuAnimator : MenuTransitionAnimator! = MenuTransitionAnimator(mode: .Presentation, shouldPassEventsOutsideMenu: false) { [unowned self] in self.dismissViewControllerAnimated(true, completion: nil) } lazy var titleView : TitleView! = { let view: TitleView = TitleView.viewFromNib() view.addTarget(self, action: #selector(toggleCoverView), forControlEvents: .TouchUpInside) return view }() lazy var characterSelect : STPopupController = { let vc = UIStoryboard(name: "CharacterPreview", bundle: nil).instantiateInitialViewController() as! CharacterPreviewController vc.viewModel = self.viewModel vc.delegate = self let popup = STPopupController(rootViewController: vc) return popup }() // MARK: - State Restoration var viewModel: TABMainViewModel! var audioPlayer: AVAudioPlayer? private var symbolController: SymbolController! private var drawingController: DrawingViewController! private var coverController: CoverViewController! private(set) var coverViewOpen = true // MARK: - Outlets @IBOutlet weak var coverViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var coverViewContainer: UIView! @IBOutlet weak var symbolViewContainer: UIView! func showMenu(sender: UIButton) { performSegueWithIdentifier("showMenu", sender: nil) } // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() assert(viewModel != nil) let menuItem = UIBarButtonItem(title: "Menu", style: .Plain, target: self, action: #selector(showMenu)) navigationItem.rightBarButtonItem = menuItem navigationItem.titleView = titleView navigationController?.navigationBar.userInteractionEnabled = false DefaultTheme.sharedAPI.themeViewController(self, type: .Practice) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch (segue.identifier, segue.destinationViewController) { case (.Some("showMenu"), let menuVC as MenuController): menuVC.delegate = self menuVC.transitioningDelegate = self menuVC.modalPresentationStyle = .Custom case (.Some("symbolController"), let symbolVC as SymbolController): symbolVC.delegate = self symbolVC.viewModel = viewModel symbolVC.updateTitleHandler = { [weak self] title in guard let strongSelf = self else { return } strongSelf.titleView.label.text = title } symbolController = symbolVC case (.Some("drawingController"), let drawingVC as DrawingViewController): drawingVC.delegate = self drawingController = drawingVC case (.Some("coverController"), let coverVC as CoverViewController): coverVC.delegate = self coverController = coverVC default: super.prepareForSegue(segue, sender: sender) } } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { symbolController.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition({ (context) in self.coverViewTopConstraint.constant = self.coverViewOpen ? 0 : -self.coverViewContainer.bounds.size.height }, completion: nil) } override func prefersStatusBarHidden() -> Bool { return true } } // MARK: - Menu Delegate extension PracticeController: MenuControllerDelegate { func menu(menu: MenuController, didSelectItem item: MenuItem) { switch item { case .Grid: drawingController.toggleGridView() menu.dismissViewControllerAnimated(true, completion: nil) case .Random: viewModel.random = !viewModel.random menu.dismissViewControllerAnimated(true, completion: nil) case .CharacterSelect: menu.dismissViewControllerAnimated(true, completion: { self.characterSelect.presentInViewController(self) }) case .Close: break } } } // MARK: - CharacterPreview Delegate extension PracticeController: CharacterPreviewDelegate { func didSelectItemAtIndexPath(indexPath: NSIndexPath) { print("tapped \(indexPath)") symbolController.showCharacterAtIndex(indexPath) } } // MARK: - SymbolController Delegate extension PracticeController: SymbolControllerDelegate { func symbolControllerWillBeginDragging(symbolController: SymbolController) { drawingController?.hidePosterImage() drawingController?.clearDrawingBoard() } } //MARK: - DrawingViewController Delegate extension PracticeController: DrawingViewControllerDelegate { func drawingViewControllerRequestingPosterImage(controller: DrawingViewController) -> UIImage? { return symbolController?.currentPosterImage() } } // MARK: - CoverView extension PracticeController: CoverViewDelegate { // MARK: - Handling Cover View Appearance @objc func toggleCoverView(animated: Bool = true) { coverViewOpen = !coverViewOpen let constant = coverViewOpen ? 0 : -coverViewContainer.bounds.size.height // if animated { if coverViewOpen { UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: .CurveLinear, animations: { () -> Void in self.coverViewTopConstraint.constant = constant self.titleView.rotateImageView(0, duration: 0.6) self.view.layoutIfNeeded() }, completion: nil) } else { UIView.animateWithDuration(0.15, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.coverViewTopConstraint.constant = constant self.titleView.rotateImageView(CGFloat(M_PI), duration: 0.15) self.view.layoutIfNeeded() }, completion: nil) } // } else { // self.coverViewTopConstraint.constant = constant // } } // MARK: - Cover View Delegate func maleAudioButtonTapped() { let ip = NSIndexPath(forItem: symbolController.displayedIndexPath.item, inSection: 0) let url = NSURL(fileURLWithPath: viewModel.maleAudioPathAtIndexPath(ip)) playAudioFile(url) } func femaleAudioButtonTapped() { let ip = NSIndexPath(forItem: symbolController.displayedIndexPath.item, inSection: 0) let url = NSURL(fileURLWithPath: viewModel.femaleAudioPathAtIndexPath(ip)) playAudioFile(url) } private func playAudioFile(url: NSURL) { audioPlayer = try? AVAudioPlayer(contentsOfURL: url, fileTypeHint: AVFileTypeWAVE) audioPlayer?.prepareToPlay() audioPlayer?.play() } } // MARK: - Transition Delegate extension PracticeController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController _: UIViewController, sourceController _: UIViewController) -> UIViewControllerAnimatedTransitioning? { return menuAnimator } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return MenuTransitionAnimator(mode: .Dismissal) } }
mit
6731030a19e7b9301a47d8f55a5cc6e9
38.247525
203
0.677598
5.478922
false
false
false
false
HcomCoolCode/hotelowy
ListOfHotels/HotelFetcher.swift
1
1348
// // HotelFetcher.swift // ListOfHotels // // Created by Tomasz Kuzma on 24/03/2016. // Copyright © 2016 Expedia. All rights reserved. // import Foundation func hotelsURL() -> NSURL { return NSURL(string: "http://www.hotels.com/hotels.json")! } public class HotelFetcher : NSObject { private let network: Network private let parser: HotelParsing init(network: Network, parser: HotelParsing) { self.network = network self.parser = parser } func fetchHotels(completion: (hotels: [Hotel]?, error: NSError?) -> ()) { network.getURL(hotelsURL()) {[weak self] (data, error) -> () in self?.fetchCompleted(data, error: error, completion: completion) } } func fetchCompleted(data: NSData?, error: NSError?, completion: (hotels: [Hotel]?, error: NSError?) -> ()) { guard let data = data else { completion(hotels: nil, error: error) return } do { let response = try parser.parseHotelData(data) completion(hotels: response?.hotels, error: nil) } catch { let parseError = NSError(domain: "hotels.com", code: 2, userInfo: nil) completion(hotels: nil, error: parseError) } } }
mit
1f8b81f66eaaee692c43e447566cbbfd
27.083333
82
0.566444
4.131902
false
false
false
false
ipapamagic/IPaURLResourceUI
Sources/IPaURLResourceUI/IPaURLRequestTaskOperation.swift
1
8688
// // IPaURLRequestOperation.swift // IPaURLResourceUI // // Created by IPa Chen on 2020/7/20. // import Foundation import IPaLog import Combine public typealias IPaURLRequestOperationCompletion = ((Data?,URLResponse?,Error?)->()) public class IPaURLRequestTaskOperation: Operation { var urlSession:URLSession var _request:URLRequest @objc dynamic var _task:URLSessionTask? public var request:URLRequest { return _request } public var task:URLSessionTask? { return _task } @objc dynamic public var progress:Double { return self.task?.progress.fractionCompleted ?? 0 } var requestCompleteBlock: IPaURLRequestOperationCompletion? init(urlSession:URLSession,request:URLRequest,complete:@escaping IPaURLRequestOperationCompletion) { self.urlSession = urlSession self._request = request self.requestCompleteBlock = complete } @objc class public override func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> { if key == "progress" { return Set(arrayLiteral: "_task","_task.progress.fractionCompleted") } return super.keyPathsForValuesAffectingValue(forKey: key) } override public var isExecuting:Bool { get { guard let task = _task else { return false } return task.state == URLSessionTask.State.running } } override public var isFinished:Bool { get { guard let task = _task else { return false } let isFinished = (task.state == URLSessionTask.State.completed) && (self.requestCompleteBlock == nil) return isFinished } } override public var isConcurrent:Bool { get { return true } } override public var isCancelled: Bool { get { guard let task = _task else { return false } return task.state == URLSessionTask.State.canceling } } override public func start() { self.willChangeValue(forKey: "isExecuting") self.executeOperation() self.didChangeValue(forKey: "isExecuting") } func executeOperation() { self.startURLConnection() } func startURLConnection() { let task = self.createTask { (responseData, response, error) in self.requestCompleteBlock?(responseData, response, error) self.willChangeValue(forKey: "isFinished") self.requestCompleteBlock = nil self.didChangeValue(forKey: "isFinished") } self._task = task task.resume() } override public func cancel() { self._task?.cancel() } func createTask(_ complete:@escaping (Data?,URLResponse?,Error?)->()) -> URLSessionTask { fatalError("do not use IPaURLRequestOperation directly!") } } public class IPaURLRequestDataTaskOperation :IPaURLRequestTaskOperation { public override func createTask(_ complete:@escaping IPaURLRequestOperationCompletion) -> URLSessionTask { urlSession.dataTask(with: request, completionHandler: complete) } } public class IPaURLRequestFormDataUploadTaskOperation:IPaURLRequestTaskOperation, IPaURLFormDataStreamWriter { var outputStream: OutputStream? var params:[String:Any] var files:[IPaMultipartFile] lazy var tempFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("IPaURLResponseUITemp\(UUID().uuidString)") init(urlSession: URLSession, request: URLRequest, params:[String:Any] = [String:Any](),files:[IPaMultipartFile], complete: @escaping IPaURLRequestOperationCompletion) { self.params = params self.files = files super.init(urlSession: urlSession, request: request, complete: complete) } override func executeOperation() { self.createOutputStream() } public override func createTask(_ complete: @escaping (Data?, URLResponse?, Error?) -> ()) -> URLSessionTask { let fileUrl = URL(fileURLWithPath: self.tempFilePath) return self.urlSession.uploadTask(with: request, fromFile: fileUrl) { data, response, error in try? FileManager.default.removeItem(atPath: self.tempFilePath) complete(data,response,error) } } public func stream(_ aStream: Stream, handle eventCode: Stream.Event) { self.streamDelegateFunction(aStream,handle: eventCode) } } public class IPaURLRequestUploadTaskOperation:IPaURLRequestTaskOperation { var file:Any init(urlSession: URLSession, request: URLRequest, file:Any, complete: @escaping IPaURLRequestOperationCompletion) { self.file = file super.init(urlSession: urlSession, request: request, complete: complete) } public override func createTask(_ complete: @escaping (Data?, URLResponse?, Error?) -> ()) -> URLSessionTask { switch file { case let fileUrl as URL: return self.urlSession.uploadTask(with: self._request, fromFile: fileUrl,completionHandler: complete) case let fileData as Data: return self.urlSession.uploadTask(with: self._request, from: fileData, completionHandler: complete) default: break } fatalError("IPaURLRequestUploadOperation: unknow file type!") } } @available(iOS 13.0, *) public class IPaURLRequestPublisherOperation<T>:Operation { var urlSession:URLSession var _request:URLRequest var anyCancellable:AnyCancellable? = nil var publisherHandler:(URLSession.DataTaskPublisher)-> AnyPublisher<T, Error> var receiveValueHandler:((T)->())? var completeHandler:((Subscribers.Completion<Error>)->())? var _isFinished = false public var request:URLRequest { return _request } init(urlSession:URLSession,request:URLRequest,handle: @escaping ((URLSession.DataTaskPublisher)-> AnyPublisher<T, Error>),receiveValue: ((T)->())?,complete:((Subscribers.Completion<Error>)->())? ) { self.urlSession = urlSession self._request = request self.publisherHandler = handle self.receiveValueHandler = receiveValue self.completeHandler = complete } override public var isExecuting:Bool { get { return anyCancellable != nil } } override public var isConcurrent:Bool { get { return true } } override public var isFinished: Bool { get { return _isFinished } } override public func start() { self.willChangeValue(forKey: "isExecuting") self.executeOperation() self.didChangeValue(forKey: "isExecuting") } func executeOperation() { self.startURLConnection() } func startURLConnection() { let dataPublisher = self.urlSession.dataTaskPublisher(for: request) let publisher:AnyPublisher<T, Error> = self.publisherHandler(dataPublisher) self.anyCancellable = publisher.sink(receiveCompletion: { result in self.willChangeValue(forKey: "isFinished") self.anyCancellable = nil self.completeHandler?(result) self._isFinished = true self.didChangeValue(forKey: "isFinished") }, receiveValue: { value in self.receiveValueHandler?(value) }) } override public func cancel() { self.anyCancellable?.cancel() } } @available(iOS 13.0, *) public class IPaURLRequestFormDataPublisherOperation<T>:IPaURLRequestPublisherOperation<T>,IPaURLFormDataStreamWriter { var outputStream:OutputStream? var files:[IPaMultipartFile] lazy var tempFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("IPaURLResponseUITemp\(UUID().uuidString)") var params: [String : Any] init(urlSession: URLSession, request: URLRequest, params:[String:Any] = [String:Any](),files:[IPaMultipartFile],handle: @escaping ((URLSession.DataTaskPublisher)-> AnyPublisher<T, Error>),receiveValue: ((T)->())?,complete:((Subscribers.Completion<Error>)->())? ) { self.params = params self.files = files super.init(urlSession: urlSession, request: request,handle: handle,receiveValue: receiveValue,complete: complete) } override func executeOperation() { self.createOutputStream() } public func stream(_ aStream: Stream, handle eventCode: Stream.Event) { self.streamDelegateFunction(aStream,handle: eventCode) } }
mit
afe4f8abbff928ce30da60f044e72c35
36.61039
268
0.654351
4.92238
false
false
false
false
iOkay/MiaoWuWu
Pods/Material/Sources/iOS/PulseAnimation.swift
1
6249
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(PulseAnimation) public enum PulseAnimation: Int { case none case center case centerWithBacking case centerRadialBeyondBounds case radialBeyondBounds case backing case point case pointWithBacking } internal extension Animation { /** Triggers the expanding animation. - Parameter layer: Container CALayer. - Parameter visualLayer: A CAShapeLayer. - Parameter point: A point to pulse from. - Parameter width: Container width. - Parameter height: Container height. - Parameter duration: Animation duration. - Parameter pulse: A Pulse instance. */ internal static func pulseExpandAnimation(layer: CALayer, visualLayer: CALayer, point: CGPoint, width: CGFloat, height: CGFloat, pulse: inout Pulse) { guard .none != pulse.animation else { return } let n = .center == pulse.animation ? width < height ? width : height : width < height ? height : width let bLayer = CAShapeLayer() let pLayer = CAShapeLayer() bLayer.addSublayer(pLayer) pulse.layers.insert(bLayer, at: 0) visualLayer.addSublayer(bLayer) bLayer.zPosition = 0 pLayer.zPosition = 0 visualLayer.masksToBounds = !(.centerRadialBeyondBounds == pulse.animation || .radialBeyondBounds == pulse.animation) Animation.animationDisabled(animations: { [visualLayer = visualLayer, pulse = pulse] in bLayer.frame = visualLayer.bounds pLayer.bounds = CGRect(x: 0, y: 0, width: n, height: n) switch pulse.animation { case .center, .centerWithBacking, .centerRadialBeyondBounds: pLayer.position = CGPoint(x: width / 2, y: height / 2) default: pLayer.position = point } pLayer.cornerRadius = n / 2 pLayer.backgroundColor = pulse.color.withAlphaComponent(pulse.opacity).cgColor pLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(scaleX: 0, y: 0)) }) bLayer.setValue(false, forKey: "animated") let duration: CFTimeInterval = .center == pulse.animation ? 0.16125 : 0.325 switch pulse.animation { case .centerWithBacking, .backing, .pointWithBacking: bLayer.add(Animation.backgroundColor(color: pulse.color.withAlphaComponent(pulse.opacity / 2), duration: duration), forKey: nil) default:break } switch pulse.animation { case .center, .centerWithBacking, .centerRadialBeyondBounds, .radialBeyondBounds, .point, .pointWithBacking: pLayer.add(Animation.scale(scale: 1, duration: duration), forKey: nil) default:break } Animation.delay(time: duration) { bLayer.setValue(true, forKey: "animated") } } /** Triggers the contracting animation. - Parameter layer: Container CALayer. - Parameter visualLayer: A CAShapeLayer. - Parameter pulse: A Pulse instance. */ internal static func pulseContractAnimation(layer: CALayer, visualLayer: CALayer, pulse: inout Pulse) { guard let bLayer = pulse.layers.popLast() else { return } guard let animated = bLayer.value(forKey: "animated") as? Bool else { return } Animation.delay(time: animated ? 0 : 0.15) { [pulse = pulse] in guard let pLayer = bLayer.sublayers?.first as? CAShapeLayer else { return } let duration = 0.325 switch pulse.animation { case .centerWithBacking, .backing, .pointWithBacking: bLayer.add(Animation.backgroundColor(color: pulse.color.withAlphaComponent(0), duration: duration), forKey: nil) default:break } switch pulse.animation { case .center, .centerWithBacking, .centerRadialBeyondBounds, .radialBeyondBounds, .point, .pointWithBacking: pLayer.add(Animation.animationGroup(animations: [ Animation.scale(scale: .center == pulse.animation ? 1 : 1.325), Animation.backgroundColor(color: pulse.color.withAlphaComponent(0)) ], duration: duration), forKey: nil) default:break } Animation.delay(time: duration) { pLayer.removeFromSuperlayer() bLayer.removeFromSuperlayer() } } } }
gpl-3.0
e0f76bfec60fe4212bee578937901c73
39.577922
151
0.647144
4.730507
false
false
false
false
csmulhern/neptune
Neptune/Neptune/TableViewController.swift
1
1379
import UIKit public typealias TableRunning = Running<UITableView> public typealias TableItem = Item<UITableView> public typealias TableSection = Section<UITableView> // MARK: - CollectionView extension UITableView: CollectionView { public typealias RunningViewType = UITableViewHeaderFooterView public typealias ItemViewType = UITableViewCell } // MARK: - TableViewController open class TableViewController: UIViewController, TableDataSourceDelegate, UIScrollViewDelegate { open private(set) var tableView: UITableView! open var modelDataSource = TableDataSource() { didSet { self.modelDataSource.setTableView(self.tableView, delegate: self) } } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let indexPath = self.tableView.indexPathForSelectedRow { self.tableView.deselectRow(at: indexPath, animated: animated) } } open override func viewDidLoad() { super.viewDidLoad() self.tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain) self.view.addSubview(self.tableView) self.modelDataSource.setTableView(self.tableView, delegate: self) } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.tableView.frame = view.bounds } }
unlicense
a8e4150f5b65a5a728886d7374f7d01a
28.978261
97
0.720087
5.263359
false
false
false
false
luckymore0520/leetcode
NextPermutation.playground/Contents.swift
1
1435
//: Playground - noun: a place where people can play import UIKit //Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. // //If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). // //The replacement must be in-place, do not allocate extra memory. // //Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. //1,2,3 → 1,3,2 //3,2,1 → 1,2,3 //1,1,5 → 1,5,1 class Solution { func nextPermutation(_ nums: inout [Int]) { if (nums.count < 2) { return } var index = 0 for i in (1...nums.count-1).reversed() { if (nums[i] > nums[i-1]) { index = i break } } //如果本身就是最大的了,逆序 if (index == 0) { nums.sort() } else { //需要找到比 index-1 位置上大的最小的数 for i in (index...nums.count-1).reversed() { if (nums[i] > nums[index-1]) { (nums[i],nums[index-1]) = (nums[index-1],nums[i]) break } } nums[index...nums.count-1].sort() } } } let solution = Solution() var nums = [1,2,3] solution.nextPermutation(&nums) print(nums)
mit
182db6476ef0d7c30a09cdec03fb8c4c
27.666667
121
0.546182
3.618421
false
false
false
false
AaronMT/firefox-ios
XCUITests/BaseTestCase.swift
6
6358
/* 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 MappaMundi import XCTest let serverPort = Int.random(in: 1025..<65000) func path(forTestPage page: String) -> String { return "http://localhost:\(serverPort)/test-fixture/\(page)" } class BaseTestCase: XCTestCase { var navigator: MMNavigator<FxUserState>! let app = XCUIApplication() var userState: FxUserState! // leave empty for non-specific tests var specificForPlatform: UIUserInterfaceIdiom? // These are used during setUp(). Change them prior to setUp() for the app to launch with different args, // or, use restart() to re-launch with custom args. var launchArguments = [LaunchArguments.ClearProfile, LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew, LaunchArguments.SkipETPCoverSheet, LaunchArguments.StageServer, LaunchArguments.DeviceName, "\(LaunchArguments.ServerPort)\(serverPort)"] func setUpScreenGraph() { navigator = createScreenGraph(for: self, with: app).navigator() userState = navigator.userState } func setUpApp() { app.launchArguments = [LaunchArguments.Test] + launchArguments app.launch() } override func setUp() { super.setUp() continueAfterFailure = false setUpApp() setUpScreenGraph() } override func tearDown() { app.terminate() super.tearDown() } var skipPlatform: Bool { guard let platform = specificForPlatform else { return false } return UIDevice.current.userInterfaceIdiom != platform } func restart(_ app: XCUIApplication, args: [String] = []) { XCUIDevice.shared.press(.home) var launchArguments = [LaunchArguments.Test] args.forEach { arg in launchArguments.append(arg) } app.launchArguments = launchArguments app.activate() } //If it is a first run, first run window should be gone func dismissFirstRunUI() { let firstRunUI = XCUIApplication().scrollViews["IntroViewController.scrollView"] if firstRunUI.exists { firstRunUI.swipeLeft() XCUIApplication().buttons["Start Browsing"].tap() } } func waitForExistence(_ element: XCUIElement, timeout: TimeInterval = 5.0, file: String = #file, line: UInt = #line) { waitFor(element, with: "exists == true", timeout: timeout, file: file, line: line) } func waitForNoExistence(_ element: XCUIElement, timeoutValue: TimeInterval = 5.0, file: String = #file, line: UInt = #line) { waitFor(element, with: "exists != true", timeout: timeoutValue, file: file, line: line) } func waitForValueContains(_ element: XCUIElement, value: String, file: String = #file, line: UInt = #line) { waitFor(element, with: "value CONTAINS '\(value)'", file: file, line: line) } private func waitFor(_ element: XCUIElement, with predicateString: String, description: String? = nil, timeout: TimeInterval = 5.0, file: String, line: UInt) { let predicate = NSPredicate(format: predicateString) let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element) let result = XCTWaiter().wait(for: [expectation], timeout: timeout) if result != .completed { let message = description ?? "Expect predicate \(predicateString) for \(element.description)" self.recordFailure(withDescription: message, inFile: file, atLine: Int(line), expected: false) } } func loadWebPage(_ url: String, waitForLoadToFinish: Bool = true, file: String = #file, line: UInt = #line) { let app = XCUIApplication() UIPasteboard.general.string = url app.textFields["url"].press(forDuration: 2.0) app.tables["Context Menu"].cells["menu-PasteAndGo"].firstMatch.tap() if waitForLoadToFinish { let finishLoadingTimeout: TimeInterval = 30 let progressIndicator = app.progressIndicators.element(boundBy: 0) waitFor(progressIndicator, with: "exists != true", description: "Problem loading \(url)", timeout: finishLoadingTimeout, file: file, line: line) } } func iPad() -> Bool { if UIDevice.current.userInterfaceIdiom == .pad { return true } return false } func waitUntilPageLoad() { let app = XCUIApplication() let progressIndicator = app.progressIndicators.element(boundBy: 0) waitForNoExistence(progressIndicator, timeoutValue: 20.0) } func waitForTabsButton() { if iPad() { waitForExistence(app.buttons["TopTabsViewController.tabsButton"], timeout: 15) } else { // iPhone sim tabs button is called differently when in portrait or landscape if (XCUIDevice.shared.orientation == UIDeviceOrientation.landscapeLeft) { waitForExistence(app.buttons["URLBarView.tabsButton"], timeout: 15) } else { waitForExistence(app.buttons["TabToolbar.tabsButton"], timeout: 15) } } } } class IpadOnlyTestCase: BaseTestCase { override func setUp() { specificForPlatform = .pad if iPad() { super.setUp() } } } class IphoneOnlyTestCase: BaseTestCase { override func setUp() { specificForPlatform = .phone if !iPad() { super.setUp() } } } extension BaseTestCase { func tabTrayButton(forApp app: XCUIApplication) -> XCUIElement { return app.buttons["TopTabsViewController.tabsButton"].exists ? app.buttons["TopTabsViewController.tabsButton"] : app.buttons["TabToolbar.tabsButton"] } } extension XCUIElement { func tap(force: Bool) { // There appears to be a bug with tapping elements sometimes, despite them being on-screen and tappable, due to hittable being false. // See: http://stackoverflow.com/a/33534187/1248491 if isHittable { tap() } else if force { coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap() } } }
mpl-2.0
b305d91a88fafe4a1199c71a80152600
35.54023
251
0.642498
4.727138
false
true
false
false
BelledonneCommunications/linphone-iphone
Classes/Swift/Conference/ViewModels/ScheduledConferencesViewModel.swift
1
3046
/* * Copyright (c) 2010-2021 Belledonne Communications SARL. * * This file is part of linphone-android * (see https://www.linphone.org). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import linphonesw class ScheduledConferencesViewModel { var core : Core { get { Core.get() } } static let shared = ScheduledConferencesViewModel() var conferences : MutableLiveData<[ScheduledConferenceData]> = MutableLiveData([]) var daySplitted : [Date : [ScheduledConferenceData]] = [:] var coreDelegate: CoreDelegateStub? var showTerminated = MutableLiveData(false) let editionEnabled = MutableLiveData(false) let conferenceScheduler = try? Core.get().createConferenceScheduler() init () { coreDelegate = CoreDelegateStub( onConferenceInfoReceived: { (core, conferenceInfo) in Log.i("[Scheduled Conferences] New conference info received") self.conferences.value!.append(ScheduledConferenceData(conferenceInfo: conferenceInfo,isFinished: false)) self.conferences.notifyValue() } ) computeConferenceInfoList() } func computeConferenceInfoList() { conferences.value!.removeAll() let now = Date().timeIntervalSince1970 // Linphone uses time_t in seconds if (showTerminated.value == true) { core.conferenceInformationList.filter{$0.duration != 0 && (TimeInterval($0.dateTime) + TimeInterval($0.duration) < now)}.forEach { conferenceInfo in conferences.value!.append(ScheduledConferenceData(conferenceInfo: conferenceInfo,isFinished: true)) } } else { let twoHoursAgo = now - 7200 // Show all conferences from 2 hour ago and forward core.getConferenceInformationListAfterTime(time: time_t(twoHoursAgo)).filter{$0.duration != 0}.forEach { conferenceInfo in conferences.value!.append(ScheduledConferenceData(conferenceInfo: conferenceInfo,isFinished: false)) } } daySplitted = [:] conferences.value!.forEach { (conferenceInfo) in let startDateDay = dateAtBeginningOfDay(for: conferenceInfo.rawDate) if (daySplitted[startDateDay] == nil) { daySplitted[startDateDay] = [] } daySplitted[startDateDay]!.append(conferenceInfo) } } func dateAtBeginningOfDay(for inputDate: Date) -> Date { var calendar = Calendar.current let timeZone = NSTimeZone.system as NSTimeZone calendar.timeZone = timeZone as TimeZone return calendar.date(from: calendar.dateComponents([.year, .month, .day], from: inputDate))! } }
gpl-3.0
4db45d03d2f431275b49ebdcef71a2c2
33.613636
151
0.7413
3.890166
false
false
false
false
robertofrontado/OkDataSources
Library/RxSwift/OkRxViewDelegate.swift
2
1967
// // OkRxViewDelegate.swift // OkDataSources // // Created by Roberto Frontado on 4/20/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // import UIKit import RxSwift public class OkRxViewDelegate<T: OkViewDataSource>: NSObject { public var dataSource: T public let onItemClicked: (_ item: T.ItemType, _ position: Int) -> Void public var onRefreshed: (() -> Observable<[T.ItemType]>)? public var onPagination: ((_ item: T.ItemType) -> Observable<[T.ItemType]>)? public var triggerTreshold: Int = 1 public var reverseTriggerTreshold: Int = 0 public init(dataSource: T, onItemClicked: @escaping (_ item: T.ItemType, _ position: Int) -> Void) { self.dataSource = dataSource self.onItemClicked = onItemClicked } // MARK: Private methods @objc internal func refreshControlValueChanged(_ refreshControl: UIRefreshControl) { refreshControl.endRefreshing() } // MARK: - Public methods // MARK: Pagination public func setOnPagination(onPagination: @escaping (_ item: T.ItemType) -> Observable<[T.ItemType]>) { setOnPagination(nil, onPagination: onPagination) } public func setOnPagination(_ triggerTreshold: Int?, onPagination: @escaping (_ item: T.ItemType) -> Observable<[T.ItemType]>) { if let triggerTreshold = triggerTreshold { self.triggerTreshold = triggerTreshold } self.onPagination = onPagination } // MARK: Pull to refresh internal func configureRefreshControl(_ refreshControl: inout UIRefreshControl?, onRefreshed: @escaping () -> Observable<[T.ItemType]>) { self.onRefreshed = onRefreshed if refreshControl == nil { refreshControl = UIRefreshControl() refreshControl!.tintColor = UIColor.gray } refreshControl!.addTarget(self, action: #selector(refreshControlValueChanged), for: .valueChanged) } }
apache-2.0
ca2de3c0dab8555b36e6679536aad1b2
34.745455
141
0.666328
4.615023
false
false
false
false
crexista/KabuKit
KabuKit/Classes/core/Swift/SceneSequenceBuilder.swift
1
4478
// // Copyright © 2017年 DWANGO Co., Ltd. // import Foundation public class BuilderState {} public class Buildable: BuilderState {} public class Unbuildable: BuilderState {} public class SceneSequenceBuilder<FirstScene: Scene, Guide: SequenceGuide, Context: BuilderState, Stage: BuilderState> { public typealias ReturnValue = FirstScene.ReturnValue fileprivate let firstScene: FirstScene fileprivate let guide: Guide fileprivate var stage: Guide.Stage? fileprivate var context: FirstScene.Context? init(scene: FirstScene, guide: Guide) { self.firstScene = scene self.guide = guide } public func setup(_ stage: Guide.Stage, with context: FirstScene.Context) -> SceneSequenceBuilder<FirstScene, Guide, Buildable, Buildable> { let builder = SceneSequenceBuilder<FirstScene, Guide, Buildable, Buildable>(scene: firstScene, guide: self.guide) builder.context = context builder.stage = stage return builder } public func setContext(_ context: FirstScene.Context) -> SceneSequenceBuilder<FirstScene, Guide, Buildable, Stage> { let builder = SceneSequenceBuilder<FirstScene, Guide, Buildable, Stage>(scene: firstScene, guide: self.guide) builder.context = context builder.stage = stage return builder } public func setStage(_ stage: Guide.Stage) -> SceneSequenceBuilder<FirstScene, Guide, Context, Buildable> { let builder = SceneSequenceBuilder<FirstScene, Guide, Context, Buildable>(scene: firstScene, guide: self.guide) builder.context = context builder.stage = stage return builder } } public extension SceneSequenceBuilder where Context == Buildable, Stage == Buildable { public typealias Subscriber = SceneSequence<FirstScene, Guide>.SequenceStatusSubscriber public typealias BuildArgument = ( stage: Guide.Stage, firstScene: FirstScene, callbacks: Subscriber ) @available(*, deprecated, message: "this method will be deleted at version 0.5.0") public func build(onInit: @escaping (Guide.Stage, FirstScene) -> Void, onActive: ((Guide.Stage, [Screen]) -> Void)? = nil, onSuspend: ((Guide.Stage, [Screen]) -> Void)? = nil, onLeave: ((Guide.Stage, [Screen], ReturnValue?) -> Void)? = nil) -> SceneSequence<FirstScene, Guide> { return build(onInitWithRewind: { (stage, scene) -> (() -> Void)? in onInit(stage, scene) return nil }, onActive: onActive, onSuspend: onSuspend, onLeave: onLeave) } @available(*, deprecated, message: "this method will be deleted at version 0.5.0") public func build(onInitWithRewind: @escaping (Guide.Stage, FirstScene) -> (() -> Void)?, onActive: ((Guide.Stage, [Screen]) -> Void)? = nil, onSuspend: ((Guide.Stage, [Screen]) -> Void)? = nil, onLeave: ((Guide.Stage, [Screen], ReturnValue?) -> Void)? = nil) -> SceneSequence<FirstScene, Guide> { guard let stage = self.stage else { fatalError() } guard let context = self.context else { fatalError() } return SceneSequence(stage: stage, scene: firstScene, guide: guide, context: context, onInit: onInitWithRewind, onActive: onActive, onSuspend: onSuspend, onLeave: onLeave) } public func build(initializer: @escaping (BuildArgument) -> (() -> Void)?) -> SceneSequence<FirstScene, Guide> { guard let stage = self.stage else { fatalError() } guard let context = self.context else { fatalError() } let subscriber = SceneSequence<FirstScene, Guide>.SequenceStatusSubscriber() let onStart = { (stage: Guide.Stage, scene: FirstScene) -> (() -> Void)? in return initializer((stage, scene, subscriber)) } return SceneSequence(stage: stage, scene: firstScene, guide: guide, context: context, subscriber: subscriber, onStart: onStart) } }
mit
7601d3931d82d3e4d9edeb5c68e4ddfc
41.216981
144
0.590168
4.780983
false
false
false
false
rasmusth/BluetoothKit
Example/Vendor/CryptoSwift/Sources/CryptoSwift/Generics.swift
1
3892
// // Generics.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 02/09/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // /** Protocol and extensions for integerFrom(bits:). Bit hakish for me, but I can't do it in any other way */ protocol Initiable { init(_ v: Int) init(_ v: UInt) } extension Int:Initiable {} extension UInt:Initiable {} extension UInt8:Initiable {} extension UInt16:Initiable {} extension UInt32:Initiable {} extension UInt64:Initiable {} /** build bit pattern from array of bits */ @_specialize(UInt8) func integerFrom<T: UnsignedInteger>(_ bits: Array<Bit>) -> T { var bitPattern:T = 0 for idx in bits.indices { if bits[idx] == Bit.one { let bit = T(UIntMax(1) << UIntMax(idx)) bitPattern = bitPattern | bit } } return bitPattern } /// Array of bytes. Caution: don't use directly because generic is slow. /// /// - parameter value: integer value /// - parameter length: length of output array. By default size of value type /// /// - returns: Array of bytes func arrayOfBytes<T: Integer>(value:T, length totalBytes: Int = MemoryLayout<T>.size) -> Array<UInt8> { let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1) valuePointer.pointee = value let bytesPointer = UnsafeMutablePointer<UInt8>(OpaquePointer(valuePointer)) var bytes = Array<UInt8>(repeating: 0, count: totalBytes) for j in 0..<min(MemoryLayout<T>.size,totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } valuePointer.deinitialize() valuePointer.deallocate(capacity: 1) return bytes } // MARK: - shiftLeft // helper to be able to make shift operation on T @_specialize(Int) func << <T:SignedInteger>(lhs: T, rhs: Int) -> Int { let a = lhs as! Int let b = rhs return a << b } @_specialize(UInt) func << <T:UnsignedInteger>(lhs: T, rhs: Int) -> UInt { let a = lhs as! UInt let b = rhs return a << b } // Generic function itself // FIXME: this generic function is not as generic as I would. It crashes for smaller types @_specialize(Int) func shiftLeft<T: SignedInteger>(_ value: T, by count: Int) -> T where T: Initiable { if (value == 0) { return 0; } let bitsCount = (MemoryLayout<T>.size * 8) let shiftCount = Int(Swift.min(count, bitsCount - 1)) var shiftedValue:T = 0; for bitIdx in 0..<bitsCount { let bit = T(IntMax(1 << bitIdx)) if ((value & bit) == bit) { shiftedValue = shiftedValue | T(bit << shiftCount) } } if (shiftedValue != 0 && count >= bitsCount) { // clear last bit that couldn't be shifted out of range shiftedValue = shiftedValue & T(~(1 << (bitsCount - 1))) } return shiftedValue } // for any f*** other Integer type - this part is so non-Generic func shiftLeft(_ value: UInt, by count: Int) -> UInt { return UInt(shiftLeft(Int(value), by: count)) } func shiftLeft(_ value: UInt8, by count: Int) -> UInt8 { return UInt8(shiftLeft(UInt(value), by: count)) } func shiftLeft(_ value: UInt16, by count: Int) -> UInt16 { return UInt16(shiftLeft(UInt(value), by: count)) } func shiftLeft(_ value: UInt32, by count: Int) -> UInt32 { return UInt32(shiftLeft(UInt(value), by: count)) } func shiftLeft(_ value: UInt64, by count: Int) -> UInt64 { return UInt64(shiftLeft(UInt(value), by: count)) } func shiftLeft(_ value: Int8, by count: Int) -> Int8 { return Int8(shiftLeft(Int(value), by: count)) } func shiftLeft(_ value: Int16, by count: Int) -> Int16 { return Int16(shiftLeft(Int(value), by: count)) } func shiftLeft(_ value: Int32, by count: Int) -> Int32 { return Int32(shiftLeft(Int(value), by: count)) } func shiftLeft(_ value: Int64, by count: Int) -> Int64 { return Int64(shiftLeft(Int(value), by: count)) }
mit
01d0b38c5fbf7c961b5d74de8b5166a9
27.408759
108
0.643628
3.541401
false
false
false
false
335g/TwitterAPIKit
Sources/APIs/FriendsAPI.swift
1
3360
// // Friends.swift // TwitterAPIKit // // Created by Yoshiki Kudo on 2015/07/05. // Copyright © 2015年 Yoshiki Kudo. All rights reserved. // import Foundation import APIKit // MARK: - Request public protocol FriendsRequestType: TwitterAPIRequestType {} public protocol FriendsGetRequestType: FriendsRequestType {} public extension FriendsRequestType { public var baseURL: NSURL { return NSURL(string: "https://api.twitter.com/1.1/friends")! } } public extension FriendsGetRequestType { public var method: APIKit.HTTPMethod { return .GET } } // MARK: - API public enum TwitterFriends { /// /// https://dev.twitter.com/rest/reference/get/friends/ids /// public struct Ids: FriendsGetRequestType { public let client: OAuthAPIClient public var path: String { return "/ids.json" } private let _parameters: [String: AnyObject?] public var parameters: AnyObject? { return queryStringsFromParameters(_parameters) } public init( _ client: OAuthAPIClient, user: User, count: Int = 5000, cursorStr: String = "-1", stringifyIds: Bool = true){ self.client = client self._parameters = [ user.key: user.obj, "cursor": cursorStr, "stringify_ids": stringifyIds, "count": count ] } public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> UserIDs { guard let dictionary = object as? [String: AnyObject], ids = UserIDs(dictionary: dictionary) else { throw DecodeError.Fail } return ids } } /// /// https://dev.twitter.com/rest/reference/get/friends/list /// public struct List: FriendsGetRequestType { public let client: OAuthAPIClient public var path: String { return "/list.json" } private let _parameters: [String: AnyObject?] public var parameters: AnyObject? { return queryStringsFromParameters(_parameters) } public init( _ client: OAuthAPIClient, user: User, count: Int = 50, cursorStr: String = "-1", skipStatus: Bool = true, includeUserEntities: Bool = false){ self.client = client self._parameters = [ user.key: user.obj, "cursor": cursorStr, "count": count, "skip_status": skipStatus, "include_user_entities": includeUserEntities ] } public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> UsersList { guard let dictionary = object as? [String: AnyObject], list = UsersList(dictionary: dictionary) else { throw DecodeError.Fail } return list } } }
mit
f7aa44c681634715480064aa978b159a
26.983333
111
0.51832
5.237129
false
false
false
false
bluezald/DesignPatterns
DesignPatterns/DesignPatterns/BuilderPattern.swift
1
2459
// // BuilderPattern.swift // DesignPatterns // // Created by Vincent Bacalso on 05/10/2016. // Copyright © 2016 bluezald. All rights reserved. // /** The builder pattern is a good choice when designing classes whose constructors or static factorieswould have more than a handful of parameters Problems Encountered, Why the use of Builder Pattern: Too many parameters on Telescoping Constructor Pattern, although this pattern is solved with Javabean Pattern: http://stackoverflow.com/a/1953567/602995 */ import UIKit /** Intent Separate the construction of a complex object from its representation so that the same construction process can create different representations. Parse a complex representation, create one of several targets. */ // The Builder pattern separates the construction of a complex object // from its representation so that the same construction process can create // different representations. class BuilderPattern: NSObject { public func demo() { let aPizza = Pizza.Builder(size: 12) .hasCheese(true) .hasPepperoni(false) .hasBacon(true).build() print(aPizza) } } public class Pizza { private var size: Int! private var hasCheese: Bool? private var hasPepperoni: Bool? private var hasBacon: Bool? public class Builder { fileprivate final var size: Int! fileprivate var hasCheese: Bool? fileprivate var hasPepperoni: Bool? fileprivate var hasBacon: Bool? init(size: Int) { self.size = size } public func hasCheese(_ hasCheese: Bool) -> Builder { self.hasCheese = hasCheese return self } public func hasPepperoni(_ hasPepperoni: Bool) -> Builder { self.hasPepperoni = hasPepperoni return self } public func hasBacon(_ hasBacon: Bool) -> Builder { self.hasBacon = hasBacon return self } public func build() -> Pizza { return Pizza(builder: self) } } private init(builder: Builder) { self.size = builder.size self.hasCheese = builder.hasCheese self.hasPepperoni = builder.hasPepperoni self.hasBacon = builder.hasBacon } } /** Common Usage or Examples: 1. In a Restaurant - The Creation of Pizza or Meal */
mit
d396f393830621cbbdee2865cb373a60
25.148936
79
0.639138
4.577281
false
false
false
false
iOS-mamu/SS
P/Library/Eureka/Source/Core/NavigationAccessoryView.swift
1
3304
// NavigationAccessoryView.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Class for the navigation accessory view used in FormViewController open class NavigationAccessoryView : UIToolbar { open var previousButton: UIBarButtonItem! open var nextButton: UIBarButtonItem! open var doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil) fileprivate var fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) fileprivate var flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) public override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 44.0)) autoresizingMask = .flexibleWidth fixedSpace.width = 22.0 initializeChevrons() setItems([previousButton, fixedSpace, nextButton, flexibleSpace, doneButton], animated: false) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } fileprivate func initializeChevrons() { var bundle = Bundle(for: self.classForCoder) if let resourcePath = bundle.path(forResource: "Eureka", ofType: "bundle") { if let resourcesBundle = Bundle(path: resourcePath) { bundle = resourcesBundle } } var imageLeftChevron = UIImage(named: "back-chevron", in: bundle, compatibleWith: nil) var imageRightChevron = UIImage(named: "forward-chevron", in: bundle, compatibleWith: nil) // RTL language support if #available(iOS 9.0, *) { imageLeftChevron = imageLeftChevron?.imageFlippedForRightToLeftLayoutDirection() imageRightChevron = imageRightChevron?.imageFlippedForRightToLeftLayoutDirection() } previousButton = UIBarButtonItem(image: imageLeftChevron, style: .plain, target: nil, action: nil) nextButton = UIBarButtonItem(image: imageRightChevron, style: .plain, target: nil, action: nil) } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {} }
mit
8156f3d1a588b2a55e8714f1e03f57c4
46.2
114
0.716404
4.781476
false
false
false
false
sunilsharma08/AppUtilityFramework
AppUtility/AUImage.swift
1
5245
// // AUImage.swift // AppUtility // // Created by Apple on 22/08/16. // Copyright © 2016 Sunil Sharma. All rights reserved. // import Foundation extension UIImage { public class func imageWithColor(color: UIColor, size: CGSize) -> UIImage { let rect: CGRect = CGRectMake(0, 0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public func fixOrientation() -> UIImage { // No-op if the orientation is already correct if ( self.imageOrientation == UIImageOrientation.Up ) { return self; } // We need to calculate the proper transformation to make the image upright. // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored. var transform: CGAffineTransform = CGAffineTransformIdentity if ( self.imageOrientation == UIImageOrientation.Down || self.imageOrientation == UIImageOrientation.DownMirrored ) { transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height) transform = CGAffineTransformRotate(transform, CGFloat(M_PI)) } if ( self.imageOrientation == UIImageOrientation.Left || self.imageOrientation == UIImageOrientation.LeftMirrored ) { transform = CGAffineTransformTranslate(transform, self.size.width, 0) transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2)) } if ( self.imageOrientation == UIImageOrientation.Right || self.imageOrientation == UIImageOrientation.RightMirrored ) { transform = CGAffineTransformTranslate(transform, 0, self.size.height); transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2)); } if ( self.imageOrientation == UIImageOrientation.UpMirrored || self.imageOrientation == UIImageOrientation.DownMirrored ) { transform = CGAffineTransformTranslate(transform, self.size.width, 0) transform = CGAffineTransformScale(transform, -1, 1) } if ( self.imageOrientation == UIImageOrientation.LeftMirrored || self.imageOrientation == UIImageOrientation.RightMirrored ) { transform = CGAffineTransformTranslate(transform, self.size.height, 0); transform = CGAffineTransformScale(transform, -1, 1); } // Now we draw the underlying CGImage into a new context, applying the transform // calculated above. let ctx: CGContextRef = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height), CGImageGetBitsPerComponent(self.CGImage), 0, CGImageGetColorSpace(self.CGImage), CGImageGetBitmapInfo(self.CGImage).rawValue)!; CGContextConcatCTM(ctx, transform) if ( self.imageOrientation == UIImageOrientation.Left || self.imageOrientation == UIImageOrientation.LeftMirrored || self.imageOrientation == UIImageOrientation.Right || self.imageOrientation == UIImageOrientation.RightMirrored ) { CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage) } else { CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage) } // And now we just create a new UIImage from the drawing context and return it return UIImage(CGImage: CGBitmapContextCreateImage(ctx)!) } public func resizeImage(maxSize:CGSize) -> UIImage { var actualHeight = self.size.height var actualWidth = self.size.width var actualRatio = actualWidth/actualHeight let maxRatio = maxSize.width/maxSize.height if actualHeight > maxSize.height || actualWidth > maxSize.width { if actualRatio < maxRatio { actualRatio = maxSize.height / actualHeight actualWidth = actualRatio * actualWidth actualHeight = maxSize.height } else if actualRatio < maxRatio { actualRatio = maxSize.height / actualHeight actualWidth = actualRatio * actualWidth actualHeight = maxSize.height } else{ actualHeight = maxSize.height actualWidth = maxSize.width } } let rect = CGRectMake(0, 0, actualWidth , actualHeight) UIGraphicsBeginImageContext(rect.size); self.drawInRect(rect) let image = UIGraphicsGetImageFromCurrentImageContext() return image } //compression should be between 0 - 1 public func compressImage(compression:CGFloat) -> UIImage? { let imageData = UIImageJPEGRepresentation(self, compression); let image = UIImage.init(data: imageData ?? NSData()) return image } }
mit
85d657b3cdc3e2df20b4955c590c8850
43.440678
134
0.625477
5.632653
false
false
false
false
frootloops/swift
test/SILGen/tsan_instrumentation.swift
1
4733
// RUN: %target-swift-frontend -sanitize=thread -emit-silgen %s | %FileCheck %s // REQUIRES: tsan_runtime func takesInout(_ p: inout Int) { } func takesInout(_ p: inout MyStruct) { } struct MyStruct { var storedProperty: Int = 77 } class MyClass { var storedProperty: Int = 22 } var gStruct = MyStruct() var gClass = MyClass() // CHECK-LABEL: sil hidden @_T020tsan_instrumentation17inoutGlobalStructyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_T020tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutyAA8MyStructVzF : $@convention(thin) (@inout MyStruct) -> () // CHECK: {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[WRITE]]) : $@convention(thin) (@inout MyStruct) -> () func inoutGlobalStruct() { takesInout(&gStruct) } // CHECK-LABEL: sil hidden @_T020tsan_instrumentation31inoutGlobalStructStoredPropertyyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_T020tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $() // CHECK: [[ELEMENT_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MyStruct, #MyStruct.storedProperty // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[ELEMENT_ADDR]] : $*Int) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutySizF : $@convention(thin) (@inout Int) -> () // CHECK: {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[ELEMENT_ADDR]]) : $@convention(thin) (@inout Int) -> () func inoutGlobalStructStoredProperty() { // This should generate two TSan inout instrumentations; one for the address // of the global and one for the address of the struct stored property. takesInout(&gStruct.storedProperty) } // CHECK-LABEL: sil hidden @_T020tsan_instrumentation30inoutGlobalClassStoredPropertyyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_T020tsan_instrumentation6gClassAA02MyC0Cvp : $*MyClass // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL_ADDR]] : $*MyClass // CHECK: [[LOADED_CLASS:%.*]] = load [copy] [[READ]] : $*MyClass // CHECK: [[VALUE_BUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[TEMPORARY:%.*]] = alloc_stack $Int // CHECK: [[BORROWED_CLASS:%.*]] = begin_borrow [[LOADED_CLASS]] : $MyClass // CHECK: [[TEMPORARY_RAW:%.*]] = address_to_pointer [[TEMPORARY]] : $*Int to $Builtin.RawPointer // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[VALUE_BUFFER]] : $*Builtin.UnsafeValueBuffer) : $() // CHECK: [[MATERIALIZE_FOR_SET:%.*]] = class_method [[BORROWED_CLASS]] : $MyClass, #MyClass.storedProperty!materializeForSet.1 : (MyClass) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?), $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed MyClass) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: [[MATERIALIZE_FOR_SET_TUPLE:%.*]] = apply [[MATERIALIZE_FOR_SET]]([[TEMPORARY_RAW]], [[VALUE_BUFFER]], [[BORROWED_CLASS]]) : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed MyClass) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: [[TEMPORARY_BUFFER:%.*]] = tuple_extract [[MATERIALIZE_FOR_SET_TUPLE]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>), 0 // CHECK: [[OPTIONAL_CALLBACK:%.*]] = tuple_extract [[MATERIALIZE_FOR_SET_TUPLE]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>), 1 // CHECK: [[BUFFER_ADDRESS:%.*]] = pointer_to_address [[TEMPORARY_BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[BUFFER_ADDRESS_DEPENDENCE:%.*]] = mark_dependence [[BUFFER_ADDRESS]] : $*Int on [[LOADED_CLASS]] : $MyClass // CHECK: end_borrow [[BORROWED_CLASS]] from [[LOADED_CLASS]] : $MyClass, $MyClass // CHECK: {{%.*}} builtin "tsanInoutAccess"([[BUFFER_ADDRESS_DEPENDENCE]] : $*Int) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutySizF : $@convention(thin) (@inout Int) -> () // CHECK: {{%.*}} apply [[TAKES_INOUT_FUNC]]([[BUFFER_ADDRESS_DEPENDENCE]]) : $@convention(thin) (@inout Int) -> () func inoutGlobalClassStoredProperty() { // This generates two TSan inout instrumentations. One for the value // buffer that is passed inout to materializeForSet and one for the // temporary buffer passed to takesInout(). takesInout(&gClass.storedProperty) }
apache-2.0
0160529f63aa214f8fe79da47998f965
68.602941
394
0.677372
3.671839
false
false
false
false
nh7a/InfoPlist
InfoPlist/InfoPlist.swift
1
3349
// // InfoPlist.swift // InfoPlist // // Created by Naoki Hiroshima on 10/2/17. // public struct InfoPlist: Decodable { public let bundleName: String public let bundleExecutable: String public let bundleIdentifier: String public let bundleVersion: String public let bundleShortVersionString: String public let bundleDevelopmentRegion: String public let bundlePackageType: String public let bundleSupportedPlatforms: [String]? public let bundleInfoDictionaryVersion: String public let deviceFamily: [Int] public let launchStoryboardName: String public let requiredDeviceCapabilities: [String] public let supportedInterfaceOrientations: [String] public let requiresIPhoneOS: Bool public let buildMachineOSBuild: String? public let minimumOSVersion: String public let mainStoryboardFile: String? // Development environment public let platformName: String? public let platformVersion: String? public let xcode: String? public let compiler: String? public let platformBuild: String? public let sdkBuild: String? public let sdkName: String? public let xcodeBuild: String? enum CodingKeys: String, CodingKey { case bundleName = "CFBundleName" // Foo case bundleExecutable = "CFBundleExecutable" // Foo case bundleIdentifier = "CFBundleIdentifier" // com.example.Foo case bundleVersion = "CFBundleVersion" // 1 case bundleShortVersionString = "CFBundleShortVersionString" // 1.0 case bundleDevelopmentRegion = "CFBundleDevelopmentRegion" // en case bundlePackageType = "CFBundlePackageType" // APPL case bundleSupportedPlatforms = "CFBundleSupportedPlatforms" // [ iPhoneSimulator ] case bundleInfoDictionaryVersion = "CFBundleInfoDictionaryVersion" // 6.0 case deviceFamily = "UIDeviceFamily" // [ 1, 2 ] case launchStoryboardName = "UILaunchStoryboardName" // LaunchScreen case requiredDeviceCapabilities = "UIRequiredDeviceCapabilities" // [ armv7 ] case supportedInterfaceOrientations = "UISupportedInterfaceOrientations" // [ UIInterfaceOrientationPortrait ] case requiresIPhoneOS = "LSRequiresIPhoneOS" // 1 case buildMachineOSBuild = "BuildMachineOSBuild" // 17A365 case minimumOSVersion = "MinimumOSVersion" // 11.0 case mainStoryboardFile = "UIMainStoryboardFile" // Main // Development environment case platformName = "DTPlatformName" // iphonesimulator case platformVersion = "DTPlatformVersion" // 11.0 case xcode = "DTXcode" // 0900 case compiler = "DTCompiler" // com.apple.compilers.llvm.clang.1_0 case platformBuild = "DTPlatformBuild" case sdkBuild = "DTSDKBuild" // 15A372 case sdkName = "DTSDKName" // iphonesimulator11.0 case xcodeBuild = "DTXcodeBuild" // 9A235 } } public extension Bundle { static let infoPlist: InfoPlist! = { guard let url = main.url(forResource: "Info", withExtension: "plist"), let data = try? Data(contentsOf: url) else { return nil } do { return try PropertyListDecoder().decode(InfoPlist.self, from: data) } catch { print("BUG: \(error)") } return nil }() }
mit
724a353582217af7d23ad4e51c036e13
40.8625
136
0.685876
4.723554
false
false
false
false
yura-voevodin/SumDUBot
Sources/App/Structures/Button.swift
1
3784
// // Button.swift // SumDUBot // // Created by Yura Voevodin on 18.09.17. // // import Foundation /// Button of Facebook Messenger structured message element. //struct Button: Codable { // /// Button type of Facebook Messenger structured message element. // /// // /// - webURL: Web URL type. // /// - postback: Postback type. // enum `Type`: String { // case webURL = "web_url" // case postback = "postback" // } // // /// Set all its property to get only. // /// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html#//apple_ref/doc/uid/TP40014097-CH41-ID18 // /// Button type. // private(set) var type: Type // /// Button title. // private(set) var title: String // /// Button payload, postback type only. // private(set) var payload: String? // /// Button URL, webURL type only. // private(set) var url: String? // // /// Creates a Button for Facebook Messenger structured message element. // /// // /// - Parameters: // /// - type: Button type. // /// - title: Button title. // /// - payload: Button payload. // /// - url: Button URL. // /// - Throws: Throws NodeError errors. // init(type: Type, title: String, payload: String? = nil, url: String? = nil) throws { // /// Set Button type. // self.type = type // /// Set Button title. // self.title = title // // /// Check what Button type is. // switch type { // /// Is a webURL type, so se its url. // case .webURL: // /// Check if url is nil. // guard let url = url else { // throw MessengerBotError.missingURL // } // self.url = url // /// Is a postback type, so se its payload. // case .postback: // /// Check if payload is nil. // guard let payload = payload else { // throw MessengerBotError.missingPayload // } // self.payload = payload // } // } // // /// Button conforms to NodeRepresentable, turn the convertible into a node. // /// // /// - Parameter context: Context beyond Node. // /// - Returns: Returns the Button Node representation. // /// - Throws: Throws NodeError errors. // public func makeNode(in context: Context?) throws -> Node { // /// Create the Node with type and title. // var node: Node = [ // "type": type.rawValue.makeNode(in: nil), // "title": title.makeNode(in: nil) // ] // // /// Extends the Node with url or payload, depends on Button type. // switch type { // /// Extends with url property. // case .webURL: // node["url"] = url?.makeNode(in: nil) ?? "" // /// Extends with payload property. // case .postback: // node["payload"] = payload?.makeNode(in: nil) ?? "" // } // // /// Create the Node. // return Node(node: node) // } // // static func groupForResponse(_ buttons: [Button]) -> [[Button]] { // var array = buttons // var smallArray: [Button] = [] // var countOfPrecessedItems = 0 // var result: [[Button]] = [] // // for (index, item) in array.enumerated() { // smallArray.append(item) // if index % 3 == 2 { // result.append(smallArray) // smallArray = [] // countOfPrecessedItems += 3 // } // } // if array.count > countOfPrecessedItems { // array.removeSubrange(0..<countOfPrecessedItems) // result.append(array) // } // return result // } //}
mit
368864285b2f554364b9e36c0c38cd4d
32.785714
171
0.526163
3.717092
false
false
false
false
ruslanskorb/CoreStore
Sources/CSXcodeDataModelSchema.swift
1
3439
// // CSXcodeDataModelSchema.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // 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 CoreData import Foundation // MARK: - CSXcodeDataModelSchema /** The `CSXcodeDataModelSchema` serves as the Objective-C bridging type for `XcodeDataModelSchema`. - SeeAlso: `XcodeDataModelSchema` */ @objc public final class CSXcodeDataModelSchema: NSObject, CSDynamicSchema, CoreStoreObjectiveCType { /** Initializes an `CSXcodeDataModelSchema` from an *.xcdatamodeld file URL. - parameter modelName: the model version, typically the file name of an *.xcdatamodeld file (without the file extension) - parameter modelVersionFileURL: the file URL that points to the .xcdatamodeld's "momd" file. */ @objc public required init(modelName: ModelVersion, modelVersionFileURL: URL) { self.bridgeToSwift = XcodeDataModelSchema( modelName: modelName, modelVersionFileURL: modelVersionFileURL ) } // MARK: NSObject public override var hash: Int { return ObjectIdentifier(self.bridgeToSwift).hashValue } public override func isEqual(_ object: Any?) -> Bool { guard let object = object as? CSXcodeDataModelSchema else { return false } return self.bridgeToSwift === object.bridgeToSwift } public override var description: String { return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)" } // MARK: CSDynamicSchema @objc public var modelVersion: ModelVersion { return self.bridgeToSwift.modelVersion } @objc public func rawModel() -> NSManagedObjectModel { return self.bridgeToSwift.rawModel() } // MARK: CoreStoreObjectiveCType public let bridgeToSwift: XcodeDataModelSchema public required init(_ swiftValue: XcodeDataModelSchema) { self.bridgeToSwift = swiftValue super.init() } } // MARK: - XcodeDataModelSchema extension XcodeDataModelSchema: CoreStoreSwiftType { // MARK: CoreStoreSwiftType public var bridgeToObjectiveC: CSXcodeDataModelSchema { return CSXcodeDataModelSchema(self) } }
mit
190ff56ea5887af0b4a24a85aef2f084
28.895652
125
0.682664
5.078287
false
false
false
false
AlexGivens/SwiftArmyKnife
Source/String+Extensions.swift
1
2300
// // String+Extensions.swift // // Copyright (c) 2017 Alex Givens (http://alexgivens.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension String { var isURL: Bool { let types: NSTextCheckingResult.CheckingType = [.link] let detector = try? NSDataDetector(types: types.rawValue) guard (detector != nil && self.characters.count > 0) else { return false } if detector!.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) > 0 { return true } return false } var isEmail: Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } var domain: String? { guard let url = URL(string: self), let host = url.host else { return nil } let components = host.components(separatedBy: ".") if components.count < 3 { return host } else { let count = components.count return components[count-2] + "." + components[count-1] } } }
mit
7d7a9d578ba024cbd05527be6e56fe54
40.071429
157
0.66913
4.315197
false
false
false
false
inkyfox/SwiftySQL
Sources/SQLInGenerator.swift
3
1420
// // SQLInGenerator.swift // SwiftySQL // // Created by Yongha Yoo (inkyfox) on 2016. 10. 24.. // Copyright © 2016년 Gen X Hippies Company. All rights reserved. // import Foundation class SQLInGenerator: SQLElementGenerator<SQLIn> { override func generate(_ element: SQLIn, forRead: Bool) -> String { var query = element.expr.sqlStringBoxedIfNeeded(forRead: forRead, by: generator) query += element.isIn ? " IN " : " NOT IN " query += element.table.sqlStringBoxedIfNeeded(forRead: forRead, by: generator) return query } override func generateFormatted(_ element: SQLIn, forRead: Bool, withIndent indent: Int) -> String { var query = element.expr.formattedSQLStringBoxedIfNeeded(forRead: forRead, withIndent: indent, by: generator) query += element.isIn ? " IN " : " NOT IN " let nextIndent = indent + query.characters.count query += element.table.formattedSQLStringBoxedIfNeeded(forRead: forRead, withIndent: nextIndent, by: generator) return query } }
mit
084ab1356c892b49ba3aebf257e5d6ea
37.297297
88
0.506704
5.34717
false
false
false
false
raphacarletti/JiraTracker
JiraTracker/AppDelegate.swift
1
4773
// // AppDelegate.swift // JiraTracker // // Created by Raphael Carletti on 10/20/17. // Copyright © 2017 Raphael Carletti. All rights reserved. // import UIKit import CoreData import FirebaseCore import IQKeyboardManagerSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //Configure Firebase FirebaseApp.configure() IQKeyboardManager.sharedManager().enable = true IQKeyboardManager.sharedManager().enableAutoToolbar = false return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "JiraTracker") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
4b4b18c9d86e07e9ba4854896232a9ff
47.693878
285
0.689019
5.905941
false
false
false
false
teambition/SegmentedControl
SegmentedControlExample/ExampleViewController.swift
1
11391
// // ExampleViewController.swift // SegmentedControlExample // // Created by 洪鑫 on 15/12/29. // Copyright © 2015年 Teambition. All rights reserved. // import UIKit import SegmentedControl private let kLivelyBlueColor = UIColor(red: 3 / 255, green: 169 / 255, blue: 244 / 255, alpha: 1) class ExampleViewController: UIViewController { @IBOutlet weak var segmentedControl1: SegmentedControl! @IBOutlet weak var segmentedControl2: SegmentedControl! @IBOutlet weak var segmentedControl3: SegmentedControl! override func viewDidLoad() { super.viewDidLoad() setupUI() } fileprivate func setupUI() { configureNavigationTitleSegmentedControl() configureNavigationBelowSegmentedControl() configureSegmentedControl1() configureSegmentedControl2() configureSegmentedControl3() } fileprivate func configureNavigationTitleSegmentedControl() { let titleStrings = ["任务", "分享", "文件", "日程"] let titles: [NSAttributedString] = { let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.darkGray] var titles = [NSAttributedString]() for titleString in titleStrings { let title = NSAttributedString(string: titleString, attributes: attributes) titles.append(title) } return titles }() let selectedTitles: [NSAttributedString] = { let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.white] var selectedTitles = [NSAttributedString]() for titleString in titleStrings { let selectedTitle = NSAttributedString(string: titleString, attributes: attributes) selectedTitles.append(selectedTitle) } return selectedTitles }() let segmentedControl = SegmentedControl.initWithTitles(titles, selectedTitles: selectedTitles) segmentedControl.delegate = self segmentedControl.backgroundColor = .clear segmentedControl.selectionBoxColor = kLivelyBlueColor segmentedControl.selectionBoxStyle = .default segmentedControl.selectionBoxCornerRadius = 15 segmentedControl.frame.size = CGSize(width: 70 * titles.count, height: 30) segmentedControl.isLongPressEnabled = true segmentedControl.isUnselectedSegmentsLongPressEnabled = true segmentedControl.longPressMinimumPressDuration = 1 segmentedControl.setTitleAttachedIcons([#imageLiteral(resourceName: "taskSegmentAdditionIcon")], selectedTitleAttachedIcons: [#imageLiteral(resourceName: "taskSegmentAdditionIconSelected")]) navigationItem.titleView = segmentedControl } fileprivate func configureNavigationBelowSegmentedControl() { let titleStrings = ["任务", "分享", "文件", "日程", "账目", "标签", "通知", "聊天", "收件箱", "联系人"] let titles: [NSAttributedString] = { let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 16), .foregroundColor: UIColor.black] var titles = [NSAttributedString]() for titleString in titleStrings { let title = NSAttributedString(string: titleString, attributes: attributes) titles.append(title) } return titles }() let selectedTitles: [NSAttributedString] = { let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 16), .foregroundColor: kLivelyBlueColor] var selectedTitles = [NSAttributedString]() for titleString in titleStrings { let selectedTitle = NSAttributedString(string: titleString, attributes: attributes) selectedTitles.append(selectedTitle) } return selectedTitles }() let segmentedControl = SegmentedControl.initWithTitles(titles, selectedTitles: selectedTitles) segmentedControl.delegate = self segmentedControl.backgroundColor = .white segmentedControl.autoresizingMask = [.flexibleRightMargin, .flexibleWidth] segmentedControl.selectionIndicatorStyle = .bottom segmentedControl.selectionIndicatorColor = kLivelyBlueColor segmentedControl.selectionIndicatorHeight = 3 segmentedControl.segmentWidth = 65 segmentedControl.frame.origin.y = UIApplication.shared.statusBarFrame.height + 44 segmentedControl.frame.size = CGSize(width: UIScreen.main.bounds.width, height: 40) view.insertSubview(segmentedControl, belowSubview: navigationController!.navigationBar) } fileprivate func configureSegmentedControl1() { let titleStrings = ["任务", "分享", "文件", "日程", "聊天"] let titles: [NSAttributedString] = { let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.white] var titles = [NSAttributedString]() for titleString in titleStrings { let title = NSAttributedString(string: titleString, attributes: attributes) titles.append(title) } return titles }() let selectedTitles: [NSAttributedString] = { let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor(white: 0.1, alpha: 1)] var selectedTitles = [NSAttributedString]() for titleString in titleStrings { let selectedTitle = NSAttributedString(string: titleString, attributes: attributes) selectedTitles.append(selectedTitle) } return selectedTitles }() segmentedControl1.setTitles(titles, selectedTitles: selectedTitles) segmentedControl1.delegate = self segmentedControl1.selectionBoxStyle = .default segmentedControl1.minimumSegmentWidth = 375.0 / 4.0 segmentedControl1.selectionBoxColor = UIColor(white: 0.62, alpha: 1) segmentedControl1.selectionIndicatorStyle = .top segmentedControl1.selectionIndicatorColor = UIColor(white: 0.3, alpha: 1) } fileprivate func configureSegmentedControl2() { let images = [#imageLiteral(resourceName: "project"), #imageLiteral(resourceName: "me"), #imageLiteral(resourceName: "notification"), #imageLiteral(resourceName: "chat")] let selectedImages = [#imageLiteral(resourceName: "project-selected"), #imageLiteral(resourceName: "me-selected"), #imageLiteral(resourceName: "notification-selected"), #imageLiteral(resourceName: "chat-selected")] segmentedControl2.setImages(images, selectedImages: selectedImages) segmentedControl2.delegate = self segmentedControl2.selectionIndicatorStyle = .bottom segmentedControl2.selectionIndicatorColor = kLivelyBlueColor segmentedControl2.selectionIndicatorHeight = 3 segmentedControl2.selectionIndicatorEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) } fileprivate func configureSegmentedControl3() { let titleStrings = ["Tasks", "Posts", "Files", "Meetings", "Favourites", "Chats"] let titles: [NSAttributedString] = { let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.darkGray] var titles = [NSAttributedString]() for titleString in titleStrings { let title = NSAttributedString(string: titleString, attributes: attributes) titles.append(title) } return titles }() let selectedTitles: [NSAttributedString] = { let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.white] var selectedTitles = [NSAttributedString]() for titleString in titleStrings { let selectedTitle = NSAttributedString(string: titleString, attributes: attributes) selectedTitles.append(selectedTitle) } return selectedTitles }() segmentedControl3.setTitles(titles, selectedTitles: selectedTitles) segmentedControl3.delegate = self segmentedControl3.layoutPolicy = .dynamic segmentedControl3.segmentSpacing = 20 segmentedControl3.selectionBoxHeight = 30 segmentedControl3.selectionHorizontalPadding = 15 segmentedControl3.selectionBoxStyle = .default segmentedControl3.selectionBoxCornerRadius = 15 segmentedControl3.shouldShowAllBox = true segmentedControl3.selectionBoxColor = kLivelyBlueColor segmentedControl3.contentInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15) segmentedControl3.setTitleAttachedIcons([#imageLiteral(resourceName: "taskSegmentAdditionIcon")], selectedTitleAttachedIcons: [#imageLiteral(resourceName: "taskSegmentAdditionIconSelected")]) segmentedControl3.titleAttachedIconPositionOffset = (5, 1) segmentedControl3.isLongPressEnabled = true segmentedControl3.isUnselectedSegmentsLongPressEnabled = true segmentedControl3.longPressMinimumPressDuration = 0.8 } } extension ExampleViewController: SegmentedControlDelegate { func segmentedControl(_ segmentedControl: SegmentedControl, didSelectIndex selectedIndex: Int) { print("Did select index \(selectedIndex)") switch segmentedControl.style { case .text: print("The title is “\(segmentedControl.titles[selectedIndex].string)”\n") case .image: print("The image is “\(segmentedControl.images[selectedIndex])”\n") } } func segmentedControl(_ segmentedControl: SegmentedControl, didLongPressIndex longPressIndex: Int) { print("Did long press index \(longPressIndex)") if UIDevice.current.userInterfaceIdiom == .pad { let viewController = UIViewController() viewController.modalPresentationStyle = .popover viewController.preferredContentSize = CGSize(width: 200, height: 300) if let popoverController = viewController.popoverPresentationController { popoverController.sourceView = view let yOffset: CGFloat = 10 popoverController.sourceRect = view.convert(CGRect(origin: CGPoint(x: 70 * CGFloat(longPressIndex), y: yOffset), size: CGSize(width: 70, height: 30)), from: navigationItem.titleView) popoverController.permittedArrowDirections = .any present(viewController, animated: true, completion: nil) } } else { let message = segmentedControl.style == .text ? "Long press title “\(segmentedControl.titles[longPressIndex].string)”" : "Long press image “\(segmentedControl.images[longPressIndex])”" let alert = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } } }
mit
f00a2cfe2d13027f37dac665463b420b
52.49763
222
0.680369
5.442623
false
false
false
false
sivu22/AnyTracker
AnyTracker/Items.swift
1
3897
// // Items.swift // AnyTracker // // Created by Cristian Sava on 07/08/16. // Copyright © 2016 Cristian Sava. All rights reserved. // import Foundation protocol ItemOps { static func createItem(withName name: String, description: String, type: ItemType, useDate: Bool, startDate: Date, endDate: Date) throws -> Item static func loadItem(withID ID:String) throws -> Item static func deleteItemFile(withID ID: String) -> Bool static func getItemType(fromID ID: String) -> ItemType? } extension ItemOps { static fileprivate func createItemID(withType type: ItemType) throws -> String { let typeIndex = type.getTypeIndex() var i = 0 var fileName: String = "" let currentTime = Utils.currentTime() while i < 10 { fileName = Constants.File.item + String(typeIndex) + String(i) + currentTime + Constants.File.ext; if !Utils.fileExists(atPath: fileName) { break } i += 1 } if i == 10 { throw Status.errorItemBadID } return fileName } static func createItem(withName name: String, description: String, type: ItemType, useDate: Bool, startDate: Date, endDate: Date) throws -> Item { var ID: String do { ID = try Self.createItemID(withType: type) } catch let error { throw error } var item: Item switch type { case .sum: item = ItemSum(withName: name, ID: ID, description: description, useDate: useDate, startDate: startDate, endDate: endDate) case .counter: item = ItemCounter(withName: name, ID: ID, description: description, useDate: useDate, startDate: startDate, endDate: endDate) case .journal: item = ItemJournal(withName: name, ID: ID, description: description, useDate: useDate, startDate: startDate, endDate: endDate) } return item } static fileprivate func loadItem(ofType type: ItemType, withContent content: String) -> Item? { switch(type) { case .sum: return ItemSum.fromJSONString(content) case .counter: return ItemCounter.fromJSONString(content) case .journal: return ItemJournal.fromJSONString(content) } } static func loadItem(withID fileName:String) throws -> Item { guard Utils.validString(fileName) && fileName.count > 5 else { Utils.debugLog("Bad filename for item") throw Status.errorInputString } guard let content = Utils.readFile(withName: fileName) else { Utils.debugLog("Failed to load item from file") throw Status.errorListFileLoad } guard let type = ItemType.getType(fromIndex: fileName[fileName.index(fileName.startIndex, offsetBy: 4)]) else { Utils.debugLog("Failed to get item type") throw Status.errorListFileLoad } guard let item = loadItem(ofType: type, withContent: content) else { Utils.debugLog("Failed to deserialize JSON item") throw Status.errorJSONDeserialize } return item } static func deleteItemFile(withID ID: String) -> Bool { let filePath = Utils.documentsPath + "/" + ID if !Utils.deleteFile(atPath: filePath) { Utils.debugLog("Failed to delete item \(ID)") return false } Utils.debugLog("Successfully deleted item \(ID)") return true } static func getItemType(fromID ID: String) -> ItemType? { let type = ItemType.getType(fromIndex: ID[ID.index(ID.startIndex, offsetBy: 4)]) return type } } struct Items: ItemOps { }
mit
86591745995047863c13cb7b4bec237a
31.739496
150
0.595226
4.654719
false
false
false
false
Draveness/RbSwift
RbSwiftTests/IO/DirSpec.swift
1
4862
// // DirSpec.swift // RbSwift // // Created by draveness on 10/04/2017. // Copyright © 2017 draveness. All rights reserved. // import Quick import Nimble import RbSwift class DirSpec: BaseSpec { override func spec() { let path: String = File.absolutePath("RbSwift/DirSpec") let originalPath = Dir.pwd beforeEach { FileUtils.mkdir_p(path) Dir.chdir(path) } afterEach { FileUtils.rm_rf(path) Dir.chdir(originalPath) } describe(".pwd") { it("returns the current working directory") { expect(Dir.pwd).to(equal(path)) } } describe(".home(path:)") { it("returns the home directory of the current user or the named user if given.") { expect(try! Dir.home(NSUserName())).to(equal(Dir.home)) } } describe(".chdir(path:)") { it("changes the curernt working directory of the process to the ginven string.") { FileUtils.mkdir_p("draveness/spool/mail") Dir.chdir("draveness/spool/mail") expect(Dir.pwd.hasSuffix("draveness/spool/mail")).to(beTrue()) let value = Dir.chdir("draveness") { return "Inside another directory" } expect(value).to(equal("Inside another directory")) } } describe(".exist(path:)") { it("returns true if the named file is a directory, false otherwise.") { let path = "what/the/fuck/is/not/exists" try? Dir.rmdir(path) expect(Dir.isExist(path)).to(beFalse()) FileUtils.mkdir_p((path)) expect(Dir.isExist(path)).to(beTrue()) try! Dir.rmdir(path) expect(Dir.isExist(path)).to(beFalse()) } } describe(".rmdir(path:)") { it("throws error if the directory isn’t exits.") { let path = "rmdir/what/the/fuck/is/not/exists" expect { try Dir.rmdir(path) }.to(throwError()) } it("throws error if the directory isn’t empty.") { let path = "rmdir/what/the/fuck/is/not/exists" // Creates directory and file FileUtils.mkdir_p(path) FileUtils.touch(path + "/file.swift") expect { try Dir.rmdir(path) }.to(throwError()) } } describe(".isExist(path:)") { beforeEach { FileUtils.mkdir_p("a/folder/with/files") FileUtils.touch("a/folder/with/files/text.swift") } afterEach { FileUtils.rm_rf("a/folder/with/files") } it("returns true if the folder is exists.") { expect(Dir.isExist("a/folder/not/exists")).to(equal(false)) expect(Dir.isExist("a/folder/with/files")).to(equal(true)) expect(Dir.isExist("a/folder/with/files/text.swift")).to(equal(false)) } } describe(".isEmpty(path:)") { beforeEach { FileUtils.mkdir_p("a/empty/folder") FileUtils.mkdir_p("a/folder/with/files") FileUtils.touch("a/folder/with/files/text.swift") } afterEach { FileUtils.rm_rf("a/empty/folder") FileUtils.rm_rf("a/folder/with/files") } it("returns true if the folder is empty or not exists.") { expect(Dir.isEmpty("a/empty/folder")).to(equal(true)) expect(Dir.isEmpty("a/folder/not/exists")).to(equal(true)) } it("returns false if the folder is not empty") { expect(Dir.isEmpty("a/folder/with/files")).to(equal(false)) } } describe(".entries(path:)") { let entriesDir = "entries" let files = ["hello.swift", "world.rb"] beforeEach { FileUtils.mkdir_p(entriesDir) files.map { File.join(entriesDir, $0) }.each { FileUtils.touch($0) } } afterEach { FileUtils.rm_rf(entriesDir) } it("returns an array containing all named filenames.") { expect(Dir.entries(entriesDir)).to(equal([".", ".."] + files)) } it("returns an empty array with not existing folder.") { expect(Dir.entries("wtf/directory")).to(equal([])) } } } }
mit
a9f93d421c39e9f18ed2f7a4502735ec
32.496552
94
0.481367
4.435616
false
false
false
false
playgroundscon/Playgrounds
Playgrounds/Controller/PresentationsFridayDataSource.swift
1
1065
// // FridayScheduleViewController.swift // Playgrounds // // Created by Andyy Hope on 18/11/16. // Copyright © 2016 Andyy Hope. All rights reserved. // import UIKit final class PresentationsFridayDataSource: NSObject { let day = ScheduleDay(sessions: []) } extension PresentationsFridayDataSource: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return day.sessions.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ScheduleSpeakerCell = tableView.dequeueReusableCell(for: indexPath) let session = day.sessions[indexPath.section] let speaker = session.speaker cell.headingLabel.text = "\(session.presentation.title)\n\(speaker.name)" cell.avatarImageView.backgroundColor = (indexPath.section % 2 == 0) ? .gray : .lightGray return cell } }
gpl-3.0
33472aa3788898c64001cae9cc0ca1c4
29.4
100
0.684211
4.728889
false
false
false
false
937447974/YJCocoa
YJCocoa/Classes/AppFrameworks/UIKit/Extension/UIControlExt.swift
1
1110
// // UIControlExt.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/6/19. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import UIKit public extension UIControl { /// 点击回调 var touchUpInsideClosure:((_ control: Any) -> ())? { get { let key = UnsafeRawPointer.init(bitPattern: "yj_touchUpInsideClosure".hashValue)! return objc_getAssociatedObject(self, key) as? ((Any) -> ()) } set { let key = UnsafeRawPointer.init(bitPattern: "yj_touchUpInsideClosure".hashValue)! if objc_getAssociatedObject(self, key) == nil { self.addTarget(self, action: #selector(UIButton.yjTouchUpInside), for: .touchUpInside) } objc_setAssociatedObject(self, key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @objc private func yjTouchUpInside() { guard let closure = self.touchUpInsideClosure else { return } closure(self) } }
mit
6019a4e5f9ee6b5ffb5d81bc7272ef04
26.769231
102
0.602955
4.165385
false
false
false
false
jkolb/Shkadov
Shkadov/renderer/Framebuffer.swift
1
1574
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb 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. */ public struct FramebufferAttachment { var render: TextureHandle = TextureHandle() var resolve: TextureHandle = TextureHandle() } public struct Framebuffer { public var colorAttachments: [FramebufferAttachment] = [] public var depthAttachment: FramebufferAttachment = FramebufferAttachment() public var stencilAttachment: FramebufferAttachment = FramebufferAttachment() public var visibilityResultBuffer: GPUBufferHandle = GPUBufferHandle() }
mit
3d6637968fec8f6fd8528f71b045a9c7
43.971429
81
0.78399
4.9653
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Banking
HatchReadyApp/apps/Hatch/iphone/native/Hatch/Extensions/UIImageExtension.swift
1
4723
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation import AVFoundation import UIKit //Custom images for the project extension UIImage{ class func backArrowWhite()->UIImage{ return UIImage(named: "back_white")! } class func backArrowGray()->UIImage{ return UIImage(named: "back_grey")! } class func menuWhite()->UIImage{ return UIImage(named: "menu_white")! } class func menuGray()->UIImage{ return UIImage(named: "menu_grey")! } class func activePageDot()->UIImage{ return UIImage(named: "page_dot_fill")! } class func inactivePageDot()->UIImage{ return UIImage(named: "page_dot")! } class func activeGreenPageDot()->UIImage{ return UIImage(named: "page_dot_fill_green")! } class func inactiveGreenPageDot()->UIImage{ return UIImage(named: "page_dot_green")! } } extension UIImage{ func croppedImage(bound : CGRect) -> UIImage { let scaledBounds : CGRect = CGRectMake(bound.origin.x * self.scale, bound.origin.y * self.scale, bound.size.width * self.scale, bound.size.height * self.scale) let imageRef = CGImageCreateWithImageInRect(self.CGImage, scaledBounds) let croppedImage : UIImage = UIImage(CGImage: imageRef!, scale: self.scale, orientation: UIImageOrientation.Up) return croppedImage; } /** Creates an image from a video. Created with help from http://stackoverflow.com/questions/8906004/thumbnail-image-of-video/8906104#8906104 - parameter videoURL: The url of the video to grab an image from - returns: The thumbnail image */ class func getThumbnailFromVideo(videoURL: NSURL) -> UIImage { let asset: AVURLAsset = AVURLAsset(URL: videoURL, options: nil) let imageGen: AVAssetImageGenerator = AVAssetImageGenerator(asset: asset) imageGen.appliesPreferredTrackTransform = true let time = CMTimeMakeWithSeconds(1.0, 600) let image: CGImageRef = try! imageGen.copyCGImageAtTime(time, actualTime: nil) let thumbnail: UIImage = UIImage(CGImage: image) return thumbnail } /** Create an image of a given color - parameter color: The color that the image will have - parameter width: Width of the returned image - parameter height: Height of the returned image - returns: An image with the color, height and width */ class func imageWithColor(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage { let rect = CGRect(x: 0, y: 0, width: width, height: height) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } /** Method to perform crop based on square inside app frame - parameter view: the view image was capture in - parameter square: the crop square over the image - parameter fromCam: determine how to handle the passed in image - returns: UIImage - the cropped image */ func cropImageInView(view: UIView, square: CGRect, fromCam: Bool) -> UIImage { var cropSquare: CGRect let frameWidth = view.frame.size.width let imageHeight = self.size.height let imageWidth = self.size.width // "if" creates a square from cameraroll image, else creates square from square frame in camera if !fromCam { var edge: CGFloat if imageWidth > imageHeight { edge = imageHeight } else { edge = imageWidth } let posX = (imageWidth - edge) / 2.0 let posY = (imageHeight - edge) / 2.0 cropSquare = CGRectMake(posX, posY, edge, edge) } else { var imageScale: CGFloat! imageScale = imageWidth / frameWidth // x and y are switched because image has -90 degrees rotation by default cropSquare = CGRectMake(square.origin.y * imageScale, square.origin.x * imageScale, square.size.width * imageScale, square.size.height * imageScale) } let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropSquare) return UIImage(CGImage: imageRef!, scale: UIScreen.mainScreen().scale, orientation: self.imageOrientation) } }
epl-1.0
9767fcf980807c00ff995778e52cb8dd
33.727941
167
0.636383
4.868041
false
false
false
false
jpsim/SourceKitten
Source/SourceKittenFramework/ByteRange.swift
1
1574
import Foundation /// Structure that represents a string range in bytes. public struct ByteRange: Equatable { /// The starting location of the range. public let location: ByteCount /// The length of the range. public let length: ByteCount /// Creates a byte range from a location and a length. /// /// - parameter location: The starting location of the range. /// - parameter length: The length of the range. public init(location: ByteCount, length: ByteCount) { self.location = location self.length = length } /// The range's upper bound. public var upperBound: ByteCount { return location + length } /// The range's lower bound. public var lowerBound: ByteCount { return location } public func contains(_ value: ByteCount) -> Bool { return location <= value && upperBound > value } public func intersects(_ otherRange: ByteRange) -> Bool { return contains(otherRange.lowerBound) || contains(otherRange.upperBound - 1) || otherRange.contains(lowerBound) || otherRange.contains(upperBound - 1) } public func intersects(_ ranges: [ByteRange]) -> Bool { return ranges.contains { intersects($0) } } public func union(with otherRange: ByteRange) -> ByteRange { let maxUpperBound = max(upperBound, otherRange.upperBound) let minLocation = min(location, otherRange.location) return ByteRange(location: minLocation, length: maxUpperBound - minLocation) } }
mit
380d8fd382d58376e3618fc7889694d5
29.862745
84
0.64676
4.873065
false
false
false
false
multinerd/Mia
Mia/Toolkits/CodableKit/CodableKit+Alamofire.swift
1
1249
// // CodableKit+Alamofire.swift // Alamofire // // Created by Michael Hedaitulla on 3/9/18. // import Foundation import Alamofire // MARK: - Alamofire response handlers public extension DataRequest { fileprivate func decodableResponseSerializer<T: Decodable>() -> DataResponseSerializer<T> { return DataResponseSerializer { _, response, data, error in guard error == nil else { return .failure(error!) } guard let data = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } return Result { try JSONDecoder().decode(T.self, from: data) } } } @discardableResult fileprivate func responseDecodable<T: Decodable>(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self { return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) } @discardableResult public func responseCodable<T: Codable>(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self { return responseDecodable(queue: queue, completionHandler: completionHandler) } }
mit
2eb401c45b8857c08adddc2673d5b9fc
33.694444
147
0.681345
4.976096
false
false
false
false
digice/ioscxn
Swift/Connection/ConnectionController.swift
1
2788
// // ConnectionController.swift // iOSCxn // // Created by Roderic Linguri // Copyright © 2017 Digices LLC. All rights reserved. // import UIKit class ConnectionController: UIViewController, UITextFieldDelegate, ConnectionManagerDelegate { // MARK: - IBOutlets @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var formView: UIView! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var methodControl: UISegmentedControl! @IBOutlet weak var urlField: UITextField! @IBOutlet weak var keyField: UITextField! @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var messageLabel: UILabel! // MARK: - Properties let manager = ConnectionManager.shared // MARK: - ConnectionController (self) func updateViewFromData() { let object = self.manager.object switch object.method { case "GET": self.methodControl.selectedSegmentIndex = 0 case "POST": self.methodControl.selectedSegmentIndex = 1 default: self.methodControl.selectedSegmentIndex = 1 } self.urlField.text = object.url self.keyField.text = object.key self.messageLabel.text = self.manager.response?.message } func updateDataFromView() { if self.methodControl.selectedSegmentIndex == 0 { self.manager.object.method = "GET" } else { self.manager.object.method = "POST" } if let u = self.urlField.text { if u.characters.count > 0 { self.manager.object.url = u } } if let k = self.keyField.text { if k.characters.count > 0 { self.manager.object.key = k } } } // MARK: - UIViewController override func awakeFromNib() { super.awakeFromNib() self.title = "Connection" self.manager.delegate = self } override func viewDidLoad() { super.viewDidLoad() self.urlField.delegate = self self.keyField.delegate = self self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))) let image = UIImage(named:"Connection_60pt")?.withRenderingMode(.alwaysTemplate) self.iconView.tintColor = UIColor(red: 15/255, green: 121/255, blue: 252/255, alpha: 1) self.iconView.image = image self.updateViewFromData() } // MARK: - UITextFieldDelegate func dismissKeyboard() { self.view.endEditing(true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } // MARK: - ConnectionManagerDelegate func connectionDidComplete(response: Response) { self.updateViewFromData() } // MARK: - IBActions @IBAction func save(_ sender: UIButton) { self.updateDataFromView() self.manager.saveDefault() } }
mit
063c206fd6af97fc05f6765b9e103bf2
21.658537
113
0.688554
4.341121
false
false
false
false
apple/swift-nio
IntegrationTests/tests_04_performance/test_01_resources/test_read_10000_chunks_from_file.swift
1
2351
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation import Dispatch import NIOCore import NIOPosix import NIOConcurrencyHelpers func run(identifier: String) { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { try! group.syncShutdownGracefully() } let loop = group.next() let threadPool = NIOThreadPool(numberOfThreads: 1) threadPool.start() defer { try! threadPool.syncShutdownGracefully() } let fileIO = NonBlockingFileIO(threadPool: threadPool) let numberOfChunks = 10_000 let allocator = ByteBufferAllocator() var fileBuffer = allocator.buffer(capacity: numberOfChunks) fileBuffer.writeString(String(repeating: "X", count: numberOfChunks)) let path = NSTemporaryDirectory() + "/\(UUID())" let fileHandle = try! NIOFileHandle(path: path, mode: [.write, .read], flags: .allowFileCreation(posixMode: 0o600)) defer { unlink(path) } try! fileIO.write(fileHandle: fileHandle, buffer: fileBuffer, eventLoop: loop).wait() let numberOfBytes = NIOAtomic<Int>.makeAtomic(value: 0) measure(identifier: identifier) { numberOfBytes.store(0) try! fileIO.readChunked(fileHandle: fileHandle, fromOffset: 0, byteCount: numberOfChunks, chunkSize: 1, allocator: allocator, eventLoop: loop) { buffer in numberOfBytes.add(buffer.readableBytes) return loop.makeSucceededFuture(()) }.wait() precondition(numberOfBytes.load() == numberOfChunks, "\(numberOfBytes.load()), \(numberOfChunks)") return numberOfBytes.load() } }
apache-2.0
bd21f7f2fc2a758a5f9c5eb5f2809097
35.169231
106
0.568269
5.283146
false
false
false
false
JadenGeller/Parsley
Sources/Sequencing.swift
1
4059
// // Sequencing.swift // Parsley // // Created by Jaden Geller on 1/12/16. // Copyright © 2016 Jaden Geller. All rights reserved. // /** Constructs a `Parser` that will parse will each element of `parsers`, sequentially. Parsing only succeeds if every parser succeeds, and the resulting parser returns an array of the results. - Parameter parsers: The sequence of parsers to sequentially run. */ public func sequence<Token, Result, Sequence: SequenceType where Sequence.Generator.Element == Parser<Token, Result>> (parsers: Sequence) -> Parser<Token, [Result]> { return Parser { state in var results = [Result]() for parser in parsers { results.append(try parser.parse(state)) } return results } } /** Constructs a `Parser` that will parse will each element of `parsers`, sequentially. Parsing only succeeds if every parser succeeds, and the resulting parser returns an array of the results. - Parameter parsers: The variadic list of parsers to sequentially run. */ public func sequence<Token, Result>(parsers: Parser<Token, Result>...) -> Parser<Token, [Result]> { return sequence(parsers) } /** Constructs a `Parser` that will run the passed-in parsers sequentially. Parsing only succeeds if both parsers succeed, and the resulting parser returns an tuple of the results. */ @warn_unused_result public func pair<Token, LeftResult, RightResult>(leftParser: Parser<Token, LeftResult>, _ rightParser: Parser<Token, RightResult>) -> Parser<Token, (LeftResult, RightResult)> { return leftParser.flatMap { a in rightParser.map { b in return (a, b) } } } /** Constructs a `Parser` that will parse each element of `parsers`, sequentially. Parsing only succeeds if every parser succeeds, and the resulting parser returns an array of the results. - Parameter parsers: The sequence of parsers to sequentially run. */ public func concat<Token, Result, Sequence: SequenceType where Sequence.Generator.Element == Parser<Token, [Result]>>(parsers: Sequence) -> Parser<Token, [Result]> { return sequence(parsers).map{ Array($0.flatten()) } } /** Constructs a `Parser` that will parse each element of `parsers`, sequentially. Parsing only succeeds if every parser succeeds, and the resulting parser returns an array of the results. - Parameter parsers: The variadic list of parsers to sequentially run. */ public func concat<Token, Result>(parsers: Parser<Token, [Result]>...) -> Parser<Token, [Result]> { return concat(parsers) } /** Constructs a `Parser` that will parse each element of `parsers`, sequentially. Parsing only succeeds if every parser succeeds, and the resulting parser returns an array of the results. - Parameter parsers: The variadic list of parsers to sequentially run. */ public func +<Token, Result>(left: Parser<Token, [Result]>, right: Parser<Token, [Result]>) -> Parser<Token, [Result]> { return concat(left, right) } /** Constructs a `Parser` that will parse `first` and then will parse `others`, prepending the result of `first` to the result of `others`. - Parameter first: The first parser to run whose result will be prepended to the result of `others`. - Parameter others: The second parser to run. The result should be an array. */ public func prepend<Token, Result>(first: Parser<Token, Result>, _ others: Parser<Token, [Result]>) -> Parser<Token, [Result]> { return pair(first, others).map{ [$0] + $1 } } /** Constructs a `Parser` that will parse `others` and then will parse `last`, appending the result of `last` to the result of `others`. - Parameter others: The first parser to run. The result should be an array. - Parameter last: The last parser to run whose result will be appended to the result of `others`. */ public func append<Token, Result>(others: Parser<Token, [Result]>, _ last: Parser<Token, Result>) -> Parser<Token, [Result]> { return pair(others, last).map{ $0 + [$1] } }
mit
331ab26a4654753b17a67a5ab0a27a85
38.784314
196
0.698374
4.187822
false
false
false
false
larryhou/swift
Tachograph/Tachograph/ImagePreviewController.swift
1
9422
// // ImagePreviewController.swift // Tachograph // // Created by larryhou on 01/08/2017. // Copyright © 2017 larryhou. All rights reserved. // import Foundation import UIKit extension CGAffineTransform { var scaleX: CGFloat { return sqrt(a*a + c*c) } var scaleY: CGFloat { return sqrt(b*b + d*d) } var scale: (CGFloat, CGFloat) { return (self.scaleX, self.scaleY) } } class ImageScrollController: PageController<ImagePreviewController, CameraModel.CameraAsset>, UIGestureRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() let pan = UIPanGestureRecognizer(target: self, action: #selector(panUpdate(sender:))) pan.delegate = self view.addGestureRecognizer(pan) } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return UIDevice.current.orientation.isPortrait } var fractionComplete = CGFloat.nan var dismissAnimator: UIViewPropertyAnimator! @objc func panUpdate(sender: UIPanGestureRecognizer) { switch sender.state { case .began: dismissAnimator = UIViewPropertyAnimator(duration: 0.2, curve: .linear) { [unowned self] in self.view.frame.origin.y = self.view.frame.height self.view.layer.cornerRadius = 40 } dismissAnimator.addCompletion { [unowned self] position in if position == .end { self.dismiss(animated: false, completion: nil) } self.fractionComplete = CGFloat.nan } dismissAnimator.pauseAnimation() case .changed: if fractionComplete.isNaN {fractionComplete = 0} let translation = sender.translation(in: view) fractionComplete += translation.y / view.frame.height fractionComplete = min(1, max(0, fractionComplete)) dismissAnimator.fractionComplete = fractionComplete sender.setTranslation(CGPoint.zero, in: view) default: if dismissAnimator.fractionComplete <= 0.25 { dismissAnimator.isReversed = true } dismissAnimator.continueAnimation(withTimingParameters: nil, durationFactor: 1.0) } } } class ImagePreviewController: ImagePeekController, PageProtocol { static func instantiate(_ storyboard: UIStoryboard) -> PageProtocol { return storyboard.instantiateViewController(withIdentifier: "ImagePreviewController") as! PageProtocol } var pageAsset: Any? { didSet { if let data = self.pageAsset as? CameraModel.CameraAsset { self.url = data.url self.data = data } } } var scaleRange: (CGFloat, CGFloat) = (1.0, 3.0) var frameImage = CGRect() weak var panGesture: UIPanGestureRecognizer? override func viewDidLoad() { super.viewDidLoad() presentController = self scaleRange = (scaleRange.0, view.frame.height / image.frame.height) frameImage = image.frame let pinch = UIPinchGestureRecognizer(target: self, action: #selector(pinchUpdate(sender:))) view.addGestureRecognizer(pinch) // let pan = UIPanGestureRecognizer(target: self, action: #selector(panUpdate(sender:))) // image.addGestureRecognizer(pan) // panGesture = pan let press = UILongPressGestureRecognizer(target: self, action: #selector(pressUpdate(sender:))) image.addGestureRecognizer(press) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) image.transform = CGAffineTransform.identity } @objc func pressUpdate(sender: UILongPressGestureRecognizer) { if sender.state != .began {return} let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "保存到相册", style: .default, handler: { _ in self.saveToAlbum() })) alertController.addAction(UIAlertAction(title: "分享", style: .default, handler: { _ in self.share() })) alertController.addAction(UIAlertAction(title: "删除", style: .destructive, handler: { _ in self.delete() })) alertController.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } var panAnimator: UIViewPropertyAnimator? var origin: CGPoint = CGPoint() @objc func panUpdate(sender: UIPanGestureRecognizer) { switch sender.state { case .began: origin = image.frame.origin case .changed: let offset = sender.translation(in: image.superview) image.frame.origin.x = origin.x + offset.x image.frame.origin.y = origin.y + offset.y case .ended: positionAdjust() default:break } } func positionAdjust() { var rect = image.superview!.convert(image.frame, to: view) rect.origin.x = max(min(rect.origin.x, 0), view.frame.width - rect.width) rect.origin.y = max(min(rect.origin.y, 0), (view.frame.height - rect.height)/2) rect = view.convert(rect, to: image.superview) let animator = UIViewPropertyAnimator(duration: 0.2, curve: .easeOut) { [unowned self] in self.image.frame = rect } animator.startAnimation() } func scaleAdjust(relatedUpdate: Bool = true, fitted: Bool = false) { scale = fitted ? scaleRange.0 : min(max(scaleRange.0, scale), scaleRange.1) let transform = CGAffineTransform(scaleX: scale, y: scale) let animator = UIViewPropertyAnimator(duration: 0.4, dampingRatio: 0.85) { [unowned self] in self.image.transform = transform } if (relatedUpdate) {animator.addCompletion { _ in self.positionAdjust() }} animator.startAnimation() } var scale: CGFloat = 1.0 @objc func pinchUpdate(sender: UIPinchGestureRecognizer) { switch sender.state { case .began: sender.scale = image.transform.scaleX case .changed: scale = sender.scale image.transform = CGAffineTransform(scaleX: scale, y: scale) case .ended: scaleAdjust() default:break } } } class ImagePeekController: UIViewController { var url: String! var data: CameraModel.CameraAsset? var index: Int = -1 @IBOutlet weak var image: UIImageView! @IBOutlet weak var indicator: UIActivityIndicatorView! weak var presentController: UIViewController? override var previewActionItems: [UIPreviewActionItem] { var actions: [UIPreviewAction] = [] actions.append(UIPreviewAction(title: "保存到相册", style: .default) { (_: UIPreviewAction, _: UIViewController) in self.saveToAlbum() }) actions.append(UIPreviewAction(title: "分享", style: .default) { (_: UIPreviewAction, _: UIViewController) in self.share() }) return actions } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) indicator.stopAnimating() self.image.image = nil let manager = AssetManager.shared if let location = manager.get(cacheOf: url) { image.image = try! UIImage(data: Data(contentsOf: location)) } else { indicator.startAnimating() manager.load(url: url, completion: { self.indicator?.stopAnimating() self.image?.image = UIImage(data: $1) }) } } func delete() { guard let url = self.url else {return} if let location = AssetManager.shared.get(cacheOf: url) { dismiss(animated: true) { let success = AssetManager.shared.remove(location.path) AlertManager.show(title: success ? "文件删除成功" : "文件删除失败", message: location.path, sender: self) } } } func share() { guard let url = self.url, let presentController = self.presentController else {return} if let location = AssetManager.shared.get(cacheOf: url) { let controller = UIActivityViewController(activityItems: [location], applicationActivities: nil) presentController.present(controller, animated: true, completion: nil) } } func saveToAlbum() { guard let url = self.url else {return} if let location = AssetManager.shared.get(cacheOf: url) { if let data = try? Data(contentsOf: location), let image = UIImage(data: data) { UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil) } } } @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo context: Any?) { AlertManager.show(title: error == nil ? "图片保存成功" : "图片保存失败", message: error?.debugDescription, sender: self) } }
mit
f48f293e822ca79f57235ada384744ef
36.497992
123
0.621292
4.742001
false
false
false
false
belatrix/iOSAllStars
AllStarsV2/AllStarsV2/WS/UserWebModel.swift
1
6842
// // UserWebModel.swift // AllStarsV2 // // Created by Kenyi Rodriguez Vergara on 20/07/17. // Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved. // import UIKit class UserWebModel: NSObject { class func uploadPhoto(_ image: UIImage, toUserSession session: SessionBE, withSuccessful success: @escaping User, withError error: @escaping ErrorResponse) { let path = "api/employee/\(session.session_user_id)/avatar/" CDMWebSender.uploadRequest(image, withURL: Constants.WEB_SERVICES, withPath: path, withParameter: nil, withToken: session.session_token) { (response) in self.getUserInformationById(session.session_user_id.intValue, withSession: session, withSuccessful: { (objUser) in success(objUser) }, withError: { (ErrorResponse) in error(ErrorResponse) }) } } class func getUserInformationById(_ userId : Int, withSession session: SessionBE, withSuccessful success: @escaping User, withError error: @escaping ErrorResponse) { let path = "api/employee/\(userId)/" CDMWebSender.doGETTokenToURL(Constants.WEB_SERVICES, withPath: path, withParameter: nil, withToken: session.session_token) { (response) in let JSON = response.JSON as? [String : Any] if response.successful{ success(UserBE.parse(JSON!)) }else{ error(ErrorResponseBE.parse(JSON, withCode: response.statusCode)) } } } class func updateUser(_ user: UserBE, withSession session: SessionBE, withSuccessful success: @escaping User, withError error: @escaping ErrorResponse) { let path = "api/employee/\(session.session_user_id)/update/" let dic : [String : Any] = ["first_name" : user.user_first_name!, "last_name" : user.user_last_name!, "skype_id" : user.user_skype_id!, "location" : user.user_location!.location_pk] CDMWebSender.doPATCHTokenToURL(Constants.WEB_SERVICES, withPath: path, withParameter: dic, withToken: session.session_token) { (response) in let JSON = response.JSON as? [String : Any] if response.successful{ success(UserBE.parse(JSON!)) }else{ error(ErrorResponseBE.parse(JSON, withCode: response.statusCode)) } } } class func logInUsername(_ username: String, withPassword password: String, withSuccessful success : @escaping UserSession, withError error : @escaping ErrorResponse){ let dic : [String : Any] = ["username" : username, "password" : password] let path = "api/employee/authenticate/" CDMWebSender.doPOSTToURL(Constants.WEB_SERVICES, withPath: path, withParameter: dic) { (response) in let JSON = response.JSON as? [String : Any] if response.successful{ success(SessionBE.parse(JSON!)) }else{ error(ErrorResponseBE.parse(JSON, withCode: response.statusCode)) } } } class func resetUserPassword(_ userSession : SessionBE, currentPassword : String, newPassword : String, withSuccessful success : @escaping UserSession, withError error : @escaping ErrorResponse) { let path = "api/employee/\(userSession.session_user_id)/update/password/" let dic : [String : Any] = ["current_password" : currentPassword, "new_password" : newPassword] CDMWebSender.doPOSTTokenToURL(Constants.WEB_SERVICES, withPath: path, withParameter: dic, withToken: userSession.session_token) { (response) in let JSON = response.JSON as? [String : Any] if response.successful{ success(userSession) }else{ error(ErrorResponseBE.parse(JSON, withCode: response.statusCode)) } } } class func forgotPasswordToEmail(_ user_email: String, withSuccessful success : @escaping Success, withError error : @escaping ErrorResponse) { let path = "api/employee/reset/password/\(user_email)/" CDMWebSender.doGETToURL(Constants.WEB_SERVICES, withPath: path, withParameter: nil) { (response) in let JSON = response.JSON as? [String : Any] if response.successful{ if let _ = response.JSON as? [String : Any] { success(true) }else{ success(false) } }else{ error(ErrorResponseBE.parse(JSON, withCode: response.statusCode)) } } } class func createUserWithEmail(_ user_email: String, withSuccessful success : @escaping Success, withError error : @escaping ErrorResponse) { let path = "api/employee/create/" let dic : [String : Any] = ["email" : user_email] CDMWebSender.doPOSTToURL(Constants.WEB_SERVICES, withPath: path, withParameter: dic) { (response) in let JSON = response.JSON as? [String : Any] if response.successful{ if let _ = response.JSON as? [String : Any] { success(true) }else{ success(false) } }else{ error(ErrorResponseBE.parse(JSON, withCode: response.statusCode)) } } } class func registerDevice(_ idDevice: String, toSession session: SessionBE, withSuccessful success : @escaping Success, withError error : @escaping ErrorResponse) { let path = "api/employee/\(session.session_user_id)/register/device/" let dic : [String : Any] = ["employee_id" : session.session_user_id, "android_device" : "", "ios_device" : idDevice] CDMWebSender.doPOSTTokenToURL(Constants.WEB_SERVICES, withPath: path, withParameter: dic, withToken: session.session_token) { (response) in let isSuccess = (response.statusCode == 202 || response.statusCode == 200) ? true : false success(isSuccess) } } }
apache-2.0
9c3244ceea718994fe2ccfb77fc0fa79
39.47929
200
0.549335
4.914511
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Song/SongViewController.swift
1
6889
// // SongViewController.swift // MusicApp // // Created by Hưng Đỗ on 6/9/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import XLPagerTabStrip import RxSwift import Action import RxDataSources import NSObject_Rx class SongViewController: UIViewController { @IBOutlet weak var tableView: UITableView! fileprivate var initialIndicatorView = InitialActivityIndicatorView() fileprivate var loadingIndicatorView = LoadingActivityIndicatorView() lazy var categoryHeaderView: CategoryHeaderView = CategoryHeaderView(size: CGSize( width: self.tableView.bounds.size.width, height: CategoryHeaderView.defaultHeight )) fileprivate var refreshControl = OnlineRefreshControl() var store: SongStore! var action: SongAction! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.addSubview(refreshControl) bindStore() bindAction() } fileprivate var SongsSection = 1 fileprivate lazy var dataSource: RxTableViewSectionedReloadDataSource<SongSection> = { [weak self] in let dataSource = RxTableViewSectionedReloadDataSource<SongSection>() dataSource.configureCell = { dataSource, tableView, indexPath, song in guard let controller = self else { fatalError("Unexpected View Controller") } return dataSource.configureCell(for: tableView, at: indexPath, in: controller, animated: controller.store.loadMoreEnabled.value) { if indexPath.section == controller.SongsSection { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SongCell.self), for: indexPath) if let cell = cell as? SongCell { let contextAction = CocoaAction { _ in return controller.action.onContextButtonTap.execute((song, controller)).map { _ in } } cell.configure(name: song.name, singer: song.singer, contextAction: contextAction) } return cell } fatalError("Unexpected Song Section") } } dataSource.titleForHeaderInSection = { dataSource, section in dataSource[section].model } return dataSource }() } extension SongViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == self.SongsSection { let categoryAction = CocoaAction { return self.action.onCategoriesButtonTap.execute(()).map { _ in } } categoryHeaderView.configure(text: store.category.value.name, action: categoryAction) return categoryHeaderView } return UIView() } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == self.SongsSection { return CategoryHeaderView.defaultHeight } return 0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let AdvertisementSection = 0 let SongSection = 1 let LoadMoreSection = 2 switch indexPath.section { case AdvertisementSection: return 50 case LoadMoreSection: return 44 case SongSection: return 44 default: fatalError("Unexpected Row Height") } } } extension SongViewController: IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return "Bài hát" } } extension SongViewController { func bindStore() { store.songs.asObservable() .filter { $0.count > 0 } .do(onNext: { [weak self] _ in self?.initialIndicatorView.stopAnimating() self?.refreshControl.endRefreshing() }) .map { songs in [ SongSection(model: "Advertisement", items: [Song(id: "ad", name: "Advertisement", singer: "Google")]), SongSection(model: "Songs", items: songs), SongSection(model: "Load More", items: [Song(id: "load", name: "Load More", singer: "Table View")]) ]} .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(rx_disposeBag) store.songs.asObservable() .filter { $0.count == 0 } .subscribe(onNext: { [weak self] _ in self?.initialIndicatorView.startAnimating(in: self?.view) }) .addDisposableTo(rx_disposeBag) store.category.asObservable() .subscribe(onNext: { [weak self] category in self?.categoryHeaderView.text = category.name }) .addDisposableTo(rx_disposeBag) store.songLoading.asObservable() .skip(3) .subscribe(onNext: { [weak self] loading in if loading { self?.loadingIndicatorView.startAnimation(in: self?.view); return } self?.loadingIndicatorView.stopAnimation() self?.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false) }) .addDisposableTo(rx_disposeBag) } func bindAction() { action.onLoadCategories.execute(()) let initialCategoryLoading = store.category.asObservable() .take(1) .map { category in category.link } let categoriesButtonTapLoading = action.onCategoriesButtonTap.elements .filter { info in info != nil } .map { category in category!.link } Observable.from([initialCategoryLoading, categoriesButtonTapLoading]) .merge() .subscribe(action.onLoad.inputs) .addDisposableTo(rx_disposeBag) refreshControl.rx.controlEvent(.valueChanged) .map { [weak self] _ in self!.store.category.value.link } .subscribe(action.onPullToRefresh.inputs) .addDisposableTo(rx_disposeBag) tableView.rx.willDisplayCell .filter { _, indexPath in indexPath.section == 2 } .filter { [weak self] _, _ in self?.store.loadMoreEnabled.value ?? true } .map { [weak self] _ in self!.store.category.value.link } .subscribe(action.onLoadMore.inputs) .addDisposableTo(rx_disposeBag) tableView.rx.modelSelected(Song.self) .subscribe(action.onSongDidSelect.inputs) .addDisposableTo(rx_disposeBag) } }
mit
5c05a0731f99b97272ab07a6bf1d56cf
35.412698
142
0.604185
5.265493
false
false
false
false
3squared/ios-charts
Charts/Classes/Renderers/ChartXAxisRenderer.swift
1
13607
// // ChartXAxisRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartXAxisRenderer: ChartAxisRendererBase { internal var _xAxis: ChartXAxis! public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, transformer: transformer) _xAxis = xAxis } public func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?]) { var a = "" let max = Int(round(xValAverageLength + Double(_xAxis.spaceBetweenLabels))) for (var i = 0; i < max; i++) { a += "h" } let widthText = a as NSString _xAxis.labelWidth = widthText.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width _xAxis.labelHeight = _xAxis.labelFont.lineHeight _xAxis.values = xValues } public override func renderAxisLabels(context context: CGContext?) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled) { return } let yoffset = CGFloat(4.0) if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset) } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.5) } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentBottom - _xAxis.labelHeight - yoffset) } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.offsetTop + yoffset) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset) drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.6) } } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(context context: CGContext?) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, _xAxis.axisLineWidth) if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } /// draws the x-labels on the specified y-position internal func drawLabels(context context: CGContext?, pos: CGFloat) { let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paraStyle.alignment = .Center let labelAttrs = [NSFontAttributeName: _xAxis.labelFont, NSForegroundColorAttributeName: _xAxis.labelTextColor, NSParagraphStyleAttributeName: paraStyle] let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) var labelMaxSize = CGSize() if (_xAxis.isWordWrapEnabled) { labelMaxSize.width = _xAxis.wordWrapWidthPercent * valueToPixelMatrix.a } for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { let label = _xAxis.values[i] if (label == nil) { continue } position.x = CGFloat(i) position.y = 0.0 position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (viewPortHandler.isInBoundsX(position.x)) { let labelns = label! as NSString if (_xAxis.isAvoidFirstLastClippingEnabled) { // avoid clipping of the last if (i == _xAxis.values.count - 1 && _xAxis.values.count > 1) { let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width if (width > viewPortHandler.offsetRight * 2.0 && position.x + width > viewPortHandler.chartWidth) { position.x -= width / 2.0 } } else if (i == 0) { // avoid clipping of the first let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width position.x += width / 2.0 } } drawLabel(context: context, label: label!, xIndex: i, x: position.x, y: pos, align: .Center, attributes: labelAttrs, constrainedToSize: labelMaxSize) } } } internal func drawLabel(context context: CGContext?, label: String, xIndex: Int, x: CGFloat, y: CGFloat, align: NSTextAlignment, attributes: [String: NSObject], constrainedToSize: CGSize) { let formattedLabel = _xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label ChartUtils.drawMultilineText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), align: align, attributes: attributes, constrainedToSize: constrainedToSize) } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(context context: CGContext?) { if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor) CGContextSetLineWidth(context, _xAxis.gridLineWidth) if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = _minX; i <= _maxX; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i) position.y = 0.0 position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (position.x >= viewPortHandler.offsetLeft && position.x <= viewPortHandler.chartWidth) { _gridLineSegmentsBuffer[0].x = position.x _gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop _gridLineSegmentsBuffer[1].x = position.x _gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(context context: CGContext?) { var limitLines = _xAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { let l = limitLines[i] position.x = CGFloat(l.limit) position.y = 0.0 position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = position.x _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop _limitLineSegmentsBuffer[1].x = position.x _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) let label = l.label // if drawing the limit-value label is enabled if (label.characters.count > 0) { let labelLineHeight = l.valueFont.lineHeight let add = CGFloat(4.0) let xOffset: CGFloat = l.lineWidth let yOffset: CGFloat = add / 2.0 if (l.labelPosition == .RightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .RightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .LeftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentTop + yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } if let image = l.image { let x = position.x - image.size.width / 2 let y = l.imagePosition == .End ? viewPortHandler.contentTop - 1 : viewPortHandler.contentBottom - image.size.height + 1 ChartUtils.drawImage(context: context, image: image, point: CGPoint( x: x, y: y)) } } CGContextRestoreGState(context) } }
apache-2.0
1f5d725a515ed56df4f4ed9f455134dd
37.769231
191
0.552142
5.775467
false
false
false
false
untitledstartup/OAuthSwift
OAuthSwift/Dictionary+OAuthSwift.swift
1
1355
// // Dictionary+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension Dictionary { func join(other: Dictionary) -> Dictionary { var joinedDictionary = Dictionary() for (key, value) in self { joinedDictionary.updateValue(value, forKey: key) } for (key, value) in other { joinedDictionary.updateValue(value, forKey: key) } return joinedDictionary } func filter(predicate: (key: Key, value: Value) -> Bool) -> Dictionary { var filteredDictionary = Dictionary() for (key, value) in self { if predicate(key: key, value: value) { filteredDictionary.updateValue(value, forKey: key) } } return filteredDictionary } func urlEncodedQueryStringWithEncoding(encoding: NSStringEncoding) -> String { var parts = [String]() for (key, value) in self { let keyString = "\(key)".urlEncodedStringWithEncoding(encoding) let valueString = "\(value)".urlEncodedStringWithEncoding(encoding) let query = "\(keyString)=\(valueString)" as String parts.append(query) } return parts.joinWithSeparator("&") } }
mit
4a0347919f22050465cf50e2c4406e64
25.057692
82
0.598524
4.839286
false
false
false
false
groue/GRDB.swift
GRDB/QueryInterface/SQL/SQLOperators.swift
1
14635
extension SQLSpecificExpressible { // MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) /// Compares two SQL expressions. /// /// For example: /// /// ```swift /// // name = 'Arthur' /// Column("name") == "Arthur" /// ``` /// /// When the right operand is nil, `IS NULL` is used instead of the /// `=` operator: /// /// ```swift /// // name IS NULL /// Column("name") == nil /// ``` public static func == (lhs: Self, rhs: (any SQLExpressible)?) -> SQLExpression { .equal(lhs.sqlExpression, rhs?.sqlExpression ?? .null) } /// The `=` SQL operator. public static func == (lhs: Self, rhs: Bool) -> SQLExpression { if rhs { return lhs.sqlExpression.is(.true) } else { return lhs.sqlExpression.is(.false) } } /// Compares two SQL expressions. /// /// For example: /// /// ```swift /// // 'Arthur' = name /// "Arthur" == Column("name") /// ``` /// /// When the left operand is nil, `IS NULL` is used instead of the /// `=` operator: /// /// ```swift /// // name IS NULL /// nil == Column("name") /// ``` public static func == (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { .equal(lhs?.sqlExpression ?? .null, rhs.sqlExpression) } /// The `=` SQL operator. public static func == (lhs: Bool, rhs: Self) -> SQLExpression { if lhs { return rhs.sqlExpression.is(.true) } else { return rhs.sqlExpression.is(.false) } } /// The `=` SQL operator. public static func == (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .equal(lhs.sqlExpression, rhs.sqlExpression) } /// Compares two SQL expressions. /// /// For example: /// /// ```swift /// // name <> 'Arthur' /// Column("name") != "Arthur" /// ``` /// /// When the right operand is nil, `IS NOT NULL` is used instead of the /// `<>` operator: /// /// ```swift /// // name IS NOT NULL /// Column("name") != nil /// ``` public static func != (lhs: Self, rhs: (any SQLExpressible)?) -> SQLExpression { !(lhs == rhs) } /// The `<>` SQL operator. public static func != (lhs: Self, rhs: Bool) -> SQLExpression { !(lhs == rhs) } /// Compares two SQL expressions. /// /// For example: /// /// ```swift /// // 'Arthur' <> name /// "Arthur" != Column("name") /// ``` /// /// When the left operand is nil, `IS NOT NULL` is used instead of the /// `<>` operator: /// /// ```swift /// // name IS NOT NULL /// nil != Column("name") /// ``` public static func != (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { !(lhs == rhs) } /// The `<>` SQL operator. public static func != (lhs: Bool, rhs: Self) -> SQLExpression { !(lhs == rhs) } /// The `<>` SQL operator. public static func != (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs == rhs) } /// The `IS` SQL operator. public static func === (lhs: Self, rhs: (any SQLExpressible)?) -> SQLExpression { .compare(.is, lhs.sqlExpression, rhs?.sqlExpression ?? .null) } /// The `IS` SQL operator. public static func === (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { if let lhs = lhs { return .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } else { return .compare(.is, rhs.sqlExpression, .null) } } /// The `IS` SQL operator. public static func === (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } /// The `IS NOT` SQL operator. public static func !== (lhs: Self, rhs: (any SQLExpressible)?) -> SQLExpression { !(lhs === rhs) } /// The `IS NOT` SQL operator. public static func !== (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { !(lhs === rhs) } /// The `IS NOT` SQL operator. public static func !== (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs === rhs) } // MARK: - Comparison Operators (<, >, <=, >=) /// The `<` SQL operator. public static func < (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// The `<` SQL operator. public static func < (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// The `<` SQL operator. public static func < (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// The `<=` SQL operator. public static func <= (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// The `<=` SQL operator. public static func <= (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// The `<=` SQL operator. public static func <= (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// The `>` SQL operator. public static func > (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// The `>` SQL operator. public static func > (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// The `>` SQL operator. public static func > (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// The `>=` SQL operator. public static func >= (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// The `>=` SQL operator. public static func >= (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// The `>=` SQL operator. public static func >= (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } } // MARK: - Inclusion Operators (BETWEEN, IN) extension Range where Bound: SQLExpressible { /// Returns an SQL expression that checks the inclusion of an expression in /// a range. /// /// For example: /// /// ```swift /// // email >= 'A' AND email < 'B' /// ("A"..<"B").contains(Column("email")) /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { (element >= lowerBound) && (element < upperBound) } } extension ClosedRange where Bound: SQLExpressible { /// Returns an SQL expression that checks the inclusion of an expression in /// a range. /// /// For example: /// /// ```swift /// // initial BETWEEN 'A' AND 'B' /// ("A"..."B").contains(Column("initial")) /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { .between( expression: element.sqlExpression, lowerBound: lowerBound.sqlExpression, upperBound: upperBound.sqlExpression) } } extension CountableRange where Bound: SQLExpressible { /// Returns an SQL expression that checks the inclusion of an expression in /// a range. /// /// For example: /// /// ```swift /// // id >= 1 AND id < 10 /// (1..<10).contains(Column("id")) /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { (element >= lowerBound) && (element < upperBound) } } extension CountableClosedRange where Bound: SQLExpressible { /// Returns an SQL expression that checks the inclusion of an expression in /// a range. /// /// For example: /// /// ```swift /// // id BETWEEN 1 AND 10 /// (1...10).contains(Column("id")) /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { .between( expression: element.sqlExpression, lowerBound: lowerBound.sqlExpression, upperBound: upperBound.sqlExpression) } } extension Sequence where Element: SQLExpressible { /// Returns an SQL expression that checks the inclusion of an expression in /// a sequence. /// /// For example: /// /// ```swift /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } extension Sequence where Element == any SQLExpressible { /// Returns an SQL expression that checks the inclusion of an expression in /// a sequence. /// /// For example: /// /// ```swift /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } // MARK: - Arithmetic Operators (+, -, *, /) extension SQLSpecificExpressible { /// The `*` SQL operator. public static func * (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `*` SQL operator. public static func * (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `*` SQL operator. public static func * (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `/` SQL operator. public static func / (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// The `/` SQL operator. public static func / (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// The `/` SQL operator. public static func / (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// The `+` SQL operator. public static func + (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `+` SQL operator. public static func + (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `+` SQL operator. public static func + (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `-` SQL operator. public static prefix func - (value: Self) -> SQLExpression { .unary(.minus, value.sqlExpression) } /// The `-` SQL operator. public static func - (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// The `-` SQL operator. public static func - (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// The `-` SQL operator. public static func - (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } // MARK: - Logical Operators (AND, OR, NOT) /// The `AND` SQL operator. public static func && (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `AND` SQL operator. public static func && (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `AND` SQL operator. public static func && (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `OR` SQL operator. public static func || (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `OR` SQL operator. public static func || (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// The `OR` SQL operator. public static func || (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression. /// /// For example: /// /// ```swift /// // NOT isBlue /// !Column("isBlue") /// ``` /// /// Some expressions are negated with specific SQL operators: /// /// ```swift /// // id NOT BETWEEN 1 AND 10 /// !((1...10).contains(Column("id"))) /// ``` public static prefix func ! (value: Self) -> SQLExpression { value.sqlExpression.is(.falsey) } } // MARK: - Like Operator extension SQLSpecificExpressible { /// The `LIKE` SQL operator. /// /// For example: /// /// ```swift /// // email LIKE '%@example.com" /// Column("email").like("%@example.com") /// /// // title LIKE '%10\%%' ESCAPE '\' /// Column("title").like("%10\\%%", escape: "\\") /// ``` public func like(_ pattern: some SQLExpressible, escape: (any SQLExpressible)? = nil) -> SQLExpression { .escapableBinary(.like, sqlExpression, pattern.sqlExpression, escape: escape?.sqlExpression) } }
mit
3ecea3506da32f61f763b3ed667449f7
31.094298
108
0.579228
4.446977
false
false
false
false
kseebaldt/KSPromise-Swift
KSPromise_Tests/Future_onFailure_Tests.swift
1
942
import XCTest import KSPromise class Future_onFailure_Tests: XCTestCase { let promise = Promise<String>() func test_whenAlreadyRejected_callsCallback() { let error = NSError(domain: "Error", code: 123, userInfo: nil) promise.reject(error) var done = false promise.future.onFailure() { (e) in done = true XCTAssertEqual(error, e, "error passed to failure is incorrect") } XCTAssert(done, "callback not called") } func test_whenRejected_callsCallback() { let error = NSError(domain: "Error", code: 123, userInfo: nil) var done = false promise.future.onFailure() { (e) in done = true XCTAssertEqual(error, e, "error passed to failure is incorrect") } promise.reject(error) XCTAssert(done, "callback not called") } }
mit
7e8c56e0401219c463b62ca431f8c930
26.705882
76
0.566879
4.640394
false
true
false
false
mzaks/FlatBuffersSwiftPerformanceTest
FBTest/bench_decode_unsafe_struct.swift
1
6195
// // bench_decode_direct5.swift // FBTest // // Created by Maxim Zaks on 27.09.16. // Copyright © 2016 maxim.zaks. All rights reserved. // import Foundation private func fromByteArray<T : Scalar>(buffer : UnsafePointer<UInt8>, _ position : Int) -> T{ return UnsafePointer<T>(buffer.advancedBy(position)).memory } private func getPropertyOffset(buffer : UnsafePointer<UInt8>, _ objectOffset : Offset, propertyIndex : Int)->Int { let offset = Int(objectOffset) let localOffset : Int32 = fromByteArray(buffer, offset) let vTableOffset : Int = offset - Int(localOffset) let vTableLength : Int16 = fromByteArray(buffer, vTableOffset) if(vTableLength<=Int16(4 + propertyIndex * 2)) { return 0 } let propertyStart = vTableOffset + 4 + (2 * propertyIndex) let propertyOffset : Int16 = fromByteArray(buffer, propertyStart) return Int(propertyOffset) } private func getOffset(buffer : UnsafePointer<UInt8>, _ objectOffset : Offset, propertyIndex : Int) -> Offset?{ let propertyOffset = getPropertyOffset(buffer, objectOffset, propertyIndex: propertyIndex) if propertyOffset == 0 { return nil } let position = objectOffset + propertyOffset let localObjectOffset : Int32 = fromByteArray(buffer, Int(position)) let offset = position + localObjectOffset if localObjectOffset == 0 { return nil } return offset } private func getVectorLength(buffer : UnsafePointer<UInt8>, _ vectorOffset : Offset?) -> Int { guard let vectorOffset = vectorOffset else { return 0 } let vectorPosition = Int(vectorOffset) let length2 : Int32 = fromByteArray(buffer, vectorPosition) return Int(length2) } private func getVectorOffsetElement(buffer : UnsafePointer<UInt8>, _ vectorOffset : Offset, index : Int) -> Offset? { let valueStartPosition = Int(vectorOffset + strideof(Int32) + (index * strideof(Int32))) let localOffset : Int32 = fromByteArray(buffer, valueStartPosition) if(localOffset == 0){ return nil } return localOffset + valueStartPosition } private func getVectorScalarElement<T : Scalar>(buffer : UnsafePointer<UInt8>, _ vectorOffset : Offset, index : Int) -> T { let valueStartPosition = Int(vectorOffset + strideof(Int32) + (index * strideof(T))) return UnsafePointer<T>(UnsafePointer<UInt8>(buffer).advancedBy(valueStartPosition)).memory } private func get<T : Scalar>(buffer : UnsafePointer<UInt8>, _ objectOffset : Offset, propertyIndex : Int, defaultValue : T) -> T{ let propertyOffset = getPropertyOffset(buffer, objectOffset, propertyIndex: propertyIndex) if propertyOffset == 0 { return defaultValue } let position = Int(objectOffset + propertyOffset) return fromByteArray(buffer, position) } private func get<T : Scalar>(buffer : UnsafePointer<UInt8>, _ objectOffset : Offset, propertyIndex : Int) -> T?{ let propertyOffset = getPropertyOffset(buffer, objectOffset, propertyIndex: propertyIndex) if propertyOffset == 0 { return nil } let position = Int(objectOffset + propertyOffset) return fromByteArray(buffer, position) as T } private func getStringBuffer(buffer : UnsafePointer<UInt8>, _ stringOffset : Offset?) -> UnsafeBufferPointer<UInt8>? { guard let stringOffset = stringOffset else { return nil } let stringPosition = Int(stringOffset) let stringLength : Int32 = fromByteArray(buffer, stringPosition) let pointer = UnsafePointer<UInt8>(buffer).advancedBy((stringPosition + strideof(Int32))) return UnsafeBufferPointer<UInt8>.init(start: pointer, count: Int(stringLength)) } private func getString(buffer : UnsafePointer<UInt8>, _ stringOffset : Offset?) -> String? { guard let stringOffset = stringOffset else { return nil } let stringPosition = Int(stringOffset) let stringLength : Int32 = fromByteArray(buffer, stringPosition) let pointer = UnsafeMutablePointer<UInt8>(buffer).advancedBy((stringPosition + strideof(Int32))) let result = String.init(bytesNoCopy: pointer, length: Int(stringLength), encoding: NSUTF8StringEncoding, freeWhenDone: false) return result } struct FooBarContainerStruct { var buffer : UnsafePointer<UInt8> = nil var myOffset : Offset = 0 init(_ data : UnsafePointer<UInt8>) { self.buffer = data self.myOffset = UnsafePointer<Offset>(buffer.advancedBy(0)).memory self.list = ListStruct(buffer: buffer, myOffset: myOffset) // set up vector } // table properties var list : ListStruct var location: UnsafeBufferPointer<UInt8> { get { return getStringBuffer(buffer, getOffset(buffer, myOffset, propertyIndex: 3))! } } var fruit: Enum { get { return Enum(rawValue: get(buffer, myOffset, propertyIndex: 2, defaultValue: Enum.Apples.rawValue))! } } var initialized: Bool { get { return get(buffer, myOffset, propertyIndex: 1, defaultValue: false) } } // definition of table vector to provice nice subscripting etc struct ListStruct { var buffer : UnsafePointer<UInt8> = nil var myOffset : Offset = 0 let offsetList : Offset? init(buffer b: UnsafePointer<UInt8>, myOffset o: Offset ) { buffer = b myOffset = o offsetList = getOffset(buffer, myOffset, propertyIndex: 0) // cache to make subscript faster } var count : Int { get { return getVectorLength(buffer, offsetList) } } subscript (index : Int) -> FooBarStruct { let ofs = getVectorOffsetElement(buffer, offsetList!, index: index)! return FooBarStruct(buffer: buffer, myOffset: ofs) } } } struct FooBarStruct { var buffer : UnsafePointer<UInt8> = nil var myOffset : Offset = 0 var name: UnsafeBufferPointer<UInt8> { get { return getStringBuffer(buffer, getOffset(buffer, myOffset, propertyIndex: 1))! } } var rating: Float64 { get { return get(buffer, myOffset, propertyIndex: 2)! } } var postfix: UInt8 { get { return get(buffer, myOffset, propertyIndex: 3)! } } var sibling: Bar { get { return get(buffer, myOffset, propertyIndex: 0)! } } }
mit
f0e0c4a9fca01a3d67da522b7c1bfe0f
39.75
135
0.692444
4.346667
false
false
false
false
practicalswift/swift
test/Index/kinds.swift
12
13116
// RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck %s // Enum enum AnEnumeration { // CHECK: [[@LINE-1]]:6 | enum/Swift | AnEnumeration | s:14swift_ide_test13AnEnumerationO | Def | rel: 0 // EnumElement case Element // CHECK: [[@LINE-1]]:8 | enumerator/Swift | Element | s:14swift_ide_test13AnEnumerationO7ElementyA2CmF | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | enum/Swift | AnEnumeration | s:14swift_ide_test13AnEnumerationO } // Struct struct AStruct { // CHECK: [[@LINE-1]]:8 | struct/Swift | AStruct | s:14swift_ide_test7AStructV | Def | rel: 0 var base: UnsafeMutablePointer<Int> // Subscript subscript(index: Int) -> Int { // CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | AStruct | s:14swift_ide_test7AStructV // Accessor + AccessorAddressor unsafeAddress { // CHECK: [[@LINE-1]]:5 | instance-method/acc-addr/Swift | | s:14swift_ide_test7AStructVyS2icilu | Def,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip return UnsafePointer(base) } // Accessor + AccessorMutableAddressor unsafeMutableAddress { // CHECK: [[@LINE-1]]:5 | instance-method/acc-mutaddr/Swift | | s:14swift_ide_test7AStructVyS2iciau | Def,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip return base } } // CHECK: [[@LINE-20]]:13 | param/Swift | index | {{.*}} | Def,RelChild | rel: 1 // CHECK: [[@LINE-21]]:20 | struct/Swift | Int | {{.*}} | Ref | rel: 0 // CHECK: [[@LINE-22]]:28 | struct/Swift | Int | {{.*}} | Ref | rel: 0 } // Class class AClass { // CHECK: [[@LINE-1]]:7 | class/Swift | AClass | s:14swift_ide_test6AClassC | Def | rel: 0 // InstanceMethod + Parameters func instanceMethod(a: Int, b b: Int, _ c: Int, d _: Int, _: Int) { // CHECK: [[@LINE-1]]:8 | instance-method/Swift | instanceMethod(a:b:_:d:_:) | s:14swift_ide_test6AClassC14instanceMethod1a1b_1d_ySi_S4itF | Def,Dyn,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC // CHECK: [[@LINE-3]]:23 | param/Swift | a | s:14swift_ide_test6AClassC14instanceMethod1a1b_1d_ySi_S4itFAEL_Sivp | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | instance-method/Swift | instanceMethod(a:b:_:d:_:) | s:14swift_ide_test6AClassC14instanceMethod1a1b_1d_ySi_S4itF // CHECK: [[@LINE-5]]:33 | param(local)/Swift | b | s:{{.*}} | Def,RelChild | rel: 1 // CHECK: [[@LINE-6]]:43 | param(local)/Swift | c | s:{{.*}} | Def,RelChild | rel: 1 // CHECK: [[@LINE-7]]:53 | param(local)/Swift | _ | s:{{.*}} | Def,RelChild | rel: 1 // CHECK: [[@LINE-8]]:61 | param/Swift | _ | s:{{.*}} | Def,RelChild | rel: 1 _ = a // CHECK: [[@LINE-1]]:9 | param/Swift | a | s:{{.*}} | Ref,Read,RelCont | rel: 1 _ = b // CHECK-NOT: [[@LINE-1]]:9 | param(local)/Swift | b | s:{{.*}} | Ref,Read,RelCont | rel: 1 _ = c // CHECK-NOT: [[@LINE-1]]:9 | param(local)/Swift | c | s:{{.*}} | Ref,Read,RelCont | rel: 1 } // ClassMethod class func classMethod() {} // CHECK: [[@LINE-1]]:14 | class-method/Swift | classMethod() | s:14swift_ide_test6AClassC11classMethodyyFZ | Def,Dyn,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC // StaticMethod static func staticMethod() {} // CHECK: [[@LINE-1]]:15 | static-method/Swift | staticMethod() | s:14swift_ide_test6AClassC12staticMethodyyFZ | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC // InstanceProperty var instanceProperty: Int { // CHECK: [[@LINE-1]]:7 | instance-property/Swift | instanceProperty | s:14swift_ide_test6AClassC16instancePropertySivp | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC // Accessor + AccessorGetter get { // CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:instanceProperty | s:14swift_ide_test6AClassC16instancePropertySivg | Def,Dyn,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | instanceProperty | s:14swift_ide_test6AClassC16instancePropertySiv return 1 } // Accessor + AccessorSetter set {} // CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:instanceProperty | s:14swift_ide_test6AClassC16instancePropertySivs | Def,Dyn,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | instanceProperty | s:14swift_ide_test6AClassC16instancePropertySiv } var observed = 0 { // Accessor + AccessorWillSet willSet {} // CHECK: [[@LINE-1]]:5 | instance-method/acc-willset/Swift | willSet:observed | s:14swift_ide_test6AClassC8observedSivw | Def,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | observed | s:14swift_ide_test6AClassC8observedSiv // Accessor + AccessorDidSet didSet {} // CHECK: [[@LINE-1]]:5 | instance-method/acc-didset/Swift | didSet:observed | s:14swift_ide_test6AClassC8observedSivW | Def,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | observed | s:14swift_ide_test6AClassC8observedSiv } // ClassProperty class let classProperty = 1 // CHECK: [[@LINE-1]]:13 | class-property/Swift | classProperty | s:14swift_ide_test6AClassC13classPropertySivpZ | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC // StaticProperty static let staticProperty = 1 // CHECK: [[@LINE-1]]:14 | static-property/Swift | staticProperty | s:14swift_ide_test6AClassC14staticPropertySivpZ | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC // Constructor init() {} // CHECK: [[@LINE-1]]:3 | constructor/Swift | init() | s:14swift_ide_test6AClassCACycfc | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC // Destructor deinit {} // CHECK: [[@LINE-1]]:3 | destructor/Swift | deinit | s:14swift_ide_test6AClassCfd | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC } // Protocol protocol AProtocol { // CHECK: [[@LINE-1]]:10 | protocol/Swift | AProtocol | s:14swift_ide_test9AProtocolP | Def | rel: 0 // AssociatedType associatedtype T // CHECK: [[@LINE-1]]:18 | type-alias/associated-type/Swift | T | s:14swift_ide_test9AProtocolP1TQa | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | protocol/Swift | AProtocol | s:14swift_ide_test9AProtocolP } // Extension extension AnEnumeration { func extFn() {} } // CHECK: [[@LINE-1]]:11 | extension/ext-enum/Swift | AnEnumeration | [[EXT_AnEnumeration_USR:s:e:s:14swift_ide_test13AnEnumerationO5extFnyyF]] | Def | rel: 0 // CHECK: [[@LINE-2]]:11 | enum/Swift | AnEnumeration | s:14swift_ide_test13AnEnumerationO | Ref,RelExt | rel: 1 // CHECK-NEXT: RelExt | extension/ext-enum/Swift | AnEnumeration | [[EXT_AnEnumeration_USR]] extension AStruct { func extFn() {} } // CHECK: [[@LINE-1]]:11 | extension/ext-struct/Swift | AStruct | [[EXT_AStruct_USR:s:e:s:14swift_ide_test7AStructV5extFnyyF]] | Def | rel: 0 // CHECK: [[@LINE-2]]:11 | struct/Swift | AStruct | s:14swift_ide_test7AStructV | Ref,RelExt | rel: 1 // CHECK-NEXT: RelExt | extension/ext-struct/Swift | AStruct | [[EXT_AStruct_USR]] extension AClass { func extFn() {} } // CHECK: [[@LINE-1]]:11 | extension/ext-class/Swift | AClass | [[EXT_AClass_USR:s:e:s:14swift_ide_test6AClassC5extFnyyF]] | Def | rel: 0 // CHECK: [[@LINE-2]]:11 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelExt | rel: 1 // CHECK-NEXT: RelExt | extension/ext-class/Swift | AClass | [[EXT_AClass_USR]] extension AProtocol { func extFn() } // CHECK: [[@LINE-1]]:11 | extension/ext-protocol/Swift | AProtocol | [[EXT_AProtocol_USR:s:e:s:14swift_ide_test9AProtocolPAAE5extFnyyF]] | Def | rel: 0 // CHECK: [[@LINE-2]]:11 | protocol/Swift | AProtocol | s:14swift_ide_test9AProtocolP | Ref,RelExt | rel: 1 // CHECK-NEXT: RelExt | extension/ext-protocol/Swift | AProtocol | [[EXT_AProtocol_USR]] // TypeAlias typealias SomeAlias = AStruct // CHECK: [[@LINE-1]]:11 | type-alias/Swift | SomeAlias | s:14swift_ide_test9SomeAliasa | Def | rel: 0 // CHECK: [[@LINE-2]]:23 | struct/Swift | AStruct | s:14swift_ide_test7AStructV | Ref | rel: 0 // GenericTypeParam struct GenericStruct<ATypeParam> {} // CHECK: [[@LINE-1]]:22 | type-alias/generic-type-param/Swift | ATypeParam | s:14swift_ide_test13GenericStructV10ATypeParamxmfp | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | GenericStruct | s:14swift_ide_test13GenericStructV func GenericFunc<ATypeParam>(_: ATypeParam) {} // CHECK-NOT: [[@LINE-1]]:18 | type-alias/generic-type-param/Swift | ATypeParam | {{.*}} | Def,RelChild | rel: 1 // Function func EmptyFunction() {} // CHECK: [[@LINE-1]]:6 | function/Swift | EmptyFunction() | s:14swift_ide_test13EmptyFunctionyyF | Def | rel: 0 // Variable var foo = 1 // CHECK: [[@LINE-1]]:5 | variable/Swift | foo | s:14swift_ide_test3fooSivp | Def | rel: 0 // PrefixOperator prefix func -(a: AStruct) -> AStruct { return a } // CHECK: [[@LINE-1]]:13 | function/prefix-operator/Swift | -(_:) | s:14swift_ide_test1sopyAA7AStructVADF | Def | rel: 0 // PostfixOperator postfix operator ++ postfix func ++(a: AStruct) -> AStruct { return a } // CHECK: [[@LINE-1]]:14 | function/postfix-operator/Swift | ++(_:) | s:14swift_ide_test2ppoPyAA7AStructVADF | Def | rel: 0 // InfixOperator func +(a: AStruct, b: AStruct) -> AStruct { return a } // CHECK: [[@LINE-1]]:6 | function/infix-operator/Swift | +(_:_:) | s:14swift_ide_test1poiyAA7AStructVAD_ADtF | Def | rel: 0 class XCTestCase {} class MyTestCase : XCTestCase { // CHECK: [[@LINE-1]]:7 | class(test)/Swift | MyTestCase | func callit() {} func testMe() { // CHECK: [[@LINE-1]]:8 | instance-method(test)/Swift | testMe() | [[MyTestCase_testMe_USR:.*]] | Def,Dyn,RelChild callit() // CHECK: [[@LINE-1]]:5 | instance-method/Swift | callit() | s:14swift_ide_test10MyTestCaseC6callityyF | Ref,Call,Dyn,RelRec,RelCall,RelCont | rel: 2 // CHECK-NEXT: RelCall,RelCont | instance-method(test)/Swift | testMe() | [[MyTestCase_testMe_USR]] } func testResult() -> Int? { return nil } // CHECK: [[@LINE-1]]:8 | instance-method/Swift | testResult() | func test(withInt: Int) {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | test(withInt:) | } class SubTestCase : MyTestCase { // CHECK: [[@LINE-1]]:7 | class(test)/Swift | SubTestCase | [[SubTestCase_USR:.*]] | Def | rel: 0 func testIt2() {} // CHECK: [[@LINE-1]]:8 | instance-method(test)/Swift | testIt2() | } extension SubTestCase { // CHECK: [[@LINE-1]]:11 | extension/ext-class(test)/Swift | SubTestCase | [[SubTestCaseExt_USR:.*]] | Def | rel: 0 // CHECK: [[@LINE-2]]:11 | class(test)/Swift | SubTestCase | [[SubTestCase_USR]] | Ref,RelExt | rel: 1 // CHECK-NEXT: RelExt | extension/ext-class(test)/Swift | SubTestCase | [[SubTestCaseExt_USR]] func testIt3() {} // CHECK: [[@LINE-1]]:8 | instance-method(test)/Swift | testIt3() | } class NonTestCase { func testMeNot() {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | testMeNot() | } // CHECK: [[@LINE+1]]:7 | class/Swift | C1 | [[C1_USR:.*]] | Def | rel: 0 class C1 {} // CHECK: [[@LINE+1]]:11 | type-alias/Swift | C1Alias | [[C1Alias_USR:.*]] | Def | rel: 0 typealias C1Alias = C1 // CHECK: [[@LINE+4]]:7 | class/Swift | SubC1 | [[SubC1_USR:.*]] | Def | rel: 0 // CHECK: [[@LINE+3]]:15 | type-alias/Swift | C1Alias | [[C1Alias_USR]] | Ref | rel: 0 // CHECK: [[@LINE+2]]:15 | class/Swift | C1 | [[C1_USR]] | Ref,Impl,RelBase | rel: 1 // CHECK-NEXT: RelBase | class/Swift | SubC1 | [[SubC1_USR]] class SubC1 : C1Alias {} struct ImplCtors { // CHECK: [[@LINE-1]]:8 | struct/Swift | ImplCtors | [[ImplCtors_USR:.*]] | Def | rel: 0 // CHECK: [[@LINE-2]]:8 | constructor/Swift | init(x:) | [[ImplCtors_init_with_param_USR:.*]] | Def,Impl,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | ImplCtors | [[ImplCtors_USR]] // CHECK: [[@LINE-4]]:8 | constructor/Swift | init() | [[ImplCtors_init_USR:.*]] | Def,Impl,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | ImplCtors | [[ImplCtors_USR]] var x = 0 } _ = ImplCtors() // CHECK: [[@LINE-1]]:5 | constructor/Swift | init() | [[ImplCtors_init_USR]] | Ref,Call | rel: 0 _ = ImplCtors(x:0) // CHECK: [[@LINE-1]]:5 | constructor/Swift | init(x:) | [[ImplCtors_init_with_param_USR]] | Ref,Call | rel: 0 var globalCompProp: Int // CHECK: [[@LINE]]:5 | variable/Swift | [[globalCompProp:.*]] | Def { // CHECK: [[@LINE]]:1 | function/acc-get/Swift | getter:globalCompProp | // CHECK-NEXT: RelChild,RelAcc | variable/Swift | [[globalCompProp]] // Check that the accessor def is not showing up twice. // CHECK-NOT: [[@LINE-3]]:1 | function/acc-get/Swift return 0 }
apache-2.0
c90a4b8b3c4b209b1544446af1ad0f56
50.035019
173
0.660186
3.076707
false
true
false
false
practicalswift/swift
test/Interpreter/SDK/class_getImageName-static.swift
37
2589
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-library -o %t/libSimpleNSObjectSubclass.dylib %S/Inputs/SimpleNSObjectSubclass.swift -Xlinker -install_name -Xlinker @executable_path/libSimpleNSObjectSubclass.dylib // RUN: %target-codesign %t/libSimpleNSObjectSubclass.dylib // RUN: %target-build-swift %s -o %t/main -lSimpleNSObjectSubclass -L%t -import-objc-header %S/Inputs/class_getImageName-static-helper.h // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/libSimpleNSObjectSubclass.dylib // REQUIRES: executable_test // REQUIRES: objc_interop import Darwin import ObjectiveC // import SimpleNSObjectSubclass // Deliberately omitted in favor of dynamic loads. // Note: The following typealias uses AnyObject instead of AnyClass so that the // function type is trivially bridgeable to Objective-C. (The representation of // AnyClass is not the same as Objective-C's 'Class' type.) typealias GetImageHook = @convention(c) (AnyObject, UnsafeMutablePointer<UnsafePointer<CChar>?>) -> ObjCBool var hook: GetImageHook? func checkThatSwiftHookWasNotInstalled() { // Check that the Swift hook did not get installed. guard let setHookPtr = dlsym(UnsafeMutableRawPointer(bitPattern: -2), getHookName()) else { // If the version of the ObjC runtime we're using doesn't have the hook, // we're good. return } let setHook = unsafeBitCast(setHookPtr, to: (@convention(c) (GetImageHook, UnsafeMutablePointer<GetImageHook?>) -> Void).self) setHook({ hook!($0, $1) }, &hook) var info: Dl_info = .init() guard 0 != dladdr(unsafeBitCast(hook, to: UnsafeRawPointer.self), &info) else { fatalError("could not get dladdr info for objc_hook_getImageName") } precondition(String(cString: info.dli_fname).hasSuffix("libobjc.A.dylib"), "hook was replaced") } // It's important that this test does not register any Swift classes with the // Objective-C runtime---that's where Swift sets up its custom hook, and we want // to check the behavior /without/ that hook. That includes the buffer types for // String and Array. Therefore, we get C strings directly from a bridging // header. guard let theClass = objc_getClass(getNameOfClassToFind()) as! AnyClass? else { fatalError("could not find class") } guard let imageName = class_getImageName(theClass) else { fatalError("could not find image") } checkThatSwiftHookWasNotInstalled() // Okay, now we can use String. precondition(String(cString: imageName).hasSuffix("libSimpleNSObjectSubclass.dylib"), "found wrong image")
apache-2.0
526ecf5ba5337b8e990e9f444ad7510a
40.758065
199
0.735033
3.916793
false
false
false
false
huonw/swift
benchmark/single-source/ArrayAppend.swift
1
11262
//===--- ArrayAppend.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks the performance of appending to an array. import TestsUtils public let ArrayAppend = [ BenchmarkInfo(name: "ArrayAppend", runFunction: run_ArrayAppend, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendArrayOfInt", runFunction: run_ArrayAppendArrayOfInt, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendAscii", runFunction: run_ArrayAppendAscii, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendAsciiSubstring", runFunction: run_ArrayAppendAsciiSubstring, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendFromGeneric", runFunction: run_ArrayAppendFromGeneric, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendGenericStructs", runFunction: run_ArrayAppendGenericStructs, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendLatin1", runFunction: run_ArrayAppendLatin1, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendLatin1Substring", runFunction: run_ArrayAppendLatin1Substring, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendLazyMap", runFunction: run_ArrayAppendLazyMap, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendOptionals", runFunction: run_ArrayAppendOptionals, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendRepeatCol", runFunction: run_ArrayAppendRepeatCol, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendReserved", runFunction: run_ArrayAppendReserved, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendSequence", runFunction: run_ArrayAppendSequence, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendStrings", runFunction: run_ArrayAppendStrings, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendToFromGeneric", runFunction: run_ArrayAppendToFromGeneric, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendToGeneric", runFunction: run_ArrayAppendToGeneric, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendUTF16", runFunction: run_ArrayAppendUTF16, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayAppendUTF16Substring", runFunction: run_ArrayAppendUTF16Substring, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayPlusEqualArrayOfInt", runFunction: run_ArrayPlusEqualArrayOfInt, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayPlusEqualFiveElementCollection", runFunction: run_ArrayPlusEqualFiveElementCollection, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayPlusEqualSingleElementCollection", runFunction: run_ArrayPlusEqualSingleElementCollection, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayPlusEqualThreeElements", runFunction: run_ArrayPlusEqualThreeElements, tags: [.validation, .api, .Array]), ] // Append single element @inline(never) public func run_ArrayAppend(_ N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<40000 { nums.append(1) } } } } // Append single element with reserve @inline(never) public func run_ArrayAppendReserved(_ N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() nums.reserveCapacity(40000) for _ in 0..<40000 { nums.append(1) } } } } // Append a sequence. Length of sequence unknown so // can't pre-reserve capacity. @inline(never) public func run_ArrayAppendSequence(_ N: Int) { let seq = stride(from: 0, to: 10_000, by: 1) for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<8 { nums.append(contentsOf: seq) } } } } // Append another array. Length of sequence known so // can pre-reserve capacity. @inline(never) public func run_ArrayAppendArrayOfInt(_ N: Int) { let other = Array(repeating: 1, count: 10_000) for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<8 { nums.append(contentsOf: other) } } } } // Identical to run_ArrayAppendArrayOfInt // except +=, to check equally performant. @inline(never) public func run_ArrayPlusEqualArrayOfInt(_ N: Int) { let other = Array(repeating: 1, count: 10_000) for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<8 { nums += other } } } } // Append another array. Length of sequence known so // can pre-reserve capacity. @inline(never) public func run_ArrayAppendStrings(_ N: Int) { let other = stride(from: 0, to: 10_000, by: 1).map { "\($0)" } for _ in 0..<N { for _ in 0..<10 { var nums = [String]() // lower inner count due to string slowness for _ in 0..<4 { nums += other } } } } struct S<T,U> { var x: T var y: U } // Append another array. Length of sequence known so // can pre-reserve capacity. @inline(never) public func run_ArrayAppendGenericStructs(_ N: Int) { let other = Array(repeating: S(x: 3, y: 4.2), count: 10_000) for _ in 0..<N { for _ in 0..<10 { var nums = [S<Int,Double>]() for _ in 0..<8 { nums += other } } } } // Append another array. Length of sequence known so // can pre-reserve capacity. @inline(never) public func run_ArrayAppendOptionals(_ N: Int) { let other: [Int?] = Array(repeating: 1, count: 10_000) for _ in 0..<N { for _ in 0..<10 { var nums = [Int?]() for _ in 0..<8 { nums += other } } } } // Append a lazily-mapped array. Length of sequence known so // can pre-reserve capacity, but no optimization points used. @inline(never) public func run_ArrayAppendLazyMap(_ N: Int) { let other = Array(0..<10_000).lazy.map { $0 * 2 } for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<8 { nums += other } } } } // Append a Repeat collection. Length of sequence known so // can pre-reserve capacity, but no optimization points used. @inline(never) public func run_ArrayAppendRepeatCol(_ N: Int) { let other = repeatElement(1, count: 10_000) for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<8 { nums += other } } } } // Append an array as a generic sequence to another array @inline(never) public func appendFromGeneric< S: Sequence >(array: inout [S.Iterator.Element], sequence: S) { array.append(contentsOf: sequence) } @inline(never) public func run_ArrayAppendFromGeneric(_ N: Int) { let other = Array(repeating: 1, count: 10_000) for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<8 { appendFromGeneric(array: &nums, sequence: other) } } } } // Append an array to an array as a generic range replaceable collection. @inline(never) public func appendToGeneric< R: RangeReplaceableCollection >(collection: inout R, array: [R.Iterator.Element]) { collection.append(contentsOf: array) } @inline(never) public func run_ArrayAppendToGeneric(_ N: Int) { let other = Array(repeating: 1, count: 10_000) for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<8 { appendToGeneric(collection: &nums, array: other) } } } } // Append an array as a generic sequence to an array as a generic range // replaceable collection. @inline(never) public func appendToFromGeneric< R: RangeReplaceableCollection, S: Sequence >(collection: inout R, sequence: S) where R.Iterator.Element == S.Iterator.Element { collection.append(contentsOf: sequence) } @inline(never) public func run_ArrayAppendToFromGeneric(_ N: Int) { let other = Array(repeating: 1, count: 10_000) for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<8 { appendToFromGeneric(collection: &nums, sequence: other) } } } } // Append a single element array with the += operator @inline(never) public func run_ArrayPlusEqualSingleElementCollection(_ N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<40_000 { nums += [1] } } } } // Append a five element array with the += operator @inline(never) public func run_ArrayPlusEqualFiveElementCollection(_ N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<40_000 { nums += [1, 2, 3, 4, 5] } } } } @inline(never) public func appendThreeElements(_ a: inout [Int]) { a += [1, 2, 3] } @inline(never) public func run_ArrayPlusEqualThreeElements(_ N: Int) { for _ in 0..<(10_000 * N) { var a: [Int] = [] appendThreeElements(&a) } } // Append the utf8 elements of an ascii string to a [UInt8] @inline(never) public func run_ArrayAppendAscii(_ N: Int) { let s = "the quick brown fox jumps over the lazy dog!" for _ in 0..<N { for _ in 0..<10 { var nums = [UInt8]() for _ in 0..<10_000 { nums += getString(s).utf8 } } } } // Append the utf8 elements of an ascii string to a [UInt8] @inline(never) public func run_ArrayAppendLatin1(_ N: Int) { let s = "the quick brown fox jumps over the lazy dog\u{00A1}" for _ in 0..<N { for _ in 0..<10 { var nums = [UInt8]() for _ in 0..<10_000 { nums += getString(s).utf8 } } } } // Append the utf8 elements of an ascii string to a [UInt8] @inline(never) public func run_ArrayAppendUTF16(_ N: Int) { let s = "the quick brown 🦊 jumps over the lazy dog" for _ in 0..<N { for _ in 0..<10 { var nums = [UInt8]() for _ in 0..<10_000 { nums += getString(s).utf8 } } } } // Append the utf8 elements of an ascii string to a [UInt8] @inline(never) public func run_ArrayAppendAsciiSubstring(_ N: Int) { let s = "the quick brown fox jumps over the lazy dog!"[...] for _ in 0..<N { for _ in 0..<10 { var nums = [UInt8]() for _ in 0..<10_000 { nums += getSubstring(s).utf8 } } } } // Append the utf8 elements of an ascii string to a [UInt8] @inline(never) public func run_ArrayAppendLatin1Substring(_ N: Int) { let s = "the quick brown fox jumps over the lazy dog\u{00A1}"[...] for _ in 0..<N { for _ in 0..<10 { var nums = [UInt8]() for _ in 0..<10_000 { nums += getSubstring(s).utf8 } } } } // Append the utf8 elements of an ascii string to a [UInt8] @inline(never) public func run_ArrayAppendUTF16Substring(_ N: Int) { let s = "the quick brown 🦊 jumps over the lazy dog"[...] for _ in 0..<N { for _ in 0..<10 { var nums = [UInt8]() for _ in 0..<10_000 { nums += getSubstring(s).utf8 } } } }
apache-2.0
a35092e915119cf6bbfe2fc7ba4f1e0f
27.787724
154
0.624556
3.56541
false
false
false
false
farion/eloquence
Eloquence/Eloquence/MainSplitViewController.swift
1
2261
import Cocoa class MainSplitViewController:NSSplitViewController, NSPageControllerDelegate, RosterViewControllerDelegate { @IBOutlet var sidebarItem: NSSplitViewItem! @IBOutlet var mainItem: NSSplitViewItem! var messageController = [EloChatId:MessageViewController]() var rosterViewController:RosterViewController? var messagePageController:NSPageController? override func viewDidLoad() { super.viewDidLoad() /* rosterViewController = RosterViewController(nibName:"RosterViewController",bundle:nil) rosterViewController!.delegate = self rosterItem = NSSplitViewItem(viewController: rosterViewController!) insertSplitViewItem(rosterItem!, atIndex: 0) messagePageController = NSPageController( messageItem = NSSplitViewItem(viewController:messagePageController!) insertSplitViewItem(messageItem!, atIndex: 1)*/ rosterViewController = sidebarItem!.viewController as? RosterViewController rosterViewController!.delegate = self messagePageController = mainItem!.viewController as? NSPageController messagePageController!.delegate = self } private func getMessageController(chatId: EloChatId) -> MessageViewController{ if(messageController[chatId] == nil){ messageController[chatId] = MessageViewController(nibName:"MessageViewController", chatId:chatId) } return messageController[chatId]! } func pageController(pageController: NSPageController, identifierForObject object: AnyObject) -> String { let chatId = object as! EloChatId return chatId.toString } func pageController(pageController: NSPageController, viewControllerForIdentifier identifier: String) -> NSViewController { return getMessageController(EloChatId(identifier:identifier)) } func didClickContact(chatId: EloChatId){ NSLog("click" + chatId.to.jid ); //TODO if I do not call it twice, the first clik nothing happens. messagePageController!.navigateForwardToObject(chatId) messagePageController!.navigateForwardToObject(chatId) } }
apache-2.0
6319914458bbde5a540f471da6bfefeb
38
127
0.705882
6.013298
false
false
false
false
IBM-Swift/Kitura
Sources/Kitura/staticFileServer/RangeHeader.swift
1
6743
/** * Copyright IBM Corporation 2017 * * 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 LoggerAPI import Foundation /// Struct that represents a Range Header defined in RFC7233. struct RangeHeader { /// type is the left side of `=` let type: String /// ranges is the right side of `=` let ranges: [Range<UInt64>] } extension RangeHeader { /// Possible errors thrown by RangeHeader.parse function enum Error: Swift.Error { /// Happens when none of the ranges in Range header was not satisfiable as per RFC 7233 (Section 4.4) case notSatisfiable /// Could not be parsed. Bad syntax case malformed } /// Check if header is a byte range header static func isBytesRangeHeader(_ rangeHeaderValue: String) -> Bool { /// Regular expression for identifying a bytes Range header. let bytesRangePattern = "^ *bytes=" let regex: NSRegularExpression do { regex = try NSRegularExpression(pattern: bytesRangePattern, options: []) } catch { Log.error("Failed to create regular expressions used to check byte Range headers") exit(1) } let matches = regex.matches(in: rangeHeaderValue, options: [], range: NSRange(location: 0, length: rangeHeaderValue.count)) return !matches.isEmpty } /// Parse a range header string into a RangeHeader structure. /// Implementation based on: [jshttp/range-parser](https://github.com/jshttp/range-parser) /// /// - Parameter size: the size of the resource /// - Parameter headerValue: the stringn to parse /// static func parse(size: UInt64, headerValue: String, shouldCombine: Bool = true) throws -> RangeHeader { guard let index = headerValue.range(of: "=")?.lowerBound else { // malformed throw RangeHeader.Error.malformed } // split the range string let startOfRangeString = headerValue.index(index, offsetBy: 1) #if swift(>=3.2) let type = String(headerValue[headerValue.startIndex..<index]) let rangeStrings = String(headerValue[startOfRangeString..<headerValue.endIndex]).components(separatedBy:",") #else let type = headerValue.substring(with: headerValue.startIndex..<index) let rangeStrings = headerValue.substring(with: startOfRangeString..<headerValue.endIndex).components(separatedBy:",") #endif // parse all ranges var ranges: [Range<UInt64>] = [] rangeStrings.forEach { rangeString in let range = rangeString.components(separatedBy: "-") guard range.count > 1 else { // one range is malformed return } let startString = range[0] let endString = range[1] let start: UInt64? var end: UInt64? if !startString.isEmpty && !endString.isEmpty { // nnn-nnn : Read both values start = UInt64(startString) end = UInt64(endString) } else if startString.isEmpty { // -nnn : Read end. Start will be calculated end = UInt64(endString) if end == nil { start = nil } else { start = size - end! end = size - 1 } } else { // nnn- : Read start. End will be calculated start = UInt64(startString) end = size - 1 } // limit last-byte-pos to current length if end != nil && end! > (size - 1) { end = size - 1 } // invalid or unsatisifiable guard let rangeStart = start, let rangeEnd = end, rangeStart <= rangeEnd, 0 <= rangeStart else { return } ranges.append(rangeStart..<rangeEnd) } guard !ranges.isEmpty else { // unsatisifiable throw RangeHeader.Error.notSatisfiable } if shouldCombine { let combinedRanges = RangeHeader.combinedRanges(ranges: ranges) return RangeHeader(type: type, ranges: combinedRanges) } else { return RangeHeader(type: type, ranges: ranges) } } } extension RangeHeader { struct IndexedRange { var index: Int var range: Range<UInt64> } /// Return an array of combined ranges (overlapping and adjacent) static func combinedRanges(ranges: [Range<UInt64>]) -> [Range<UInt64>] { // map [Range]s to [IndexedRange]s and sort them by range.lowerBound var index = 0 var ordered = ranges.map { range in let i = IndexedRange(index: index, range: range) index += 1 return i }.sorted { (rangeA: IndexedRange, rangeB: IndexedRange) -> Bool in return rangeA.range.lowerBound < rangeB.range.lowerBound } // try to combine them var j = 0 for i in 1..<ordered.count { let indexedRange = ordered[i] let currentIndexedRange = ordered[j] if indexedRange.range.lowerBound > (currentIndexedRange.range.upperBound + 1) { // next range j += 1 ordered[j] = indexedRange } else if indexedRange.range.upperBound > currentIndexedRange.range.upperBound { // extend range ordered[j] = IndexedRange( index: min(currentIndexedRange.index, indexedRange.index), range: currentIndexedRange.range.lowerBound..<indexedRange.range.upperBound) } } ordered = Array(ordered.prefix(j + 1)) // trim ordered array // map [IndexedRange]s back to [Range]s but sort them in their original order let combined = ordered.sorted { (rangeA: IndexedRange, rangeB: IndexedRange) -> Bool in return rangeA.index < rangeB.index }.map { indexedRange in return indexedRange.range } return combined } }
apache-2.0
d8bb86296837b7f28ab88017e11f37bc
36.049451
131
0.586386
4.751938
false
false
false
false
zmian/xcore.swift
Sources/Xcore/SwiftUI/Components/DynamicTextField/TextField/Styles/DynamicTextFieldStyle+Prominent.swift
1
4553
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import SwiftUI public struct ProminentDynamicTextFieldStyle<S: InsettableShape>: DynamicTextFieldStyle { public enum Prominence: Equatable { case fill case outline(OutlineValidationColor) public static var outline: Self { outline(.automatic) } public enum OutlineValidationColor { /// If `disableFloatingPlaceholder` attributes is set to `true` then validation /// color is applied to the border; otherwise, ignored. case automatic /// Enable validation color border. case enable /// Disable validation color border. case disable } } private let shape: S private let prominence: Prominence private let padding: EdgeInsets? public init( _ prominence: Prominence, shape: S, padding: EdgeInsets? = nil ) { self.shape = shape self.prominence = prominence self.padding = padding } public func makeBody(configuration: Self.Configuration) -> some View { InternalBody( configuration: configuration, shape: shape, prominence: prominence, padding: padding ) } } // MARK: - Internal extension ProminentDynamicTextFieldStyle { private struct InternalBody: View { @Environment(\.textFieldAttributes) private var attributes @Environment(\.theme) private var theme let configuration: DynamicTextFieldStyleConfiguration let shape: S let prominence: Prominence let padding: EdgeInsets? var body: some View { DynamicTextField.default(configuration) .padding(finalPadding) .applyIf(prominence == .fill) { $0.backgroundColor(theme.backgroundSecondaryColor) } .clipShape(shape) .contentShape(shape) .apply { if case .outline = prominence { let color = outlineBorderColor $0.border(shape, width: color == nil ? 0.5 : 1, color: color) } else { $0 } } } private var finalPadding: EdgeInsets { if let padding = padding { return padding } else { var padding: EdgeInsets = .zero if attributes.disableFloatingPlaceholder { padding.vertical = .s4 } else { padding.vertical = .s2 } if S.self == Capsule.self { padding.horizontal = .s4 } else { padding.horizontal = .s3 } return padding } } private var outlineBorderColor: Color? { guard case let .outline(validationColor) = prominence else { return nil } var color: Color? { if configuration.text.isEmpty { return nil } return configuration.isValid ? nil : attributes.errorColor } switch validationColor { case .automatic: return attributes.disableFloatingPlaceholder ? color : nil case .enable: return color case .disable: return nil } } } } // MARK: - Dot Syntax Support extension DynamicTextFieldStyle where Self == ProminentDynamicTextFieldStyle<RoundedRectangle> { public static var prominent: Self { prominent() } public static func prominent( _ prominence: Self.Prominence = .fill, cornerRadius: CGFloat = AppConstants.tileCornerRadius, padding: EdgeInsets? = nil ) -> Self { prominent( prominence, shape: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous), padding: padding ) } } extension DynamicTextFieldStyle { public static func prominent<S: InsettableShape>( _ prominence: Self.Prominence = .fill, shape: S, padding: EdgeInsets? = nil ) -> Self where Self == ProminentDynamicTextFieldStyle<S> { .init(prominence, shape: shape, padding: padding) } }
mit
c9cf8d0442fe3569e15734ea2bfdbe28
27.993631
96
0.539323
5.226177
false
true
false
false
Flar49/coin-price-widget-ios
PoloniexParser/Model/Candlestick.swift
1
461
// // Created by Eugene Tartakovsky on 21/11/2016. // Copyright (c) 2016 tartakovsky. All rights reserved. // import Foundation enum CandlestickPeriod: Int { case fiveMinutes = 300 case fifteenMinutes = 900 case thirtyMinutes = 1800 case twoHours = 7200 case fourHours = 14400 case day = 86400 func toSeconds() -> Int { return self.rawValue } func toMinutes() -> Int { return self.rawValue/60 } }
mit
709bbe24d1c72b5bdccfa33922e73ca9
19.043478
55
0.637744
3.87395
false
false
false
false
RajanFernandez/MotoParks
MotoParks/Controllers/MapViewController/MapViewController.swift
1
3953
// // ViewController.swift // WellingtonMotorbikeParks // // Created by Rajan Fernandez on 20/06/16. // Copyright © 2016 Rajan Fernandez. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController { @IBOutlet var mapView: MKMapView! @IBOutlet var centerOnLocationButton: UIBarButtonItem! @IBOutlet var infoButton: UIBarButtonItem! let pinReuseIdentifier = "ParkAnnotation" let farParkColorAlphaComponent: CGFloat = 0.6 let closeParkDistance: Double = 500 var locationManager = CLLocationManager() var dataSource = ParkLocationDataSource.shared var lastKnownUserLocation: MKUserLocation? var locationAccessIsAuthorized: Bool { return CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways } let wellingtonRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: -41.286781914499926, longitude: 174.77909061803408), span: MKCoordinateSpan(latitudeDelta: 0.03924177397755102, longitudeDelta: 0.030196408891356441)) override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self locationManager.delegate = self mapView.setRegion(wellingtonRegion, animated: false) do { try dataSource.loadParkLocationsIfRequiredWithDataSetNamed("parks") } catch { let alert = UIAlertController(title: "Woops...", message: "Sorry, an error occured while loading data. Please try restarting the app.", preferredStyle: .alert) let action = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(action) DispatchQueue.main.async { [weak self] in self?.present(alert, animated: true, completion: nil) } } if let parks = dataSource.allParks { mapView.addAnnotations(parks) } // Hide the info button for now infoButton.tintColor = UIColor.clear infoButton.isEnabled = false } override func viewDidAppear(_ animated: Bool) { if CLLocationManager.authorizationStatus() == .notDetermined { locationManager.requestWhenInUseAuthorization() } mapView.showsUserLocation = locationAccessIsAuthorized } /// Returns the distance of a given motor bike park to the users location. /// /// - Parameters: /// - park: A motorbike parking location /// - userLocation: The users location /// - Returns: The distance to the given park from the user location in metres. func distanceToPark(_ park: Park, from userLocation: MKUserLocation) -> Double? { return userLocation.location?.distance(from: park.location) } /// Provides a alpha value for map annocation views based on the distance the user is from the /// /// - Parameters: /// - park: A map /// - userLocation: The users current location /// - Returns: A UIColor func alpha(for park: Park, withUserLocation userLocation: MKUserLocation) -> CGFloat { guard let distance = distanceToPark(park, from: userLocation), distance < closeParkDistance else { return farParkColorAlphaComponent } // In the close park range, the alpha component is decreased and then guard statement above ensures that far away parks are dim on the map. // ^ // Alpha |--__ // | --__ // | | // | |_____________ // |___________________________________ // ^close park threshold distance let alphaComponent = 1 - (1 - farParkColorAlphaComponent) / 4 * CGFloat(distance / closeParkDistance) return alphaComponent } }
mit
ee578b20c168fb7f1bfaefad5f86be1e
35.934579
237
0.628796
5.086229
false
false
false
false
LinShiwei/HealthyDay
HealthyDay/StepLineChart.swift
1
6690
// // StepLineChart.swift // HealthyDay // // Created by Sun Haoting on 16/10/14. // Copyright © 2016年 Linsw. All rights reserved. // import UIKit class StepLineChart: UIScrollView { internal var stepEverydayViews = [StepEverydayView]() private var viewSize : CGSize = CGSize(width: UIScreen.main.bounds.width / 7, height: UIScreen.main.bounds.height * 3.5 / 15.0) private var stepCountsData = [Int]() private var maxStepCount = Int() private var currentIndex = 0 private var linesInStepLineChart = [CAShapeLayer]() private var dotsPosition = [CGPoint]() private var gradientLayer = CAGradientLayer() private var gradientMaskView = CAShapeLayer() private var dateLabels = [UILabel]() override func layoutSubviews() { super.layoutSubviews() // initStepEverydayView() } private func initScrollView() { // autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] bounces = true isScrollEnabled = true clipsToBounds = true showsHorizontalScrollIndicator = false } init(frame: CGRect, stepCountsData: [Int], maxStepCount: Int){ super.init(frame: frame) self.stepCountsData = stepCountsData self.maxStepCount = maxStepCount initScrollView() if stepCountsData.count != 0 { initStepEverydayView() initGradiantLayer() initGradientMaskView() initLine() } initDateLabel() } private func dayOfTheWeek(offset: Int) -> String { let interval = Date().timeIntervalSince1970 + 8 * 3600 let days = Int(interval / 86400) + offset switch (days - 3) % 7 { case 0: return "周日" case 1: return "周一" case 2: return "周二" case 3: return "周三" case 4: return "周四" case 5: return "周五" case 6: return "周六" default: fatalError("weekday Error") } } private func initDateLabel() { let currentDate = Date() var stepRange = Int() if stepCountsData.isEmpty == true { stepRange = 6 } else { stepRange = stepCountsData.count + 5 } for day in 0...stepRange { let dateDescription = Date(timeInterval: 24*3600*Double(-stepRange + 3 + day), since: currentDate).formatDescription() let range = dateDescription.index(dateDescription.startIndex, offsetBy: 8)..<dateDescription.index(dateDescription.startIndex, offsetBy: 10) let dayOfWeek = dayOfTheWeek(offset: -stepRange + 3 + day) let text = dayOfWeek + "\n" + dateDescription.substring(with: range) let dateLabel = UILabel(frame: CGRect(x: viewSize.width * CGFloat(day), y: viewSize.height, width: viewSize.width, height: viewSize.height / 3.5)) dateLabel.text = text dateLabel.textColor = rgbColor(red: 0x9F, green: 0x9F, blue: 0x9F, alpha: 1) dateLabel.textAlignment = .center dateLabel.numberOfLines = 0 dateLabel.font = UIFont(name: "STHeitiSC-Light", size: viewSize.width / 4.5) dateLabels.append(dateLabel) addSubview(dateLabel) } } private func initStepEverydayView() { for index in 0..<stepCountsData.count { let proportion = CGFloat(stepCountsData[index]) / CGFloat(maxStepCount) var isToday = false if index == stepCountsData.count - 1 { isToday = true } let stepEverydayView = StepEverydayView(frame: CGRect(x: CGFloat(3+index) * viewSize.width, y: 0, width: viewSize.width, height: viewSize.height),proportion: proportion,stepCount: stepCountsData[index], isToday: isToday ) stepEverydayViews.append(stepEverydayView) stepEverydayView.layer.zPosition = 1 addSubview(stepEverydayView) let dotPosition = CGPoint(x: (3.5 + CGFloat(index)) * viewSize.width, y: stepEverydayView.dotPosition().y) dotsPosition.append(dotPosition) } } private func initLine() { for index in 0..<stepCountsData.count - 1 { let path = UIBezierPath() path.move(to: dotsPosition[index]) path.addLine(to: dotsPosition[index + 1]) // path.close() let lineInLineChart = CAShapeLayer() lineInLineChart.path = path.cgPath lineInLineChart.lineWidth = 3.5 lineInLineChart.strokeColor = UIColor.gray.cgColor lineInLineChart.fillColor = UIColor.gray.cgColor layer.addSublayer(lineInLineChart) } } private func initGradiantLayer() { guard gradientLayer.superlayer == nil else {return} gradientLayer.frame = CGRect(x: 3.5 * viewSize.width, y: viewSize.height / 3.5, width: CGFloat(stepCountsData.count - 1) * viewSize.width, height: viewSize.height * 2.5 / 3.5) gradientLayer.colors = [theme.thickLineChartColor.cgColor, theme.lightLineChartColor.cgColor] layer.addSublayer(gradientLayer) } private func initGradientMaskView() { guard gradientMaskView.superlayer == nil else {return} let path = UIBezierPath() path.move(to: dotsPosition[0]) for index in 0..<stepCountsData.count - 1 { path.addLine(to: dotsPosition[index + 1]) } path.addLine(to: CGPoint(x: dotsPosition[stepCountsData.count - 1].x, y: viewSize.height / 3.5)) path.addLine(to: CGPoint(x: dotsPosition[0].x, y: viewSize.height / 3.5)) path.close() gradientMaskView.path = path.cgPath gradientMaskView.fillColor = UIColor.white.cgColor layer.addSublayer(gradientMaskView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal func currentCenter() -> CGPoint { let x = contentOffset.x + bounds.width / 2.0 let y = contentOffset.y return CGPoint(x: x, y: y) } internal func contentOffsetForIndex(_ index: Int) -> CGPoint { let centerX = centerForViewAtIndex(index).x let x: CGFloat = centerX - self.bounds.width / 2.0 return CGPoint(x: x, y: 0) } internal func centerForViewAtIndex(_ index: Int) -> CGPoint { let y = bounds.midY let x = CGFloat(index) * viewSize.width + viewSize.width / 2 return CGPoint(x: x, y: y) } }
mit
683124f7e3e5be2209d0fef0f569df6e
36.621469
233
0.608049
4.424585
false
false
false
false
griotspeak/Rational
Carthage/Checkouts/SwiftCheck/Tests/PathSpec.swift
1
2398
// // PathSpec.swift // SwiftCheck // // Created by Robert Widmann on 2/10/16. // Copyright © 2016 Robert Widmann. All rights reserved. // import SwiftCheck import XCTest struct Path<A : Arbitrary> : Arbitrary { let unPath : [A] private static func pathFrom(x : A) -> Gen<[A]> { return Gen.sized { n in return Gen<[A]>.oneOf( [Gen.pure([])] + A.shrink(x).map { pathFrom($0).resize(n - 1) } ).map { [x] + $0 } } } static var arbitrary : Gen<Path<A>> { return A.arbitrary >>- { x in return pathFrom(x).map(Path.init) } } } func path<A>(p : A -> Bool, _ pth : Path<A>) -> Bool { return pth.unPath.reduce(true, combine: { $0 && p($1) }) } func somePath<A>(p : A -> Bool, _ pth : Path<A>) -> Property { return path({ !p($0) }, pth).expectFailure } struct Extremal<A : protocol<Arbitrary, LatticeType>> : Arbitrary { let getExtremal : A static var arbitrary : Gen<Extremal<A>> { return Gen<A>.frequency([ (1, Gen.pure(A.min)), (1, Gen.pure(A.max)), (8, A.arbitrary) ]).map(Extremal.init) } static func shrink(x : Extremal<A>) -> [Extremal<A>] { return A.shrink(x.getExtremal).map(Extremal.init) } } class PathSpec : XCTestCase { private static func smallProp<A : protocol<IntegerType, Arbitrary>>(pth : Path<A>) -> Bool { return path({ x in return (x >= -100 || -100 >= 0) && x <= 100 }, pth) } private static func largeProp<A : protocol<IntegerType, Arbitrary>>(pth : Path<A>) -> Property { return somePath({ x in return (x < -1000000 || x > 1000000) }, pth) } func testAll() { property("Int") <- forAll { (x : Path<Int>) in return somePath({ x in return (x < 1000000 || x > -1000000) }, x) } property("Int32") <- forAll { (x : Path<Int32>) in return path({ x in return (x >= -100 || -100 >= 0) && x <= 100 }, x) } property("UInt") <- forAll { (x : Path<UInt>) in return somePath({ x in return (x < 1000000 || x > 0) }, x) } property("UInt32") <- forAll { (x : Path<UInt32>) in return path({ x in return (x >= 0 || -100 >= 0) && x <= 100 }, x) } property("Large Int") <- forAll { (x : Path<Large<Int>>) in return PathSpec.largeProp(Path(unPath: x.unPath.map { $0.getLarge })) } property("Large UInt") <- forAll { (x : Path<Large<UInt>>) in return PathSpec.largeProp(Path(unPath: x.unPath.map { $0.getLarge })) } } }
mit
e1d34a4e85476010897c6d5ec6f6da35
22.732673
97
0.578223
2.745704
false
false
false
false
ncsrobin/Fuber
SplashScreenUI/TileGridView.swift
1
6415
/** * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import Commons class TileGridView: UIView { fileprivate var containerView: UIView! fileprivate var modelTileView: TileView! fileprivate var centerTileView: TileView? = nil fileprivate var numberOfRows = 0 fileprivate var numberOfColumns = 0 fileprivate var logoLabel: UILabel! fileprivate var tileViewRows: [[TileView]] = [] fileprivate var beginTime: CFTimeInterval = 0 fileprivate let kRippleDelayMultiplier: TimeInterval = 0.0006666 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() containerView.center = center modelTileView.center = containerView.center if let centerTileView = centerTileView { // Custom offset needed for UILabel font let center = CGPoint(x: centerTileView.bounds.midX + 31, y: centerTileView.bounds.midY) logoLabel.center = center } } init(TileFileName: String) { modelTileView = TileView(TileFileName: TileFileName) super.init(frame: CGRect.zero) clipsToBounds = true layer.masksToBounds = true containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 630.0, height: 990.0)) containerView.backgroundColor = UIColor.fuberBlue() containerView.clipsToBounds = false containerView.layer.masksToBounds = false addSubview(containerView) renderTileViews() logoLabel = generateLogoLabel() centerTileView?.addSubview(logoLabel) layoutIfNeeded() } func startAnimating() { beginTime = CACurrentMediaTime() startAnimatingWithBeginTime(beginTime) } } extension TileGridView { fileprivate func generateLogoLabel()->UILabel { let label = UILabel() label.text = "F BER" label.font = UIFont.systemFont(ofSize: 50) label.textColor = UIColor.white label.sizeToFit() label.center = CGPoint(x: bounds.midX, y: bounds.midY) return label } fileprivate func renderTileViews() { let width = containerView.bounds.width let height = containerView.bounds.height let modelImageWidth = modelTileView.bounds.width let modelImageHeight = modelTileView.bounds.height numberOfColumns = Int(ceil((width - modelTileView.bounds.size.width / 2.0) / modelTileView.bounds.size.width)) numberOfRows = Int(ceil((height - modelTileView.bounds.size.height / 2.0) / modelTileView.bounds.size.height)) for y in 0..<numberOfRows { var tileRows: [TileView] = [] for x in 0..<numberOfColumns { let view = TileView() view.frame = CGRect(x: CGFloat(x) * modelImageWidth, y:CGFloat(y) * modelImageHeight, width: modelImageWidth, height: modelImageHeight) if view.center == containerView.center { centerTileView = view } containerView.addSubview(view) tileRows.append(view) if y != 0 && y != numberOfRows - 1 && x != 0 && x != numberOfColumns - 1 { view.shouldEnableRipple = true } } tileViewRows.append(tileRows) } if let centerTileView = centerTileView { containerView.bringSubview(toFront: centerTileView) } } fileprivate func startAnimatingWithBeginTime(_ beginTime: TimeInterval) { let linearTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let keyframe = CAKeyframeAnimation(keyPath: "transform.scale") keyframe.timingFunctions = [linearTimingFunction, CAMediaTimingFunction(controlPoints: 0.6, 0.0, 0.15, 1.0), linearTimingFunction] keyframe.repeatCount = Float.infinity; keyframe.duration = kAnimationDuration keyframe.isRemovedOnCompletion = false keyframe.keyTimes = [0.0, 0.45, 0.887, 1.0] keyframe.values = [0.75, 0.75, 1.0, 1.0] keyframe.beginTime = beginTime keyframe.timeOffset = kAnimationTimeOffset containerView.layer.add(keyframe, forKey: "scale") for tileRows in tileViewRows { for view in tileRows { let distance = distanceFromCenterViewWithView(view) var vector = normalizedVectorFromCenterViewToView(view) vector = CGPoint(x: vector.x * kRippleMagnitudeMultiplier * distance, y: vector.y * kRippleMagnitudeMultiplier * distance) view.startAnimatingWithDuration(kAnimationDuration, beginTime: beginTime, rippleDelay: kRippleDelayMultiplier * TimeInterval(distance), rippleOffset: vector) } } } fileprivate func distanceFromCenterViewWithView(_ view: UIView)->CGFloat { guard let centerTileView = centerTileView else { return 0.0 } let normalizedX = (view.center.x - centerTileView.center.x) let normalizedY = (view.center.y - centerTileView.center.y) return sqrt(normalizedX * normalizedX + normalizedY * normalizedY) } fileprivate func normalizedVectorFromCenterViewToView(_ view: UIView)->CGPoint { let length = distanceFromCenterViewWithView(view) guard let centerTileView = centerTileView , length != 0 else { return CGPoint.zero } let deltaX = view.center.x - centerTileView.center.x let deltaY = view.center.y - centerTileView.center.y return CGPoint(x: deltaX / length, y: deltaY / length) } }
apache-2.0
51d3883154c84c565b851c8564ecb114
35.657143
165
0.70491
4.615108
false
false
false
false
Altece/Reggie
Source/Node.swift
1
718
import Foundation /// A specific identifiable state within an automata. public struct State { fileprivate let id: UUID = UUID() /// Create a state node for an automata. public init() {} } extension State: Hashable { public static func ==(lhs: State, rhs: State) -> Bool { return lhs.id == rhs.id } public func hash(into hasher: inout Hasher) { return hasher.combine(id) } } /// A type to denote whether or not a node represents the end /// of a passing "word" within an automata's "language". public enum Termination { /// Denotes a possible end of a match within the automata. case terminating /// Denotes a regular, nothing-special node within the automata. case nonterminating }
mit
bd3f23f12120302835e6bead507b3ed5
23.758621
66
0.697772
3.902174
false
false
false
false
ryanbaldwin/RealmSwiftFHIR
firekit/firekit/classes/models/RealmTypes.swift
2
8432
// // RealmTypes.swift // SwiftFHIR // // Updated for Realm support by Ryan Baldwin on 2017-08-09 // Copyright @ 2017 Bunnyhug. All rights fall under Apache 2 // import Foundation import Realm import RealmSwift final public class RealmString: Object, Codable { @objc public dynamic var pk: String = UUID().uuidString @objc public dynamic var value: String = "" public convenience init(val: String) { self.init() self.value = val } public convenience init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() self.init(val: try container.decode(String.self)) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.value) } override open static func primaryKey() -> String? { return "pk" } } extension RealmString: Populatable { public func populate(from other: Any) { guard let o = other as? RealmString else { print("Tried to populate a RealmString from \(type(of: other)). Skipping.") return } value = o.value } } final public class RealmInt: Object, Codable { @objc public dynamic var pk: String = UUID().uuidString @objc public dynamic var value: Int = 0 public convenience init(val: Int) { self.init() self.value = val } public convenience init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() self.init(val: try container.decode(Int.self)) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.value) } override open static func primaryKey() -> String? { return "pk" } } extension RealmInt: Populatable { public func populate(from other: Any) { guard let o = other as? RealmInt else { print("Tried to populate a RealmInt from \(type(of: other)). Skipping.") return } value = o.value } } final public class RealmDecimal: Object, Codable { @objc public dynamic var pk: String = UUID().uuidString @objc private dynamic var _value = "0" public var value: Decimal { get { return Decimal(string: _value)! } set { _value = String(describing: newValue) } } public convenience init(string val: String) { self.init() self._value = val } public convenience init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() do { self.init(string: try container.decode(String.self)) return } catch { // failed to decode RealmDecimal as String, try Double } do { self.init(string: "\(try container.decode(Double.self))") return } catch { // failed to decode RealmDecimal as Double, try Int } self.init(string: "\(try container.decode(Int.self))") } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.value) } public override class func ignoredProperties() -> [String] { return ["value"] } override open static func primaryKey() -> String? { return "pk" } public static func ==(lhs: RealmDecimal, rhs: RealmDecimal) -> Bool { return lhs.value.isEqual(to: rhs.value) } public static func ==(lhs: RealmDecimal?, rhs: RealmDecimal) -> Bool { if let lhs = lhs { return lhs == rhs } return false } public static func ==(lhs: RealmDecimal, rhs: RealmDecimal?) -> Bool { if let rhs = rhs { return lhs == rhs } return false } } extension RealmDecimal: Populatable { public func populate(from other: Any) { guard let o = other as? RealmDecimal else { print("Tried to populate a RealmDecimal from \(type(of: other)). Skipping.") return } _value = o._value } } final public class RealmURL: Object, Codable { @objc public dynamic var pk: String = UUID().uuidString @objc private dynamic var _value: String? private var _url: URL? = nil public var value: URL? { get { if _url == nil { _url = URL(string: _value ?? "") } return _url } set { _url = newValue _value = newValue?.absoluteString ?? "" } } public convenience init(from decoder: Decoder) throws { self.init() let container = try decoder.singleValueContainer() value = try container.decode(URL.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.value) } public override class func ignoredProperties() -> [String] { return ["value", "_url"] } override open static func primaryKey() -> String? { return "pk" } } extension RealmURL: Populatable { public func populate(from other: Any) { guard let o = other as? RealmURL else { print("Tried to populate a RealmURL from \(type(of: other)). Skipping.") return } _value = o._value } } /// Realm is limited in its polymorphism and can't contain a List of different /// classes. As a result, for example, deserializing from JSON into a DomainResource /// will fail if that resource has any contained resources. /// /// In normal SwiftFHIR the `DomainResource.contained` works fine, but because of /// Realm's polymorphic limitations it fails. `DomainResource.contained: RealmSwift<Resource>` /// will blow up at runtime. The workaround is to create a `ContainedResource: Resource` /// Which will store the same information as `Resource`, but will also provide functionality /// to store the original JSON and inflate it on demand into the proper type. final public class ContainedResource: Resource { private enum CodingKeys: String, CodingKey { case resourceType } @objc public dynamic var resourceType: String? @objc dynamic var json: Data? lazy public var resource: FHIRAbstractBase? = { guard let resourceType = self.resourceType, let json = self.json else { return nil } do { return try JSONDecoder().decode(resourceType, from: json) } catch let error { print("Failed to decode contained resource. Returning nil: \(error)") } return nil }() public override class func ignoredProperties() -> [String] { return ["resource"] } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) resourceType = try container.decodeIfPresent(String.self, forKey: .resourceType) } public required init() { super.init() } public required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } public required init(value: Any, schema: RLMSchema) { super.init(value: value, schema: schema) } public override func encode(to encoder: Encoder) throws { guard let resource = resource else { return } try resource.encode(to: encoder) } public override func populate(from other: Any) { guard let o = other as? ContainedResource else { print("Tried to populate a ContainedResource from \(type(of: other)). Skipping") return } super.populate(from: other) resourceType = o.resourceType json = o.json } public override func copy(with zone: NSZone? = nil) -> Any { let copy = ContainedResource() copy._versionId = _versionId copy.id = id copy.implicitRules = implicitRules copy.language = language copy.upsert(meta: meta) copy.resourceType = resourceType copy.json = json return copy } }
apache-2.0
2298b3f21c776ac5d14ef61cd887a4bc
28.795053
95
0.602585
4.653422
false
false
false
false
dbart01/Spyder
Spyder/Payload.swift
1
2974
// // Payload.swift // Spyder // // Copyright (c) 2016 Dima Bart // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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 OWNER 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. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // import Foundation struct Payload { let url: URL? let contents: Data // ---------------------------------- // MARK: - Init - // init?(_ value: String?) { guard let value = value else { return nil } if value.contains("{") { self.url = nil self.contents = value.data(using: .utf8)! } else { let url = URL(fileURLWithPath: (value as NSString).expandingTildeInPath) if let contents = try? Data(contentsOf: url) { self.url = url self.contents = contents } else { return nil } } } init(message: String) { self.url = nil self.contents = Payload.default(with: message) } // ---------------------------------- // MARK: - Default - // static private func `default`(with message: String) -> Data { let payload = [ "aps" : [ "sound" : "default", "alert" : message, ] ] return self.serialize(payload)! } static private func serialize(_ payload: [String: Any]) -> Data? { return try? JSONSerialization.data(withJSONObject: payload, options: []) } }
bsd-2-clause
1b9e880b3724b64fc217b65408fa6ad0
34.404762
84
0.616678
4.654147
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/Auction Listings/ListingsCountdownManager.swift
2
2744
import UIKit import RxSwift class ListingsCountdownManager: NSObject { @IBOutlet weak var countdownLabel: UILabel! @IBOutlet weak var countdownContainerView: UIView! let formatter = NumberFormatter() let sale = Variable<Sale?>(nil) let time = SystemTime() var provider: Networking! { didSet { time.sync(provider) .dispatchAsyncMainScheduler() .take(1) .subscribe(onNext: { [weak self] (_) in self?.startTimer() self?.setLabelsHidden(false) }) .addDisposableTo(rx_disposeBag) } } fileprivate var _timer: Timer? = nil override func awakeFromNib() { super.awakeFromNib() formatter.minimumIntegerDigits = 2 } /// Immediately invalidates the timer. No further updates will be made to the UI after this method is called. func invalidate() { _timer?.invalidate() } func setFonts() { (countdownContainerView.subviews).forEach { (view) -> () in if let label = view as? UILabel { label.font = UIFont.serifFont(withSize: 15) } } countdownLabel.font = UIFont.sansSerifFont(withSize: 20) } func setLabelsHidden(_ hidden: Bool) { countdownContainerView.isHidden = hidden } func setLabelsHiddenIfSynced(_ hidden: Bool) { if time.inSync() { setLabelsHidden(hidden) } } func hideDenomenatorLabels() { for subview in countdownContainerView.subviews { subview.isHidden = subview != countdownLabel } } func startTimer() { let timer = Timer(timeInterval: 0.49, target: self, selector: #selector(ListingsCountdownManager.tick(_:)), userInfo: nil, repeats: true) RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) _timer = timer self.tick(timer) } func tick(_ timer: Timer) { guard let sale = sale.value else { return } guard time.inSync() else { return } guard sale.id != "" else { return } if sale.isActive(time) { let now = time.date() let components = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: sale.endDate) self.countdownLabel.text = "\(formatter.string(from: (components.hour ?? 0) as NSNumber)!) : \(formatter.string(from: (components.minute ?? 0) as NSNumber)!) : \(formatter.string(from: (components.second ?? 0) as NSNumber)!)" } else { self.countdownLabel.text = "CLOSED" hideDenomenatorLabels() timer.invalidate() _timer = nil } } }
mit
a5f4ee6c5b02d26036e7430402d7cb1d
29.153846
237
0.586006
4.604027
false
false
false
false
tadija/AEConsole
Sources/AEConsole/Console.swift
1
2471
/** * https://github.com/tadija/AEConsole * Copyright © 2016-2020 Marko Tadić * Licensed under the MIT license */ import UIKit import AELog /// Facade for displaying debug log in Console UI overlay on top of your app. open class Console: LogDelegate { // MARK: - Properties /// Singleton public static let shared = Console() /// Console Settings public var settings: Settings { return brain.settings } internal let brain = Brain(with: Settings()) private var window: UIWindow? // MARK: - API /// Enable Console UI by calling this method in AppDelegate's `didFinishLaunchingWithOptions:` /// /// - Parameter window: Main window for the app (AppDelegate's window). open func configure(in window: UIWindow?) { Log.shared.delegate = self self.window = window self.brain.configureConsole(in: window) } /// Current state of Console UI visibility open var isHidden: Bool { return !brain.console.isOnScreen } /// Toggle Console UI open func toggle() { if let view = brain.console { if !view.isOnScreen { activateConsoleUI() } view.toggleUI() } } /// Add any log line manually (lines from AELog will automatically be added) open func addLogLine(line: CustomStringConvertible) { DispatchQueue.main.async { [weak self] in self?.brain.addLogLine(line) } } /// Export all log lines to AELog_{timestamp}.txt file inside of App Documents directory. open func exportLogFile(completion: @escaping (() throws -> URL) -> Void) { brain.exportLogFile(completion: completion) } // MARK: - Init fileprivate init() { NotificationCenter.default.addObserver( self, selector: #selector(activateConsoleUI), name: UIApplication.didBecomeActiveNotification, object: nil ) } deinit { NotificationCenter.default.removeObserver(self) } @objc fileprivate func activateConsoleUI() { if let window = window { window.bringSubviewToFront(brain.console) if settings.isShakeGestureEnabled { brain.console.becomeFirstResponder() } } } // MARK: - LogDelegate open func didLog(line: Line, mode: Log.Mode) { addLogLine(line: line) } }
mit
0171d838412b0650080833b5c76e2184
25.548387
98
0.609964
4.720841
false
false
false
false
theappbusiness/TABScrollingContentView
Pods/TABSwiftLayout/Sources/Constraint.swift
1
9414
/* Copyright © 2015 The App Business. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE APP BUSINESS `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 APP BUSINESS 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. */ #if os(OSX) import AppKit public typealias View = NSView public typealias LayoutPriority = NSLayoutPriority #else import UIKit public typealias View = UIView public typealias LayoutPriority = UILayoutPriority #endif /// A required constraint. Do not exceed this. public let LayoutPriorityRequired: LayoutPriority = 1000 /// This is the priority level with which a button resists compressing its content. public let LayoutPriorityDefaultHigh: LayoutPriority = 750 /// This is the priority level at which a button hugs its contents horizontally. public let LayoutPriorityDefaultLow: LayoutPriority = 250 /** * The classes included in this file extend NSLayoutConstraints, provide Swift implementations and cross-platform support for iOS, OSX, Watch and Apple TV */ /** * Defines various constraint traits (bitmask) that define the type of constraints applied to a view. */ public struct ConstraintsTraitMask: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// No constraints applied public static var None: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 0) } /// A top margin constraint is applied public static var TopMargin: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 0) } /// A left margin constraint is applied public static var LeftMargin: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 1) } /// A right margin constraint is applied public static var RightMargin: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 2) } /// A bottom margin constraint is applied public static var BottomMargin: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 3) } /// A horitzontal alignment constraint is applied public static var HorizontalAlignment: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 4) } /// A vertical aligntment constraint is applied public static var VerticalAlignment: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 5) } /// A horizontal sizing constraint is applied public static var HorizontalSizing: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 6) } /// A vertical sizing constraint is applied public static var VerticalSizing: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 7) } /// Horizontal margin constraints are applied (Left and Right) public static var HorizontalMargins: ConstraintsTraitMask { return LeftMargin.union(RightMargin) } /// Vertical margin constraints are applied (Top and Right) public static var VerticalMargins: ConstraintsTraitMask { return TopMargin.union(BottomMargin) } } // MARK: - This extends UI/NS View to provide additional constraints support public extension View { /// Returns all constraints relevant to this view public var viewConstraints: [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() for constraint in self.constraints { constraints.append(constraint) } if let superviewConstraints = self.superview?.constraints { for constraint in superviewConstraints { if constraint.firstItem as? View != self && constraint.secondItem as? View != self { continue } constraints.append(constraint) } } return constraints } /** Returns all constraints for this view that match the specified traits - parameter trait: The traits to lookup - returns: An array of constraints. If no constraints exist, an empty array is returned. This method never returns nil */ public func constraints(forTrait trait: ConstraintsTraitMask) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() for constraint in self.constraints { if constraint.trait == trait { constraints.append(constraint) } } if let superviewConstraints = self.superview?.constraints { for constraint in superviewConstraints { if constraint.firstItem as? View != self && constraint.secondItem as? View != self { continue } if trait.contains(constraint.trait) { constraints.append(constraint) } } } return constraints } /** Returns true if at least one constraint with the specified trait exists - parameter trait: The trait to test - returns: True if a constrait exists, false otherwise */ public func contains(trait: ConstraintsTraitMask) -> Bool { var traits = ConstraintsTraitMask.None for constraint in constraints(forTrait: trait) { traits.insert(constraint.trait) } return traits.contains(trait) } } /** Defines an abstract representation of a constraint */ public protocol ConstraintDefinition { var priority: LayoutPriority { get } var constant: CGFloat { get set } var multiplier: CGFloat { get } var relation: NSLayoutRelation { get } var firstAttribute: NSLayoutAttribute { get } var secondAttribute: NSLayoutAttribute { get } var trait: ConstraintsTraitMask { get } } /** We extend the existing NSLayoutConstraint, as well as our own implementation ConstraintDefinition */ extension NSLayoutConstraint: ConstraintDefinition { } /** This extension provides a Swift value-type representation of NSLayoutConstraint */ public extension ConstraintDefinition { public var trait: ConstraintsTraitMask { let left = self.firstAttribute == .left || self.firstAttribute == .leading let right = self.firstAttribute == .right || self.firstAttribute == .trailing let top = self.firstAttribute == .top let bottom = self.firstAttribute == .bottom let width = self.firstAttribute == .width let height = self.firstAttribute == .height let centerX = self.firstAttribute == .centerX let centerY = self.firstAttribute == .centerY if width { return .HorizontalSizing } if height { return .VerticalSizing } if centerX { return .HorizontalAlignment } if centerY { return .VerticalAlignment } if left { return .LeftMargin } if right { return .RightMargin } if top { return .TopMargin } if bottom { return .BottomMargin } return .None } } /** * A Swift value-type implementation of NSLayoutConstraint */ public struct Constraint: ConstraintDefinition { public internal(set) var priority: LayoutPriority public var constant: CGFloat public internal(set) var multiplier: CGFloat public internal(set) var relation: NSLayoutRelation public internal(set) var firstAttribute: NSLayoutAttribute public internal(set) var secondAttribute: NSLayoutAttribute private var _enabled = true public var enabled: Bool { get { return self._enabled } set { self._enabled = enabled if (self.enabled) { NSLayoutConstraint.activate([self.constraint()]) } else { NSLayoutConstraint.deactivate([self.constraint()]) } } } public unowned var firstView: View { didSet { precondition(firstView.superview != nil, "The first view MUST be inserted into a superview before constraints can be applied") } } public weak var secondView: View? private weak var _constraint: NSLayoutConstraint? public init(view: View) { self.firstView = view self.firstAttribute = .notAnAttribute self.secondAttribute = .notAnAttribute self.constant = 0 self.multiplier = 1 self.relation = .equal self.priority = 250 view.translatesAutoresizingMaskIntoConstraints = false } public mutating func constraint() -> NSLayoutConstraint { if self._constraint == nil { self._constraint = NSLayoutConstraint( item: self.firstView, attribute: firstAttribute, relatedBy: self.relation, toItem: self.secondView, attribute: self.secondAttribute, multiplier: self.multiplier, constant: self.constant) } return self._constraint! } }
mit
38aabb58215b8142ba9f47075910ab2a
32.379433
154
0.719749
5.04448
false
false
false
false
BellAppLab/JustTest
JustTest/JustTest/Photo+Serialising.swift
1
1555
// // Photo+Serialising.swift // JustTest // // Created by André Abou Chami Campana on 06/04/2016. // Copyright © 2016 Bell App Lab. All rights reserved. // import Foundation extension Photo: ResponseCollectionSerializable { /* For each element in the array contained in the 'data' node of the JSON response, we should pass the object contained in 'photos' to this method */ static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Photo] { var result = [Photo]() guard let representation = representation as? [String: AnyObject] else { return result } guard let userAdded = representation["user_added"] as? [[String: AnyObject]] else { return result } //If we don't have any user added photos and the Street View one is present, we short circuit if userAdded.isEmpty, let streetViewURL = representation["google_streetview"] as? String { result.append(Photo(id: NSUUID().UUIDString, thumbURL: streetViewURL)) return result } for photoRepresentation in userAdded { if let id = photoRepresentation["id"] as? Int { if let thumbURL = ((photoRepresentation["json_data"] as? [String: AnyObject])?["thumb"] as? [String: AnyObject])?["url"] as? String { //Not particularly pretty, but trying to be concise here result.append(Photo(id: "\(id)", thumbURL: thumbURL)) } } } return result } }
mit
bd2e7eba8627ed20c5f9082760722e57
38.820513
206
0.631681
4.622024
false
false
false
false
kdw9/TIY-Assignments
Collect-Em-All/Collect-Em-All/CardsCollectionViewController.swift
1
4692
// // CardsCollectionViewController.swift // Collect-Em-All // // Created by Keron Williams on 10/22/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit protocol CharacterListTableViewControllerDelegate { func characterWasChosen(chosenCharacter: String) } class CardsCollectionViewController: UICollectionViewController, UIPopoverPresentationControllerDelegate, CharacterListTableViewControllerDelegate { var visibleCards = [String]() let allCards = ["Obi-Wan Kenobi": "Kenobi.jpg", "Leia Organa": "Organa.jpg", "R2-D2": "R2.jpg", "Luke Skywalker": "Skywalker.jpg", "Grand Moff Tarkin": "Tarkin.jpg", "Darth Vader": "Vader.jpg"] var remainingCharacters = ["Obi-Wan Kenobi", "Leia Organa", "R2-D2", "Luke Skywalker", "Grand Moff Tarkin", "Darth Vader"] override func viewDidLoad() { super.viewDidLoad() title = "Collect-Em-All" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowCharacterListPopoverSegue" { let destVC = segue.destinationViewController as!CharacterListTableViewController destVC.characters = remainingCharacters destVC.popoverPresentationController?.delegate = self destVC.delegate = self let contentHeight = 44.0 * CGFloat (remainingCharacters.count) destVC.preferredContentSize = CGSizeMake(200.0, contentHeight) } } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return visibleCards.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CardCell", forIndexPath: indexPath) as! CardCell // Configure the cell let characterName = visibleCards[indexPath.item] cell.nameLabel.text = characterName cell.imageView.image = UIImage (named: allCards [characterName]!) return cell } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ // MARK: - UIPopoverPresentationController Delegate func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } // MARK: - CharacterListTableViewController Delegate func characterWasChosen(chosenCharacter: String) { navigationController?.dismissViewControllerAnimated(true, completion: nil) visibleCards.append(chosenCharacter) let rowToRemove = (remainingCharacters as NSArray).indexOfObject(chosenCharacter) remainingCharacters.removeAtIndex(rowToRemove) if remainingCharacters.count == 0 { } collectionView?.reloadData() } }
cc0-1.0
d57f4da187fb3d145154a16da3a9532e
31.804196
197
0.702196
5.651807
false
false
false
false
bananafish911/SmartReceiptsiOS
SmartReceipts/Modules/Edit Trip/EditTripFormView.swift
1
4347
// // EditTripFormView.swift // SmartReceipts // // Created by Bogdan Evsenev on 12/06/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import Eureka import RxSwift fileprivate let NAME_ROW_TAG = "name" class EditTripFormView: FormViewController { let errorSubject = PublishSubject<String>() let tripSubject = PublishSubject<WBTrip>() private var isNewTrip: Bool! private var trip: WBTrip? required init(trip: WBTrip?) { super.init(nibName: nil, bundle: nil) isNewTrip = trip == nil self.trip = trip if trip == nil { self.trip = WBTrip() self.trip?.startDate = NSDate().atBeginningOfDay() var dayComponents = DateComponents() dayComponents.day = Int(WBPreferences.defaultTripDuration()) - 1 self.trip?.endDate = (Calendar.current.date(byAdding: dayComponents, to: self.trip!.startDate)! as NSDate).atBeginningOfDay() self.trip?.defaultCurrency = Currency.currency(forCode: WBPreferences.defaultCurrency()) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.bounces = false //MARK: FORM form +++ Section() <<< TextRow(NAME_ROW_TAG) { row in row.title = LocalizedString("edit.trip.name.label") row.value = trip?.name row.add(rule: RuleRequired()) }.onChange({ [weak self] row in self?.trip?.name = row.value ?? "" }).cellSetup({ cell, _ in cell.configureCell() if self.isNewTrip { _ = cell.textField.becomeFirstResponder() } }) <<< DateInlineRow() { row in row.title = LocalizedString("edit.trip.start.date.label") row.value = trip?.startDate }.onChange({ [weak self] row in self?.trip?.startDate = row.value! }).cellSetup({ cell, _ in cell.configureCell() }) <<< DateInlineRow() { row in row.title = LocalizedString("edit.trip.end.date.label") row.value = trip?.endDate }.onChange({ [weak self] row in self?.trip?.endDate = row.value! }).cellSetup({ cell, _ in cell.configureCell() }) <<< PickerInlineRow<String>() { row in row.title = LocalizedString("edit.trip.default.currency.label") row.options = Currency.allCurrencyCodesWithCached() row.value = trip?.defaultCurrency.code ?? WBPreferences.defaultCurrency() }.onChange({ [weak self] row in self?.trip?.defaultCurrency = Currency.currency(forCode: row.value ?? WBPreferences.defaultCurrency()!) }).cellSetup({ cell, _ in cell.configureCell() }) <<< TextRow() { row in row.title = LocalizedString("edit.trip.comment.label") row.value = trip?.comment ?? "" }.onChange({ [weak self] row in self?.trip?.comment = row.value ?? "" }).cellSetup({ cell, _ in cell.configureCell() }) if WBPreferences.trackCostCenter() { form.allSections.first! <<< TextRow() { row in row.title = LocalizedString("edit.trip.cost.center.label") row.value = trip?.costCenter ?? "" }.onChange({ [weak self] row in self?.trip?.costCenter = row.value ?? "" }).cellSetup({ cell, _ in cell.configureCell() }) } } func done() { if let errors = form.rowBy(tag: NAME_ROW_TAG)?.validate() { if errors.count > 0 { errorSubject.onNext(LocalizedString("edit.trip.name.missing.alert.message")) } else { tripSubject.onNext(trip!) } } } } fileprivate extension BaseCell { fileprivate func configureCell() { textLabel?.font = UIFont.boldSystemFont(ofSize: 17) detailTextLabel?.textColor = AppTheme.themeColor detailTextLabel?.font = UIFont.boldSystemFont(ofSize: 17) } }
agpl-3.0
8530fbf8c5932030086aef715fd79adf
32.953125
115
0.553843
4.673118
false
true
false
false
irisapp/das-quadrat
Source/Shared/Keychain.swift
1
3894
// // FSKeychain.swift // Quadrat // // Created by Constantine Fry on 26/10/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation import Security /** The error domain for errors returned by `Keychain Service`. The `code` property will contain OSStatus. See SecBase.h for error codes. The `userInfo` is always nil and there is no localized description provided. */ public let QuadratKeychainOSSatusErrorDomain = "QuadratKeychainOSSatusErrorDomain" class Keychain { var logger: Logger? private let keychainQuery: [String:AnyObject] init(configuration: Configuration) { #if os(iOS) let serviceAttribute = "Foursquare2API-FSKeychain" #else let serviceAttribute = "Foursquare Access Token" #endif var accountAttribute: String if let userTag = configuration.userTag { accountAttribute = configuration.client.identifier + "_" + userTag } else { accountAttribute = configuration.client.identifier } keychainQuery = [ kSecClass as String : kSecClassGenericPassword, kSecAttrAccessible as String : kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, kSecAttrService as String : serviceAttribute, kSecAttrAccount as String : accountAttribute ] } func accessToken() throws -> String? { var query = keychainQuery query[kSecReturnData as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitOne /** Fixes the issue with Keychain access in release mode. https://devforums.apple.com/message/1070614#1070614 */ var dataTypeRef: AnyObject? = nil let status = withUnsafeMutablePointer(&dataTypeRef) {cfPointer -> OSStatus in SecItemCopyMatching(query, UnsafeMutablePointer(cfPointer)) } var accessToken: String? = nil if status == errSecSuccess { if let retrievedData = dataTypeRef as? NSData { if retrievedData.length != 0 { accessToken = NSString(data: retrievedData, encoding: NSUTF8StringEncoding) as? String } } } if status != errSecSuccess && status != errSecItemNotFound { let error = errorWithStatus(status) self.logger?.logError(error, withMessage: "Keychain can't read access token.") throw error } return accessToken } func deleteAccessToken() throws { let query = keychainQuery let status = SecItemDelete(query) if status != errSecSuccess && status != errSecItemNotFound { let error = errorWithStatus(status) self.logger?.logError(error, withMessage: "Keychain can't delete access token .") throw error } } func saveAccessToken(accessToken: String) throws { do { if let _ = try self.accessToken() { try deleteAccessToken() } } catch { } var query = keychainQuery let accessTokenData = accessToken.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) query[kSecValueData as String] = accessTokenData let status = SecItemAdd(query, nil) if status != errSecSuccess { let error = errorWithStatus(status) self.logger?.logError(error, withMessage: "Keychain can't add access token.") throw error } } private func errorWithStatus(status: OSStatus) -> NSError { return NSError(domain: QuadratKeychainOSSatusErrorDomain, code: Int(status), userInfo: nil) } func allAllAccessTokens() -> [String] { return [""] } }
bsd-2-clause
cd614bcfcb19d8d84a340ca7f91b26e4
34.081081
110
0.616333
5.312415
false
false
false
false
apple/swift
test/RemoteAST/parameterized_existentials.swift
5
1922
// RUN: %target-swift-remoteast-test -disable-availability-checking %s | %FileCheck %s // REQUIRES: swift-remoteast-test @_silgen_name("printDynamicTypeAndAddressForExistential") func printDynamicTypeAndAddressForExistential<T>(_: T) @_silgen_name("stopRemoteAST") func stopRemoteAST() protocol Paddock<Animal> { associatedtype Animal } struct Chicken {} struct Coop: Paddock { typealias Animal = Chicken } struct Pig {} struct Pen: Paddock { typealias Animal = Pig } struct Field<Animal>: Paddock {} protocol SharedYard<Animal1, Animal2, Animal3, Animal4> { associatedtype Animal1 associatedtype Animal2 associatedtype Animal3 associatedtype Animal4 } class Lea: SharedYard { typealias Animal1 = Chicken typealias Animal2 = Pig typealias Animal3 = Chicken typealias Animal4 = Pig init() {} } let coop = Coop() // CHECK: Coop printDynamicTypeAndAddressForExistential(coop as any Paddock) // CHECK-NEXT: Coop printDynamicTypeAndAddressForExistential(coop as any Paddock<Chicken>) // CHECK-NEXT: Coop.Type printDynamicTypeAndAddressForExistential(Coop.self as (any Paddock<Chicken>.Type)) // CHECK-NEXT: Coop.Type.Type.Type.Type printDynamicTypeAndAddressForExistential(Coop.Type.Type.Type.self as (any Paddock<Chicken>.Type.Type.Type.Type)) let pen = Pen() // CHECK-NEXT: Pen printDynamicTypeAndAddressForExistential(pen as any Paddock) // CHECK-NEXT: Pen printDynamicTypeAndAddressForExistential(pen as any Paddock<Pig>) let lea = Lea() // CHECK-NEXT: Lea printDynamicTypeAndAddressForExistential(lea as any SharedYard) // CHECK-NEXT: Lea printDynamicTypeAndAddressForExistential(lea as any SharedYard<Chicken, Pig, Chicken, Pig>) func freeRange<Animal>(_ x: Animal.Type) { printDynamicTypeAndAddressForExistential(Field<Animal>() as any Paddock<Animal>) } // CHECK-NEXT: Field<Chicken> freeRange(Chicken.self) // CHECK-NEXT: Field<Pig> freeRange(Pig.self) stopRemoteAST()
apache-2.0
0ea456769e137e458bd516fd567d24b5
22.728395
112
0.774194
3.313793
false
false
false
false
rnystrom/GitHawk
Classes/Systems/AppRouter/AppSplitViewController.swift
1
1415
// // AppSplitViewController.swift // Freetime // // Created by Ryan Nystrom on 10/6/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import UIKit final class AppSplitViewController: UISplitViewController { private let tabDelegateController = TabBarControllerDelegate() private let appSplitViewDelegateController = SplitViewControllerDelegate() override func viewDidLoad() { super.viewDidLoad() masterTabBarController?.delegate = tabDelegateController delegate = appSplitViewDelegateController preferredDisplayMode = .allVisible } var detailNavigationController: UINavigationController? { return viewControllers.last as? UINavigationController } var masterTabBarController: UITabBarController? { return viewControllers.first as? UITabBarController } func resetEmpty() { let controller = UIViewController() controller.view.backgroundColor = Styles.Colors.background reset( viewControllers: [UINavigationController(rootViewController: controller)], clearDetail: true ) } func reset(viewControllers: [UIViewController], clearDetail: Bool) { masterTabBarController?.viewControllers = viewControllers if clearDetail { detailNavigationController?.viewControllers = [SplitPlaceholderViewController()] } } }
mit
5a056be8f984dd406c9f9cb56c8a1424
29.085106
92
0.711457
6.042735
false
false
false
false
fromkk/Valy
Sources/Valy.swift
1
4411
// // Valy.swift // ValidatorSample // // Created by Kazuya Ueoka on 2016/11/14. // Copyright © 2016年 Timers Inc. All rights reserved. // import Foundation public enum ValyRule: AnyValidatorRule { case required case match(String) case pattern(String) case alphabet case digit case alnum case number case minLength(Int) case maxLength(Int) case exactLength(Int) case numericMin(Double) case numericMax(Double) case numericBetween(min: Double, max: Double) private func hasValue(with value: String?) -> String? { guard let value: String = value else { return nil } if 0 < value.count { return value } else { return nil } } public func run(with value: String?) -> Bool { switch self { case .required: return nil != self.hasValue(with: value) case .minLength(let length): guard let value: String = self.hasValue(with: value) else { return true } return length <= value.count case .maxLength(let length): guard let value: String = self.hasValue(with: value) else { return true } return length >= value.count case .exactLength(let length): guard let value: String = self.hasValue(with: value) else { return true } return length == value.count case .numericMin(let min): guard let value: String = self.hasValue(with: value) else { return true } guard let v: Double = Double(value) else { return true } return min <= v case .numericMax(let max): guard let value: String = self.hasValue(with: value) else { return true } guard let v: Double = Double(value) else { return true } return v <= max case .numericBetween(let min, let max): guard let value: String = self.hasValue(with: value) else { return true } guard let v: Double = Double(value) else { return true } return min <= v && v <= max case .match(let match): guard let value: String = self.hasValue(with: value) else { return true } return match == value case .pattern(let pattern): guard let value: String = self.hasValue(with: value) else { return true } do { let regexp: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: []) let range: NSRange = (value as NSString).range(of: value) return 0 < regexp.numberOfMatches(in: value, options: [], range: range) } catch { return true } case .alphabet: return ValyRule.pattern("^[a-zA-Z]+$").run(with: value) case .digit: return ValyRule.pattern("^[0-9]+$").run(with: value) case .alnum: return ValyRule.pattern("^[a-zA-Z0-9]+$").run(with: value) case .number: return ValyRule.pattern("^[\\+\\-]?[0-9\\.,]+$").run(with: value) } } } public class Valy: AnyValidatable { public typealias ErrorGenerator = (_ rule: AnyValidatorRule) -> String? private (set) public var rules: [AnyValidatorRule] = [] public var failed: ErrorGenerator? public func errorMessage(_ result: ValidatorResult) -> String? { switch result { case .success: return nil case .failure(let rule): return self.failed?(rule) } } private init() {} private init(rules: [AnyValidatorRule]) { self.rules = rules } public static func factory() -> AnyValidator { return Valy.init() } public static func factory(rules: [AnyValidatorRule]) -> AnyValidatable { return Valy.init(rules: rules) } public func add(rule: AnyValidatorRule) -> AnyValidatable { self.rules.append(rule) return self } public func add(rules: [AnyValidatorRule]) -> AnyValidatable { self.rules += rules return self } }
mit
ebb7a0a648a441eaa19339a7bd29fdd9
29.4
104
0.538113
4.488798
false
false
false
false
tardieu/swift
test/IDE/import_as_member.swift
2
3356
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.A -always-argument-labels > %t.printed.A.txt // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.B -always-argument-labels > %t.printed.B.txt // RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt // RUN: %FileCheck %s -check-prefix=PRINTB -strict-whitespace < %t.printed.B.txt // PRINT: struct Struct1 { // PRINT-NEXT: var x: Double // PRINT-NEXT: var y: Double // PRINT-NEXT: var z: Double // PRINT-NEXT: init() // PRINT-NEXT: init(x x: Double, y y: Double, z z: Double) // PRINT-NEXT: } // Make sure the other extension isn't here. // PRINT-NOT: static var static1: Double // PRINT: extension Struct1 { // PRINT-NEXT: static var globalVar: Double // PRINT-NEXT: init(value value: Double) // PRINT-NEXT: init(specialLabel specialLabel: ()) // PRINT-NEXT: func inverted() -> Struct1 // PRINT-NEXT: mutating func invert() // PRINT-NEXT: func translate(radians radians: Double) -> Struct1 // PRINT-NEXT: func scale(_ radians: Double) -> Struct1 // PRINT-NEXT: var radius: Double { get nonmutating set } // PRINT-NEXT: var altitude: Double{{$}} // PRINT-NEXT: var magnitude: Double { get } // PRINT-NEXT: static func staticMethod() -> Int32 // PRINT-NEXT: static var property: Int32 // PRINT-NEXT: static var getOnlyProperty: Int32 { get } // PRINT-NEXT: func selfComesLast(x x: Double) // PRINT-NEXT: func selfComesThird(a a: Int32, b b: Float, x x: Double) // PRINT-NEXT: } // PRINT-NOT: static var static1: Double // Make sure the other extension isn't here. // PRINTB-NOT: static var globalVar: Double // PRINTB: extension Struct1 { // PRINTB: static var static1: Double // PRINTB-NEXT: static var static2: Float // PRINTB-NEXT: init(float value: Float) // PRINTB-NEXT: static var zero: Struct1 { get } // PRINTB-NEXT: } // PRINTB: var currentStruct1: Struct1 // PRINTB-NOT: static var globalVar: Double // RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules -verify-ignore-unknown import ImportAsMember.A import ImportAsMember.B let iamStructFail = IAMStruct1CreateSimple() // expected-error@-1{{missing argument for parameter #1 in call}} var iamStruct = Struct1(x: 1.0, y: 1.0, z: 1.0) let gVarFail = IAMStruct1GlobalVar // expected-error@-1{{IAMStruct1GlobalVar' has been renamed to 'Struct1.globalVar'}} let gVar = Struct1.globalVar print("\(gVar)") let iamStructInitFail = IAMStruct1CreateSimple(42) // expected-error@-1{{'IAMStruct1CreateSimple' has been replaced by 'Struct1.init(value:)'}} let iamStructInitFail2 = Struct1(value: 42) let gVar2 = Struct1.static2 // Instance properties iamStruct.radius += 1.5 _ = iamStruct.magnitude // Static properties iamStruct = Struct1.zero // Global properties currentStruct1.x += 1.5 // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: 'IAMStruct1CreateSimple' declared here // <unknown>:0: error: unexpected note produced: 'IAMStruct1GlobalVar' was obsoleted in Swift 3 // <unknown>:0: error: unexpected note produced: 'IAMStruct1CreateSimple' was obsoleted in Swift 3
apache-2.0
076aba45b5a485ea9eaf7ae1311036a8
38.482353
206
0.710072
3.255092
false
false
false
false
tardieu/swift
test/Parse/super.swift
25
2900
// RUN: %target-typecheck-verify-swift class B { var foo: Int func bar() {} init() {} init(x: Int) {} subscript(x: Int) -> Int { get {} set {} } } class D : B { override init() { super.init() } override init(x:Int) { let _: () -> B = super.init // expected-error {{partial application of 'super.init' initializer chain is not allowed}} } convenience init(y:Int) { let _: () -> D = self.init // expected-error {{partial application of 'self.init' initializer delegation is not allowed}} } init(z: Int) { super .init(x: z) } func super_calls() { super.foo // expected-error {{expression resolves to an unused l-value}} super.foo.bar // expected-error {{value of type 'Int' has no member 'bar'}} super.bar // expected-error {{expression resolves to an unused function}} super.bar() super.init // expected-error{{'super.init' cannot be called outside of an initializer}} super.init() // expected-error{{'super.init' cannot be called outside of an initializer}} super.init(0) // expected-error{{'super.init' cannot be called outside of an initializer}} super[0] // expected-error {{expression resolves to an unused l-value}} super .bar() } func bad_super_1() { super.$0 // expected-error{{expected identifier or 'init'}} } func bad_super_2() { super(0) // expected-error{{expected '.' or '[' after 'super'}} } } class Closures : B { func captureWeak() { let g = { [weak self] () -> Void in // expected-note * {{'self' explicitly captured here}} super.foo() // expected-error {{using 'super' in a closure where 'self' is explicitly captured is not yet supported}} } g() } func captureUnowned() { let g = { [unowned self] () -> Void in // expected-note * {{'self' explicitly captured here}} super.foo() // expected-error {{using 'super' in a closure where 'self' is explicitly captured is not yet supported}} } g() } func nestedInner() { let g = { () -> Void in let h = { [weak self] () -> Void in // expected-note * {{'self' explicitly captured here}} super.foo() // expected-error {{using 'super' in a closure where 'self' is explicitly captured is not yet supported}} nil ?? super.foo() // expected-error {{using 'super' in a closure where 'self' is explicitly captured is not yet supported}} } h() } g() } func nestedOuter() { let g = { [weak self] () -> Void in // expected-note * {{'self' explicitly captured here}} let h = { () -> Void in super.foo() // expected-error {{using 'super' in a closure where 'self' is explicitly captured is not yet supported}} nil ?? super.foo() // expected-error {{using 'super' in a closure where 'self' is explicitly captured is not yet supported}} } h() } g() } }
apache-2.0
9c8d0fc8b5432ffa0a1514efa7298356
30.521739
132
0.603793
3.771131
false
false
false
false
Antondomashnev/ADPuzzleAnimation
Source/Private/PieceAnimation.swift
1
3893
// // PieceAnimation.swift // ADPuzzleLoader // // Created by Anton Domashnev on 1/9/16. // Copyright © 2016 Anton Domashnev. All rights reserved. // import UIKit extension CAAnimation { //MARK: - Interface static func basicForwardPieceAnimation(piece: Piece, velocity: Double, delay: CFTimeInterval, scale: Double) -> CAAnimation { func setDefaultValuesForAnimation(animation: CAAnimation) { animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) } func setAnimationDurationBasedOnVelocity(animation: CAAnimation, velocity: Double) { animation.duration = 10.0 / velocity } let moveAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position") setDefaultValuesForAnimation(moveAnimation) setAnimationDurationBasedOnVelocity(moveAnimation, velocity: velocity) moveAnimation.fromValue = NSValue(CGPoint: piece.initialPosition) moveAnimation.toValue = NSValue(CGPoint: piece.desiredPosition) moveAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.0, 0.84, 0.49, 1.00) let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.scale") setDefaultValuesForAnimation(scaleAnimation) setAnimationDurationBasedOnVelocity(scaleAnimation, velocity: velocity) scaleAnimation.fromValue = scale scaleAnimation.toValue = 1 scaleAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.0, 0.84, 0.49, 1.00) let forwardAnimation = CAAnimationGroup() setDefaultValuesForAnimation(forwardAnimation) setAnimationDurationBasedOnVelocity(forwardAnimation, velocity: velocity) forwardAnimation.animations = [moveAnimation, scaleAnimation] forwardAnimation.beginTime = CACurrentMediaTime() + delay return forwardAnimation } static func basicBackwardPieceAnimation(piece: Piece, velocity: Double, delay: CFTimeInterval, scale: Double) -> CAAnimation { func setDefaultValuesForAnimation(animation: CAAnimation) { animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) } func setAnimationDurationBasedOnVelocity(animation: CAAnimation, velocity: Double) { animation.duration = 10.0 / velocity } let moveAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position") setDefaultValuesForAnimation(moveAnimation) setAnimationDurationBasedOnVelocity(moveAnimation, velocity: velocity) moveAnimation.fromValue = NSValue(CGPoint: piece.initialPosition) moveAnimation.toValue = NSValue(CGPoint: piece.desiredPosition) moveAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 1.0, 0.0, 1.0, 0.67) let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.scale") setDefaultValuesForAnimation(scaleAnimation) setAnimationDurationBasedOnVelocity(scaleAnimation, velocity: velocity) scaleAnimation.fromValue = 1 scaleAnimation.toValue = scale scaleAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 1.0, 0.0, 1.0, 0.67) let forwardAnimation = CAAnimationGroup() setDefaultValuesForAnimation(forwardAnimation) setAnimationDurationBasedOnVelocity(forwardAnimation, velocity: velocity) forwardAnimation.animations = [moveAnimation, scaleAnimation] forwardAnimation.beginTime = CACurrentMediaTime() + delay return forwardAnimation } }
mit
213d974a1fa6e92b0b79767570a04d99
45.891566
130
0.71557
5.774481
false
false
false
false
epavlov/outside
Outside/LocationManager.swift
1
1916
// // LocationManager.swift // Outside // // Created by Eugene Pavlov on 12/27/16. // Copyright © 2016 Eugene Pavlov. All rights reserved. // import Foundation import CoreLocation /// Location manager class to aquire user device location and load coordinates into another Location singleton class class LocationManager: NSObject, CLLocationManagerDelegate { let locationManager = CLLocationManager() var currentLocation: CLLocation! override init() { super.init() // Set up location manager locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest // accuracy locationManager.requestWhenInUseAuthorization() // ask for tracking location when app in use locationManager.startMonitoringSignificantLocationChanges() // start tracking location } /** Function to ask user for using location - parameter completion: Bool, Optional completion handler - returns: Bool */ func locationAuthStatus(completion: (_ result: Bool) -> Void = { _ in }) { if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { currentLocation = locationManager.location setCoordinates(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude) completion(true) } else { locationManager.requestWhenInUseAuthorization() locationAuthStatus() } } /** Function to set user device coordinates into Location singleton class - parameter latitude: CLLocationDegrees - parameter longitude: CLLocationDegrees */ func setCoordinates(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { Location.sharedInstance.latitude = latitude Location.sharedInstance.longitude = longitude } }
gpl-3.0
2c26dde2c19f007f9735562adc914c44
33.196429
122
0.688251
6.137821
false
false
false
false
swiftingio/architecture-wars-mvc
MyCards/MyCards/CardDetailsViewController.swift
1
11915
// // CardDetailsViewController.swift // MyCards // // Created by Maciej Piotrowski on 16/10/16. // import UIKit final class CardDetailsViewController: UIViewController { fileprivate var history: [Card] = [] fileprivate var card: Card { didSet { front.image = card.front back.image = card.back name.text = card.name doneButton.isEnabled = card.isValid } } fileprivate var mode: Mode { didSet { configureNavigationItem() configureModeForViews() } } fileprivate let worker: CoreDataWorkerProtocol fileprivate let loader: ResourceLoading // MARK: Views // codebeat:disable[TOO_MANY_IVARS] fileprivate lazy var editButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editTapped)) fileprivate lazy var cancelButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelTapped)) fileprivate lazy var doneButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped)) fileprivate lazy var front: CardView = CardView(image: self.card.front).with { $0.tapped = { [unowned self] in self.cardTapped(.front) } } fileprivate lazy var back: CardView = CardView(image: self.card.back) .with { $0.tapped = { [unowned self] in self.cardTapped(.back) } } fileprivate lazy var name: UITextField = UITextField.makeNameField().with { $0.text = self.card.name $0.autocapitalizationType = .sentences $0.delegate = self $0.addTarget(self, action: #selector(nameChanged(sender:)), for: .editingChanged) } fileprivate lazy var toolbar: UIToolbar = UIToolbar.constrained().with { let delete = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(removeTapped)) let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) $0.items = [flexible, delete, flexible] } // codebeat:enable[TOO_MANY_IVARS] init(card: Card, mode: Mode = .normal, worker: CoreDataWorkerProtocol = CoreDataWorker(), loader: ResourceLoading = NetworkLoader.shared) { self.card = card self.mode = mode self.worker = worker self.loader = loader self.history.append(self.card) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } override func viewDidLoad() { super.viewDidLoad() configureViews() configureNavigationItem() configureModeForViews() configureConstraints() } } extension CardDetailsViewController { fileprivate func configureViews() { view.backgroundColor = .white view.addSubview(name) view.addSubview(front) view.addSubview(back) view.addSubview(toolbar) } fileprivate func configureConstraints() { view.subviews.forEach { $0.translatesAutoresizingMaskIntoConstraints = false } var constraints: [NSLayoutConstraint] = [] constraints.append(name.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40)) constraints.append(name.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20)) constraints.append(name.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20)) constraints.append(front.leadingAnchor.constraint(equalTo: name.leadingAnchor, constant: 0)) constraints.append(front.trailingAnchor.constraint(equalTo: name.trailingAnchor, constant: 0)) constraints.append(front.topAnchor.constraint(equalTo: name.bottomAnchor, constant: 20)) constraints.append(front.heightAnchor.constraint(equalTo: front.widthAnchor, multiplier: 1 / .cardRatio)) constraints.append(back.topAnchor.constraint(equalTo: front.bottomAnchor, constant: 20)) constraints.append(back.leadingAnchor.constraint(equalTo: front.leadingAnchor, constant: 0)) constraints.append(back.trailingAnchor.constraint(equalTo: front.trailingAnchor, constant: 0)) constraints.append(back.heightAnchor.constraint(equalTo: front.heightAnchor, constant: 0)) constraints.append(toolbar.heightAnchor.constraint(equalToConstant: 40)) constraints.append(toolbar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)) constraints.append(toolbar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)) constraints.append(toolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)) NSLayoutConstraint.activate(constraints) } fileprivate func configureNavigationItem() { title = mode == .create ? .AddNewCard : .CardDetails doneButton.isEnabled = card.isValid switch mode { case .normal: navigationItem.rightBarButtonItems = [editButton] case .edit, .create: navigationItem.rightBarButtonItems = [doneButton] } navigationItem.leftBarButtonItem = cancelButton } fileprivate func configureModeForViews() { let editMode = mode != .normal name.resignFirstResponder() name.isUserInteractionEnabled = editMode name.placeholder = editMode ? .EnterCardName : .NoName front.photoCamera.isHidden = !editMode back.photoCamera.isHidden = !editMode toolbar.isHidden = !(mode == .edit) } @objc fileprivate func doneTapped() { guard card.isValid else { return } persist(card) switch mode { case .create: dismiss() default: mode = .normal } } @objc fileprivate func removeTapped() { worker.remove(entities: [card]) { [weak self] error in error.flatMap { print("\($0)") } DispatchQueue.main.async { self?.dismiss() } } } @objc fileprivate func cancelTapped() { switch mode { case .create, .normal: dismiss() case .edit: history.last.flatMap { card = $0 } mode = .normal } } @objc fileprivate func editTapped() { mode = .edit } @objc fileprivate func nameChanged(sender textField: UITextField) { guard let name = textField.text else { return } card = Card(identifier: card.identifier, name: name, front: card.front, back: card.back) } fileprivate func persist(_ card: Card) { guard card.isValid else { return } worker.upsert(entities: [card]) { [weak self, loader] error in loader.upload(object: [card], to: "/cards", parser: CardParser()) { _ in } guard let strongSelf = self, error == nil else { return } strongSelf.history.append(card) } } fileprivate func cardTapped(_ side: Card.Side) { switch mode { case .edit, .create: showImagePickerSources(for: side) case .normal: showImage(for: side) } } fileprivate func showImagePickerSources(for side: Card.Side) { view.endEditing(true) let title: String = .Set + " " + side.description let actionSheet = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) let actions: [UIImagePickerControllerSourceType] = UIImagePickerController.availableImagePickerSources() actions.forEach { source in let action = UIAlertAction(title: source.description, style: .default) { [unowned self] _ in self.showImagePicker(sourceType: source, for: side) } actionSheet.addAction(action) } let cancel = UIAlertAction(title: .Cancel, style: .cancel, handler: nil) actionSheet.addAction(cancel) present(actionSheet, animated: true, completion: nil) } fileprivate func showImage(for side: Card.Side) { view.endEditing(true) var image: UIImage? switch side { case .front: image = front.image case .back: image = back.image } guard let i = image else { return } let vc = CardPhotoViewController(image: i) present(vc, animated: true, completion: nil) } private func showImagePicker(sourceType: UIImagePickerControllerSourceType, for side: Card.Side) { let imagePicker: UIViewController if sourceType == .camera { imagePicker = PhotoCaptureViewController(side: side).with { $0.delegate = self } } else { imagePicker = ImagePickerController().with { $0.delegate = self $0.view.backgroundColor = .white $0.side = side } } present(imagePicker, animated: true, completion: nil) } fileprivate func set(_ image: UIImage, for side: Card.Side) { var front: UIImage? var back: UIImage? switch side { case .front: front = image back = card.back case .back: front = card.front back = image } card = Card(identifier: card.identifier, name: card.name, front: front, back: back) } } extension CardDetailsViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } extension CardDetailsViewController { enum Mode { case normal case edit case create } } extension CardDetailsViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage, let side = (picker as? ImagePickerController)?.side else { return } showImageCropping(for: image, side: side) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss() } func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { viewController.title = .SelectCardPhoto } fileprivate func showImageCropping(for image: UIImage = #imageLiteral(resourceName: "background"), side: Card.Side) { let vc = CropViewController(image: image, side: side) vc.delegate = self dismiss(animated: true) { self.present(vc, animated: true, completion: nil) } } fileprivate func process(_ image: UIImage, for side: Card.Side) { defer { dismiss() } let width: CGFloat = 600 let height: CGFloat = width / .cardRatio let size = CGSize(width: width, height: height) guard let resized = image.resized(to: size) else { return } set(resized, for: side) } } extension CardDetailsViewController: PhotoCaptureViewControllerDelegate { func photoCaptureViewController(_ viewController: PhotoCaptureViewController, didTakePhoto photo: UIImage, for side: Card.Side) { process(photo, for: side) } } extension CardDetailsViewController: CropViewControllerDelegate { func cropViewController(_ viewController: CropViewController, didCropPhoto photo: UIImage, for side: Card.Side) { process(photo, for: side) } }
mit
f3d37115d4d96c6c77fcaf04ac0fab98
36.003106
123
0.6423
4.962516
false
false
false
false
Samiabo/Weibo
Weibo/Weibo/Classes/Home/StatusViewCell.swift
1
4429
// // StatusViewCell.swift // Weibo // // Created by han xuelong on 2017/1/4. // Copyright © 2017年 han xuelong. All rights reserved. // import UIKit import SDWebImage private let edgeMargin: CGFloat = 15 private let itemMargin: CGFloat = 10 class StatusViewCell: UITableViewCell { @IBOutlet weak var contentLabelWidthCons: NSLayoutConstraint! @IBOutlet weak var bgView: UIView! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var verifiedView: UIImageView! @IBOutlet weak var screenNameLabel: UILabel! @IBOutlet weak var vipView: UIImageView! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var sourceLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var retweetedContentL: UILabel! @IBOutlet weak var picView: PicCollectionView! @IBOutlet weak var picViewHeightCons: NSLayoutConstraint! @IBOutlet weak var picViewWidthCons: NSLayoutConstraint! @IBOutlet weak var picViewBottomCons: NSLayoutConstraint! @IBOutlet weak var retweetedContentLTopCons: NSLayoutConstraint! var viewModel:StatusViewModel? { didSet { guard let viewModel = viewModel else { return } iconView.sd_setImage(with: viewModel.profileURL as? URL, placeholderImage: UIImage(named: "avatar_default_small")) verifiedView.image = viewModel.verifiedImage screenNameLabel.text = viewModel.status?.user?.screen_name vipView.image = viewModel.vipImage timeLabel.text = viewModel.createAtText if let sourceText = viewModel.sourceText { sourceLabel.text = "from" + sourceText } else { sourceLabel.text = nil } contentLabel.text = viewModel.status?.text screenNameLabel.textColor = viewModel.vipImage == nil ? UIColor.black : UIColor.orange let picViewSize = calculate(picCount: viewModel.picURLs.count) picViewWidthCons.constant = picViewSize.width picViewHeightCons.constant = picViewSize.height picView.picURLs = viewModel.picURLs if viewModel.status?.retweeted_status != nil { if let screenName = viewModel.status?.retweeted_status?.user?.screen_name, let retweetedText = viewModel.status?.retweeted_status?.text { retweetedContentL.text = "@" + screenName + ":" + retweetedText bgView.isHidden = false retweetedContentLTopCons.constant = 15 } } else { retweetedContentLTopCons.constant = 0 retweetedContentL.text = nil bgView.isHidden = true } } } override func awakeFromNib() { super.awakeFromNib() contentLabelWidthCons.constant = UIScreen.main.bounds.size.width - 2*edgeMargin } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } // MARK: - calculate collectionView size extension StatusViewCell { func calculate(picCount: Int) -> CGSize { //no pic, 1 pic, 4 pics, other if picCount == 0 { picViewBottomCons.constant = 0 return .zero } picViewBottomCons.constant = 10 let layout = picView.collectionViewLayout as! UICollectionViewFlowLayout if picCount == 1 { let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: viewModel?.picURLs.last?.absoluteString) layout.itemSize = (image?.size)! return (image?.size)! } let imageWH = (UIScreen.main.bounds.size.width - 2*edgeMargin - 2*itemMargin) / 3 layout.itemSize = CGSize(width: imageWH, height: imageWH) if picCount == 4 { let picViewWH = 2*imageWH + itemMargin return CGSize(width: picViewWH, height: picViewWH) } let rows = CGFloat((picCount - 1) / 3 + 1) let picViewH = rows * imageWH + (rows - 1) * itemMargin let picViewW = UIScreen.main.bounds.size.width - 2 * edgeMargin return CGSize(width: picViewW, height: picViewH) } }
mit
3db8c951a2f91e6c18164f55f4812a68
31.072464
153
0.622684
5.041002
false
false
false
false
BaiduCloudTeam/PaperInSwift
PaperInSwift/Custom Layout/CHCollectionViewSmallLayout.swift
1
1190
// // CHCollectionViewSmallLayout.swift // PaperInSwift // // Created by PeterFrank on 10/11/15. // Copyright © 2015 Team_ChineseHamburger. All rights reserved. // Good Night import UIKit class CHCollectionViewSmallLayout: CHStickyHeaderLayout { override init() { super.init() self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { self.setup() } func setup() { self.itemSize = CGSizeMake(142, 254) let top:CGFloat = isiPhone5() ? 314 : 224 self.sectionInset = UIEdgeInsetsMake(top, -CGRectGetWidth(UIScreen.mainScreen().bounds), 0, 2) self.minimumInteritemSpacing = 10.0 self.minimumLineSpacing = 2.0 self.scrollDirection = .Horizontal self.headerReferenceSize = UIScreen.mainScreen().bounds.size self.collectionView!.pagingEnabled = false } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } func isiPhone5() ->Bool { return UIScreen.mainScreen().currentMode?.size == CGSizeMake(640, 1136) } }
mit
d309af7ce8a237907c509acaf4df2004
27.333333
102
0.648444
4.555556
false
false
false
false
makelove/Developing-iOS-8-Apps-with-Swift
Lession10/Smashtag/Smashtag/Twitter/MediaItem.swift
4
1376
// // MediaItem.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation // holds the network url and aspectRatio of an image attached to a Tweet // created automatically when a Tweet object is created public struct MediaItem { public let url: NSURL! public var aspectRatio: Double = 0 public var description: String { return (url.absoluteString ?? "no url") + " (aspect ratio = \(aspectRatio))" } // MARK: - Private Implementation init?(data: NSDictionary?) { var valid = false if let urlString = data?.valueForKeyPath(TwitterKey.MediaURL) as? NSString { if let url = NSURL(string: urlString as String) { self.url = url let h = data?.valueForKeyPath(TwitterKey.Height) as? NSNumber let w = data?.valueForKeyPath(TwitterKey.Width) as? NSNumber if h != nil && w != nil && h?.doubleValue != 0 { aspectRatio = w!.doubleValue / h!.doubleValue valid = true } } } if !valid { return nil } } struct TwitterKey { static let MediaURL = "media_url_https" static let Width = "sizes.small.w" static let Height = "sizes.small.h" } }
apache-2.0
0555509d2310b7f638c6cea58ab76a5a
28.913043
115
0.578488
4.571429
false
false
false
false
vtourraine/ThirdPartyMailer
Example/ThirdPartyMailerExample/ViewController.swift
1
1533
// // ViewController.swift // ThirdPartyMailerExample // // Created by Vincent Tourraine on 28/03/16. // Copyright © 2016-2022 Vincent Tourraine. All rights reserved. // import UIKit import ThirdPartyMailer class ViewController: UITableViewController { let clients = ThirdPartyMailClient.clients // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return clients.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let client = clients[indexPath.row] cell.textLabel?.text = client.name if ThirdPartyMailer.isMailClientAvailable(client) { cell.detailTextLabel?.text = NSLocalizedString("Available", comment: "") cell.detailTextLabel?.textColor = view.tintColor } else { cell.detailTextLabel?.text = NSLocalizedString("Unavailable", comment: "") cell.detailTextLabel?.textColor = .red } return cell } // MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let client = clients[indexPath.row] ThirdPartyMailer.openCompose(client, subject: NSLocalizedString("Test ThirdPartyMailer", comment: "")) tableView.deselectRow(at: indexPath, animated: true) } }
mit
477ae427b8a93748bf98a14b130afb87
30.265306
110
0.686031
4.990228
false
false
false
false
benlangmuir/swift
test/SILOptimizer/cast_folding_objc.swift
5
11593
// RUN: %target-swift-frontend -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xllvm -sil-disable-pass=PerfInliner -emit-sil %s | %FileCheck %s // We want to check two things here: // - Correctness // - That certain "is" checks are eliminated based on static analysis at compile-time // // In ideal world, all those testNN functions should be simplified down to a single basic block // which returns either true or false, i.e. all type checks should folded statically. // REQUIRES: objc_interop import Foundation class ObjCX : NSObject {} struct CX: _ObjectiveCBridgeable { func _bridgeToObjectiveC() -> ObjCX { return ObjCX() } static func _forceBridgeFromObjectiveC(_ source: ObjCX, result: inout CX?) {} static func _conditionallyBridgeFromObjectiveC(_ source: ObjCX, result: inout CX?) -> Bool { return false } static func _unconditionallyBridgeFromObjectiveC(_ source: ObjCX?) -> CX { var result: CX? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } // Check casts to types which are _ObjectiveCBridgeable func cast0(_ o: AnyObject) -> Bool { return o is CX } // CHECK-LABEL: sil hidden [noinline] @$s17cast_folding_objc5test0SbyF // CHECK: bb0 // Check that cast is not eliminated even though cast0 is a conversion // from a class to struct, because it casts to a struct implementing // the _BridgedToObjectiveC protocol // CHECK: checked_cast // CHECK: return @inline(never) func test0() -> Bool { return cast0(NSNumber(value:1)) } // Check that this cast does not get eliminated, because // the compiler does not statically know if this object // is NSNumber can be converted into Int. // CHECK-LABEL: sil [noinline] @$s17cast_folding_objc35testMayBeBridgedCastFromObjCtoSwiftySiyXlF // CHECK: unconditional_checked_cast_addr // CHECK: return @inline(never) public func testMayBeBridgedCastFromObjCtoSwift(_ o: AnyObject) -> Int { return o as! Int } // Check that this cast does not get eliminated, because // the compiler does not statically know if this object // is NSString can be converted into String. // CHECK-LABEL: sil [noinline] @$s17cast_folding_objc41testConditionalBridgedCastFromObjCtoSwiftySSSgyXlF // CHECK: unconditional_checked_cast_addr // CHECK: return @inline(never) public func testConditionalBridgedCastFromObjCtoSwift(_ o: AnyObject) -> String? { return o as? String } public func castObjCToSwift<T>(_ t: T) -> Int { return t as! Int } // Check that compiler understands that this cast always fails // CHECK-LABEL: sil [noinline] {{.*}}@$s17cast_folding_objc37testFailingBridgedCastFromObjCtoSwiftySiSo8NSStringCF // CHECK: [[ONE:%[0-9]+]] = integer_literal $Builtin.Int1, -1 // CHECK: cond_fail [[ONE]] : $Builtin.Int1, "failed cast" // CHECK-NEXT: unreachable // CHECK-NEXT: } @inline(never) public func testFailingBridgedCastFromObjCtoSwift(_ ns: NSString) -> Int { return castObjCToSwift(ns) } // Check that compiler understands that this cast always fails // CHECK-LABEL: sil [noinline] {{.*}}@$s17cast_folding_objc37testFailingBridgedCastFromSwiftToObjCySiSSF // CHECK: [[ONE:%[0-9]+]] = integer_literal $Builtin.Int1, -1 // CHECK: cond_fail [[ONE]] : $Builtin.Int1, "failed cast" // CHECK-NEXT: unreachable // CHECK-NEXT: } @inline(never) public func testFailingBridgedCastFromSwiftToObjC(_ s: String) -> NSInteger { return s as! NSInteger } @inline(never) public func testCastNSObjectToAnyClass(_ o: NSObject) -> AnyClass { return o as! AnyClass } @inline(never) public func testCastNSObjectToClassObject(_ o: NSObject) -> NSObject.Type { return o as! NSObject.Type } @inline(never) public func testCastNSObjectToAnyType(_ o: NSObject) -> Any.Type { return o as! Any.Type } @inline(never) public func testCastNSObjectToEveryType<T>(_ o: NSObject) -> T.Type { return o as! T.Type } @inline(never) public func testCastNSObjectToNonClassType(_ o: NSObject) -> Int.Type { return o as! Int.Type } @inline(never) public func testCastAnyObjectToAnyClass(_ o: AnyObject) -> AnyClass { return o as! AnyClass } @inline(never) public func testCastAnyObjectToClassObject(_ o: AnyObject) -> AnyObject.Type { return o as! AnyObject.Type } @inline(never) public func testCastAnyObjectToAnyType(_ o: AnyObject) -> Any.Type { return o as! Any.Type } @inline(never) public func testCastAnyObjectToEveryType<T>(_ o: AnyObject) -> T.Type { return o as! T.Type } @inline(never) public func testCastAnyObjectToNonClassType(_ o: AnyObject) -> Int.Type { return o as! Int.Type } @inline(never) public func testCastAnyToAny2Class(_ o: Any) -> AnyClass { return o as! AnyClass } @inline(never) public func testCastAnyToClassObject(_ o: Any) -> AnyObject.Type { return o as! AnyObject.Type } @inline(never) public func testCastAnyToAny2Type(_ o: Any) -> Any.Type { return o as! Any.Type } @inline(never) public func testCastAnyToEveryType<T>(_ o: Any) -> T.Type { return o as! T.Type } @inline(never) public func testCastAnyToNonClassType(_ o: Any) -> Int.Type { return o as! Int.Type } @inline(never) public func testCastEveryToAnyClass<T>(_ o: T) -> AnyClass { return o as! AnyClass } @inline(never) public func testCastEveryToClassObject<T>(_ o: T) -> AnyObject.Type { return o as! AnyObject.Type } @inline(never) public func testCastEveryToAnyType<T>(_ o: T) -> Any.Type { return o as! Any.Type } @inline(never) public func testCastEveryToEvery2Type<T, U>(_ o: U) -> T.Type { return o as! T.Type } @inline(never) public func testCastEveryToNonClassType<T>(_ o: T) -> Int.Type { return o as! Int.Type } func cast<U, V>(_ u: U.Type) -> V? { return u as? V } public protocol P { } // Any casts from P.Protocol to P.Type should fail. @inline(never) public func testCastPProtocolToPType() -> ObjCP.Type? { return cast(ObjCP.self) } @objc public protocol ObjCP { } @inline(never) public func testCastObjCPProtocolToObjCPType() -> ObjCP.Type? { return cast(ObjCP.self) } @inline(never) public func testCastProtocolCompositionProtocolToProtocolCompositionType() -> (P & ObjCP).Type? { return cast((P & ObjCP).self) } @inline(never) public func testCastProtocolCompositionProtocolToProtocolType () -> P.Type? { return (P & ObjCP).self as? P.Type } print("test0=\(test0())") // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastNSObjectToEveryType{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastNSObjectToNonClassType // CHECK: [[ONE:%[0-9]+]] = integer_literal $Builtin.Int1, -1 // CHECK: cond_fail [[ONE]] : $Builtin.Int1, "failed cast" // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastAnyObjectToEveryType{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastAnyObjectToNonClassType // CHECK: [[MT:%[0-9]+]] = metatype $@thin Int.Type // CHECK: return [[MT]] // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastAnyToAny2Class{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastAnyToClassObject{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastAnyToAny2Type{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastAnyToEveryType{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastAnyToNonClassType // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastEveryToAnyClass{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastEveryToClassObject{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastEveryToAnyType{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastEveryToEvery2Type{{.*}} // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastEveryToNonClassType // CHECK: unconditional_checked_cast_addr // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastPProtocolToPType // CHECK: %0 = enum $Optional{{.*}}, #Optional.none!enumelt // CHECK-NEXT: return %0 // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastObjCPProtocolTo{{.*}}PType // CHECK: %0 = enum $Optional{{.*}}, #Optional.none!enumelt // CHECK-NEXT: return %0 // CHECK-LABEL: sil [noinline] {{.*}}@{{.*}}testCastProtocolComposition{{.*}}Type // CHECK: %0 = enum $Optional{{.*}}, #Optional.none!enumelt // CHECK-NEXT: return %0 // Check that compiler understands that this cast always succeeds. // Since it is can be statically proven that NSString is bridgeable to String, // _forceBridgeFromObjectiveC from String should be invoked instead of // a more general, but less effective swift_bridgeNonVerbatimFromObjectiveC, which // also performs conformance checks at runtime. @inline(never) public func testBridgedCastFromObjCtoSwift(_ ns: NSString) -> String { return ns as String } // Check that compiler understands that this cast always succeeds // CHECK-LABEL: sil [noinline] @$s17cast_folding_objc30testBridgedCastFromSwiftToObjCySo8NSStringCSSF // CHECK-NOT: {{ cast}} // CHECK: function_ref @$sSS10FoundationE19_bridgeToObjectiveC{{[_0-9a-zA-Z]*}}F // CHECK: apply // CHECK: return @inline(never) public func testBridgedCastFromSwiftToObjC(_ s: String) -> NSString { return s as NSString } public class MyString: NSString {} // Check that the cast-optimizer bails out on a conditional downcast to a subclass of a // bridged ObjC class. // CHECK-LABEL: sil [noinline] @{{.*}}testConditionalBridgedCastFromSwiftToNSObjectDerivedClass{{.*}} // CHECK: bb0([[ARG:%.*]] : $String): // CHECK: [[FUNC:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveC{{[_0-9a-zA-Z]*}}F // CHECK: [[BRIDGED_VALUE:%.*]] = apply [[FUNC]]([[ARG]]) // CHECK-NOT: apply // CHECK-NOT: unconditional_checked_cast // CHECK: checked_cast_br [[BRIDGED_VALUE]] : $NSString to MyString, [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]([[CAST_BRIDGED_VALUE:%.*]] : $MyString) // CHECK: [[SOME:%.*]] = enum $Optional<MyString>, #Optional.some!enumelt, [[CAST_BRIDGED_VALUE]] : $MyString // CHECK: br [[CONT_BB:bb[0-9]+]]([[SOME]] : // // CHECK: [[FAIL_BB]]: // CHECK: strong_release [[BRIDGED_VALUE]] // CHECK: [[NONE:%.*]] = enum $Optional<MyString>, #Optional.none!enumelt // CHECK: br [[CONT_BB]]([[NONE]] : // // CHECK: [[CONT_BB:bb[0-9]+]]([[RESULT:%.*]] : // CHECK: return [[RESULT]] // CHECK: } // end sil function '${{.*}}testConditionalBridgedCastFromSwiftToNSObjectDerivedClass{{.*}}' @inline(never) public func testConditionalBridgedCastFromSwiftToNSObjectDerivedClass(_ s: String) -> MyString? { return s as? MyString } // Check that the cast-optimizer does not bail out on an unconditional downcast to a subclass of a // bridged ObjC class. // CHECK-LABEL: sil [noinline] @{{.*}}testForcedBridgedCastFromSwiftToNSObjectDerivedClass{{.*}} // CHECK: function_ref @$sSS10FoundationE19_bridgeToObjectiveC{{[_0-9a-zA-Z]*}}F // CHECK: apply // CHECK-NOT: apply // CHECK-NOT: checked_cast_br // CHECK: unconditional_checked_cast // CHECK-NOT: apply // CHECK-NOT: unconditional // CHECK-NOT: checked_cast // CHECK: return @inline(never) public func testForcedBridgedCastFromSwiftToNSObjectDerivedClass(_ s: String) -> MyString { return s as! MyString } // rdar://problem/51078136 func foo(x: CFMutableDictionary) -> [AnyHashable:AnyObject]? { return x as? [AnyHashable:AnyObject] }
apache-2.0
4483e6cd4cadd7e1b45cdf5c53f18f91
30.848901
146
0.699733
3.67565
false
true
false
false
MuYangZhe/Swift30Projects
Project 10 - Interests/Interests/AppDelegate.swift
1
4584
// // AppDelegate.swift // Interests // // Created by 牧易 on 17/7/21. // Copyright © 2017年 MuYi. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Interests") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
6b5106f39901bf79cee4741845fb4d43
48.215054
285
0.685165
5.830573
false
false
false
false
remobjects/Marzipan
CodeGen4/CGObjectiveCCodeGenerator.swift
1
20981
// // Abstract base implementation for Objective-C. Inherited by specific .m and .h Generators // public __abstract class CGObjectiveCCodeGenerator : CGCStyleCodeGenerator { public init() { keywords = ["__nonnull", "__null_unspecified", "__nullable", "__strong", "__unsafe_unretained", "__weak", "id", "in", "self", "super", "auto", "break", "case", "char", "const", "continue", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "return", "int", "long", "register", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "colatile", "while"].ToList() as! List<String> } // // Statements // // in C-styleCG Base class /* override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) { // handled in base } */ /* override func generateIfElseStatement(_ statement: CGIfThenElseStatement) { // handled in base } */ /* override func generateForToLoopStatement(_ statement: CGForToLoopStatement) { // handled in base } */ override func generateForEachLoopStatement(_ statement: CGForEachLoopStatement) { Append("for (") generateIdentifier(statement.LoopVariableName) Append(" in ") generateExpression(statement.Collection) AppendLine(")") generateStatementIndentedUnlessItsABeginEndBlock(statement.NestedStatement) } /* override func generateWhileDoLoopStatement(_ statement: CGWhileDoLoopStatement) { // handled in base } */ /* override func generateDoWhileLoopStatement(_ statement: CGDoWhileLoopStatement) { // handled in base } */ /* override func generateInfiniteLoopStatement(_ statement: CGInfiniteLoopStatement) { // handled in base } */ /* override func generateSwitchStatement(_ statement: CGSwitchStatement) { // handled in base } */ override func generateLockingStatement(_ statement: CGLockingStatement) { AppendLine("@synchronized(") generateExpression(statement.Expression) Append(")") AppendLine("{") incIndent() generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement) decIndent() AppendLine("}") } override func generateUsingStatement(_ statement: CGUsingStatement) { assert(false, "generateUsingStatement is not supported in Objective-C") } override func generateAutoReleasePoolStatement(_ statement: CGAutoReleasePoolStatement) { AppendLine("@autoreleasepool") AppendLine("{") incIndent() generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement) decIndent() AppendLine("}") } override func generateTryFinallyCatchStatement(_ statement: CGTryFinallyCatchStatement) { AppendLine("@try") AppendLine("{") incIndent() generateStatements(statement.Statements) decIndent() AppendLine("}") if let finallyStatements = statement.FinallyStatements, finallyStatements.Count > 0 { AppendLine("@finally") AppendLine("{") incIndent() generateStatements(finallyStatements) decIndent() AppendLine("}") } if let catchBlocks = statement.CatchBlocks, catchBlocks.Count > 0 { for b in catchBlocks { if let name = b.Name, let type = b.`Type` { Append("@catch (") generateTypeReference(type) if !objcTypeRefereneIsPointer(type) { Append(" ") } generateIdentifier(name) AppendLine(")") } else { AppendLine("@catch") } AppendLine("{") incIndent() generateStatements(b.Statements) decIndent() AppendLine("}") } } } /* override func generateReturnStatement(_ statement: CGReturnStatement) { // handled in base } */ override func generateThrowStatement(_ statement: CGThrowStatement) { if let value = statement.Exception { Append("@throw ") generateExpression(value) AppendLine(";") } else { AppendLine("@throw;") } } /* override func generateBreakStatement(_ statement: CGBreakStatement) { // handled in base } */ /* override func generateContinueStatement(_ statement: CGContinueStatement) { // handled in base } */ override func generateVariableDeclarationStatement(_ statement: CGVariableDeclarationStatement) { if let type = statement.`Type` { generateTypeReference(type) if !objcTypeRefereneIsPointer(type) { Append(" ") } } else { Append("id ") } generateIdentifier(statement.Name) if let value = statement.Value { Append(" = ") generateExpression(value) } AppendLine(";") } /* override func generateAssignmentStatement(_ statement: CGAssignmentStatement) { // handled in base } */ override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) { Append("self = [") if let callSite = statement.CallSite { generateExpression(callSite) } else { generateExpression(CGSelfExpression.`Self`) } Append(" init") if let name = statement.ConstructorName { generateIdentifier(uppercaseFirstLetter(name)) objcGenerateCallParameters(statement.Parameters, skipFirstName: true) } else { objcGenerateCallParameters(statement.Parameters) } Append("]") AppendLine(";") } // // Expressions // /* override func generateNamedIdentifierExpression(_ expression: CGNamedIdentifierExpression) { // handled in base } */ /* override func generateAssignedExpression(_ expression: CGAssignedExpression) { // handled in base } */ /* override func generateSizeOfExpression(_ expression: CGSizeOfExpression) { // handled in base } */ override func generateTypeOfExpression(_ expression: CGTypeOfExpression) { Append("[") if let typeReferenceExpression = expression.Expression as? CGTypeReferenceExpression { generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true) } else { generateExpression(expression.Expression) } Append(" class]") } override func generateDefaultExpression(_ expression: CGDefaultExpression) { assert(false, "generateDefaultExpression is not supported in Objective-C") } override func generateSelectorExpression(_ expression: CGSelectorExpression) { Append("@selector(\(expression.Name))") } override func generateTypeCastExpression(_ cast: CGTypeCastExpression) { Append("((") generateTypeReference(cast.TargetType)//, ignoreNullability: true) Append(")(") generateExpression(cast.Expression) Append("))") } override func generateInheritedExpression(_ expression: CGInheritedExpression) { Append("super") } override func generateSelfExpression(_ expression: CGSelfExpression) { Append("self") } override func generateNilExpression(_ expression: CGNilExpression) { Append("nil") } override func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) { Append(CGPropertyDefinition.MAGIC_VALUE_PARAMETER_NAME) } override func generateAwaitExpression(_ expression: CGAwaitExpression) { assert(false, "generateAwaitExpression is not supported in Objective-C") } override func generateAnonymousMethodExpression(_ expression: CGAnonymousMethodExpression) { // todo } override func generateAnonymousTypeExpression(_ expression: CGAnonymousTypeExpression) { // todo } /* override func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) { // handled in base } */ /* override func generateUnaryOperatorExpression(_ expression: CGUnaryOperatorExpression) { // handled in base } */ /* override func generateBinaryOperatorExpression(_ expression: CGBinaryOperatorExpression) { // handled in base } */ /* override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) { // handled in base } */ /* override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) { // handled in base } */ /* override func generateIfThenElseExpression(_ expression: CGIfThenElseExpression) { // handled in base } */ /* override func generateArrayElementAccessExpression(_ expression: CGArrayElementAccessExpression) { // handled in base } */ internal func objcGenerateCallSiteForExpression(_ expression: CGMemberAccessExpression, forceSelf: Boolean = false) { if let callSite = expression.CallSite { if let typeReferenceExpression = expression.CallSite as? CGTypeReferenceExpression { generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true) } else { generateExpression(callSite) } } else if forceSelf { generateExpression(CGSelfExpression.`Self`) } } internal func objcGenerateStorageModifierPrefixIfNeeded(_ storageModifier: CGStorageModifierKind) { switch storageModifier { case .Strong: Append("__strong ") case .Weak: Append("__weak ") case .Unretained: Append("__unsafe_unretained") } } func objcGenerateCallParameters(_ parameters: List<CGCallParameter>, skipFirstName: Boolean = false) { for p in 0 ..< parameters.Count { let param = parameters[p] if param.EllipsisParameter { if p > 0 { Append(", ") } else { Append(":") } } else { if p > 0 { Append(" ") } if let name = param.Name, p > 0 || !skipFirstName { generateIdentifier(name) } Append(":") } generateExpression(param.Value) } } func objcGenerateFunctionCallParameters(_ parameters: List<CGCallParameter>) { for p in 0 ..< parameters.Count { let param = parameters[p] if p > 0 { Append(", ") } generateExpression(param.Value) } } func objcGenerateAttributeParameters(_ parameters: List<CGCallParameter>) { // not needed } func objcGenerateDefinitionParameters(_ parameters: List<CGParameterDefinition>) { for p in 0 ..< parameters.Count { let param = parameters[p] if p > 0 { Append(" ") } if let externalName = param.ExternalName { generateIdentifier(externalName) } Append(":(") if let type = param.`Type` { generateTypeReference(type) } else { assert("CGParameterDefinition needs a type, for Objective-C") } switch param.Modifier { case .Var: Append("*") case .Out: Append("*") default: } Append(")") generateIdentifier(param.Name) } } func objcGenerateAncestorList(_ type: CGClassOrStructTypeDefinition) { if type.Ancestors.Count > 0 { Append(" : ") for a in 0 ..< type.Ancestors.Count { if let ancestor = type.Ancestors[a] { if a > 0 { Append(", ") } generateTypeReference(ancestor, ignoreNullability: true) } } } else if type is CGClassTypeDefinition { Append(" : NSObject") } if type.ImplementedInterfaces.Count > 0 { Append(" <") for a in 0 ..< type.ImplementedInterfaces.Count { if let interface = type.ImplementedInterfaces[a] { if a > 0 { Append(", ") } generateTypeReference(interface, ignoreNullability: true) } } Append(">") } } override func generateFieldAccessExpression(_ expression: CGFieldAccessExpression) { if let callSite = expression.CallSite { if expression.CallSiteKind != .Static || !(callSite is CGSelfExpression) { objcGenerateCallSiteForExpression(expression, forceSelf: true) Append("->") } } generateIdentifier(expression.Name) } override func generateMethodCallExpression(_ method: CGMethodCallExpression) { if method.CallSite != nil { Append("[") objcGenerateCallSiteForExpression(method, forceSelf: true) Append(" ") Append(method.Name) objcGenerateCallParameters(method.Parameters) Append("]") } else { // nil means its a function Append(method.Name) Append("(") objcGenerateFunctionCallParameters(method.Parameters) Append(")") } } override func generateNewInstanceExpression(_ expression: CGNewInstanceExpression) { Append("[[") generateExpression(expression.`Type`, ignoreNullability:true) Append(" alloc] init") if let name = expression.ConstructorName { generateIdentifier(uppercaseFirstLetter(name)) objcGenerateCallParameters(expression.Parameters, skipFirstName: true) } else { objcGenerateCallParameters(expression.Parameters) } Append("]") } override func generatePropertyAccessExpression(_ property: CGPropertyAccessExpression) { objcGenerateCallSiteForExpression(property, forceSelf: true) Append(".") Append(property.Name) if let params = property.Parameters, params.Count > 0 { assert(false, "Index properties are not supported in Objective-C") } } override func generateEnumValueAccessExpression(_ expression: CGEnumValueAccessExpression) { if let namedType = expression.Type as? CGNamedTypeReference { generateIdentifier(namedType.Name+"_"+expression.ValueName) // Obj-C enums must be unique } } override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) { Append("@") super.generateStringLiteralExpression(expression) } /* override func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) { // handled in base } */ /* override func generateIntegerLiteralExpression(_ expression: CGIntegerLiteralExpression) { // handled in base } */ /* override func generateFloatLiteralExpression(_ literalExpression: CGFloatLiteralExpression) { // handled in base } */ override func generateArrayLiteralExpression(_ array: CGArrayLiteralExpression) { Append("@[") for e in 0 ..< array.Elements.Count { if e > 0 { Append(", ") } generateExpression(array.Elements[e]) } Append("]") } override func generateSetLiteralExpression(_ expression: CGSetLiteralExpression) { assert(false, "Sets are not supported in Objective-C") } override func generateDictionaryExpression(_ dictionary: CGDictionaryLiteralExpression) { assert(dictionary.Keys.Count == dictionary.Values.Count, "Number of keys and values in Dictionary doesn't match.") Append("@{") for e in 0 ..< dictionary.Keys.Count { if e > 0 { Append(", ") } generateExpression(dictionary.Keys[e]) Append(": ") generateExpression(dictionary.Values[e]) } Append("}") } /* override func generateTupleExpression(_ expression: CGTupleLiteralExpression) { // default handled in base } */ override func generateSetTypeReference(_ setType: CGSetTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateSetTypeReference is not supported in Objective-C") } override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateSequenceTypeReference is not supported in Objective-C") } // // Type Definitions // override func generateAttribute(_ attribute: CGAttribute, inline: Boolean) { // no-op, we dont support attribtes in Objective-C } override func generateAliasType(_ type: CGTypeAliasDefinition) { } override func generateBlockType(_ block: CGBlockTypeDefinition) { } override func generateEnumType(_ type: CGEnumTypeDefinition) { // overriden in H } override func generateClassTypeStart(_ type: CGClassTypeDefinition) { // overriden in M and H } override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { AppendLine() AppendLine("@end") } func objcGenerateFields(_ type: CGTypeDefinition) { var hasFields = false for m in type.Members { if let property = m as? CGPropertyDefinition { // 32-bit OS X Objective-C needs properies explicitly synthesized if property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil { if !hasFields { hasFields = true AppendLine("{") incIndent() } if let type = property.`Type` { generateTypeReference(type) if !objcTypeRefereneIsPointer(type) { Append(" ") } } else { Append("id ") } Append("__p_") generateIdentifier(property.Name, escaped: false) AppendLine(";") } } else if let field = m as? CGFieldDefinition { if !hasFields { hasFields = true AppendLine("{") incIndent() } if let type = field.`Type` { generateTypeReference(type) if !objcTypeRefereneIsPointer(type) { Append(" ") } } else { Append("id ") } generateIdentifier(field.Name) AppendLine(";") } } if hasFields { decIndent() AppendLine("}") } } override func generateStructTypeStart(_ type: CGStructTypeDefinition) { // overriden in H } override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { // overriden in H } override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { // overriden in H } override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { // overriden in H } override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { // overriden in M and H } override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) { AppendLine("@end") } // // Type Members // func generateMethodDefinitionHeader(_ method: CGMethodLikeMemberDefinition, type: CGTypeDefinition) { if method.Static { Append("+ ") } else { Append("- ") } if let ctor = method as? CGConstructorDefinition { Append("(instancetype)init") generateIdentifier(uppercaseFirstLetter(ctor.Name)) } else { Append("(") if let returnType = method.ReturnType { generateTypeReference(returnType) } else { Append("void") } Append(")") generateIdentifier(method.Name) } objcGenerateDefinitionParameters(method.Parameters) } override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { // overriden in H } override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { // overriden in H } override func generateDestructorDefinition(_ dtor: CGDestructorDefinition, type: CGTypeDefinition) { } override func generateFinalizerDefinition(_ finalizer: CGFinalizerDefinition, type: CGTypeDefinition) { } override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) { // overriden in M } override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) { // overriden in H and M } override func generateEventDefinition(_ event: CGEventDefinition, type: CGTypeDefinition) { } override func generateCustomOperatorDefinition(_ customOperator: CGCustomOperatorDefinition, type: CGTypeDefinition) { } // // Type References // internal func objcTypeRefereneIsPointer(_ type: CGTypeReference) -> Boolean { if let type = type as? CGNamedTypeReference { return type.IsClassType } else if let type = type as? CGPredefinedTypeReference { return type.Kind == CGPredefinedTypeKind.String || type.Kind == CGPredefinedTypeKind.Object } return false } override func generateNamedTypeReference(_ type: CGNamedTypeReference, ignoreNullability: Boolean) { super.generateNamedTypeReference(type, ignoreNamespace: true, ignoreNullability: ignoreNullability) if type.IsClassType && !ignoreNullability { Append(" *") } } override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { switch (type.Kind) { case .Int: Append("NSInteger") case .UInt: Append("NSUInteger") case .Int8: Append("int8") case .UInt8: Append("uint8") case .Int16: Append("int16") case .UInt16: Append("uint16") case .Int32: Append("int32") case .UInt32: Append("uint32") case .Int64: Append("int64") case .UInt64: Append("uint64") case .IntPtr: Append("NSInteger") case .UIntPtr: Append("NSUInteger") case .Single: Append("float") case .Double: Append("double") case .Boolean: Append("BOOL") case .String: if ignoreNullability { Append("NSString") } else { Append("NSString *") } case .AnsiChar: Append("char") case .UTF16Char: Append("UInt16") case .UTF32Char: Append("UInt32") case .Dynamic: Append("id") case .InstanceType: Append("instancetype") case .Void: Append("void") case .Object: if ignoreNullability { Append("NSObject") } else { Append("NSObject *") } case .Class: Append("Class") } } override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { let block = type.Block if let returnType = block.ReturnType { generateTypeReference(returnType) } else { Append("void") } Append("(^)(") for p in 0 ..< block.Parameters.Count { if p > 0 { Append(", ") } if let type = block.Parameters[p].`Type` { generateTypeReference(type) } else { Append("id") } } Append(")") } override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) { Append("__kindof ") generateTypeReference(type.`Type`) } override func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) { } override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { } }
bsd-3-clause
ef330649221fc93e2e6ac3f8e284792e
25.356784
141
0.710186
3.739572
false
false
false
false
fizx/jane
swift/Jane/Sources/Jane/Storage.swift
1
2897
import Algorithm import Foundation import Promises struct Index: Hashable { var name: BytesWrapper var unique: Bool = false } protocol StorageMapper { associatedtype V func toValue(v: V) -> BytesWrapper func primaryIndex(v: V) -> BytesWrapper? func secondaryIndexes(v: V) -> [Index: BytesWrapper] } protocol StorageMappable { func toValue() -> BytesWrapper func primaryIndex() -> BytesWrapper? func secondaryIndexes() -> [Index: BytesWrapper] } protocol RawStorage { func get(key: BytesWrapper) -> Promise<BytesWrapper?> func range(from: BytesWrapper, to: BytesWrapper, inclusive: Bool) -> Promise<[BytesWrapper]> func put(key: BytesWrapper, value: BytesWrapper) -> Promise<Void> func remove(key: BytesWrapper) -> Promise<Void> func transactionally(key: BytesWrapper, transaction: @escaping () -> Promise<Void>) -> Promise<Void> } struct BytesWrapper: Comparable, Equatable, Hashable, Codable { let array: [UInt8] init(data: Data) { self.array = [UInt8](data) } init(array: [UInt8]) { self.array = array } init(string: String) { self.array = Array(string.utf8) } func toData() -> Data { return Data(self.array) } static func < (lhs: BytesWrapper, rhs: BytesWrapper) -> Bool { for (l, r) in zip(lhs.array, rhs.array) { if (l < r) { return true } else if (l > r) { return false } } return lhs.array.count < rhs.array.count } } class MemoryStorage: RawStorage { private var raw = SortedDictionary<BytesWrapper, BytesWrapper>() func get(key: BytesWrapper) -> Promise<BytesWrapper?>{ return Promise(raw.findValue(for: key)) } func range(from: BytesWrapper, to: BytesWrapper, inclusive: Bool) -> Promise<[BytesWrapper]> { var answers: [BytesWrapper] = [] for key in raw.keys { if key < from || key > to { continue } if (!inclusive && key == to) { continue } if let value = raw.findValue(for: key) { answers.append(value) } } return Promise(answers) } func put(key: BytesWrapper, value: BytesWrapper) -> Promise<Void> { if raw.findValue(for: key) != nil { raw.update(value: value, for: key) } else { raw.insert(value: value, for: key) } return Promise(()) } func remove(key: BytesWrapper) -> Promise<Void> { raw.removeValue(for: key) return Promise(()) } // It's a lie. We don't do anything transactionally. func transactionally(key: BytesWrapper, transaction: @escaping () -> Promise<Void>) -> Promise<Void> { return transaction() } }
mit
1cd5b432be6268b0289839b913199775
27.401961
106
0.57853
4.051748
false
false
false
false
m-schmidt/Refracto
Refracto/FormulaInputCell.swift
1
2144
// FormulaCell.swift import UIKit class FormulaInputCell: UICollectionViewCell { static let identifier = "FormulaInputCell" private let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { label.backgroundColor = Colors.formulaBackground label.textColor = Colors.formulaForeground label.textAlignment = .center label.lineBreakMode = .byTruncatingTail label.numberOfLines = 1 label.isAccessibilityElement = false embedd(view: label) } override var isSelected: Bool { didSet { let text = label.attributedText?.string ?? "" self.configure(text: text) } } func configure(text: String) { let attributes = Self.textAttributes(selected: self.isSelected) let attributedText = NSAttributedString(string: text, attributes: attributes) UIView.transition(with: label, duration: 0.2, options: .transitionCrossDissolve, animations: { [weak self] in self?.label.attributedText = attributedText }) } } // MARK: - Text Attributes fileprivate let fontSize: CGFloat = 17.0 extension FormulaInputCell { static func lineHeight() -> CGFloat { let standardHeight = UIFont.systemFont(ofSize: fontSize, weight: .semibold).lineHeight let selectedHeight = UIFont.systemFont(ofSize: fontSize, weight: .bold).lineHeight return max(standardHeight, selectedHeight) } static func textAttributes(selected: Bool) -> [NSAttributedString.Key:Any] { if selected { return [ .font: UIFont.systemFont(ofSize: fontSize, weight: .bold), .foregroundColor: Colors.accent ] } else { return [ .font: UIFont.systemFont(ofSize: fontSize, weight: .semibold), .foregroundColor: Colors.formulaForeground ] } } }
bsd-3-clause
66e258e37f83de4852df817320a0de22
30.072464
94
0.617071
4.986047
false
false
false
false
DerLobi/Depressed
Depressed?/ViewModel/EvaluationViewModel.swift
1
5120
import Foundation /// Viewmodel transforming `Evaluation` model data for presentation to the user. public struct EvaluationViewModel { /// Diagnosis of how severe the depression is. public let diagnosis: String /// Phrase describing the diagnosis. public let diagnosisText: String /// Explanation that relates the users answers to the diagnosis. public let explanationText: String /// Warning message in case the user answered that they had thoughts /// about suicide or self harm. public let suicidalText: String? /// The total score of the user's answers. public let score: String /// Whether the score should be displayed. If a depressive disorder is not /// considered, we don't want to display the score. public let shouldDisplayScore: Bool /// The titles of the questions the user has answered and the corresponding score. public let answers: [(String, String)] /// The viewmodel for the 'Find Help' information. public let findingHelpViewModel: FindingHelpViewModel? /// Whether or not to display the 'Find Help' information. public var shouldDisplayFindingHelpInformation: Bool { return findingHelpViewModel != nil } /// Whether or not the user should be prompted to rate the app or leave a review public var shouldPromptForReview: Bool { if ProcessInfo.processInfo.environment["UITests"]?.isEmpty == false { return false } return settings.didShowRatingPrompt == false && settings.numberOfFinishedSurveys > 1 } private let settings: SettingsProtocol /// Creates a new view model from the given evaluation. /// /// - parameter evaluation: An `Evaluation`. /// - parameter findingHelpInformation: A `FindingHelpInformation` or `nil` if none is available. /// - parameter settings: An instance conforming to `SettingsProtocol`. Used to determine if we should prompt for a review /// /// - returns: a newly initialized `EvaluationViewModel` instance public init(evaluation: EvaluationType, findingHelpInformation: FindingHelpInformation?, settings: SettingsProtocol) { self.settings = settings if let findingHelpInformation = findingHelpInformation { findingHelpViewModel = FindingHelpViewModel(info: findingHelpInformation) } else { findingHelpViewModel = nil } if evaluation.depressiveDisorderConsidered { explanationText = NSLocalizedString("explanation_depression", comment: "") switch evaluation.severity { case .noDepression: diagnosis = NSLocalizedString("diagnosis_no_depression", comment: "") diagnosisText = NSLocalizedString("diagnosis_text_no_depression", comment: "") case .minimalDepression: diagnosis = NSLocalizedString("diagnosis_minimal_depression", comment: "") diagnosisText = NSLocalizedString("diagnosis_text_minimal_depression", comment: "") case .mildDepression: diagnosis = NSLocalizedString("diagnosis_mild_depression", comment: "") diagnosisText = NSLocalizedString("diagnosis_text_mild_depression", comment: "") case .moderateDepression: diagnosis = NSLocalizedString("diagnosis_moderate_depression", comment: "") diagnosisText = NSLocalizedString("diagnosis_text_moderate_depression", comment: "") case .moderatelySevereDepression: diagnosis = NSLocalizedString("diagnosis_moderately_severe_depression", comment: "") diagnosisText = NSLocalizedString("diagnosis_text_moderately_severe_depression", comment: "") case .severeDepression: diagnosis = NSLocalizedString("diagnosis_severe_depression", comment: "") diagnosisText = NSLocalizedString("diagnosis_text_severe_depression", comment: "") } } else { diagnosis = NSLocalizedString("diagnosis_no_depression", comment: "") diagnosisText = NSLocalizedString("diagnosis_text_no_depression", comment: "") if evaluation.numberOfAnswersCritical { explanationText = NSLocalizedString("explanation_no_depression_first_questions_not_critical", comment: "") } else { explanationText = NSLocalizedString("explanation_no_depression_not_enough_answers_critical", comment: "") } } if evaluation.suicidal { suicidalText = NSLocalizedString("suicidal_text", comment: "") } else { suicidalText = nil } shouldDisplayScore = evaluation.depressiveDisorderConsidered score = String(evaluation.score) answers = evaluation.answers.map { ($0.question.title, String($0.answerScore.rawValue)) } } /// Called when the viewController asked the system to request a review from the user public func didShowReviewPrompt() { settings.didShowRatingPrompt = true } }
mit
99d503680d311668309729f496fb346e
42.02521
141
0.666797
5.140562
false
false
false
false
weareyipyip/SwiftStylable
Sources/SwiftStylable/Classes/Style/Stylers/ForegroundStyler.swift
1
1913
// // ButtonStyleSet.swift // SwiftStylable // // Created by Marcel Bloemendaal on 17/04/2018. // import Foundation class ForegroundStyler : Styler { private weak var _view: ForegroundStylable? private var _canBeHighlighted:Bool private var _canBeSelected:Bool private var _canBeDisabled:Bool // ----------------------------------------------------------------------------------------------------------------------- // // MARK: Initializers // // ----------------------------------------------------------------------------------------------------------------------- init(_ view: ForegroundStylable, canBeHighlighted:Bool = false, canBeSelected:Bool = false, canBeDisabled:Bool = false) { self._view = view self._canBeHighlighted = canBeHighlighted self._canBeSelected = canBeSelected self._canBeDisabled = canBeDisabled } // ----------------------------------------------------------------------------------------------------------------------- // // MARK: Public methods // // ----------------------------------------------------------------------------------------------------------------------- open func applyStyle(_ style:Style) { guard let view = self._view else { return } if let foregroundColor = style.foregroundStyle.foregroundColor { view.foregroundColor = foregroundColor } if self._canBeHighlighted { if let highlightedForegroundColor = style.foregroundStyle.highlightedForegroundColor { view.highlightedForegroundColor = highlightedForegroundColor } } if self._canBeSelected { if let selectedForegroundColor = style.foregroundStyle.selectedForegroundColor { view.selectedForegroundColor = selectedForegroundColor } } if self._canBeDisabled { if let disabledForegroundColor = style.foregroundStyle.disabledForegroundColor { view.disabledForegroundColor = disabledForegroundColor } } } }
mit
1684cf36635f78f68ec1aae3ef3df811
28.430769
123
0.548353
5.241096
false
false
false
false
WilliamDenniss/native-apps-ios-concept
SigninVC/WebViewWKViewController.swift
1
1320
// // WebViewWKViewController.swift // SigninVC // // Created by William Denniss on 6/27/15. // import UIKit import WebKit class WebViewWKViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! var urlToLoad: NSURL? = nil; @IBOutlet weak var activityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView() webView.navigationDelegate = self self.view.insertSubview(webView, atIndex: 0) webView.frame = self.view.frame webView.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+50, self.view.frame.size.width, self.view.frame.size.height) if (urlToLoad != nil) { loadURL(urlToLoad!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadURL(_urlToLoad: NSURL) { urlToLoad = _urlToLoad if (webView != nil) { webView.loadRequest(NSURLRequest(URL: urlToLoad!)) } } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { activityIndicator.stopAnimating() } @IBAction func onDone(sender: AnyObject) { self.presentingViewController!.dismissViewControllerAnimated(true, completion:nil) } }
apache-2.0
e9caee2183daed7b6523a36010fa06df
21.758621
142
0.708333
4.342105
false
false
false
false
ahoppen/swift
test/SILGen/convenience_init_peer_delegation.swift
17
9819
// RUN: %target-swift-emit-silgen -enable-objc-interop -disable-objc-attr-requires-foundation-module %s | %FileCheck %s class X { init() { } // Convenience inits must dynamically dispatch designated inits... // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfC // CHECK: class_method {{%.*}}, #X.init!allocator convenience init(convenience: ()) { self.init() } // ...but can statically invoke peer convenience inits // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC17doubleConvenienceACyt_tcfC // CHECK: function_ref @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfC convenience init(doubleConvenience: ()) { self.init(convenience: ()) } // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s32convenience_init_peer_delegation1XC8requiredACyt_tcfC required init(required: ()) { } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC19requiredConvenienceACyt_tcfC required convenience init(requiredConvenience: ()) { self.init(required: ()) } // Convenience inits must dynamically dispatch required peer convenience inits // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC25requiredDoubleConvenienceACyt_tcfC // CHECK: class_method {{%.*}}, #X.init!allocator required convenience init(requiredDoubleConvenience: ()) { self.init(requiredDoubleConvenience: ()) } } class Y: X { // This is really a designated initializer. Ensure that we don't try to // treat it as an override of the base class convenience initializer (and // override a nonexistent vtable entry) just because it has the same name. init(convenience: ()) { super.init() } // Conversely, a designated init *can* be overridden as a convenience // initializer. override convenience init() { self.init(convenience: ()) } required init(required: ()) { super.init() } required init(requiredConvenience: ()) { super.init() } required init(requiredDoubleConvenience: ()) { super.init() } } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation11invocations2xtyAA1XCm_tF func invocations(xt: X.Type) { // CHECK: function_ref @$s32convenience_init_peer_delegation1XCACycfC _ = X() // CHECK: function_ref @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfC _ = X(convenience: ()) // CHECK: function_ref @$s32convenience_init_peer_delegation1XC17doubleConvenienceACyt_tcfC _ = X(doubleConvenience: ()) // CHECK: function_ref @$s32convenience_init_peer_delegation1XC8requiredACyt_tcfC _ = X(required: ()) // CHECK: function_ref @$s32convenience_init_peer_delegation1XC19requiredConvenienceACyt_tcfC _ = X(requiredConvenience: ()) // CHECK: function_ref @$s32convenience_init_peer_delegation1XC25requiredDoubleConvenienceACyt_tcfC _ = X(requiredDoubleConvenience: ()) // CHECK: class_method {{%.*}}, #X.init!allocator _ = xt.init(required: ()) // CHECK: class_method {{%.*}}, #X.init!allocator _ = xt.init(requiredConvenience: ()) // CHECK: class_method {{%.*}}, #X.init!allocator _ = xt.init(requiredDoubleConvenience: ()) } class ObjCBase { init(swift: ()) {} @objc(initAsObjC) init(objc: ()) {} // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfC // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfc : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfC' // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfc // CHECK: class_method {{%.+}} : $@thick ObjCBase.Type, #ObjCBase.init!allocator // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfc' // CHECK-LABEL: sil hidden [thunk] [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfcTo // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfc : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfcTo' @objc convenience init(objcToSwift: ()) { self.init(swift: ()) } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC07swiftToE1CACyt_tcfC // CHECK: class_method %0 : $@thick ObjCBase.Type, #ObjCBase.init!allocator // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC07swiftToE1CACyt_tcfC' convenience init(swiftToObjC: ()) { self.init(objc: ()) } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE1CACyt_tcfC // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE1CACyt_tcfc : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC06objcToE1CACyt_tcfC' // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE1CACyt_tcfc // CHECK: objc_method {{%.+}} : $ObjCBase, #ObjCBase.init!initializer.foreign // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC06objcToE1CACyt_tcfc' // CHECK-LABEL: sil hidden [thunk] [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE1CACyt_tcfcTo // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE1CACyt_tcfc : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC06objcToE1CACyt_tcfcTo' @objc convenience init(objcToObjC: ()) { self.init(objc: ()) } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC22objcToSwiftConvenienceACyt_tcfC // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC22objcToSwiftConvenienceACyt_tcfc : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC22objcToSwiftConvenienceACyt_tcfC' // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC22objcToSwiftConvenienceACyt_tcfc // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC07swiftToE1CACyt_tcfC : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC22objcToSwiftConvenienceACyt_tcfc' // CHECK-LABEL: sil hidden [thunk] [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC22objcToSwiftConvenienceACyt_tcfcTo // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC22objcToSwiftConvenienceACyt_tcfc : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC22objcToSwiftConvenienceACyt_tcfcTo' @objc convenience init(objcToSwiftConvenience: ()) { self.init(swiftToObjC: ()) } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC07swiftToE12CConvenienceACyt_tcfC // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC11objcToSwiftACyt_tcfC // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC07swiftToE12CConvenienceACyt_tcfC' convenience init(swiftToObjCConvenience: ()) { self.init(objcToSwift: ()) } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE12CConvenienceACyt_tcfC // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE12CConvenienceACyt_tcfc : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC06objcToE12CConvenienceACyt_tcfC' // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE12CConvenienceACyt_tcfc // CHECK: objc_method {{%.+}} : $ObjCBase, #ObjCBase.init!initializer.foreign // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC06objcToE12CConvenienceACyt_tcfc' // CHECK-LABEL: sil hidden [thunk] [ossa] @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE12CConvenienceACyt_tcfcTo // CHECK: function_ref @$s32convenience_init_peer_delegation8ObjCBaseC06objcToE12CConvenienceACyt_tcfc : // CHECK: end sil function '$s32convenience_init_peer_delegation8ObjCBaseC06objcToE12CConvenienceACyt_tcfcTo' @objc convenience init(objcToObjCConvenience: ()) { self.init(objcToObjC: ()) } } // CHECK-LABEL: sil_vtable X // -- designated init() // CHECK: @$s32convenience_init_peer_delegation1XCACycfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XCACycfc // -- no unrequired convenience inits // CHECK-NOT: @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfc // CHECK-NOT: @$s32convenience_init_peer_delegation1XC17doubleConvenienceACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC17doubleConvenienceACyt_tcfc // -- designated init(required:) // CHECK: @$s32convenience_init_peer_delegation1XC8requiredACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC8requiredACyt_tcfc // -- convenience init(requiredConvenience:) // CHECK: @$s32convenience_init_peer_delegation1XC19requiredConvenienceACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC19requiredConvenienceACyt_tcfc // -- convenience init(requiredDoubleConvenience:) // CHECK: @$s32convenience_init_peer_delegation1XC25requiredDoubleConvenienceACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC25requiredDoubleConvenienceACyt_tcfc // CHECK-LABEL: sil_vtable Y // -- designated init() overridden by convenience init // CHECK: @$s32convenience_init_peer_delegation1YCACycfC // CHECK-NOT: @$s32convenience_init_peer_delegation1YCACycfc // -- Y.init(convenience:) is a designated init // CHECK: @$s32convenience_init_peer_delegation1YC0A0ACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1YC0A0ACyt_tcfc
apache-2.0
0b09fc55aa8d3087f198e7fabe62a8a1
54.162921
126
0.750178
3.588816
false
false
false
false
StanZabroda/Hydra
Hydra/HRAllMusicCell.swift
1
2979
import UIKit class HRAllMusicCell: UITableViewCell { var audioAristLabel : AttributedLabel var audioTitleLabel : AttributedLabel var audioDurationTime : AttributedLabel! var progressView : UIProgressView! var downloadButton : UIButton! var allMusicController : AllMusicController! var audioModel : HRAudioItemModel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.audioTitleLabel = AttributedLabel() self.audioTitleLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 15)! self.audioTitleLabel.textColor = UIColor.blackColor() self.audioTitleLabel.backgroundColor = UIColor.whiteColor() self.audioAristLabel = AttributedLabel() self.audioAristLabel.font = UIFont(name: "HelveticaNeue-Light", size: 13)! self.audioAristLabel.textColor = UIColor.grayColor() self.audioAristLabel.backgroundColor = UIColor.whiteColor() self.progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Default) self.progressView.tintColor = UIColor.blackColor() self.progressView.hidden = true self.downloadButton = UIButton(type: UIButtonType.System) self.downloadButton.setImage(UIImage(named: "downloadButton"), forState: UIControlState.Normal) self.downloadButton.tintColor = UIColor.blackColor() super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier) self.downloadButton.addTarget(self, action: "startDownload", forControlEvents: UIControlEvents.TouchUpInside) self.contentView.addSubview(self.audioAristLabel) self.contentView.addSubview(self.audioTitleLabel) self.contentView.addSubview(self.progressView) self.contentView.addSubview(self.downloadButton) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() //audioTitleLabel self.audioTitleLabel.frame = CGRectMake(self.separatorInset.left, 10, screenSizeWidth-70, 20) self.audioAristLabel.frame = CGRectMake(self.separatorInset.left, 40, screenSizeWidth-70, 20) self.progressView.frame = CGRectMake(0, self.contentView.frame.height-2, self.contentView.frame.width, 2) self.downloadButton.frame = CGRectMake(self.contentView.frame.width-65, 5, 60, 60) } override func prepareForReuse() { super.prepareForReuse() self.progressView.hidden = true //self.avatar.image = nil } func startDownload() { self.downloadButton.hidden = true self.allMusicController.downloadAudio(self.audioModel, progressView: self.progressView) } }
mit
2d9514c851c09b0d861415cdc7fd2641
37.192308
117
0.671031
5.189895
false
false
false
false
s-aska/Justaway-for-iOS
Justaway/EditorViewController.swift
1
17699
import UIKit import EventBox import Photos import Async import MediaPlayer class EditorViewController: UIViewController { struct Static { static let instance = EditorViewController() } struct UploadImage { let data: Data let asset: PHAsset } // MARK: Properties @IBOutlet weak var replyToContainerView: BackgroundView! @IBOutlet weak var replyToIconImageView: UIImageView! @IBOutlet weak var replyToNameLabel: DisplayNameLable! @IBOutlet weak var replyToScreenNameLabel: ScreenNameLable! @IBOutlet weak var replyToStatusLabel: StatusLable! @IBOutlet weak var replyToStatusLabelHeightConstraint: NSLayoutConstraint! @IBOutlet weak var replyCancelButton: MenuButton! @IBOutlet weak var countLabel: MenuLable! @IBOutlet weak var containerView: UIView! @IBOutlet weak var containerViewButtomConstraint: NSLayoutConstraint! // Used to adjust the height when the keyboard hides and shows. @IBOutlet weak var textView: AutoExpandTextView! @IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint! // Used to AutoExpandTextView @IBOutlet weak var imageContainerView: UIScrollView! @IBOutlet weak var imageContainerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var imageContentView: UIView! @IBOutlet weak var collectionView: ImagePickerCollectionView! @IBOutlet weak var collectionHeightConstraint: NSLayoutConstraint! @IBOutlet weak var collectionMenuView: MenuView! @IBOutlet weak var imageView1: UIImageView! @IBOutlet weak var imageView2: UIImageView! @IBOutlet weak var imageView3: UIImageView! @IBOutlet weak var imageView4: UIImageView! @IBOutlet weak var halfButton: MenuButton! let refreshControl = UIRefreshControl() var images: [UploadImage] = [] var imageViews: [UIImageView] = [] var picking = false let imageContainerHeightConstraintDefault: CGFloat = 100 override var nibName: String { return "EditorViewController" } var inReplyToStatusId: String? var messageTo: TwitterUser? // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureEvent() Async.main { self.view.isHidden = false self.show() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) EventBox.off(self) } // MARK: - Configuration func configureView() { view.isHidden = true textView.configure(heightConstraint: textViewHeightConstraint) imageViews = [imageView1, imageView2, imageView3, imageView4] for imageView in imageViews { imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill imageView.isUserInteractionEnabled = true imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(EditorViewController.removeImage(_:)))) } replyToIconImageView.layer.cornerRadius = 3 replyToIconImageView.clipsToBounds = true resetPickerController() configureTextView() configureCollectionView() } func configureTextView() { // swiftlint:disable:next force_try let isKatakana = try! NSRegularExpression(pattern: "[\\u30A0-\\u30FF]", options: .caseInsensitive) textView.callback = { [weak self] in guard let `self` = self else { return } let count = TwitterText.count(self.textView.text, hasImage: self.images.count > 0) self.countLabel.text = String(140 - count) self.halfButton.isHidden = isKatakana.firstMatch( in: self.textView.text, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.textView.text.utf16.count) ) == nil } } func configureCollectionView() { collectionView.callback = { (asset: PHAsset) in let options = PHImageRequestOptions() options.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat options.isSynchronous = false options.isNetworkAccessAllowed = true PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData: Data?, dataUTI: String?, orientation: UIImageOrientation, info: [AnyHashable: Any]?) -> Void in if let imageData = imageData { if self.images.count > 0 { var i = 0 for image in self.images { if imageData == image.data { self.removeImageIndex(i) return } i += 1 } } let i = self.images.count if i >= 4 { return } self.images.append(UploadImage(data: imageData, asset: asset)) self.imageViews[i].image = UIImage(data: imageData) self.collectionView.highlightRows = self.images.map({ $0.asset }) self.collectionView.reloadHighlight() if self.imageContainerHeightConstraint.constant == 0 { self.imageContainerHeightConstraint.constant = self.imageContainerHeightConstraintDefault UIView.animate(withDuration: 0.2, animations: { () -> Void in self.view.layoutIfNeeded() }) } } }) } refreshControl.addTarget(self, action: #selector(loadImages), for: UIControlEvents.valueChanged) collectionView.addSubview(refreshControl) collectionView.alwaysBounceVertical = true } func loadImages() { Async.background { () -> Void in let options = PHFetchOptions() options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] var rows = [PHAsset]() let assets: PHFetchResult = PHAsset.fetchAssets(with: .image, options: options) assets.enumerateObjects({ (asset, index, stop) -> Void in rows.append(asset as PHAsset) }) self.collectionView.rows = rows Async.main { () -> Void in self.collectionView.reloadData() self.refreshControl.endRefreshing() } } } func configureEvent() { EventBox.onMainThread(self, name: NSNotification.Name.UIKeyboardWillShow) { n in self.keyboardWillChangeFrame(n, showsKeyboard: true) } EventBox.onMainThread(self, name: NSNotification.Name.UIKeyboardWillHide) { n in self.keyboardWillChangeFrame(n, showsKeyboard: false) } } func resetPickerController() { images = [] for imageView in imageViews { imageView.image = nil } collectionView.rows = [] collectionView.highlightRows = [] collectionHeightConstraint.constant = 0 imageContainerHeightConstraint.constant = 0 collectionMenuView.isHidden = true } // MARK: - Keyboard Event Notifications func keyboardWillChangeFrame(_ notification: Notification, showsKeyboard: Bool) { let userInfo = notification.userInfo! // swiftlint:disable force_cast let animationDuration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey]as! NSValue).cgRectValue // swiftlint:enable force_cast if showsKeyboard { let orientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation if orientation.isLandscape { containerViewButtomConstraint.constant = keyboardScreenEndFrame.size.width } else { containerViewButtomConstraint.constant = keyboardScreenEndFrame.size.height } collectionHeightConstraint.constant = 0 collectionMenuView.isHidden = true } else { // en: UIKeyboardWillHideNotification occurs when you scroll through the conversion candidates in iOS9 // ja: iOS9 では変換候補をスクロールする際 UIKeyboardWillHideNotification が発生する if !textView.text.isEmpty && !picking { return } containerViewButtomConstraint.constant = 0 } self.view.setNeedsUpdateConstraints() UIView.animate(withDuration: animationDuration, delay: 0, options: .beginFromCurrentState, animations: { self.containerView.alpha = showsKeyboard || self.picking ? 1 : 0 self.view.layoutIfNeeded() }, completion: { finished in if !showsKeyboard && !self.picking { self.view.removeFromSuperview() } }) } // MARK: - Actions @IBAction func hide(_ sender: UIButton) { if picking { picking = false textView.becomeFirstResponder() } else { hide() } } @IBAction func image(_ sender: UIButton) { image() } @IBAction func music(_ sender: UIButton) { guard let item = MPMusicPlayerController.systemMusicPlayer().nowPlayingItem else { if let url = URL.init(string: "googleplaymusic://") { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) return } } ErrorAlert.show("Missing music", message: "Sorry, support the apple music only") return } var text = "" if let title = item.title { text += title } if let artist = item.artist { text += " - " + artist } if !text.isEmpty { textView.text = "#NowPlaying " + text textView.selectedRange = NSRange.init(location: 0, length: 0) } if let artwork = item.value(forProperty: MPMediaItemPropertyArtwork) as? MPMediaItemArtwork { if let image = artwork.image(at: artwork.bounds.size), let imageData = UIImagePNGRepresentation(image) { let i = self.images.count if i >= 4 { return } self.images.append(UploadImage(data: imageData, asset: PHAsset())) self.imageViews[i].image = image if self.imageContainerHeightConstraint.constant == 0 { self.imageContainerHeightConstraint.constant = self.imageContainerHeightConstraintDefault UIView.animate(withDuration: 0.2, animations: { () -> Void in self.view.layoutIfNeeded() }) } } } } @IBAction func half(_ sender: AnyObject) { let text = NSMutableString(string: textView.text) as CFMutableString CFStringTransform(text, nil, kCFStringTransformFullwidthHalfwidth, false) textView.text = text as String } @IBAction func send(_ sender: UIButton) { let text = textView.text if (text?.isEmpty)! && images.count == 0 { hide() } else { if let messageTo = messageTo { Twitter.postDirectMessage(text!, userID: messageTo.userID) } else { Twitter.statusUpdate(text!, inReplyToStatusID: self.inReplyToStatusId, images: self.images.map({ $0.data }), mediaIds: []) } hide() } } func removeImage(_ sender: UITapGestureRecognizer) { guard let index = sender.view?.tag else { return } if images.count <= index { return } removeImageIndex(index) } func removeImageIndex(_ index: Int) { images.remove(at: index) var i = 0 for imageView in imageViews { if images.count > i { imageView.image = UIImage(data: images[i].data) } else { imageView.image = nil } i += 1 } if images.count == 0 { imageContainerHeightConstraint.constant = 0 UIView.animate(withDuration: 0.2, animations: { () -> Void in self.view.layoutIfNeeded() }) } collectionView.highlightRows = images.map({ $0.asset }) collectionView.reloadHighlight() } @IBAction func replyCancel(_ sender: UIButton) { if let inReplyToStatusId = inReplyToStatusId { let pattern = " ?https?://twitter\\.com/[0-9a-zA-Z_]+/status/\(inReplyToStatusId)" textView.text = textView.text.replacingOccurrences(of: pattern, with: "", options: .regularExpression, range: nil) } inReplyToStatusId = nil replyToContainerView.isHidden = true textView.text = textView.text.replacingOccurrences(of: "^.*@[0-9a-zA-Z_]+ *", with: "", options: .regularExpression, range: nil) } func image() { if messageTo != nil { ErrorAlert.show("Not supported image with DirectMessage") return } picking = true let height = UIApplication.shared.keyWindow?.frame.height ?? 480 collectionHeightConstraint.constant = height - imageContainerHeightConstraintDefault - 10 collectionMenuView.isHidden = false textView.resignFirstResponder() if collectionView.rows.count == 0 { loadImages() } } func show() { textView.becomeFirstResponder() textView.callback?() } func hide() { picking = false inReplyToStatusId = nil messageTo = nil replyToContainerView.isHidden = true textView.reset() resetPickerController() if textView.isFirstResponder { textView.resignFirstResponder() } else { view.removeFromSuperview() } } class func show(_ text: String? = nil, range: NSRange? = nil, inReplyToStatus: TwitterStatus? = nil, messageTo: TwitterUser? = nil) { if let vc = ViewTools.frontViewController() { Static.instance.view.frame = vc.view.frame Static.instance.resetPickerController() Static.instance.textView.text = text ?? "" Static.instance.countLabel.isHidden = messageTo != nil Static.instance.replyCancelButton.isHidden = messageTo != nil Static.instance.messageTo = messageTo if let inReplyToStatus = inReplyToStatus { Static.instance.inReplyToStatusId = inReplyToStatus.statusID Static.instance.replyToNameLabel.text = inReplyToStatus.user.name Static.instance.replyToScreenNameLabel.text = "@" + inReplyToStatus.user.screenName Static.instance.replyToStatusLabel.text = inReplyToStatus.text Static.instance.replyToStatusLabelHeightConstraint.constant = measure(inReplyToStatus.text as NSString, fontSize: Static.instance.replyToStatusLabel.font?.pointSize ?? 12, wdith: Static.instance.replyToStatusLabel.frame.size.width) Static.instance.replyToContainerView.isHidden = false if let url = inReplyToStatus.user.profileImageURL { ImageLoaderClient.displayUserIcon(url, imageView: Static.instance.replyToIconImageView) } } else if let messageTo = messageTo { Static.instance.inReplyToStatusId = nil Static.instance.replyToNameLabel.text = messageTo.name Static.instance.replyToScreenNameLabel.text = "@" + messageTo.screenName Static.instance.replyToStatusLabel.text = "" Static.instance.replyToStatusLabelHeightConstraint.constant = 0 Static.instance.replyToContainerView.isHidden = false if let url = messageTo.profileImageURL { ImageLoaderClient.displayUserIcon(url, imageView: Static.instance.replyToIconImageView) } } else { Static.instance.inReplyToStatusId = nil Static.instance.replyToContainerView.isHidden = true } if let selectedRange = range { Static.instance.textView.selectedRange = selectedRange } vc.view.addSubview(Static.instance.view) } } class func hide() { if Static.instance.textView == nil { return } Static.instance.hide() } class func measure(_ text: NSString, fontSize: CGFloat, wdith: CGFloat) -> CGFloat { return ceil(text.boundingRect( with: CGSize.init(width: wdith, height: 0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: fontSize)], context: nil).size.height) } }
mit
2d708784d22ffd3023da47d1a3e185be
37.556769
138
0.603035
5.441911
false
false
false
false
minikin/Algorithmics
Pods/Charts/Charts/Classes/Renderers/ChartYAxisRenderer.swift
5
16754
// // ChartYAxisRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class ChartYAxisRenderer: ChartAxisRendererBase { public var yAxis: ChartYAxis? public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, transformer: transformer) self.yAxis = yAxis } /// Computes the axis values. public func computeAxis(var yMin yMin: Double, var yMax: Double) { guard let yAxis = yAxis else { return } // calculate the starting and entry point of the y-labels (depending on // zoom / contentrect bounds) if (viewPortHandler.contentWidth > 10.0 && !viewPortHandler.isFullyZoomedOutY) { let p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) let p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) if (!yAxis.isInverted) { yMin = Double(p2.y) yMax = Double(p1.y) } else { yMin = Double(p1.y) yMax = Double(p2.y) } } computeAxisValues(min: yMin, max: yMax) } /// Sets up the y-axis labels. Computes the desired number of labels between /// the two given extremes. Unlike the papareXLabels() method, this method /// needs to be called upon every refresh of the view. public func computeAxisValues(min min: Double, max: Double) { guard let yAxis = yAxis else { return } let yMin = min let yMax = max let labelCount = yAxis.labelCount let range = abs(yMax - yMin) if (labelCount == 0 || range <= 0) { yAxis.entries = [Double]() return } let rawInterval = range / Double(labelCount) var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval)) let intervalMagnitude = pow(10.0, round(log10(interval))) let intervalSigDigit = (interval / intervalMagnitude) if (intervalSigDigit > 5) { // Use one order of magnitude higher, to avoid intervals like 0.9 or 90 interval = floor(10.0 * intervalMagnitude) } // force label count if yAxis.isForceLabelsEnabled { let step = Double(range) / Double(labelCount - 1) if yAxis.entries.count < labelCount { // Ensure stops contains at least numStops elements. yAxis.entries.removeAll(keepCapacity: true) } else { yAxis.entries = [Double]() yAxis.entries.reserveCapacity(labelCount) } var v = yMin for (var i = 0; i < labelCount; i++) { yAxis.entries.append(v) v += step } } else { // no forced count // if the labels should only show min and max if (yAxis.isShowOnlyMinMaxEnabled) { yAxis.entries = [yMin, yMax] } else { let first = ceil(Double(yMin) / interval) * interval let last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval) var f: Double var i: Int var n = 0 for (f = first; f <= last; f += interval) { ++n } if (yAxis.entries.count < n) { // Ensure stops contains at least numStops elements. yAxis.entries = [Double](count: n, repeatedValue: 0.0) } else if (yAxis.entries.count > n) { yAxis.entries.removeRange(n..<yAxis.entries.count) } for (f = first, i = 0; i < n; f += interval, ++i) { if (f == 0.0) { // Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0) f = 0.0 } yAxis.entries[i] = Double(f) } } } } /// draws the y-axis labels to the screen public override func renderAxisLabels(context context: CGContext) { guard let yAxis = yAxis else { return } if (!yAxis.isEnabled || !yAxis.isDrawLabelsEnabled) { return } let xoffset = yAxis.xOffset let yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var xPos = CGFloat(0.0) var textAlign: NSTextAlignment if (dependency == .Left) { if (labelPosition == .OutsideChart) { textAlign = .Right xPos = viewPortHandler.offsetLeft - xoffset } else { textAlign = .Left xPos = viewPortHandler.offsetLeft + xoffset } } else { if (labelPosition == .OutsideChart) { textAlign = .Left xPos = viewPortHandler.contentRight + xoffset } else { textAlign = .Right xPos = viewPortHandler.contentRight - xoffset } } drawYLabels(context: context, fixedPosition: xPos, offset: yoffset - yAxis.labelFont.lineHeight, textAlign: textAlign) } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(context context: CGContext) { guard let yAxis = yAxis else { return } if (!yAxis.isEnabled || !yAxis.drawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, yAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, yAxis.axisLineWidth) if (yAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, yAxis.axisLineDashPhase, yAxis.axisLineDashLengths, yAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (yAxis.axisDependency == .Left) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } else { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } /// draws the y-labels on the specified x-position internal func drawYLabels(context context: CGContext, fixedPosition: CGFloat, offset: CGFloat, textAlign: NSTextAlignment) { guard let yAxis = yAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor let valueToPixelMatrix = transformer.valueToPixelMatrix var pt = CGPoint() for (var i = 0; i < yAxis.entryCount; i++) { let text = yAxis.getFormattedLabel(i) if (!yAxis.isDrawTopYLabelEntryEnabled && i >= yAxis.entryCount - 1) { break } pt.x = 0 pt.y = CGFloat(yAxis.entries[i]) pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) pt.x = fixedPosition pt.y += offset ChartUtils.drawText(context: context, text: text, point: pt, align: textAlign, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } private var _gridLineBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(context context: CGContext) { guard let yAxis = yAxis else { return } if !yAxis.isEnabled { return } if yAxis.drawGridLinesEnabled { CGContextSaveGState(context) CGContextSetShouldAntialias(context, yAxis.gridAntialiasEnabled) CGContextSetStrokeColorWithColor(context, yAxis.gridColor.CGColor) CGContextSetLineWidth(context, yAxis.gridLineWidth) CGContextSetLineCap(context, yAxis.gridLineCap) if (yAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, yAxis.gridLineDashPhase, yAxis.gridLineDashLengths, yAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) // draw the horizontal grid for (var i = 0, count = yAxis.entryCount; i < count; i++) { position.x = 0.0 position.y = CGFloat(yAxis.entries[i]) position = CGPointApplyAffineTransform(position, valueToPixelMatrix) _gridLineBuffer[0].x = viewPortHandler.contentLeft _gridLineBuffer[0].y = position.y _gridLineBuffer[1].x = viewPortHandler.contentRight _gridLineBuffer[1].y = position.y CGContextStrokeLineSegments(context, _gridLineBuffer, 2) } CGContextRestoreGState(context) } if yAxis.drawZeroLineEnabled { // draw zero line var position = CGPoint(x: 0.0, y: 0.0) transformer.pointValueToPixel(&position) drawZeroLine(context: context, x1: viewPortHandler.contentLeft, x2: viewPortHandler.contentRight, y1: position.y, y2: position.y); } } /// Draws the zero line at the specified position. public func drawZeroLine( context context: CGContext, x1: CGFloat, x2: CGFloat, y1: CGFloat, y2: CGFloat) { guard let yAxis = yAxis, zeroLineColor = yAxis.zeroLineColor else { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, zeroLineColor.CGColor) CGContextSetLineWidth(context, yAxis.zeroLineWidth) if (yAxis.zeroLineDashLengths != nil) { CGContextSetLineDash(context, yAxis.zeroLineDashPhase, yAxis.zeroLineDashLengths!, yAxis.zeroLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextMoveToPoint(context, x1, y1) CGContextAddLineToPoint(context, x2, y2) CGContextDrawPath(context, CGPathDrawingMode.Stroke) CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(context context: CGContext) { guard let yAxis = yAxis else { return } var limitLines = yAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { let l = limitLines[i] if !l.isEnabled { continue } position.x = 0.0 position.y = CGFloat(l.limit) position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _limitLineSegmentsBuffer[0].y = position.y _limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight _limitLineSegmentsBuffer[1].y = position.y CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) let label = l.label // if drawing the limit-value label is enabled if (label.characters.count > 0) { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = 4.0 + l.xOffset let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset if (l.labelPosition == .RightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .RightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .LeftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } CGContextRestoreGState(context) } }
mit
2609773555b0a4efaaa6bca9011d5a2a
33.193878
184
0.523815
5.747513
false
false
false
false
chenqihui/QHAwemeDemo
QHAwemeDemo/Modules/QHNavigationControllerMan/OtherTransition/QHPresentPushTransition.swift
1
1481
// // QHPresentPushTransition.swift // QHAwemeDemo // // Created by Anakin chen on 2017/10/29. // Copyright © 2017年 AnakinChen Network Technology. All rights reserved. // import UIKit class QHPresentPushTransition: QHBaseTransition { let offSetHeight: CGFloat = 0 override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return transitionDuration } override func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromVC = transitionContext.viewController(forKey: .from) let toVC = transitionContext.viewController(forKey: .to) let containerView = transitionContext.containerView containerView.addSubview(fromVC!.view) let toViewFrame = CGRect(x: 0, y: fromVC!.view.frame.size.height - offSetHeight, width: fromVC!.view.frame.size.width, height: fromVC!.view.frame.size.height + offSetHeight) toVC?.view.frame = toViewFrame containerView.addSubview((toVC?.view)!) UIView.animate(withDuration: transitionDuration, delay: 0, options: .curveEaseOut, animations: { let fromViewFrame = fromVC?.view.frame toVC?.view.frame = fromViewFrame! }) { (bFinish) in toVC?.view.frame = (fromVC?.view.frame)! transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
mit
f896b31266fc9bcb41d8c4f376de5580
36.897436
181
0.692152
4.877888
false
false
false
false