repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
cornerstonecollege/401
olderFiles/401_2016_2/swift_examples/Enums/Enums/main.swift
1
1728
// // main.swift // Enums // // Created by Luiz on 2016-09-27. // Copyright © 2016 Ideia do Luiz. All rights reserved. // import Foundation // Example 1 enum HTTPError { case Unauthorized case NotFound case BadGateway } var myError = HTTPError.NotFound switch myError { case HTTPError.NotFound: print("NotFound"); print(myError.hashValue) case .BadGateway: print("Bad Gateway"); default: print("Unknown"); } // Example 2 enum CardinalPoint:Int // enums with raw values { case NORTH = 0 case SOUTH = 1 case WEST = 2 case EAST = 3 } let c = CardinalPoint.NORTH print(c.rawValue) let x = 2 let myCardinalPoint = CardinalPoint(rawValue: x) print(myCardinalPoint!) // Example 3 enum HTTPErrorWithDetail { case Unauthorized(detail:String) case NotFound(detail:String, moreDetails:String?) case BadGateway(detail:String) } let myConstant = HTTPErrorWithDetail.NotFound(detail: "The page does not exist", moreDetails: nil) switch myConstant { case HTTPErrorWithDetail.NotFound(let detailInfo, _): print(detailInfo) default: print("Not enough info.") } let const1 = HTTPErrorWithDetail.Unauthorized(detail: "Hhahaha") let const2 = HTTPErrorWithDetail.Unauthorized(detail: "Hello World") let arr = [const1, const2] for element in arr { switch element { case .Unauthorized(let theDetails) where theDetails.hasPrefix("Hello"): print(element) default: break } } // Example for pure SWITCHES let string = "my very nice string" switch string { case let s where s.hasPrefix("Hi"): print("Started with hi") case "a", "Hello World", "hahahah": print("Not a very nice string") case "b": fallthrough case "c": print("b or c") default: print("Nothing interesting") }
gpl-3.0
4d5c212e9fa0d7fa131f2f617254f80d
19.081395
98
0.714534
3.553498
false
false
false
false
KazuCocoa/sampleTddInSwift
AppMenu/AppMenu/MenuTableDefaultDataSource.swift
1
1554
// // MenuTableDefaultDataSource.swift // AppMenu // // Created by KazuakiMATSUO on 1/2/15. // Copyright (c) 2015 KazuakiMATSUO. All rights reserved. // import Foundation import UIKit class MenuTableDefaultDataSource : NSObject, MenuTableDataSource { var menuItems: [MenuItem]? func setMenuItems(menuItems: [MenuItem]) { self.menuItems = menuItems } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Ideally we should be reusing table view cells here let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil) let menuItem = menuItems?[indexPath.row] cell.textLabel!.text = menuItem?.title cell.detailTextLabel!.text = menuItem?.subTitle // TODO //cell.imageView!.image = UIImage(named: menuItem?.iconName) cell.accessoryType = .DisclosureIndicator return cell } func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return 1 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let menuItem = menuItems?[indexPath.row] let notification = NSNotification(name: MenuTableDataSourceDidSelectItemNotification, object:menuItem) NSNotificationCenter.defaultCenter().postNotification(notification) } }
mit
43adaafd6ad0ca847bfe589d44b06dc2
30.734694
110
0.681467
5.25
false
false
false
false
shepperdr/SwiftX
SwiftX/AppDelegate.swift
2
6494
// // AppDelegate.swift // SwiftX // // Created by Taylor Mott on 16 Jun 15. // Copyright (c) 2015 Mott Applications. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. UINavigationBar.appearance().tintColor = UIColor(red: 45/255.0, green: 24/255.0, blue: 100/255.0, alpha: 1.0) UITextField.appearance().tintColor = UIColor(red: 45/255.0, green: 24/255.0, blue: 100/255.0, alpha: 1.0) UITextView.appearance().tintColor = UIColor(red: 45/255.0, green: 24/255.0, blue: 100/255.0, alpha: 1.0) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // 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 inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // 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 applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.mottapplications.SwiftX" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SwiftX", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftX.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
4ee92daa480a76f4bb3e7ece77c9ed7d
54.982759
290
0.71081
5.489434
false
false
false
false
wusuowei/WTCarouselFlowLayout
Example/WTCarouselFlowLayout/ViewController.swift
1
2853
// // ViewController.swift // WTCarouselFlowLayout // // Created by [email protected] on 08/31/2017. // Copyright (c) 2017 [email protected]. All rights reserved. // import UIKit import WTCarouselFlowLayout class ViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var descriptionLabel: UILabel! @objc var selectedIndex = 0 @objc let movieList = MovieModel.movieModels() @objc var pageSize: CGSize { let layout = self.collectionView.collectionViewLayout as! WTCarouselFlowLayout var pageSize = layout.itemSize pageSize.width += layout.minimumLineSpacing return pageSize } override func viewDidLoad() { super.viewDidLoad() setupFlowLayout() refreshView() } @objc func setupFlowLayout() { let layout = self.collectionView.collectionViewLayout as! WTCarouselFlowLayout layout.itemSize = CGSize(width: 85, height: 125) layout.scrollDirection = .horizontal layout.itemSpacing = 15 // layout.itemSpacing = -15 layout.sideItemScale = 0.7 layout.sideItemAlpha = 0.7 layout.sideItemBaselineType = .center layout.sideItemOffset = 0.0 } } extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return movieList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell cell.model = movieList[indexPath.row] return cell } @objc func refreshView() { guard selectedIndex < movieList.count else { return } let model = movieList[selectedIndex] self.titleLabel.text = model.title self.descriptionLabel.text = model.detail } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: true) selectedIndex = indexPath.row } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { refreshView() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let pageSide = self.pageSize.width let offset = scrollView.contentOffset.x selectedIndex = Int(floor((offset - pageSide / 2) / pageSide) + 1) refreshView() } }
mit
6b3facf9736322f35e375ad6fed1d737
31.793103
135
0.692955
5.215722
false
false
false
false
CoderJackyHuang/ITClient-Swift
ITClient-Swift/Controller/Profile/AboutUsController.swift
1
1608
// // AboutUsController.swift // ITClient-Swift // // Created by huangyibiao on 15/9/24. // Copyright © 2015年 huangyibiao. All rights reserved. // import Foundation import UIKit /// About us /// /// Author: 黄仪标 /// Blog: http://www.hybblog.com/ /// Github: http://github.com/CoderJackyHuang/ /// Email: [email protected] /// Weibo: JackyHuang(标哥) class AboutUsController: BaseController { private var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() hyb_navWithTitle("关于我们") self.tableView = createTableView() let headerView = UIView() let imageView = UIImageView(image: UIImage(named: "icon")) headerView.addSubview(imageView) imageView.sizeToFit() imageView.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(headerView) make.centerY.equalTo(headerView).offset(-100) } let tipLabel = UILabel() tipLabel.text = "博客:http://www.hybblog.com/\n微博:JackyHuang标哥\nGithub:http://github.com/CoderJackyHuang/" tipLabel.numberOfLines = 0 tipLabel.textAlignment = .Left tipLabel.textColor = UIColor.blueColor() headerView.addSubview(tipLabel) tipLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(imageView.snp_bottom).offset(10) } self.tableView.tableHeaderView = headerView headerView.snp_makeConstraints { (make) -> Void in make.height.equalTo(self.view.hyb_height) make.width.equalTo(self.view.hyb_width) } } }
mit
beaebb006281182bee41f11ff85aaf4f
27
108
0.681557
3.803398
false
false
false
false
Egibide-DAM/swift
02_ejemplos/06_tipos_personalizados/02_clases_estructuras/06_tipos_referencia.playground/Contents.swift
1
509
struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } let hd = Resolution(width: 1920, height: 1080) let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 let alsoTenEighty = tenEighty alsoTenEighty.frameRate = 30.0 print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
apache-2.0
02014063ead82913769e62616bc30e74
19.36
74
0.715128
3.885496
false
false
false
false
YF-Raymond/DouYUzhibo
DYZB/DYZB/Classes/Home/Controller/HomeViewController.swift
1
3559
// // HomeViewController.swift // DYZB // // Created by Raymond on 2016/12/23. // Copyright © 2016年 Raymond. All rights reserved. // import UIKit fileprivate let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 fileprivate lazy var pageTitleView : PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScrennW, height: kTitleViewH) let titles = ["推荐", "手游", "娱乐", "游戏", "趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.backgroundColor = UIColor.white titleView.delegate = self return titleView }() fileprivate lazy var pageContentView : PageContentView = {[weak self] in // 1.确定内容的 frame let contentH = kScrennH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabBarH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScrennW, height: contentH ) // 2.确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(RecommentViewController()) for _ in 0..<4 { let vc = UIViewController() vc.view.backgroundColor = UIColor.white childVcs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentVc: self) contentView.delegate = self return contentView }() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置 UI 界面 setupUI() } } // MARK:- 设置 UI 界面 extension HomeViewController { fileprivate func setupUI() { // 1.设置导航栏 setupNavigationBar() automaticallyAdjustsScrollViewInsets = false // 2.添加pageContentView view.addSubview(pageContentView) // 3.添加TitleView view.addSubview(pageTitleView) } // 设置导航栏 private func setupNavigationBar() { // 1.设置左侧的 Item let btn = UIButton() btn.setImage(UIImage(named:"homeLogoIcon"), for: .normal) btn.sizeToFit() navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn) // 2.设置右侧的 Item let size = CGSize(width: 40, height: 40) let searchItem = UIBarButtonItem(imageName: "searchBtnIcon", highImageName: "searchBtnIconHL", size: size) let scanItem = UIBarButtonItem(imageName: "scanIcon", highImageName: "scanIconHL", size: size) let historyItem = UIBarButtonItem(imageName: "viewHistoryIcon", highImageName: "viewHistoryIconHL", size: size) let messageItem = UIBarButtonItem(imageName: "siteMessageHome", highImageName: "siteMessageHomeH", size: size) navigationItem.rightBarButtonItems = [searchItem, scanItem, historyItem, messageItem] } } // MARK:- 遵守PageTitleViewDelegate extension HomeViewController : PageTitleViewDelegate{ func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } } // MARK:- 遵守PageContentViewDelegate extension HomeViewController : PageContentViewDelegate { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
5bd3921b1af192cf67981e40a51f8904
36.108696
123
0.66901
4.962209
false
false
false
false
grandiere/box
box/View/GridVisorDownload/VGridVisorDownloadBase.swift
1
3078
import UIKit class VGridVisorDownloadBase:UIView { private weak var imageView:UIImageView! private weak var background:UIView! private weak var label:UILabel! private let kAnimationDuration:TimeInterval = 1 private let kMargin:CGFloat = 10 private let kCornerRadius:CGFloat = 70 private let kDownloadedRadius:CGFloat = 8 init() { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor(white:1, alpha:0.2) translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false let images:[UIImage] = [ #imageLiteral(resourceName: "assetDownload0"), #imageLiteral(resourceName: "assetDownload1"), #imageLiteral(resourceName: "assetDownload2"), #imageLiteral(resourceName: "assetDownload3"), #imageLiteral(resourceName: "assetDownload4")] let background:UIView = UIView() background.isUserInteractionEnabled = false background.translatesAutoresizingMaskIntoConstraints = false background.backgroundColor = UIColor(white:1, alpha:0.9) background.clipsToBounds = true background.layer.cornerRadius = kCornerRadius self.background = background let imageView:UIImageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.isUserInteractionEnabled = false imageView.animationImages = images imageView.animationDuration = kAnimationDuration imageView.startAnimating() self.imageView = imageView let label:UILabel = UILabel() label.alpha = 0 label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.isUserInteractionEnabled = false label.textAlignment = NSTextAlignment.center label.numberOfLines = 0 self.label = label addSubview(background) addSubview(imageView) addSubview(label) NSLayoutConstraint.equals( view:background, toView:self, margin:kMargin) NSLayoutConstraint.equals( view:imageView, toView:self) NSLayoutConstraint.equals( view:label, toView:self) } required init?(coder:NSCoder) { return nil } deinit { imageView.stopAnimating() } //MARK: public func downloadedReady(model:MGridVisorDownloadProtocol) { label.attributedText = model.descr imageView.stopAnimating() imageView.isHidden = true layer.cornerRadius = kDownloadedRadius background.layer.cornerRadius = kDownloadedRadius } func downloadedAnimation() { background.backgroundColor = UIColor(white:1, alpha:0.98) label.alpha = 1 } }
mit
8146cbdef6d58fa6ccfd3f5b2d742fa2
30.090909
68
0.642625
5.862857
false
false
false
false
jlecomte/iOSTwitterApp
Twiddlator/ComposeViewController.swift
1
2340
// // ComposeViewController.swift // Twiddlator // // Created by Julien Lecomte on 9/27/14. // Copyright (c) 2014 Julien Lecomte. All rights reserved. // import UIKit class ComposeViewController: UIViewController, UITextViewDelegate { @IBOutlet var statusTextView: UITextView! var countdownLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false var navbar = navigationController?.navigationBar countdownLabel = UILabel(frame: CGRectMake(280, 16, 40, 30)) countdownLabel.font = UIFont(name: "Helvetica", size: 12) countdownLabel.text = "140" countdownLabel.sizeToFit() navbar?.addSubview(countdownLabel) statusTextView.delegate = self statusTextView.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onCancel(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func onTweet(sender: AnyObject) { let client = TwitterClient.sharedInstance client.tweet(statusTextView.text) { (error: NSError!) -> Void in if error != nil { UIAlertView( title: "Error", message: "Your tweet could not be sent. Please try again later.", delegate: self, cancelButtonTitle: "Dismiss").show() } else { self.dismissViewControllerAnimated(true, completion: nil) } } } func textViewDidChange(textView: UITextView) { var n = 140 - countElements(textView.text) countdownLabel.text = "\(n)" if n < 10 { countdownLabel.textColor = UIColor.redColor() } else if n < 30 { countdownLabel.textColor = UIColor.orangeColor() } else { countdownLabel.textColor = UIColor.blackColor() } } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { var newLength = countElements(textView.text) - range.length + countElements(text) if newLength <= 140 { return true } return false } }
mit
a68ea13dbdf96c8926a00fa29d271d4a
27.536585
119
0.614957
5.318182
false
false
false
false
banxi1988/Staff
Staff/ClockRecordListViewController.swift
1
7503
// // ClockRecordListViewController.swift // Staff // // Created by Haizhen Lee on 16/3/1. // Copyright © 2016年 banxi1988. All rights reserved. // import Foundation // Build for target uicontroller import UIKit import SwiftyJSON import BXModel import BXiOSUtils import BXForm //-ClockRecordListViewController(m=ClockRecord,adapter=c):cvc class ClockRecordListViewController : UICollectionViewController,UICollectionViewDelegateFlowLayout{ init(){ super.init(collectionViewLayout: UICollectionViewFlowLayout()) } // must needed for iOS 8 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var allOutlets :[UIView]{ return [] } var flowLayout:UICollectionViewFlowLayout = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: screenWidth - 30, height: 44) layout.scrollDirection = .Vertical layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) layout.minimumInteritemSpacing = 10 layout.minimumLineSpacing = 10 return layout }() func commonInit(){ for childView in allOutlets{ self.view.addSubview(childView) childView.translatesAutoresizingMaskIntoConstraints = false } installConstaints() setupAttrs() } func installConstaints(){ } func setupAttrs(){ collectionView?.collectionViewLayout = flowLayout } override func loadView(){ super.loadView() self.view.backgroundColor = AppColors.colorBackground self.collectionView?.backgroundColor = AppColors.colorBackground commonInit() } struct CellIdentifiers{ static let recordCell = "record_cell" static let firstRecordCell = "first_record_cell" static let sectionHeader = "sectionHeader" } override func viewDidLoad() { super.viewDidLoad() title = "打卡记录" navigationItem.title = title collectionView?.registerClass(ClockRecordCell.self, forCellWithReuseIdentifier: CellIdentifiers.recordCell) collectionView?.registerClass(FirstRecordCell.self, forCellWithReuseIdentifier: CellIdentifiers.firstRecordCell) collectionView?.registerClass(RecordDateRangeHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: CellIdentifiers.sectionHeader) let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addRecord:") navigationItem.rightBarButtonItem = addButton NSNotificationCenter.defaultCenter().addObserverForName(AppEvents.ClockDataSetChanged, object: nil, queue: nil) { [weak self] (notif) -> Void in if (notif.object as? NSObject) != self{ self?.loadData() } } loadData() } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } var recordDateRanges: [RecordDateRange] = [] func loadData(){ let today = NSDate() recordDateRanges.removeAll() recordDateRanges.append(RecordDateRange(monthDate: today)) recordDateRanges.append(RecordDateRange(monthDate: calendar.bx_prevMonthDate(today))) collectionView?.reloadData() if #available(iOS 9.0, *) { flowLayout.sectionHeadersPinToVisibleBounds = true } } func addRecord(sender:AnyObject){ let vc = ClockRecordEditorViewController() showViewController(vc, sender: self) } // MARK: Helper func recordDateRangeAtSection(section:Int) -> RecordDateRange{ return recordDateRanges[section] } func recordsOfSection(section:Int) -> [ClockRecord]{ return recordDateRangeAtSection(section).records } func recordAtIndexPath(indexPath:NSIndexPath) -> ClockRecord{ let records = recordsOfSection(indexPath.section) return records[indexPath.item] } var numberOfSections:Int{ return recordDateRanges.count } func numberOfItemsInSection(section:Int) -> Int { return recordsOfSection(section).count } // MARK: DataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return numberOfSections } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberOfItemsInSection(section) } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let item = recordAtIndexPath(indexPath) let identifier = item.isFirstRecordOfDay ? CellIdentifiers.firstRecordCell : CellIdentifiers.recordCell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! ClockRecordCell cell.bind(item) // swipe let swipeGestureRecognizer = UIPanGestureRecognizer(target: cell, action: "handlePanGesture:") cell.addGestureRecognizer(swipeGestureRecognizer) swipeGestureRecognizer.delegate = cell collectionView.panGestureRecognizer.requireGestureRecognizerToFail(swipeGestureRecognizer) cell.delegate = self cell.indexPath = indexPath return cell } // MARK: Delegate func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ let item = recordAtIndexPath(indexPath) let itemWidth = screenWidth let itemHeight:CGFloat = item.isFirstRecordOfDay ? 90:30 return CGSize(width: itemWidth, height: itemHeight) } // MARK: Section Header override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader{ let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: CellIdentifiers.sectionHeader, forIndexPath: indexPath) as! RecordDateRangeHeaderView let range = recordDateRangeAtSection(indexPath.section) header.bind(range) return header }else{ fatalError("Unsupported kind: \(kind)") } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { let width = collectionView.bounds.width let height: CGFloat = 36 return CGSize(width: width, height: height) } } extension ClockRecordListViewController: ClockRecordCellDelegate{ func deleteRecordAtIndexPath(indexPath:NSIndexPath){ let record = recordAtIndexPath(indexPath) ClockRecordService.sharedService.delete(record) let records = recordsOfSection(indexPath.section) if let index = records.indexOf(record){ recordDateRangeAtSection(indexPath.section).records.removeAtIndex(index) } collectionView?.deleteItemsAtIndexPaths([indexPath]) collectionView?.reloadData() flowLayout.invalidateLayout() if numberOfItemsInSection(indexPath.section) == 0{ loadData() } NSNotificationCenter.defaultCenter().postNotificationName(AppEvents.ClockDataSetChanged, object: self) } func clockRecordCell(cell: ClockRecordCell, deleteAtIndexPath indexPath: NSIndexPath) { bx_prompt("确定删除这条打卡记录?"){ sure in self.deleteRecordAtIndexPath(indexPath) } } }
mit
3903ebd9412959ade42a3e992ed3d52d
31.206897
185
0.745985
5.461988
false
false
false
false
kyuridenamida/atcoder-tools
tests/resources/test_codegen/template_jinja.swift
2
1080
import Foundation {% if mod %} let MOD = {{ mod }} {% endif %} {% if yes_str %} let YES = "{{ yes_str }}" {% endif %} {% if no_str %} let NO = "{{ no_str }}" {% endif %} {% if prediction_success %} func solve({{ formal_arguments }}) { {% if yes_str %} var ans = false print(ans ? YES : NO) {% else %} var ans = 0 print(ans) {% endif %} } {% endif %} func main() { {% if prediction_success %} var tokenIndex = 0, tokenBuffer = [String]() func readString() -> String { if tokenIndex >= tokenBuffer.count { tokenIndex = 0 tokenBuffer = readLine()!.split(separator: " ").map { String($0) } } defer { tokenIndex += 1 } return tokenBuffer[tokenIndex] } func readInt() -> Int { Int(readString())! } func readDouble() -> Double { Double(readString())! } {{input_part}} _ = solve({{ actual_arguments }}) {% else %} // Failed to predict input format {% endif %} } #if DEBUG let caseNumber = 1 _ = freopen("in_\(caseNumber).txt", "r", stdin) #endif main()
mit
a30c05c6dce1e54d85e0b88ab746f3b0
19.769231
78
0.531481
3.648649
false
false
false
false
lazytype/FingerTree
FingerTree/Measure.swift
1
3120
// Measure.swift // // Copyright (c) 2015-Present, Michael Mitchell // // 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. protocol Monoid { static var identity: Self {get} func append(_ other: Self) -> Self } precedencegroup Additive { associativity: left } infix operator <> : Additive internal func <> <TAnnotation: Monoid>(lhs: TAnnotation, rhs: TAnnotation) -> TAnnotation { return lhs.append(rhs) } internal protocol Measurable { associatedtype Annotation: Monoid var measure: Annotation {get} } struct Value<T>: Measurable, CustomStringConvertible { typealias Annotation = Size let value: T init(_ value: T) { self.value = value } var measure: Size { return 1 } var description: String { return "'\(value)'" } } extension Measurable { func makeElement() -> TreeElement<Self, Annotation> { return TreeElement.aValue(self) } } typealias Size = Int extension Size: Monoid { static var identity: Size = 0 func append(_ other: Size) -> Size { return self + other } } struct Prioritized<T>: Measurable { typealias Annotation = Priority let value: T let priority: Int init(_ value: T, priority: Int) { self.value = value self.priority = priority } var measure: Priority { return Priority.value(priority) } } enum Priority: Monoid { case negativeInfinity case value(Int) static var identity: Priority { return Priority.negativeInfinity } func append(_ other: Priority) -> Priority { switch (self, other) { case (.negativeInfinity, _): return other case (_, .negativeInfinity): return self case let (.value(value), .value(otherValue)): return value > otherValue ? self : other default: // All cases have actually been exhausted. Remove when the compiler is smarter about this. return self } } } func == (lhs: Priority, rhs: Priority) -> Bool { switch (lhs, rhs) { case (.negativeInfinity, .negativeInfinity): return true case let (.value(lvalue), .value(rvalue)): return lvalue == rvalue default: return false } }
mit
0749bcb070932c22d69f3a175c4df244
24.785124
97
0.701603
4.273973
false
false
false
false
RobinFalko/Ubergang
Examples/TweenApp/Pods/Ubergang/Ubergang/Core/Engine.swift
1
2119
// // Engine.swift // Ubergang // // Created by Robin Frielingsdorf on 09/01/16. // Copyright © 2016 Robin Falko. All rights reserved. // import Foundation import UIKit open class Engine: NSObject { public typealias Closure = () -> Void fileprivate var displayLink: CADisplayLink? var closures = [String : Closure]() var mapTable = NSMapTable<AnyObject, AnyObject>(keyOptions: NSPointerFunctions.Options.strongMemory, valueOptions: NSPointerFunctions.Options.weakMemory) open static var instance: Engine = { let engine = Engine() engine.start() return engine }() func start() { if displayLink == nil { displayLink = CADisplayLink(target: self, selector: #selector(Engine.update)) displayLink!.add(to: RunLoop.current, forMode: RunLoopMode.commonModes) } } func stop() { displayLink?.remove(from: RunLoop.current, forMode: RunLoopMode.commonModes) displayLink = nil } @objc func update() { let enumerator = mapTable.objectEnumerator() while let any: AnyObject = enumerator?.nextObject() as AnyObject! { if let loopable = any as? WeaklyLoopable { loopable.loopWeakly() } } for (_, closure) in closures { closure() } } func register(_ closure: @escaping Closure, forKey key: String) { closures[key] = closure start() } func register(_ loopable: WeaklyLoopable, forKey key: String) { mapTable.setObject(loopable as AnyObject?, forKey: key as AnyObject?) start() } func unregister(_ key: String) { mapTable.removeObject(forKey: key as AnyObject?) closures.removeValue(forKey: key) if mapTable.count == 0 && closures.isEmpty { stop() } } func contains(_ key: String) -> Bool { return mapTable.object(forKey: key as AnyObject?) != nil || closures[key] != nil } }
apache-2.0
365b4af91086cd80ab82e6679c878391
25.148148
157
0.581209
4.781038
false
false
false
false
omiz/CarBooking
CarBooking/Data/Objects/DecodableArray.swift
1
1473
// // DecodableArray.swift // CarBooking // // Created by Omar Allaham on 10/18/17. // Copyright © 2017 Omar Allaham. All rights reserved. // import Foundation import Foundation import SwiftyJSON import TRON protocol JSONDecodableArray: BaseObject { associatedtype Element var array: [Element] { get } } class DecodableArray<E: JSONDecodable>: NSObject, NSCoding, JSONDecodableArray { var id: Int = 0 typealias Element = E let rawValue: String let array: [E] override var description: String { return rawValue } override var debugDescription: String { return rawValue } required init(json: JSON) throws { if json["error"].intValue < 0 { throw DataError.serverError } array = json.arrayValue.map { try? Element(json: $0) }.filter { $0 != nil } as? [Element] ?? [] rawValue = json.description } required init(coder decoder: NSCoder) { rawValue = decoder.decodeObject(forKey: "rawValue") as? String ?? "" array = decoder.decodeObject(forKey: "array") as? [Element] ?? [] } func encode(with coder: NSCoder) { coder.encode(rawValue, forKey: "rawValue") coder.encode(array, forKey: "array") } static func ==(lhs: DecodableArray, rhs: DecodableArray) -> Bool { return lhs.rawValue == rhs.rawValue } }
mit
ff5d8e8661f61d5c063a4f8b0f52dd4a
21.30303
103
0.594429
4.44713
false
false
false
false
yasuoza/graphPON
graphPON WatchKit Extension/Interfaces/SummaryChartInterfaceController.swift
1
3225
import WatchKit import Foundation import GraphPONDataKit class SummaryChartInterfaceController: WKInterfaceController { @IBOutlet weak var durationLabel: WKInterfaceLabel! @IBOutlet weak var chartValueLabel: WKInterfaceLabel! @IBOutlet weak var chartImageView: WKInterfaceImage! @IBOutlet weak var durationControlButtonGroup: WKInterfaceGroup! @IBOutlet weak var inThisMonthButton: WKInterfaceButton! @IBOutlet weak var last30DaysButton: WKInterfaceButton! private var serviceCode: String! private var duration: HdoService.Duration = .InThisMonth override init() { super.init() PacketInfoManager.sharedManager.fetchLatestPacketLog(completion: { _ in let hddService = PacketInfoManager.sharedManager.hddServices.first Context.sharedContext.serviceCode = hddService?.hddServiceCode Context.sharedContext.serviceNickname = hddService?.nickName }) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) NSNotificationCenter.defaultCenter().addObserverForName( PacketInfoManager.LatestPacketLogsDidFetchNotification, object: nil, queue: nil, usingBlock: { _ in if let serviceCode = Context.sharedContext.serviceCode { self.serviceCode = serviceCode self.reloadChartData() } }) } override func willActivate() { super.willActivate() if self.serviceCode != Context.sharedContext.serviceCode { self.serviceCode = Context.sharedContext.serviceCode self.reloadChartData() } } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } // MARK: - Actions @IBAction func InThisMonthButtonAction() { self.inThisMonthButton.setBackgroundColor(UIColor.blackColor().colorWithAlphaComponent(0.8)) self.last30DaysButton.setBackgroundColor(UIColor.clearColor()) self.duration = .InThisMonth self.reloadChartData() } @IBAction func last30DaysButtonAction() { self.inThisMonthButton.setBackgroundColor(UIColor.clearColor()) self.last30DaysButton.setBackgroundColor(UIColor.blackColor().colorWithAlphaComponent(0.8)) self.duration = .InLast30Days self.reloadChartData() } @IBAction func showSummaryChartMenuAction() { self.presentControllerWithName("ServiceListInterfaceController", context: nil) self.reloadChartData() } // MARK: - Update views private func reloadChartData() { let frame = CGRectMake(0, 0, contentFrame.width, contentFrame.height / 2) let scene = SummaryChartScene(serviceCode: serviceCode, duration: duration) let image = scene.drawImage(frame: frame) self.chartImageView.setImage(image) self.chartValueLabel.setText(scene.valueText) self.durationLabel.setText(scene.durationText) self.setTitle(Context.sharedContext.serviceNickname) } }
mit
bee2b21053ef3fad8348636bf465c093
34.054348
100
0.695814
5.429293
false
false
false
false
LYM-mg/MGOFO
MGOFO/MGOFO/Class/Tools/UpdateTool.swift
1
2401
// // UpdateTool.swift // ProductionReport // // Created by i-Techsys.com on 17/3/22. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit import MBProgressHUD class UpdateTool: NSObject { static let share = UpdateTool() func checkUpdate() { let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String NetWorkTools.requestData(type: .get, urlString: "http://api.i-techsys.com:7125/ReportService/Version", succeed: { (result, err) in // let hud = MBProgressHUD.showAdded(to: MGKeyWindow!, animated: true) // hud?.mode = .indeterminate // indeterminate annularDeterminate // hud?.labelText = "检查更新" // hud?.hide(true) guard let serVersion = result as? String else { return } if currentVersion == serVersion { debugPrint("已是最新版本") }else{ // 去下载 let _ = UIAlertView(title: "App已经优化", message: "", cancleTitle: "取消", otherButtonTitle: ["升级"], onDismissBlock: { (index) in self.jumpToAppStoreDownload() }, onCancleBlock: { debugPrint("取消") }) } }) { (err) in self.showInfo(info: "网络出错") } } func jumpToAppStoreDownload() { guard let url = URL(string: "http://itunes.apple.com/lookup?id=\(appid)") else { return } if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } // if #available(iOS 10.0, *) { // UIApplicationOpenURLOptionsKey UIApplicationOpenSettingsURLString // if UIApplication.shared.canOpenURL(url) { // let options = [UIApplicationOpenURLOptionUniversalLinksOnly : true] // UIApplication.shared.open(url, options: options, completionHandler: nil) // UIApplication.shared.open(url, options: options, completionHandler: { (_) in // }) // } // // if UIApplication.shared.canOpenURL(url) { // UIApplication.shared.openURL(url) // } // // }else { // if UIApplication.shared.canOpenURL(url) { // UIApplication.shared.openURL(url) // } // } } }
mit
84de9286fb064731dc7ccb6ae7c4d7e6
38.728814
140
0.562287
4.364991
false
false
false
false
lkzhao/MCollectionView
Examples/ChatExample (Advance)/MessageCell.swift
1
3929
// // MessageTextCell.swift // MCollectionViewExample // // Created by YiLun Zhao on 2016-02-20. // Copyright © 2016 lkzhao. All rights reserved. // import UIKit import MCollectionView class MessageCell: DynamicView { var textLabel = UILabel() var imageView: UIImageView? var message: Message! { didSet { textLabel.text = message.content textLabel.textColor = message.textColor textLabel.font = UIFont.systemFont(ofSize: message.fontSize) layer.cornerRadius = message.roundedCornder ? 10 : 0 if message.type == .image { imageView = imageView ?? UIImageView() imageView?.image = UIImage(named: message.content) imageView?.frame = bounds imageView?.contentMode = .scaleAspectFill imageView?.clipsToBounds = true imageView?.layer.cornerRadius = layer.cornerRadius addSubview(imageView!) } else { imageView?.removeFromSuperview() imageView = nil } if message.showShadow { layer.shadowOffset = CGSize(width: 0, height: 5) layer.shadowOpacity = 0.3 layer.shadowRadius = 8 layer.shadowColor = message.shadowColor.cgColor layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath } else { layer.shadowOpacity = 0 layer.shadowColor = nil } backgroundColor = message.backgroundColor } } override init(frame: CGRect) { super.init(frame: frame) addSubview(textLabel) textLabel.frame = frame textLabel.numberOfLines = 0 layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale isOpaque = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() if message?.showShadow ?? false { layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath } textLabel.frame = bounds.insetBy(dx: message.cellPadding, dy: message.cellPadding) imageView?.frame = bounds } static func sizeForText(_ text: String, fontSize: CGFloat, maxWidth: CGFloat, padding: CGFloat) -> CGSize { let maxSize = CGSize(width: maxWidth, height: 0) let font = UIFont.systemFont(ofSize: fontSize) var rect = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [ NSFontAttributeName: font ], context: nil) rect.size = CGSize(width: ceil(rect.size.width) + 2 * padding, height: ceil(rect.size.height) + 2 * padding) return rect.size } static func frameForMessage(_ message: Message, containerWidth: CGFloat) -> CGRect { if message.type == .image { var imageSize = UIImage(named: message.content)!.size let maxImageSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: 120) if imageSize.width > maxImageSize.width { imageSize.height /= imageSize.width/maxImageSize.width imageSize.width = maxImageSize.width } if imageSize.height > maxImageSize.height { imageSize.width /= imageSize.height/maxImageSize.height imageSize.height = maxImageSize.height } return CGRect(origin: CGPoint(x: message.alignment == .right ? containerWidth - imageSize.width : 0, y: 0), size: imageSize) } if message.alignment == .center { let size = sizeForText(message.content, fontSize: message.fontSize, maxWidth: containerWidth, padding: message.cellPadding) return CGRect(x: (containerWidth - size.width)/2, y: 0, width: size.width, height: size.height) } else { let size = sizeForText(message.content, fontSize: message.fontSize, maxWidth: containerWidth - 50, padding: message.cellPadding) let origin = CGPoint(x: message.alignment == .right ? containerWidth - size.width : 0, y: 0) return CGRect(origin: origin, size: size) } } }
mit
bae73e2807e3b26de141e7eb33c22616
36.056604
138
0.684827
4.504587
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.MotionDetected.swift
1
2047
import Foundation public extension AnyCharacteristic { static func motionDetected( _ value: Bool = false, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Motion Detected", format: CharacteristicFormat? = .bool, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.motionDetected( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func motionDetected( _ value: Bool = false, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Motion Detected", format: CharacteristicFormat? = .bool, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Bool> { GenericCharacteristic<Bool>( type: .motionDetected, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
e16277043a052b9c7afd678e48ce185b
32.557377
67
0.578407
5.473262
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.CurrentMediaState.swift
1
2053
import Foundation public extension AnyCharacteristic { static func currentMediaState( _ value: UInt8 = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Current Media State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 5, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.currentMediaState( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func currentMediaState( _ value: UInt8 = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Current Media State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 5, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<UInt8> { GenericCharacteristic<UInt8>( type: .currentMediaState, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
c66b723287276e1b1daeffd045b7e95f
32.655738
67
0.578665
5.374346
false
false
false
false
Ge3kXm/MXWB
MXWB/Classes/OAuth/OAuthVC.swift
1
3437
// // OAuthVC // MXWB // // Created by maRk on 2017/4/18. // Copyright © 2017年 maRk. All rights reserved. // import UIKit class OAuthVC: UIViewController { // MARK: - Lazyload lazy var webView :UIWebView = { let webView = UIWebView(frame: UIScreen.main.bounds) webView.delegate = self return webView }() let oAuthRequest = URLRequest(url: URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(MXWB_APP_KEY)&redirect_uri=\(MXWB_APP_REDIRECT_URL)")!) // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() initUI() initNav() startLoading() } // MARK: - PrivateFunc private func initUI() { view.addSubview(webView) } private func initNav() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.plain, target: self, action: #selector(OAuthVC.closeBtnClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填", style: UIBarButtonItemStyle.plain, target: self, action: #selector(OAuthVC.fullBtnClick)) } private func startLoading() { webView.loadRequest(oAuthRequest) } @objc func closeBtnClick() { dismiss(animated: true, completion: nil) } @objc func fullBtnClick() { let jsString = "document.getElementById('userId').value = '[email protected]'" webView.stringByEvaluatingJavaScript(from: jsString) let jsString2 = "document.getElementById('passwd').value = '4839286mm'" webView.stringByEvaluatingJavaScript(from: jsString2) } } extension OAuthVC: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard let requestURlString = request.url?.absoluteString else { MXLog("url is not valid") return false } if !requestURlString.contains("https://www.google.com") { MXLog("is not autoPage") return true } MXLog("is autoPage") let key = "code=" if requestURlString.contains(key) { let requestToken = request.url?.query!.substring(from: key.endIndex) getAccessToken(requestToken: requestToken) MXLog(requestToken) return false } return true } private func getAccessToken(requestToken: String?) { let path = "oauth2/access_token" let parameters = ["client_id": MXWB_APP_KEY, "client_secret": MXWB_APP_SECREAT, "grant_type": "authorization_code", "code": requestToken, "redirect_uri": MXWB_APP_REDIRECT_URL] HttpManager.sharedManager.post(path, parameters: parameters, progress: nil, success: { (sessionTask: URLSessionDataTask, obj: Any) in MXLog(obj) let account = OAuthAccount(dict: (obj as! [String: Any])) account.getUserInfo(finished: { (fullInfoAcctount, error) in MXLog(fullInfoAcctount?.saveAccount()) NotificationCenter.default.post(name: Notification.Name(MXWB_NOTIFICATION_SWITCHROOTVC_KEY), object: false) }) self.dismiss(animated: true, completion: nil) }) { (sessionTask: URLSessionDataTask?, error: Error) in MXLog(error) } } }
apache-2.0
9873799ffa2967791f0bc67310b3fd74
32.242718
184
0.627044
4.469974
false
false
false
false
jum/Charts
Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift
8
1580
// // RadarChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class RadarChartDataSet: LineRadarChartDataSet, IRadarChartDataSet { private func initialize() { self.valueFont = NSUIFont.systemFont(ofSize: 13.0) } public required init() { super.init() initialize() } public required override init(entries: [ChartDataEntry]?, label: String?) { super.init(entries: entries, label: label) initialize() } // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// flag indicating whether highlight circle should be drawn or not /// **default**: false open var drawHighlightCircleEnabled: Bool = false /// `true` if highlight circle should be drawn, `false` ifnot open var isDrawHighlightCircleEnabled: Bool { return drawHighlightCircleEnabled } open var highlightCircleFillColor: NSUIColor? = NSUIColor.white /// The stroke color for highlight circle. /// If `nil`, the color of the dataset is taken. open var highlightCircleStrokeColor: NSUIColor? open var highlightCircleStrokeAlpha: CGFloat = 0.3 open var highlightCircleInnerRadius: CGFloat = 3.0 open var highlightCircleOuterRadius: CGFloat = 4.0 open var highlightCircleStrokeWidth: CGFloat = 2.0 }
apache-2.0
d3a566c258450d61b78d802eb12407a8
25.779661
85
0.674684
4.906832
false
false
false
false
LoveAlwaysYoung/EnjoyUniversity
EnjoyUniversity/EnjoyUniversity/Classes/View/Activity/EUActivityParticipatorsViewController.swift
1
5668
// // EUActivityParticipatorsViewController.swift // EnjoyUniversity // // Created by lip on 17/4/11. // Copyright © 2017年 lip. All rights reserved. // import UIKit class EUActivityParticipatorsViewController: EUBaseViewController { let ACTIVITYPARTICIPATORCELL = "ACTIVITYPARTICIPATORCELL" let nomemberimageview = UIImageView(image: UIImage(named: "av_nomember")) let nomemberlabel = UILabel(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.width, height: 15))) /// 参与者数据源 var participatorslist:UserInfoListViewModel? /// 社团 ID var avid:Int = 0 override func viewDidLoad() { super.viewDidLoad() tableview.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) tableview.register(EUActivityMemberCell.self, forCellReuseIdentifier: ACTIVITYPARTICIPATORCELL) navitem.title = "审核" tableview.tableFooterView = UIView() if participatorslist?.activityParticipatorList.count == 0{ tableview.separatorStyle = .none nomemberimageview.frame.size = CGSize(width: 50, height: 50) nomemberimageview.center.x = view.center.x nomemberimageview.center.y = view.center.y - 90 tableview.addSubview(nomemberimageview) nomemberlabel.textAlignment = .center nomemberlabel.text = "暂无小伙伴参加" nomemberlabel.font = UIFont.boldSystemFont(ofSize: 13) nomemberlabel.center.y = nomemberimageview.frame.maxY + 10 tableview.addSubview(nomemberlabel) } } override func loadData() { participatorslist?.loadActivityMemberInfoList(avid: avid) { (isSuccess, hasMember) in self.refreshControl?.endRefreshing() if !isSuccess{ SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1) return } if !hasMember{ return } self.tableview.reloadData() self.nomemberlabel.removeFromSuperview() self.nomemberimageview.removeFromSuperview() } } } // MARK: - 代理相关方法 extension EUActivityParticipatorsViewController{ override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return participatorslist?.activityParticipatorList.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableview.dequeueReusableCell(withIdentifier: ACTIVITYPARTICIPATORCELL) as? EUActivityMemberCell cell?.userinfo = participatorslist?.activityParticipatorList[indexPath.row] return cell ?? UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let phone = participatorslist?.activityParticipatorList[indexPath.row].model?.uid else{ return } // 点击直接弹出拨打电话界面 UIApplication.shared.open(URL(string: "telprompt://\(phone)")!, options: [:], completionHandler: nil) } /// 左滑删除 func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .delete } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } /// 定义文字 func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "拒绝参加" } /// T 人 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { guard let uid = participatorslist?.activityParticipatorList[indexPath.row].model?.uid else{ return } let alert = UIAlertController(title: nil, message: "请填写拒绝理由", preferredStyle: .alert) alert.addTextField { (textfield) in textfield.placeholder = "拒绝理由" } let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil) let confirm = UIAlertAction(title: "确定", style: .destructive) { (alertaction) in let reason = alert.textFields![0].text SwiftyProgressHUD.showLoadingHUD() EUNetworkManager.shared.removeSomeOneFromMyActovoty(uid: uid, avid: self.avid, reason: reason, completion: { (isSuccess, isRemoved) in SwiftyProgressHUD.hide() if !isSuccess{ SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1) return } if !isRemoved{ SwiftyProgressHUD.showFaildHUD(text: "异常操作", duration: 1) return } SwiftyProgressHUD.showSuccessHUD(duration: 1) self.participatorslist?.activityParticipatorList.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) }) } alert.addAction(cancel) alert.addAction(confirm) present(alert, animated: true) { tableView.reloadRows(at: [indexPath], with: .automatic) } } }
mit
2d2d41aa67a8cc173a9788815222999f
34.127389
146
0.624116
5.173546
false
false
false
false
mattwelborn/HSTracker
HSTracker/Logging/Enums/Rarity.swift
1
454
// // Rarity.swift // HSTracker // // Created by Benjamin Michotte on 6/03/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation enum Rarity: String { case Free = "free", Common = "common", Rare = "rare", Epic = "epic", Legendary = "legendary", Golden = "golden" static func allValues() -> [Rarity] { return [.Free, .Common, .Rare, .Epic, .Legendary] } }
mit
bc48421939bffde6690b9976c269463f
19.590909
60
0.569536
3.406015
false
false
false
false
ylovesy/CodeFun
mayu/Longest Common Prefix.swift
1
573
import Foundation /* 14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. */ private class Solution { func longestCommonPrefix(_ strs: [String]) -> String { if strs.count == 0 { return "" } var prefixStr = strs[0] var idx = 0 while idx < strs.count { while !strs[idx].hasPrefix(prefixStr) { prefixStr = prefixStr.substring(to: prefixStr.endIndex) } idx += 1 } return prefixStr } }
apache-2.0
23eadd7ab5ce6597b1fe285aba0acec2
25.045455
87
0.560209
4.620968
false
false
false
false
jbttn/playgrounds
Spiral.playground/section-1.swift
1
4511
struct Matrix { let rows: Int, columns: Int var flatGrid: [Int] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns self.flatGrid = Array(count: rows * columns, repeatedValue: 0) } subscript(row: Int, column: Int) -> Int { get { return self.flatGrid[(row * self.columns) + column] } set { self.flatGrid[(row * self.columns) + column] = newValue } } } struct Position { var row = 0 var column = 0 } class Navigator { let directionsBeforeStepIncrease = 2 /// Keeps track of how many directions we can travel until we need to increase the maximum number of steps we can take for each direction var directionCount: Int /// The maximum number of steps we can take in the current direction before we need to turn var maxSteps: Int /// The current number of steps we have taken in the current direction var currentDirectionSteps: Int /// The direction we are currently traveling var currentDirection: Direction /// Our position in the grid var currentPosition: Position enum Direction { case Up case Down case Left case Right } init(startingPosition: Position) { directionCount = directionsBeforeStepIncrease maxSteps = 1 currentDirectionSteps = 0 currentDirection = .Right currentPosition = startingPosition } func step() { switch currentDirection { case .Up: currentPosition.row = currentPosition.row - 1 case .Down: currentPosition.row = currentPosition.row + 1 case .Left: currentPosition.column = currentPosition.column - 1 case .Right: currentPosition.column = currentPosition.column + 1 } // We made a step currentDirectionSteps++ // If we have reached the maximum number of steps for this direction... if (currentDirectionSteps == maxSteps) { setNextDirection() currentDirectionSteps = 0 // If the direction counter reaches 0 then we need to increase the number of steps we can take for the next direction if (directionCount <= 0) { directionCount = directionsBeforeStepIncrease maxSteps++ } } } /// Decrement the direction counter and set the new direction private func setNextDirection() { directionCount-- switch currentDirection { case .Up: currentDirection = .Left case .Down: currentDirection = .Right case .Left: currentDirection = .Down case .Right: currentDirection = .Up } } } class SpiralGenerator { var matrix: Matrix var navigator: Navigator let startingLength: Int init(length: Int, matrixSize: Int) { assert(matrixSize % 2 != 0, "Matrix size must be an odd number") var startingPosition = Position(row: matrixSize / 2, column: matrixSize / 2) matrix = Matrix(rows: matrixSize, columns: matrixSize) navigator = Navigator(startingPosition: startingPosition) startingLength = length if (startingLength > matrix.rows * matrix.columns) { startingLength = matrix.rows * matrix.columns } } func generate() -> Void { spiral(1) printSpiral() } private func spiral(length: Int) { if (length <= startingLength) { matrix[navigator.currentPosition.row, navigator.currentPosition.column] = length navigator.step() let newLength = length + 1 spiral(newLength) } } private func printSpiral() { for row in 0...matrix.rows-1 { for column in 0...matrix.columns-1 { var num = matrix[row, column] if (num != 0) { if (num < 10) { print(" 0\(num) ") } else { print(" \(num) ") } } else { print(" XX ") } } print("\n\n") } } } var spiral = SpiralGenerator(length:81, matrixSize: 9) spiral.generate()
mit
a3a21dc512a6f44d3f405bbfd5528746
29.073333
141
0.550211
5.143672
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Rule/Rule.swift
1
2273
// // Rule.swift // // // Created by Vladislav Fitc on 04/05/2020. // import Foundation public struct Rule { /// Unique identifier for the rule. public var objectID: ObjectID /// Conditions of the rule. public var conditions: [Condition]? /// Consequence of the rule. public var consequence: Consequence? /// Whether the rule is enabled. Disabled rules remain in the index, but are not applied at query time. public var isEnabled: Bool? /// By default, rules are permanently valid /// When validity periods are specified, the rule applies only during those periods; /// it is ignored the rest of the time. The list must not be empty. public var validity: [TimeRange]? /// This field is intended for rule management purposes, in particular to ease searching for rules and /// presenting them to human readers. It is not interpreted by the API. public var description: String? public init(objectID: ObjectID) { self.objectID = objectID } } extension Rule: Builder {} extension Rule: Codable { enum CodingKeys: String, CodingKey { case objectID case conditions case consequence case isEnabled = "enabled" case validity case description } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.objectID = try container.decode(forKey: .objectID) self.conditions = try container.decodeIfPresent(forKey: .conditions) self.consequence = try container.decodeIfPresent(forKey: .consequence) self.isEnabled = try container.decodeIfPresent(forKey: .isEnabled) self.validity = try container.decodeIfPresent(forKey: .validity) self.description = try container.decodeIfPresent(forKey: .description) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(objectID, forKey: .objectID) try container.encodeIfPresent(conditions, forKey: .conditions) try container.encodeIfPresent(consequence, forKey: .consequence) try container.encodeIfPresent(isEnabled, forKey: .isEnabled) try container.encodeIfPresent(validity, forKey: .validity) try container.encodeIfPresent(description, forKey: .description) } }
mit
05e5d5bcc8e00742d19ed4a013eb734f
30.569444
105
0.732512
4.483235
false
false
false
false
haskelash/OraChat
OraChat/Clients/MessageClient.swift
1
3707
// // MessageClient.swift // OraChat // // Created by Haskel Ash on 8/23/16. // Copyright © 2016 Haskel Ash. All rights reserved. // import Alamofire class MessageClient { static let headers = [ "Content-Type": "application/json; charset=utf-8", "Accept": "application/json", "Authorization": "Bearer \(KeychainAccount.globalAccount.getToken())"] class func getList(chatID chatID: Int, success: ([Message])->()) { let endpoint = "https://private-d9e5b-oracodechallenge.apiary-mock.com/chats/\(chatID)/messages" Alamofire.request(.GET, endpoint, headers: headers, parameters: ["page": "1", "limit": "20"]) .responseJSON(completionHandler: { response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") success(messagesFromJSON(JSON)) } }) } class func createMessage(chatID chatID: Int, message: String, success: (Message)->()) { let endpoint = "https://private-d9e5b-oracodechallenge.apiary-mock.com/chats/\(chatID)/messages" Alamofire.request(.POST, endpoint, headers: headers, parameters: ["message": message], encoding: .JSON) .responseJSON(completionHandler: { response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") if let messageObject = messageFromJSON(JSON) { success(messageObject) } } }) } private class func messagesFromJSON(json: AnyObject) -> [Message] { if let data = json["data"] as? [AnyObject] { let messages = data.map({(messageData: AnyObject) -> Message? in if let messageID = messageData["id"] as? Int, let userID = messageData["user_id"] as? Int, let text = messageData["message"] as? String, let author = messageData["user"]??["name"] as? String, let creationString = messageData["created"] as? String { return Message(messageID: messageID, userID: userID, text: text, author: author, creationString: creationString) } return nil }) return messages.filter({$0 != nil}).map({$0!}) } return [Message]() } private class func messageFromJSON(json: AnyObject) -> Message? { if let dict = json as? [String: AnyObject], let data = dict["data"], let messageID = data["id"] as? Int, let userID = data["user_id"] as? Int, let text = data["message"] as? String, let author = data["user"]??["name"] as? String, let creationString = data["created"] as? String { return Message(messageID: messageID, userID: userID, text: text, author: author, creationString: creationString) } return nil } }
mit
1221f24fcd501bec68ad728228f8e942
39.282609
111
0.529951
4.928191
false
false
false
false
HarveyHu/PoolScoreboard
Pool Scoreboard/Pool Scoreboard/ClockViewController.swift
1
8416
// // ClockViewController.swift // Pool Scoreboard // // Created by HarveyHu on 12/01/2017. // Copyright © 2017 HarveyHu. All rights reserved. // import UIKit class ClockViewController: BaseViewController, UIPickerViewDataSource, UIPickerViewDelegate { let stopwatchView = UIView() let clockLabel = UILabel() let startButton = UIButton() let stopButton = UIButton() let extensionButton = UIButton() let viewModel = ClockViewModel() let pickerView = UIPickerView() var pickerDataArray = Array<Int>() override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) clockLabel.layer.cornerRadius = clockLabel.frame.size.width / 2.0 clockLabel.layer.masksToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func setUI() { super.setUI() self.view.addSubview(stopwatchView) self.stopwatchView.addSubview(clockLabel) self.stopwatchView.addSubview(startButton) self.stopwatchView.addSubview(stopButton) self.stopwatchView.addSubview(extensionButton) self.stopwatchView.addSubview(pickerView) self.view.backgroundColor = UIColor.white self.stopwatchView.backgroundColor = UIColor.black clockLabel.text = "\(viewModel.countdownSeconds)" clockLabel.textAlignment = .center clockLabel.textColor = UIColor.themeOrange() clockLabel.font = UIFont.boldSystemFont(ofSize: 100.0) clockLabel.layer.borderWidth = 10.0 clockLabel.layer.borderColor = UIColor.white.cgColor clockLabel.layer.masksToBounds = true clockLabel.adjustsFontSizeToFitWidth = true startButton.setTitle("START", for: .normal) startButton.setTitleColor(UIColor.white, for: .normal) startButton.setTitleColor(UIColor.orange, for: .highlighted) startButton.titleLabel?.font = UIFont.systemFont(ofSize: 30.0) startButton.titleLabel?.adjustsFontSizeToFitWidth = true stopButton.setTitle("STOP", for: .normal) stopButton.titleLabel?.font = UIFont.systemFont(ofSize: 30.0) stopButton.setTitleColor(UIColor.orange, for: .highlighted) stopButton.titleLabel?.adjustsFontSizeToFitWidth = true extensionButton.setTitle("EXTENSION", for: .normal) extensionButton.titleLabel?.font = UIFont.systemFont(ofSize: 30.0) extensionButton.setTitleColor(UIColor.orange, for: .highlighted) extensionButton.titleLabel?.adjustsFontSizeToFitWidth = true if pickerDataArray.count == 0 { for index in 10...100 { pickerDataArray.append(index) } } pickerView.dataSource = self pickerView.delegate = self pickerView.backgroundColor = UIColor.white pickerView.isHidden = true pickerView.selectRow(viewModel.countdownSeconds - 10, inComponent: 0, animated: false) } override func setUIConstraints() { super.setUIConstraints() let screenWidth = UIScreen.main.bounds.width stopwatchView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(20) make.leading.equalToSuperview().offset(10) make.trailing.equalToSuperview().offset(-10) make.bottom.equalToSuperview().offset(-10) } clockLabel.snp.makeConstraints { (make) in make.top.equalTo(screenWidth * 0.25) make.centerX.equalToSuperview() make.width.equalTo(self.view.snp.width).multipliedBy(0.5) make.height.equalTo(clockLabel.snp.width) } startButton.snp.makeConstraints { (make) in make.top.equalTo(clockLabel.snp.bottom).offset(50.0) make.centerX.equalToSuperview().offset(-screenWidth * 0.25) make.width.equalTo(screenWidth * 0.25) make.height.equalTo(startButton.snp.width).multipliedBy(0.5) } stopButton.snp.makeConstraints { (make) in make.top.equalTo(startButton.snp.top) make.centerX.equalToSuperview().offset(screenWidth * 0.25) make.width.equalTo(screenWidth * 0.25) make.height.equalTo(stopButton.snp.width).multipliedBy(0.5) } extensionButton.snp.makeConstraints { (make) in make.top.equalTo(startButton.snp.bottom).offset(20.0) make.centerX.equalToSuperview() make.width.equalTo(screenWidth * 0.5) make.height.equalTo(stopButton.snp.width).multipliedBy(0.5) } pickerView.snp.makeConstraints { (make) in make.bottom.equalToSuperview() make.leading.equalToSuperview() make.trailing.equalToSuperview() } } override func setUIEvents() { super.setUIEvents() startButton.rx.tap.asDriver() .drive(onNext: {[weak self] (tap) in guard let strongSelf = self else {return} strongSelf.viewModel.startTimer() strongSelf.viewModel.seconds.drive(onNext: { (second) in strongSelf.clockLabel.text = "\(second)" }, onCompleted: nil, onDisposed: nil) .disposed(by: strongSelf.disposeBag) }, onCompleted: nil, onDisposed: nil) .disposed(by: disposeBag) stopButton.rx.tap.asDriver() .drive(onNext: {[weak self] (tap) in guard let strongSelf = self else {return} strongSelf.viewModel.stopTimer() strongSelf.viewModel.seconds.drive(onNext: { (second) in strongSelf.clockLabel.text = "\(second)" }, onCompleted: nil, onDisposed: nil) .disposed(by: strongSelf.disposeBag) }, onCompleted: nil, onDisposed: nil) .disposed(by: disposeBag) extensionButton.rx.tap.asDriver() .drive(onNext: {[weak self] (tap) in guard let strongSelf = self else {return} strongSelf.viewModel.extentionCall() strongSelf.viewModel.seconds.drive(onNext: { (second) in strongSelf.clockLabel.text = "\(second)" }, onCompleted: nil, onDisposed: nil) .disposed(by: strongSelf.disposeBag) }, onCompleted: nil, onDisposed: nil) .disposed(by: disposeBag) pickerView.rx.itemSelected.asDriver() .drive(onNext: {[weak self] (rowAndComponent) in guard let strongSelf = self else {return} strongSelf.viewModel.stopTimer() strongSelf.viewModel.countdownSeconds = self!.pickerDataArray[rowAndComponent.0] strongSelf.clockLabel.text = "\(strongSelf.pickerDataArray[rowAndComponent.0])" strongSelf.pickerView.isHidden = true }, onCompleted: nil, onDisposed: nil) .disposed(by: disposeBag) let tapGR_clockLabel = UITapGestureRecognizer() tapGR_clockLabel.rx.event.asDriver().drive(onNext: {[weak self](tap) in if self!.pickerView.isHidden { self?.pickerView.isHidden = false } else { self?.pickerView.isHidden = true } }, onCompleted: nil, onDisposed: nil) .disposed(by: disposeBag) clockLabel.isUserInteractionEnabled = true clockLabel.addGestureRecognizer(tapGR_clockLabel) } // MARK - UIPickerView // returns the number of 'columns' to display. func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } // returns the # of rows in each component.. func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.pickerDataArray.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return "\(self.pickerDataArray[row])"; } }
mit
a038831f323b4acb596b8cc592f977a5
37.600917
111
0.615805
5.112394
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/RuleConfigurations/AttributesConfiguration.swift
1
1374
struct AttributesConfiguration: SeverityBasedRuleConfiguration, Equatable { var severityConfiguration = SeverityConfiguration(.warning) private(set) var alwaysOnSameLine = Set<String>() private(set) var alwaysOnNewLine = Set<String>() var consoleDescription: String { return severityConfiguration.consoleDescription + ", always_on_same_line: \(alwaysOnSameLine.sorted())" + ", always_on_line_above: \(alwaysOnNewLine.sorted())" } init(alwaysOnSameLine: [String] = ["@IBAction", "@NSManaged"], alwaysInNewLine: [String] = []) { self.alwaysOnSameLine = Set(alwaysOnSameLine) self.alwaysOnNewLine = Set(alwaysOnNewLine) } mutating func apply(configuration: Any) throws { guard let configuration = configuration as? [String: Any] else { throw ConfigurationError.unknownConfiguration } if let alwaysOnSameLine = configuration["always_on_same_line"] as? [String] { self.alwaysOnSameLine = Set(alwaysOnSameLine) } if let alwaysOnNewLine = configuration["always_on_line_above"] as? [String] { self.alwaysOnNewLine = Set(alwaysOnNewLine) } if let severityString = configuration["severity"] as? String { try severityConfiguration.apply(configuration: severityString) } } }
mit
7ef4a5a8f9f1aa6cece5d1d03cf75f7a
38.257143
85
0.6623
4.960289
false
true
false
false
jfosterdavis/FlashcardHero
FlashcardHeroTests/QuizletTests.swift
1
3624
// // QuizletTests.swift // FlashcardHeroTests // // Created by Jacob Foster Davis on 10/24/16. // Copyright © 2016 Zero Mu, LLC. All rights reserved. // import XCTest @testable import FlashcardHero class FlashcardHeroTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testQuizletTests() { //testQuizletSearchTestNoCriteria() testQuizletSearchTestSimple() testQuizletGetSet() testQuizletGetSetTermsOnly() } func testQuizletSearchTestNoCriteria() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. print("Starting Test") //using nothing. This should fail let testExpectation = expectation(description: "async request") QuizletClient.sharedInstance.getQuizletSearchSetsBy() { (results, error) in print("Reached CompletionHandler of getQuizletSearchSetsBy noCriteriaExpectation") print("results: \(results)") print("error: \(error)") if error != nil { testExpectation.fulfill() } } waitForExpectations(timeout: 10.0, handler: nil) } func testQuizletSearchTestSimple() { //using a search term let testExpectation = expectation(description: "async request") QuizletClient.sharedInstance.getQuizletSearchSetsBy("birds") { (results, error) in print("Reached CompletionHandler of getQuizletSearchSetsBy") print("results: \(results)") print("error: \(error)") if error == nil { testExpectation.fulfill() } } waitForExpectations(timeout: 10.0, handler: nil) } func testQuizletGetSet() { //using a search term let testExpectation = expectation(description: "async request") QuizletClient.sharedInstance.getQuizletSetTermsBy(6009523, termsOnly: false) { (results, error) in print("Reached CompletionHandler of getQuizletSearchSetsBy") print("results: \(results)") print("error: \(error)") if error == nil { testExpectation.fulfill() } } waitForExpectations(timeout: 10.0, handler: nil) } func testQuizletGetSetTermsOnly() { //using a search term let testExpectation = expectation(description: "async request") QuizletClient.sharedInstance.getQuizletSetTermsBy(6009523, termsOnly: true) { (results, error) in print("Reached CompletionHandler of getQuizletSearchSetsBy") print("results: \(results)") print("error: \(error)") if error == nil { testExpectation.fulfill() } } waitForExpectations(timeout: 10.0, handler: nil) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
apache-2.0
a927b58648d1265b5a7b63d7a30f5519
30.780702
111
0.580734
5.44812
false
true
false
false
stulevine/firefox-ios
Sync/StorageClient.swift
1
15483
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Alamofire import Shared import Account // Not an error that indicates a server problem, but merely an // error that encloses a StorageResponse. public class StorageResponseError<T>: ErrorType { public let response: StorageResponse<T> public init(_ response: StorageResponse<T>) { self.response = response } public var description: String { return "Error." } } public class RequestError: ErrorType { public let error: NSError? public init(_ err: NSError?) { self.error = err } public var description: String { let str = self.error?.localizedDescription ?? "No description" return "Request error: \(str)." } } public class BadRequestError<T>: StorageResponseError<T> { public let request: NSURLRequest public init(request: NSURLRequest, response: StorageResponse<T>) { self.request = request super.init(response) } override public var description: String { return "Bad request." } } public class ServerError<T>: StorageResponseError<T> { override public var description: String { return "Server error." } override public init(_ response: StorageResponse<T>) { super.init(response) } } public class NotFound<T>: StorageResponseError<T> { override public var description: String { return "Not found." } override public init(_ response: StorageResponse<T>) { super.init(response) } } public class RecordParseError: ErrorType { public var description: String { return "Failed to parse record." } } public class MalformedMetaGlobalError: ErrorType { public var description: String { return "Supplied meta/global for upload did not serialize to valid JSON." } } // Returns milliseconds. Handles decimals. private func optionalSecondsHeader(input: AnyObject?) -> Timestamp? { if input == nil { return nil } if let val = input as? String { if let timestamp = decimalSecondsStringToTimestamp(val) { return timestamp } } if let seconds: Double = input as? Double { // Oh for a BigDecimal library. return Timestamp(seconds * 1000) } if let seconds: NSNumber = input as? NSNumber { // Who knows. return seconds.unsignedLongLongValue * 1000 } return nil } private func optionalIntegerHeader(input: AnyObject?) -> Int64? { if input == nil { return nil } if let val = input as? String { return NSScanner(string: val).scanLongLong() } if let val: Double = input as? Double { // Oh for a BigDecimal library. return Int64(val) } if let val: NSNumber = input as? NSNumber { // Who knows. return val.longLongValue } return nil } private func optionalUIntegerHeader(input: AnyObject?) -> Timestamp? { if input == nil { return nil } if let val = input as? String { return NSScanner(string: val).scanUnsignedLongLong() } if let val: Double = input as? Double { // Oh for a BigDecimal library. return Timestamp(val) } if let val: NSNumber = input as? NSNumber { // Who knows. return val.unsignedLongLongValue } return nil } public struct ResponseMetadata { public let alert: String? public let nextOffset: String? public let records: UInt64? public let quotaRemaining: Int64? public let timestampMilliseconds: Timestamp // Non-optional. Server timestamp when handling request. public let lastModifiedMilliseconds: Timestamp? // Included for all success responses. Collection or record timestamp. public let backoffMilliseconds: UInt64? public let retryAfterMilliseconds: UInt64? public init(response: NSHTTPURLResponse) { self.init(headers: response.allHeaderFields) } public init(headers: [NSObject : AnyObject]) { alert = headers["X-Weave-Alert"] as? String nextOffset = headers["X-Weave-Next-Offset"] as? String records = optionalUIntegerHeader(headers["X-Weave-Records"]) quotaRemaining = optionalIntegerHeader(headers["X-Weave-Quota-Remaining"]) timestampMilliseconds = optionalSecondsHeader(headers["X-Weave-Timestamp"]) ?? 0 lastModifiedMilliseconds = optionalSecondsHeader(headers["X-Last-Modified"]) backoffMilliseconds = optionalSecondsHeader(headers["X-Weave-Backoff"]) ?? optionalSecondsHeader(headers["X-Backoff"]) retryAfterMilliseconds = optionalSecondsHeader(headers["Retry-After"]) } } public struct StorageResponse<T> { public let value: T public let metadata: ResponseMetadata init(value: T, metadata: ResponseMetadata) { self.value = value self.metadata = metadata } init(value: T, response: NSHTTPURLResponse) { self.value = value self.metadata = ResponseMetadata(response: response) } } public typealias Authorizer = (NSMutableURLRequest) -> NSMutableURLRequest public typealias ResponseHandler = (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void private func errorWrap<T>(deferred: Deferred<Result<T>>, handler: ResponseHandler) -> ResponseHandler { return { (request, response, data, error) in println("Response is \(response), data is \(data)") if let error = error { println("Got error.") deferred.fill(Result<T>(failure: RequestError(error))) return } if response == nil { // TODO: better error. println("No response") let result = Result<T>(failure: RecordParseError()) deferred.fill(result) return } let response = response! println("Status code: \(response.statusCode)") let err = StorageResponse(value: response, metadata: ResponseMetadata(response: response)) if response.statusCode >= 500 { let result = Result<T>(failure: ServerError(err)) deferred.fill(result) return } if response.statusCode == 404 { let result = Result<T>(failure: NotFound(err)) deferred.fill(result) return } if response.statusCode >= 400 { let result = Result<T>(failure: BadRequestError(request: request, response: err)) deferred.fill(result) return } handler(request, response, data, error) } } // Don't forget to batch downloads. public class Sync15StorageClient { private let authorizer: Authorizer private let serverURI: NSURL let workQueue: dispatch_queue_t let resultQueue: dispatch_queue_t public init(token: TokenServerToken, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t) { self.workQueue = workQueue self.resultQueue = resultQueue // This is a potentially dangerous assumption, but failable initializers up the stack are a giant pain. self.serverURI = NSURL(string: token.api_endpoint)! self.authorizer = { (r: NSMutableURLRequest) -> NSMutableURLRequest in let helper = HawkHelper(id: token.id, key: token.key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!) r.addValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization") return r } } public init(serverURI: NSURL, authorizer: Authorizer, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t) { self.serverURI = serverURI self.authorizer = authorizer self.workQueue = workQueue self.resultQueue = resultQueue } func requestGET(url: NSURL) -> Request { let req = NSMutableURLRequest(URL: url) req.HTTPMethod = Method.GET.rawValue req.addValue("application/json", forHTTPHeaderField: "Accept") let authorized: NSMutableURLRequest = self.authorizer(req) return Alamofire.request(authorized) .validate(contentType: ["application/json"]) } func requestDELETE(url: NSURL) -> Request { let req = NSMutableURLRequest(URL: url) req.HTTPMethod = Method.DELETE.rawValue req.addValue("1", forHTTPHeaderField: "X-Confirm-Delete") let authorized: NSMutableURLRequest = self.authorizer(req) return Alamofire.request(authorized) } private func doOp<T>(op: (NSURL) -> Request, path: String, f: (JSON) -> T?) -> Deferred<Result<StorageResponse<T>>> { let deferred = Deferred<Result<StorageResponse<T>>>(defaultQueue: self.resultQueue) let req = op(self.serverURI.URLByAppendingPathComponent(path)) req.responseParsedJSON(errorWrap(deferred, { (_, response, data, error) in if let json: JSON = data as? JSON { if let v = f(json) { let storageResponse = StorageResponse<T>(value: v, response: response!) deferred.fill(Result(success: storageResponse)) } else { deferred.fill(Result(failure: RecordParseError())) } return } deferred.fill(Result(failure: RecordParseError())) })) return deferred } private func putResource<T>(path: String, body: JSON, ifUnmodifiedSince: Timestamp?, f: (JSON) -> T?) -> Deferred<Result<StorageResponse<T>>> { func requestPUT(url: NSURL) -> Request { let req = NSMutableURLRequest(URL: url) req.HTTPMethod = Method.PUT.rawValue req.addValue("application/json", forHTTPHeaderField: "Accept") let authorized: NSMutableURLRequest = self.authorizer(req) if let ifUnmodifiedSince = ifUnmodifiedSince { req.addValue(millisecondsToDecimalSeconds(ifUnmodifiedSince), forHTTPHeaderField: "X-If-Unmodified-Since") } req.HTTPBody = body.toString().dataUsingEncoding(NSUTF8StringEncoding)! return Alamofire.request(authorized) .validate(contentType: ["application/json"]) } return doOp(requestPUT, path: path, f: f) } private func getResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Result<StorageResponse<T>>> { return doOp(self.requestGET, path: path, f: f) } private func deleteResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Result<StorageResponse<T>>> { return doOp(self.requestDELETE, path: path, f: f) } func getInfoCollections() -> Deferred<Result<StorageResponse<InfoCollections>>> { return getResource("info/collections", f: InfoCollections.fromJSON) } func getMetaGlobal() -> Deferred<Result<StorageResponse<GlobalEnvelope>>> { return getResource("storage/meta/global", f: { GlobalEnvelope($0) }) } func uploadMetaGlobal(metaGlobal: MetaGlobal, ifUnmodifiedSince: Timestamp?) -> Deferred<Result<StorageResponse<JSON>>> { let payload = metaGlobal.toPayload() if payload.isError { return Deferred(value: Result(failure: MalformedMetaGlobalError())) } // TODO finish this! let record: JSON = JSON(["payload": payload, "id": "global"]) return putResource("storage/meta/global", body: record, ifUnmodifiedSince: ifUnmodifiedSince, f: { $0 }) } func wipeStorage() -> Deferred<Result<StorageResponse<JSON>>> { // In Sync 1.5 it's preferred that we delete the root, not /storage. return deleteResource("", f: { $0 }) } // TODO: it would be convenient to have the storage client manage Keys, // but of course we need to use a different set of keys to fetch crypto/keys // itself. func clientForCollection<T: CleartextPayloadJSON>(collection: String, factory: (String) -> T?) -> Sync15CollectionClient<T> { let storage = self.serverURI.URLByAppendingPathComponent("storage", isDirectory: true) return Sync15CollectionClient(client: self, serverURI: storage, collection: collection, factory: factory) } } /** * We'd love to nest this in the overall storage client, but Swift * forbids the nesting of a generic class inside another class. */ public class Sync15CollectionClient<T: CleartextPayloadJSON> { private let client: Sync15StorageClient private let factory: (String) -> T? private let collectionURI: NSURL init(client: Sync15StorageClient, serverURI: NSURL, collection: String, factory: (String) -> T?) { self.client = client self.factory = factory self.collectionURI = serverURI.URLByAppendingPathComponent(collection, isDirectory: false) } private func uriForRecord(guid: String) -> NSURL { return self.collectionURI.URLByAppendingPathComponent(guid) } public func get(guid: String) -> Deferred<Result<StorageResponse<Record<T>>>> { let deferred = Deferred<Result<StorageResponse<Record<T>>>>(defaultQueue: client.resultQueue) let req = client.requestGET(uriForRecord(guid)) req.responseParsedJSON(errorWrap(deferred, { (_, response, data, error) in if let json: JSON = data as? JSON { let envelope = EnvelopeJSON(json) println("Envelope: \(envelope) is valid \(envelope.isValid())") let record = Record<T>.fromEnvelope(envelope, payloadFactory: self.factory) if let record = record { let storageResponse = StorageResponse(value: record, response: response!) deferred.fill(Result(success: storageResponse)) return } } else { println("Couldn't cast JSON.") } deferred.fill(Result(failure: RecordParseError())) })) return deferred } /** * Unlike every other Sync client, we use the application/json format for fetching * multiple requests. The others use application/newlines. We don't want to write * another Serializer, and we're loading everything into memory anyway. */ public func getSince(since: Timestamp) -> Deferred<Result<StorageResponse<[Record<T>]>>> { let deferred = Deferred<Result<StorageResponse<[Record<T>]>>>(defaultQueue: client.resultQueue) let req = client.requestGET(self.collectionURI.withQueryParam("full", value: "1")) req.responseParsedJSON(errorWrap(deferred, { (_, response, data, error) in if let json: JSON = data as? JSON { func recordify(json: JSON) -> Record<T>? { let envelope = EnvelopeJSON(json) return Record<T>.fromEnvelope(envelope, payloadFactory: self.factory) } if let arr = json.asArray { let response = StorageResponse(value: optFilter(arr.map(recordify)), response: response!) deferred.fill(Result(success: response)) return } } deferred.fill(Result(failure: RecordParseError())) return })) return deferred } }
mpl-2.0
2491709cd2551940a8576d9aba186b70
34.188636
147
0.639734
4.765466
false
false
false
false
tscholze/swift-sepp-the-server
Sepp/Classes/Templating/TemplateBuilder.swift
1
2039
// // TemplateBuilder.swift // Sepp // // Created by Tobias Scholze on 08/12/15. // Copyright © 2015 Tobias Scholze. All rights reserved. // import Foundation import Mustache class TemplateBuilder { /// Returns a rendering without custom data for identifier /// /// - parameter identifier: Template identifier class func getRendering(identifier: String) -> String { let template = try! Template(named: identifier) return try! template.render() } /// Returns a rendering with custom data for identifier /// /// - parameter identifier: Template identifier /// - parameter data: String dictionary with data class func getRendering(identifier: String, data: [String: String]) -> String { let template = try! Template(named: identifier) return try! template.render(Box(data)) } /// Returns a rendering for a directory listing /// /// - parameter folder: Name of the folder /// - parameter data: Listing html content class func getRenderingForDirectoryListing(folder: String, listing: String) -> String { let data = ["folder": folder, "listing": listing] return getRendering("dirlisting", data: data) } /// Returns a rendering for a directory item /// /// - parameter link: Link aka path to the directory /// - parameter item: Name / human readable identifier of the item class func getRenderingForDirectoryListingItem(link: String, item: String) -> String { let data = ["link": link, "item": item] return getRendering("dirlisting-item", data: data) } /// Returns a rendering for a file item /// /// - parameter link: Link aka path to the file /// - parameter item: Name / human readable identifier of the item class func getRenderingForDirectoryListingDirectory(link: String, item: String) -> String { let data = ["link": link, "item": item] return getRendering("dirlisting-directory", data: data) } }
mit
b9734f69e4dc7cb25d64220b83487605
31.887097
93
0.649657
4.538976
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/Font/Decoder/SFNTFontFace/OTFGSUB.swift
1
2083
// // OTFGSUB.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // struct OTFGSUB: ByteDecodable { var version: Fixed16Number<BEInt32> var scriptListOffset: BEUInt16 var featureListOffset: BEUInt16 var lookupListOffset: BEUInt16 var scriptList: OTFScriptList var featureList: OTFFeatureList var lookupList: OTFLookupList init(from data: inout Data) throws { let copy = data self.version = try data.decode(Fixed16Number<BEInt32>.self) self.scriptListOffset = try data.decode(BEUInt16.self) self.featureListOffset = try data.decode(BEUInt16.self) self.lookupListOffset = try data.decode(BEUInt16.self) self.scriptList = try OTFScriptList(copy.dropFirst(Int(scriptListOffset))) self.featureList = try OTFFeatureList(copy.dropFirst(Int(featureListOffset))) self.lookupList = try OTFLookupList(copy.dropFirst(Int(lookupListOffset))) } }
mit
2325317133a2f0387e9b8bd4bf6bcd8e
42.395833
85
0.732117
4.157685
false
false
false
false
skedgo/tripkit-ios
Sources/TripKit/search/TKRegionAutocompleter.swift
1
2017
// // TKRegionAutocompleter.swift // TripKit-iOS // // Created by Adrian Schönig on 6/8/21. // Copyright © 2021 SkedGo Pty Ltd. All rights reserved. // import Foundation import MapKit /// An autocompleter for cities in supported TripGo regions /// /// Implements ``TKAutocompleting``, providing instances of ``TKRegion/City`` in /// ``TKAutocompletionResult/object``. public class TKRegionAutocompleter: TKAutocompleting { public init() { } public func autocomplete(_ input: String, near mapRect: MKMapRect, completion: @escaping (Result<[TKAutocompletionResult], Error>) -> Void) { let scoredMatches = TKRegionManager.shared.regions .flatMap { region -> [(TKRegion.City, score: Int)] in if input.isEmpty { return region.cities.map { ($0, 100) } } else { return region.cities.compactMap { city in guard let name = city.title else { return nil } let titleScore = TKAutocompletionResult.nameScore(searchTerm: input, candidate: name) guard titleScore > 0 else { return nil } let distanceScore = TKAutocompletionResult.distanceScore(from: city.coordinate, to: .init(mapRect), longDistance: true) let rawScore = (titleScore * 9 + distanceScore) / 10 let score = TKAutocompletionResult.rangedScore(for: rawScore, min: 10, max: 70) return (city, score) } } } let image = TKAutocompletionResult.image(for: .city) let results = scoredMatches.map { tuple -> TKAutocompletionResult in return TKAutocompletionResult( object: tuple.0, title: tuple.0.title!, // we filtered those out without a name image: image, score: tuple.score ) } completion(.success(results)) } public func annotation(for result: TKAutocompletionResult, completion: @escaping (Result<MKAnnotation?, Error>) -> Void) { let city = result.object as! TKRegion.City completion(.success(city)) } }
apache-2.0
48e8d272776fc693e9cc0bdb88ebf552
34.350877
143
0.655583
4.457965
false
false
false
false
Swift-Kit/JZHoverNSButton
JZHoverNSButton.swift
1
3249
// // JZHoverNSButton.swift // // Created by Joey on 8/28/15. // Copyright (c) 2015 Joey Zhou. All rights reserved. // import Cocoa class JZHoverNSButton: NSButton { var trackingArea:NSTrackingArea! var hoverBackgroundColor: NSColor = NSColor.grayColor() var originalBackgroundColor: NSColor = NSColor.whiteColor() var hoverBackgroundImage: NSImage! var originalBackgroundImage: NSImage! var attributedStr: NSMutableAttributedString! // MARK: - Initializers override init(frame frameRect: NSRect) { super.init(frame: frameRect) // set tracking area let opts: NSTrackingAreaOptions = ([NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.ActiveAlways]) trackingArea = NSTrackingArea(rect: bounds, options: opts, owner: self, userInfo: nil) self.addTrackingArea(trackingArea) } required init?(coder: NSCoder) { super.init(coder: coder) // set tracking area let opts: NSTrackingAreaOptions = ([NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.ActiveAlways]) trackingArea = NSTrackingArea(rect: bounds, options: opts, owner: self, userInfo: nil) self.addTrackingArea(trackingArea) } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) // Drawing code here. } // MARK: mouse events override func mouseEntered(theEvent: NSEvent) { let cell = self.cell as! NSButtonCell cell.backgroundColor = hoverBackgroundColor cell.image = hoverBackgroundImage } override func mouseExited(theEvent: NSEvent) { let cell = self.cell as! NSButtonCell cell.backgroundColor = originalBackgroundColor cell.image = originalBackgroundImage } // MARK: background setters func setImages(bgColor: NSColor, imageOriginal: NSImage, imageHover: NSImage) { self.hoverBackgroundColor = bgColor self.originalBackgroundColor = bgColor self.originalBackgroundImage = imageOriginal self.hoverBackgroundImage = imageHover } func setColors(originalBgColor: NSColor, hoverBgColor:NSColor) { self.hoverBackgroundColor = hoverBgColor self.originalBackgroundColor = originalBgColor self.originalBackgroundImage = nil self.hoverBackgroundImage = nil } // MARK: attributed text setters func setText(str: String, color: NSColor, size: Int64) { attributedStr = NSMutableAttributedString(string: str) attributedStr.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length:attributedStr.length)) attributedStr.addAttribute(NSFontSizeAttribute, value: size.description, range: NSRange(location: 0, length:attributedStr.length)) self.attributedTitle = attributedStr } func setText(str: String, color: NSColor) { attributedStr = NSMutableAttributedString(string: str) attributedStr.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length:attributedStr.length)) self.attributedTitle = attributedStr } }
mit
190d7e0b0158fc3aa355a138c0428eeb
35.931818
138
0.694983
5.32623
false
false
false
false
arvedviehweger/swift
test/Prototypes/BigInt.swift
1
54699
//===--- BigInt.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 // //===----------------------------------------------------------------------===// // XFAIL: linux // RUN: rm -rf %t ; mkdir -p %t // RUN: %target-build-swift -swift-version 4 -o %t/a.out %s // RUN: %target-run %t/a.out // REQUIRES: executable_test // REQUIRES: CPU=x86_64 import StdlibUnittest import Darwin extension FixedWidthInteger { /// Returns the high and low parts of a potentially overflowing addition. func addingFullWidth(_ other: Self) -> (high: Self, low: Self) { let sum = self.addingReportingOverflow(other) return (sum.overflow == .overflow ? 1 : 0, sum.partialValue) } /// Returns the high and low parts of two seqeuential potentially overflowing /// additions. static func addingFullWidth(_ x: Self, _ y: Self, _ z: Self) -> (high: Self, low: Self) { let xy = x.addingReportingOverflow(y) let xyz = xy.partialValue.addingReportingOverflow(z) let high: Self = (xy.overflow == .overflow ? 1 : 0) + (xyz.overflow == .overflow ? 1 : 0) return (high, xyz.partialValue) } /// Returns a tuple containing the value that would be borrowed from a higher /// place and the partial difference of this value and `rhs`. func subtractingWithBorrow(_ rhs: Self) -> (borrow: Self, partialValue: Self) { let difference = subtractingReportingOverflow(rhs) return (difference.overflow == .overflow ? 1 : 0, difference.partialValue) } /// Returns a tuple containing the value that would be borrowed from a higher /// place and the partial value of `x` and `y` subtracted from this value. func subtractingWithBorrow(_ x: Self, _ y: Self) -> (borrow: Self, partialValue: Self) { let firstDifference = subtractingReportingOverflow(x) let secondDifference = firstDifference.partialValue.subtractingReportingOverflow(y) let borrow: Self = (firstDifference.overflow == .overflow ? 1 : 0) + (secondDifference.overflow == .overflow ? 1 : 0) return (borrow, secondDifference.partialValue) } } //===--- BigInt -----------------------------------------------------------===// //===----------------------------------------------------------------------===// /// A dynamically-sized signed integer. /// /// The `_BigInt` type is fully generic on the size of its "word" -- the /// `BigInt` alias uses the system's word-sized `UInt` as its word type, but /// any word size should work properly. public struct _BigInt<Word: FixedWidthInteger & UnsignedInteger> : BinaryInteger, SignedInteger, CustomStringConvertible, CustomDebugStringConvertible where Word.Magnitude == Word { /// The binary representation of the value's magnitude, with the least /// significant word at index `0`. /// /// - `_data` has no trailing zero elements /// - If `self == 0`, then `isNegative == false` and `_data == []` internal var _data: [Word] = [] /// A Boolean value indicating whether this instance is negative. public private(set) var isNegative = false /// A Boolean value indicating whether this instance is equal to zero. public var isZero: Bool { return _data.count == 0 } //===--- Numeric initializers -------------------------------------------===// /// Creates a new instance equal to zero. public init() { } /// Creates a new instance using `_data` as the data collection. init<C: Collection>(_ _data: C) where C.Iterator.Element == Word { self._data = Array(_data) _standardize() } public init(integerLiteral value: Int) { self.init(value) } public init<T : BinaryInteger>(_ source: T) { var source = source if source < 0 as T { if source.bitWidth <= UInt64.bitWidth { let sourceMag = Int(extendingOrTruncating: source).magnitude self = _BigInt(sourceMag) self.isNegative = true return } else { // Have to kind of assume that we're working with another BigInt here self.isNegative = true source *= -1 } } // FIXME: This is broken on 32-bit arch w/ Word = UInt64 let wordRatio = UInt.bitWidth / Word.bitWidth _sanityCheck(wordRatio != 0) for i in 0..<source.countRepresentedWords { var sourceWord = source._word(at: i) for _ in 0..<wordRatio { _data.append(Word(extendingOrTruncating: sourceWord)) sourceWord >>= Word.bitWidth } } _standardize() } public init?<T : BinaryInteger>(exactly source: T) { self.init(source) } public init<T : BinaryInteger>(extendingOrTruncating source: T) { self.init(source) } public init<T : BinaryInteger>(clamping source: T) { self.init(source) } public init<T : FloatingPoint>(_ source: T) { fatalError("Not implemented") } public init?<T : FloatingPoint>(exactly source: T) { fatalError("Not implemented") } /// Returns a randomly-generated word. static func _randomWord() -> Word { // This handles up to a 64-bit word if Word.bitWidth > UInt32.bitWidth { return Word(arc4random()) << 32 | Word(arc4random()) } else { return Word(extendingOrTruncating: arc4random()) } } /// Creates a new instance whose magnitude has `randomBits` bits of random /// data. The sign of the new value is randomly selected. public init(randomBits: Int) { let (words, extraBits) = randomBits.quotientAndRemainder(dividingBy: Word.bitWidth) // Get the bits for any full words. self._data = (0..<words).map({ _ in _BigInt._randomWord() }) // Get another random number - the highest bit will determine the sign, // while the lower `Word.bitWidth - 1` bits are available for any leftover // bits in `randomBits`. let word = _BigInt._randomWord() if extraBits != 0 { let mask = ~((~0 as Word) << Word(extraBits)) _data.append(word & mask) } isNegative = word & ~(~0 >> 1) == 0 _standardize() } //===--- Private methods ------------------------------------------------===// /// Standardizes this instance after mutation, removing trailing zeros /// and making sure zero is nonnegative. Calling this method satisfies the /// two invariants. mutating func _standardize(source: String = #function) { defer { _checkInvariants(source: source + " >> _standardize()") } while _data.last == 0 { _data.removeLast() } // Zero is never negative. isNegative = isNegative && _data.count != 0 } /// Checks and asserts on invariants -- all invariants must be satisfied /// at the end of every mutating method. /// /// - `_data` has no trailing zero elements /// - If `self == 0`, then `isNegative == false` func _checkInvariants(source: String = #function) { if _data.count == 0 { assert(isNegative == false, "\(source): isNegative with zero length _data") } assert(_data.last != 0, "\(source): extra zeroes on _data") } //===--- Word-based arithmetic ------------------------------------------===// mutating func _unsignedAdd(_ rhs: Word) { defer { _standardize() } // Quick return if `rhs == 0` guard rhs != 0 else { return } // Quick return if `self == 0` if isZero { _data.append(rhs) return } // Add `rhs` to the first word, catching any carry. var carry: Word (carry, _data[0]) = _data[0].addingFullWidth(rhs) // Handle any additional carries for i in 1..<_data.count { // No more action needed if there's nothing to carry if carry == 0 { break } (carry, _data[i]) = _data[i].addingFullWidth(carry) } // If there's any carry left, add it now if carry != 0 { _data.append(1) } } /// Subtracts `rhs` from this instance, ignoring the sign. /// /// - Precondition: `rhs <= self.magnitude` mutating func _unsignedSubtract(_ rhs: Word) { _precondition(_data.count > 1 || _data[0] > rhs) // Quick return if `rhs == 0` guard rhs != 0 else { return } // If `isZero == true`, then `rhs` must also be zero. _precondition(!isZero) var carry: Word (carry, _data[0]) = _data[0].subtractingWithBorrow(rhs) for i in 1..<_data.count { // No more action needed if there's nothing to carry if carry == 0 { break } (carry, _data[i]) = _data[i].subtractingWithBorrow(carry) } _sanityCheck(carry == 0) _standardize() } /// Adds `rhs` to this instance. mutating func add(_ rhs: Word) { if isNegative { // If _data only contains one word and `rhs` is greater, swap them, // make self positive and continue with unsigned subtraction. var rhs = rhs if _data.count == 1 && _data[0] < rhs { swap(&rhs, &_data[0]) isNegative = false } _unsignedSubtract(rhs) } else { // positive or zero _unsignedAdd(rhs) } } /// Subtracts `rhs` from this instance. mutating func subtract(_ rhs: Word) { guard rhs != 0 else { return } if isNegative { _unsignedAdd(rhs) } else if isZero { isNegative = true _data.append(rhs) } else { var rhs = rhs if _data.count == 1 && _data[0] < rhs { swap(&rhs, &_data[0]) isNegative = true } _unsignedSubtract(rhs) } } /// Multiplies this instance by `rhs`. mutating func multiply(by rhs: Word) { // If either `self` or `rhs` is zero, the result is zero. guard !isZero && rhs != 0 else { self = 0 return } // If `rhs` is a power of two, can just left shift `self`. let rhsLSB = rhs.trailingZeroBitCount if rhs >> rhsLSB == 1 { self <<= rhsLSB return } var carry: Word = 0 for i in 0..<_data.count { let product = _data[i].multipliedFullWidth(by: rhs) (carry, _data[i]) = product.low.addingFullWidth(carry) carry = carry &+ product.high } // Add the leftover carry if carry != 0 { _data.append(carry) } _standardize() } /// Divides this instance by `rhs`, returning the remainder. @discardableResult mutating func divide(by rhs: Word) -> Word { _precondition(rhs != 0, "divide by zero") // No-op if `rhs == 1` or `self == 0`. if rhs == 1 || isZero { return 0 } // If `rhs` is a power of two, can just right shift `self`. let rhsLSB = rhs.trailingZeroBitCount if rhs >> rhsLSB == 1 { defer { self >>= rhsLSB } return _data[0] & ~(~0 << rhsLSB) } var carry: Word = 0 for i in (0..<_data.count).reversed() { let lhs = (high: carry, low: _data[i]) (_data[i], carry) = rhs.dividingFullWidth(lhs) } _standardize() return carry } //===--- Numeric --------------------------------------------------------===// public typealias Magnitude = _BigInt public var magnitude: _BigInt { var result = self result.isNegative = false return result } /// Adds `rhs` to this instance, ignoring any signs. mutating func _unsignedAdd(_ rhs: _BigInt) { defer { _checkInvariants() } let commonCount = Swift.min(_data.count, rhs._data.count) let maxCount = Swift.max(_data.count, rhs._data.count) _data.reserveCapacity(maxCount) // Add the words up to the common count, carrying any overflows var carry: Word = 0 for i in 0..<commonCount { (carry, _data[i]) = Word.addingFullWidth(_data[i], rhs._data[i], carry) } // If there are leftover words in `self`, just need to handle any carries if _data.count > rhs._data.count { for i in commonCount..<maxCount { // No more action needed if there's nothing to carry if carry == 0 { break } (carry, _data[i]) = _data[i].addingFullWidth(carry) } // If there are leftover words in `rhs`, need to copy to `self` with carries } else if _data.count < rhs._data.count { for i in commonCount..<maxCount { // Append remaining words if nothing to carry if carry == 0 { _data.append(contentsOf: rhs._data.suffix(from: i)) break } let sum: Word (carry, sum) = rhs._data[i].addingFullWidth(carry) _data.append(sum) } } // If there's any carry left, add it now if carry != 0 { _data.append(1) } } /// Subtracts `rhs` from this instance, ignoring the sign. /// /// - Precondition: `rhs.magnitude <= self.magnitude` (unchecked) /// - Precondition: `rhs._data.count <= self._data.count` mutating func _unsignedSubtract(_ rhs: _BigInt) { _precondition(rhs._data.count <= _data.count) var carry: Word = 0 for i in 0..<rhs._data.count { (carry, _data[i]) = _data[i].subtractingWithBorrow(rhs._data[i], carry) } for i in rhs._data.count..<_data.count { // No more action needed if there's nothing to carry if carry == 0 { break } (carry, _data[i]) = _data[i].subtractingWithBorrow(carry) } _sanityCheck(carry == 0) _standardize() } public static func +=(lhs: inout _BigInt, rhs: _BigInt) { defer { lhs._checkInvariants() } if lhs.isNegative == rhs.isNegative { lhs._unsignedAdd(rhs) } else { lhs -= -rhs } } public static func -=(lhs: inout _BigInt, rhs: _BigInt) { defer { lhs._checkInvariants() } // Subtracting something of the opposite sign just adds magnitude. guard lhs.isNegative == rhs.isNegative else { lhs._unsignedAdd(rhs) return } // Comare `lhs` and `rhs` so we can use `_unsignedSubtract` to subtract // the smaller magnitude from the larger magnitude. switch lhs._compareMagnitude(to: rhs) { case .equal: lhs = 0 case .greaterThan: lhs._unsignedSubtract(rhs) case .lessThan: // x - y == -y + x == -(y - x) var result = rhs result._unsignedSubtract(lhs) result.isNegative = !lhs.isNegative lhs = result } } public static func *=(lhs: inout _BigInt, rhs: _BigInt) { // If either `lhs` or `rhs` is zero, the result is zero. guard !lhs.isZero && !rhs.isZero else { lhs = 0 return } var newData: [Word] = Array(repeating: 0, count: lhs._data.count + rhs._data.count) let (a, b) = lhs._data.count > rhs._data.count ? (lhs._data, rhs._data) : (rhs._data, lhs._data) _sanityCheck(a.count >= b.count) var carry: Word = 0 for ai in 0..<a.count { carry = 0 for bi in 0..<b.count { // Each iteration needs to perform this operation: // // newData[ai + bi] += (a[ai] * b[bi]) + carry // // However, `a[ai] * b[bi]` produces a double-width result, and both // additions can overflow to a higher word. The following two lines // capture the low word of the multiplication and additions in // `newData[ai + bi]` and any addition overflow in `carry`. let product = a[ai].multipliedFullWidth(by: b[bi]) (carry, newData[ai + bi]) = Word.addingFullWidth( newData[ai + bi], product.low, carry) // Now we combine the high word of the multiplication with any addition // overflow. It is safe to add `product.high` and `carry` here without // checking for overflow, because if `product.high == .max - 1`, then // `carry <= 1`. Otherwise, `carry <= 2`. // // Worst-case (aka 9 + 9*9 + 9): // // newData a[ai] b[bi] carry // 0b11111111 + (0b11111111 * 0b11111111) + 0b11111111 // 0b11111111 + (0b11111110_____00000001) + 0b11111111 // (0b11111111_____00000000) + 0b11111111 // (0b11111111_____11111111) // // Second-worse case: // // 0b11111111 + (0b11111111 * 0b11111110) + 0b11111111 // 0b11111111 + (0b11111101_____00000010) + 0b11111111 // (0b11111110_____00000001) + 0b11111111 // (0b11111111_____00000000) _sanityCheck( product.high.addingReportingOverflow(carry).overflow == .none) carry = product.high &+ carry } // Leftover `carry` is inserted in new highest word. _sanityCheck(newData[ai + b.count] == 0) newData[ai + b.count] = carry } lhs._data = newData lhs.isNegative = lhs.isNegative != rhs.isNegative lhs._standardize() } /// Divides this instance by `rhs`, returning the remainder. @discardableResult mutating func _internalDivide(by rhs: _BigInt) -> _BigInt { _precondition(!rhs.isZero, "Divided by zero") defer { _checkInvariants() } // Handle quick cases that don't require division: // If `abs(self) < abs(rhs)`, the result is zero, remainder = self // If `abs(self) == abs(rhs)`, the result is 1 or -1, remainder = 0 switch _compareMagnitude(to: rhs) { case .lessThan: defer { self = 0 } return self case .equal: self = isNegative != rhs.isNegative ? -1 : 1 return 0 default: break } var tempSelf = self.magnitude let n = tempSelf.bitWidth - rhs.magnitude.bitWidth var quotient: _BigInt = 0 var tempRHS = rhs.magnitude << n var tempQuotient: _BigInt = 1 << n for _ in (0...n).reversed() { if tempRHS._compareMagnitude(to: tempSelf) != .greaterThan { tempSelf -= tempRHS quotient += tempQuotient } tempRHS >>= 1 tempQuotient >>= 1 } // `tempSelf` is the remainder - match sign of original `self` tempSelf.isNegative = self.isNegative tempSelf._standardize() quotient.isNegative = isNegative != rhs.isNegative self = quotient _standardize() return tempSelf } public static func /=(lhs: inout _BigInt, rhs: _BigInt) { lhs._internalDivide(by: rhs) } // FIXME: Remove once default implementations are provided: public static func +(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt { var lhs = lhs lhs += rhs return lhs } public static func -(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt { var lhs = lhs lhs -= rhs return lhs } public static func *(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt { var lhs = lhs lhs *= rhs return lhs } public static func /(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt { var lhs = lhs lhs /= rhs return lhs } public static func %(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt { var lhs = lhs lhs %= rhs return lhs } //===--- BinaryInteger --------------------------------------------------===// /// Creates a new instance using the given data array in two's complement /// representation. init(_twosComplementData: [Word]) { guard _twosComplementData.count > 0 else { self = 0 return } // Is the highest bit set? isNegative = _twosComplementData.last!.leadingZeroBitCount == 0 if isNegative { _data = _twosComplementData.map(~) self._unsignedAdd(1 as Word) } else { _data = _twosComplementData } _standardize() } /// Returns an array of the value's data using two's complement representation. func _dataAsTwosComplement() -> [Word] { // Special cases: // * Nonnegative values are already in 2's complement if !isNegative { // Positive values need to have a leading zero bit if _data.last?.leadingZeroBitCount == 0 { return _data + [0] } else { return _data } } // * -1 will get zeroed out below, easier to handle here if _data.count == 1 && _data.first == 1 { return [~0] } var x = self x._unsignedSubtract(1 as Word) if x._data.last!.leadingZeroBitCount == 0 { // The highest bit is set to 1, which moves to 0 after negation. // We need to add another word at the high end so the highest bit is 1. return x._data.map(~) + [Word.max] } else { // The highest bit is set to 0, which moves to 1 after negation. return x._data.map(~) } } public func _word(at n: Int) -> UInt { let ratio = UInt.bitWidth / Word.bitWidth _sanityCheck(ratio != 0) var twosComplementData = _dataAsTwosComplement() // Find beginning of range. If we're beyond the value, return 1s or 0s. let start = n * ratio if start >= twosComplementData.count { return isNegative ? UInt.max : 0 } // Find end of range. If the range extends beyond the representation, // add bits to the end. let end = (n + 1) * ratio if end > twosComplementData.count { twosComplementData.append(contentsOf: repeatElement(isNegative ? Word.max : 0, count: end - twosComplementData.count)) } // Build the correct word from the range determined above. let wordSlice = twosComplementData[start..<end] var result: UInt = 0 for v in wordSlice.reversed() { result <<= Word.bitWidth result |= UInt(extendingOrTruncating: v) } return result } /// The number of bits used for storage of this value. Always a multiple of /// `Word.bitWidth`. public var bitWidth: Int { if isZero { return 0 } else { let twosComplementData = _dataAsTwosComplement() // If negative, it's okay to have 1s padded on high end if isNegative { return twosComplementData.count * Word.bitWidth } // If positive, need to make space for at least one zero on high end return twosComplementData.count * Word.bitWidth - twosComplementData.last!.leadingZeroBitCount + 1 } } /// The number of sequential zeros in the least-significant position of this /// value's binary representation. /// /// The numbers 1 and zero have zero trailing zeros. public var trailingZeroBitCount: Int { guard !isZero else { return 0 } let i = _data.index(where: { $0 != 0 })! _sanityCheck(_data[i] != 0) return i * Word.bitWidth + _data[i].trailingZeroBitCount } public static func %=(lhs: inout _BigInt, rhs: _BigInt) { defer { lhs._checkInvariants() } lhs = lhs._internalDivide(by: rhs) } public func quotientAndRemainder(dividingBy rhs: _BigInt) -> (_BigInt, _BigInt) { var x = self let r = x._internalDivide(by: rhs) return (x, r) } public static func &=(lhs: inout _BigInt, rhs: _BigInt) { var lhsTemp = lhs._dataAsTwosComplement() let rhsTemp = rhs._dataAsTwosComplement() // If `lhs` is longer than `rhs`, behavior depends on sign of `rhs` // * If `rhs < 0`, length is extended with 1s // * If `rhs >= 0`, length is extended with 0s, which crops `lhsTemp` if lhsTemp.count > rhsTemp.count && !rhs.isNegative { lhsTemp.removeLast(lhsTemp.count - rhsTemp.count) } // If `rhs` is longer than `lhs`, behavior depends on sign of `lhs` // * If `lhs < 0`, length is extended with 1s, so `lhs` should get extra // bits from `rhs` // * If `lhs >= 0`, length is extended with 0s if lhsTemp.count < rhsTemp.count && lhs.isNegative { lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count]) } // Perform bitwise & on words that both `lhs` and `rhs` have. for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) { lhsTemp[i] &= rhsTemp[i] } lhs = _BigInt(_twosComplementData: lhsTemp) } public static func |=(lhs: inout _BigInt, rhs: _BigInt) { var lhsTemp = lhs._dataAsTwosComplement() let rhsTemp = rhs._dataAsTwosComplement() // If `lhs` is longer than `rhs`, behavior depends on sign of `rhs` // * If `rhs < 0`, length is extended with 1s, so those bits of `lhs` // should all be 1 // * If `rhs >= 0`, length is extended with 0s, which is a no-op if lhsTemp.count > rhsTemp.count && rhs.isNegative { lhsTemp.replaceSubrange(rhsTemp.count..<lhsTemp.count, with: repeatElement(Word.max, count: lhsTemp.count - rhsTemp.count)) } // If `rhs` is longer than `lhs`, behavior depends on sign of `lhs` // * If `lhs < 0`, length is extended with 1s, so those bits of lhs // should all be 1 // * If `lhs >= 0`, length is extended with 0s, so those bits should be // copied from rhs if lhsTemp.count < rhsTemp.count { if lhs.isNegative { lhsTemp.append(contentsOf: repeatElement(Word.max, count: rhsTemp.count - lhsTemp.count)) } else { lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count]) } } // Perform bitwise | on words that both `lhs` and `rhs` have. for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) { lhsTemp[i] |= rhsTemp[i] } lhs = _BigInt(_twosComplementData: lhsTemp) } public static func ^=(lhs: inout _BigInt, rhs: _BigInt) { var lhsTemp = lhs._dataAsTwosComplement() let rhsTemp = rhs._dataAsTwosComplement() // If `lhs` is longer than `rhs`, behavior depends on sign of `rhs` // * If `rhs < 0`, length is extended with 1s, so those bits of `lhs` // should all be flipped // * If `rhs >= 0`, length is extended with 0s, which is a no-op if lhsTemp.count > rhsTemp.count && rhs.isNegative { for i in rhsTemp.count..<lhsTemp.count { lhsTemp[i] = ~lhsTemp[i] } } // If `rhs` is longer than `lhs`, behavior depends on sign of `lhs` // * If `lhs < 0`, length is extended with 1s, so those bits of `lhs` // should all be flipped copies of `rhs` // * If `lhs >= 0`, length is extended with 0s, so those bits should // be copied from rhs if lhsTemp.count < rhsTemp.count { if lhs.isNegative { lhsTemp += rhsTemp.suffix(from: lhsTemp.count).map(~) } else { lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count]) } } // Perform bitwise ^ on words that both `lhs` and `rhs` have. for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) { lhsTemp[i] ^= rhsTemp[i] } lhs = _BigInt(_twosComplementData: lhsTemp) } public static prefix func ~(x: _BigInt) -> _BigInt { return -x - 1 } //===--- SignedNumeric --------------------------------------------------===// public static prefix func -(x: inout _BigInt) { defer { x._checkInvariants() } guard x._data.count > 0 else { return } x.isNegative = !x.isNegative } //===--- Strideable -----------------------------------------------------===// public func distance(to other: _BigInt) -> _BigInt { return other - self } public func advanced(by n: _BigInt) -> _BigInt { return self + n } //===--- Other arithmetic -----------------------------------------------===// /// Returns the greatest common divisor for this value and `other`. public func greatestCommonDivisor(with other: _BigInt) -> _BigInt { // Quick return if either is zero if other.isZero { return magnitude } if isZero { return other.magnitude } var (x, y) = (self.magnitude, other.magnitude) let (xLSB, yLSB) = (x.trailingZeroBitCount, y.trailingZeroBitCount) // Remove any common factor of two let commonPower = Swift.min(xLSB, yLSB) x >>= commonPower y >>= commonPower // Remove any remaining factor of two if xLSB != commonPower { x >>= xLSB - commonPower } if yLSB != commonPower { y >>= yLSB - commonPower } while !x.isZero { // Swap values to ensure that `x >= y`. if x._compareMagnitude(to: y) == .lessThan { swap(&x, &y) } // Subtract smaller and remove any factors of two x._unsignedSubtract(y) x >>= x.trailingZeroBitCount } // Add original common factor of two back into result y <<= commonPower return y } /// Returns the lowest common multiple for this value and `other`. public func lowestCommonMultiple(with other: _BigInt) -> _BigInt { let gcd = greatestCommonDivisor(with: other) if _compareMagnitude(to: other) == .lessThan { return ((self / gcd) * other).magnitude } else { return ((other / gcd) * self).magnitude } } //===--- String methods ------------------------------------------------===// /// Creates a new instance from the given string. /// /// - Parameters: /// - source: The string to parse for the new instance's value. If a /// character in `source` is not in the range `0...9` or `a...z`, case /// insensitive, or is not less than `radix`, the result is `nil`. /// - radix: The radix to use when parsing `source`. `radix` must be in the /// range `2...36`. The default is `10`. public init?(_ source: String, radix: Int = 10) { assert(2...36 ~= radix, "radix must be in range 2...36") let radix = Word(radix) func valueForCodeUnit(_ unit: UTF16.CodeUnit) -> Word? { switch unit { // "0"..."9" case 48...57: return Word(unit - 48) // "a"..."z" case 97...122: return Word(unit - 87) // "A"..."Z" case 65...90: return Word(unit - 55) // invalid character default: return nil } } var source = source // Check for a single prefixing hyphen let negative = source.hasPrefix("-") if negative { source = String(source.characters.dropFirst()) } // Loop through characters, multiplying for v in source.utf16.map(valueForCodeUnit) { // Character must be valid and less than radix guard let v = v else { return nil } guard v < radix else { return nil } self.multiply(by: radix) self.add(v) } self.isNegative = negative } /// Returns a string representation of this instance. /// /// - Parameters: /// - radix: The radix to use when converting this instance to a string. /// The value passed as `radix` must be in the range `2...36`. The /// default is `10`. /// - lowercase: Whether to use lowercase letters to represent digits /// greater than 10. The default is `true`. public func toString(radix: Int = 10, lowercase: Bool = true) -> String { assert(2...36 ~= radix, "radix must be in range 2...36") let digitsStart = ("0" as UnicodeScalar).value let lettersStart = ((lowercase ? "a" : "A") as UnicodeScalar).value - 10 func toLetter(_ x: UInt32) -> UnicodeScalar { return x < 10 ? UnicodeScalar(digitsStart + x)! : UnicodeScalar(lettersStart + x)! } let radix = _BigInt(radix) var result: [UnicodeScalar] = [] var x = self.magnitude while !x.isZero { let remainder: _BigInt (x, remainder) = x.quotientAndRemainder(dividingBy: radix) result.append(toLetter(UInt32(remainder))) } let sign = isNegative ? "-" : "" let rest = result.count == 0 ? "0" : String(String.UnicodeScalarView(result.reversed())) return sign + rest } public var description: String { return decimalString } public var debugDescription: String { return "_BigInt(\(hexString), words: \(_data.count))" } /// A string representation of this instance's value in base 2. public var binaryString: String { return toString(radix: 2) } /// A string representation of this instance's value in base 10. public var decimalString: String { return toString(radix: 10) } /// A string representation of this instance's value in base 16. public var hexString: String { return toString(radix: 16, lowercase: false) } /// A string representation of this instance's value in base 36. public var compactString: String { return toString(radix: 36, lowercase: false) } //===--- Comparable -----------------------------------------------------===// enum _ComparisonResult { case lessThan, equal, greaterThan } /// Returns whether this instance is less than, greather than, or equal to /// the given value. func _compare(to rhs: _BigInt) -> _ComparisonResult { // Negative values are less than positive values guard isNegative == rhs.isNegative else { return isNegative ? .lessThan : .greaterThan } switch _compareMagnitude(to: rhs) { case .equal: return .equal case .lessThan: return isNegative ? .greaterThan : .lessThan case .greaterThan: return isNegative ? .lessThan : .greaterThan } } /// Returns whether the magnitude of this instance is less than, greather /// than, or equal to the magnitude of the given value. func _compareMagnitude(to rhs: _BigInt) -> _ComparisonResult { guard _data.count == rhs._data.count else { return _data.count < rhs._data.count ? .lessThan : .greaterThan } // Equal number of words: compare from most significant word for i in (0..<_data.count).reversed() { if _data[i] < rhs._data[i] { return .lessThan } if _data[i] > rhs._data[i] { return .greaterThan } } return .equal } public static func ==(lhs: _BigInt, rhs: _BigInt) -> Bool { return lhs._compare(to: rhs) == .equal } public static func < (lhs: _BigInt, rhs: _BigInt) -> Bool { return lhs._compare(to: rhs) == .lessThan } //===--- Hashable -------------------------------------------------------===// public var hashValue: Int { #if arch(i386) || arch(arm) let p: UInt = 16777619 let h: UInt = (2166136261 &* p) ^ (isNegative ? 1 : 0) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) let p: UInt = 1099511628211 let h: UInt = (14695981039346656037 &* p) ^ (isNegative ? 1 : 0) #else fatalError("Unimplemented") #endif return Int(bitPattern: _data.reduce(h, { ($0 &* p) ^ UInt($1) })) } //===--- Bit shifting operators -----------------------------------------===// static func _shiftLeft(_ data: inout [Word], byWords words: Int) { guard words > 0 else { return } data.insert(contentsOf: repeatElement(0, count: words), at: 0) } static func _shiftRight(_ data: inout [Word], byWords words: Int) { guard words > 0 else { return } data.removeFirst(Swift.min(data.count, words)) } public static func <<=(lhs: inout _BigInt, rhs: Int) { defer { lhs._checkInvariants() } guard rhs != 0 else { return } guard rhs > 0 else { lhs >>= -rhs return } // We can add `rhs / bits` extra words full of zero at the low end. let extraWords = rhs / Word.bitWidth lhs._data.reserveCapacity(lhs._data.count + extraWords + 1) _BigInt._shiftLeft(&lhs._data, byWords: extraWords) // Each existing word will need to be shifted left by `rhs % bits`. // For each pair of words, we'll use the high `offset` bits of the // lower word and the low `Word.bitWidth - offset` bits of the higher // word. let highOffset = rhs % Word.bitWidth let lowOffset = Word.bitWidth - highOffset // If there's no offset, we're finished, as `rhs` was a multiple of // `Word.bitWidth`. guard highOffset != 0 else { return } // Add new word at the end, then shift everything left by `offset` bits. lhs._data.append(0) for i in ((extraWords + 1)..<lhs._data.count).reversed() { lhs._data[i] = lhs._data[i] << highOffset | lhs._data[i - 1] >> lowOffset } // Finally, shift the lowest word. lhs._data[extraWords] = lhs._data[extraWords] << highOffset lhs._standardize() } public static func >>=(lhs: inout _BigInt, rhs: Int) { defer { lhs._checkInvariants() } guard rhs != 0 else { return } guard rhs > 0 else { lhs <<= -rhs return } var tempData = lhs._dataAsTwosComplement() // We can remove `rhs / bits` full words at the low end. // If that removes the entirety of `_data`, we're done. let wordsToRemove = rhs / Word.bitWidth _BigInt._shiftRight(&tempData, byWords: wordsToRemove) guard tempData.count != 0 else { lhs = lhs.isNegative ? -1 : 0 return } // Each existing word will need to be shifted right by `rhs % bits`. // For each pair of words, we'll use the low `offset` bits of the // higher word and the high `_BigInt.Word.bitWidth - offset` bits of // the lower word. let lowOffset = rhs % Word.bitWidth let highOffset = Word.bitWidth - lowOffset // If there's no offset, we're finished, as `rhs` was a multiple of // `Word.bitWidth`. guard lowOffset != 0 else { lhs = _BigInt(_twosComplementData: tempData) return } // Shift everything right by `offset` bits. for i in 0..<(tempData.count - 1) { tempData[i] = tempData[i] >> lowOffset | tempData[i + 1] << highOffset } // Finally, shift the highest word and standardize the result. tempData[tempData.count - 1] >>= lowOffset lhs = _BigInt(_twosComplementData: tempData) } public static func <<(lhs: _BigInt, rhs: Int) -> _BigInt { var lhs = lhs lhs <<= rhs return lhs } public static func >>(lhs: _BigInt, rhs: Int) -> _BigInt { var lhs = lhs lhs >>= rhs return lhs } } //===--- Bit --------------------------------------------------------------===// //===----------------------------------------------------------------------===// /// A one-bit fixed width integer. struct Bit : FixedWidthInteger, UnsignedInteger { typealias Magnitude = Bit var value: UInt8 = 0 // Initializers init(integerLiteral value: Int) { self = Bit(value) } init(bigEndian value: Bit) { self = value } init(littleEndian value: Bit) { self = value } init?<T: FloatingPoint>(exactly source: T) { switch source { case T(0): value = 0 case T(1): value = 1 default: return nil } } init<T: FloatingPoint>(_ source: T) { self = Bit(exactly: source.rounded(.down))! } init<T: BinaryInteger>(_ source: T) { switch source { case 0: value = 0 case 1: value = 1 default: fatalError("Can't represent \(source) as a Bit") } } init<T: BinaryInteger>(extendingOrTruncating source: T) { value = UInt8(source & 1) } init(_truncatingBits bits: UInt) { value = UInt8(bits & 1) } init<T: BinaryInteger>(clamping source: T) { value = source >= 1 ? 1 : 0 } // FixedWidthInteger, BinaryInteger static var bitWidth: Int { return 1 } var bitWidth: Int { return 1 } var trailingZeroBitCount: Int { return value.trailingZeroBitCount } static var max: Bit { return 1 } static var min: Bit { return 0 } static var isSigned: Bool { return false } var nonzeroBitCount: Int { return value.nonzeroBitCount } var leadingZeroBitCount: Int { return value.nonzeroBitCount - 7 } var bigEndian: Bit { return self } var littleEndian: Bit { return self } var byteSwapped: Bit { return self } func _word(at n: Int) -> UInt { return UInt(value) } // Hashable, CustomStringConvertible var hashValue: Int { return Int(value) } var description: String { return "\(value)" } // Arithmetic Operations / Operators func _checkOverflow(_ v: UInt8) -> ArithmeticOverflow { let mask: UInt8 = ~0 << 1 return v & mask == 0 ? .none : .overflow } func addingReportingOverflow(_ rhs: Bit) -> (partialValue: Bit, overflow: ArithmeticOverflow) { let result = value &+ rhs.value return (Bit(result & 1), _checkOverflow(result)) } func subtractingReportingOverflow(_ rhs: Bit) -> (partialValue: Bit, overflow: ArithmeticOverflow) { let result = value &- rhs.value return (Bit(result & 1), _checkOverflow(result)) } func multipliedReportingOverflow(by rhs: Bit) -> (partialValue: Bit, overflow: ArithmeticOverflow) { let result = value &* rhs.value return (Bit(result), .none) } func dividedReportingOverflow(by rhs: Bit) -> (partialValue: Bit, overflow: ArithmeticOverflow) { return rhs == 0 ? (self, .none) : (self, .overflow) } func remainderReportingOverflow(dividingBy rhs: Bit) -> (partialValue: Bit, overflow: ArithmeticOverflow) { fatalError() } static func +=(lhs: inout Bit, rhs: Bit) { let result = lhs.addingReportingOverflow(rhs) assert(result.overflow == .none, "Addition overflow") lhs = result.partialValue } static func -=(lhs: inout Bit, rhs: Bit) { let result = lhs.subtractingReportingOverflow(rhs) assert(result.overflow == .none, "Subtraction overflow") lhs = result.partialValue } static func *=(lhs: inout Bit, rhs: Bit) { let result = lhs.multipliedReportingOverflow(by: rhs) assert(result.overflow == .none, "Multiplication overflow") lhs = result.partialValue } static func /=(lhs: inout Bit, rhs: Bit) { let result = lhs.dividedReportingOverflow(by: rhs) assert(result.overflow == .none, "Division overflow") lhs = result.partialValue } static func %=(lhs: inout Bit, rhs: Bit) { assert(rhs != 0, "Modulo sum overflow") lhs.value = 0 // No remainders with bit division! } func multipliedFullWidth(by other: Bit) -> (high: Bit, low: Bit) { return (0, self * other) } func dividingFullWidth(_ dividend: (high: Bit, low: Bit)) -> (quotient: Bit, remainder: Bit) { assert(self != 0, "Division overflow") assert(dividend.high == 0, "Quotient overflow") return (dividend.low, 0) } // FIXME: Remove once default implementations are provided: public static func +(_ lhs: Bit, _ rhs: Bit) -> Bit { var lhs = lhs lhs += rhs return lhs } public static func -(_ lhs: Bit, _ rhs: Bit) -> Bit { var lhs = lhs lhs -= rhs return lhs } public static func *(_ lhs: Bit, _ rhs: Bit) -> Bit { var lhs = lhs lhs *= rhs return lhs } public static func /(_ lhs: Bit, _ rhs: Bit) -> Bit { var lhs = lhs lhs /= rhs return lhs } public static func %(_ lhs: Bit, _ rhs: Bit) -> Bit { var lhs = lhs lhs %= rhs return lhs } // Bitwise operators static prefix func ~(x: Bit) -> Bit { return Bit(~x.value & 1) } // Why doesn't the type checker complain about these being missing? static func &=(lhs: inout Bit, rhs: Bit) { lhs.value &= rhs.value } static func |=(lhs: inout Bit, rhs: Bit) { lhs.value |= rhs.value } static func ^=(lhs: inout Bit, rhs: Bit) { lhs.value ^= rhs.value } static func ==(lhs: Bit, rhs: Bit) -> Bool { return lhs.value == rhs.value } static func <(lhs: Bit, rhs: Bit) -> Bool { return lhs.value < rhs.value } static func <<(lhs: Bit, rhs: Bit) -> Bit { return rhs == 0 ? lhs : 0 } static func >>(lhs: Bit, rhs: Bit) -> Bit { return rhs == 0 ? lhs : 0 } static func <<=(lhs: inout Bit, rhs: Bit) { if rhs != 0 { lhs = 0 } } static func >>=(lhs: inout Bit, rhs: Bit) { if rhs != 0 { lhs = 0 } } } //===--- Tests ------------------------------------------------------------===// //===----------------------------------------------------------------------===// typealias BigInt = _BigInt<UInt> typealias BigInt8 = _BigInt<UInt8> typealias BigIntBit = _BigInt<Bit> func testBinaryInit<T: BinaryInteger>(_ x: T) -> BigInt { return BigInt(x) } func randomBitLength() -> Int { return Int(arc4random_uniform(1000) + 2) } var BitTests = TestSuite("Bit") BitTests.test("Basics") { let x = Bit.max let y = Bit.min expectTrue(x == 1 as Int) expectTrue(y == 0 as Int) expectTrue(x < Int.max) expectGT(x, y) expectEqual(x, x) expectEqual(x, x ^ 0) expectGT(x, x & 0) expectEqual(x, x | 0) expectLT(y, y | 1) expectEqual(x, ~y) expectEqual(y, ~x) expectEqual(x, x + y) expectGT(x, x &+ x) } var BigIntTests = TestSuite("BigInt") BigIntTests.test("Initialization") { let x = testBinaryInit(1_000_000 as Int) expectEqual(x._data[0], 1_000_000) let y = testBinaryInit(1_000 as UInt16) expectEqual(y._data[0], 1_000) let z = testBinaryInit(-1_000_000 as Int) expectEqual(z._data[0], 1_000_000) expectTrue(z.isNegative) let z6 = testBinaryInit(z * z * z * z * z * z) expectEqual(z6._data, [12919594847110692864, 54210108624275221]) expectFalse(z6.isNegative) } BigIntTests.test("Identity/Fixed point") { let x = BigInt(repeatElement(UInt.max, count: 20)) let y = -x expectEqual(x / x, 1) expectEqual(x / y, -1) expectEqual(y / x, -1) expectEqual(y / y, 1) expectEqual(x % x, 0) expectEqual(x % y, 0) expectEqual(y % x, 0) expectEqual(y % y, 0) expectEqual(x * 1, x) expectEqual(y * 1, y) expectEqual(x * -1, y) expectEqual(y * -1, x) expectEqual(-x, y) expectEqual(-y, x) expectEqual(x + 0, x) expectEqual(y + 0, y) expectEqual(x - 0, x) expectEqual(y - 0, y) expectEqual(x - x, 0) expectEqual(y - y, 0) } BigIntTests.test("Max arithmetic") { let x = BigInt(repeatElement(UInt.max, count: 50)) let y = BigInt(repeatElement(UInt.max, count: 35)) let (q, r) = x.quotientAndRemainder(dividingBy: y) expectEqual(q * y + r, x) expectEqual(q * y, x - r) } BigIntTests.test("Zero arithmetic") { let zero: BigInt = 0 expectTrue(zero.isZero) expectFalse(zero.isNegative) let x: BigInt = 1 expectTrue((x - x).isZero) expectFalse((x - x).isNegative) let y: BigInt = -1 expectTrue(y.isNegative) expectTrue((y - y).isZero) expectFalse((y - y).isNegative) expectEqual(x * zero, zero) expectCrashLater() _ = x / zero } BigIntTests.test("Conformances") { // Comparable let x = BigInt(Int.max) let y = x * x * x * x * x expectLT(y, y + 1) expectGT(y, y - 1) expectGT(y, 0) let z = -y expectLT(z, z + 1) expectGT(z, z - 1) expectLT(z, 0) expectEqual(-z, y) expectEqual(y + z, 0) // Hashable expectNotEqual(x.hashValue, y.hashValue) expectNotEqual(y.hashValue, z.hashValue) let set = Set([x, y, z]) expectTrue(set.contains(x)) expectTrue(set.contains(y)) expectTrue(set.contains(z)) expectFalse(set.contains(-x)) } BigIntTests.test("BinaryInteger interop") { let x: BigInt = 100 let xComp = UInt8(x) expectTrue(x == xComp) expectTrue(x < xComp + 1) expectFalse(xComp + 1 < x) let y: BigInt = -100 let yComp = Int8(y) expectTrue(y == yComp) expectTrue(y < yComp + (1 as Int8)) expectFalse(yComp + (1 as Int8) < y) // should be: expectTrue(y < yComp + 1), but: // warning: '+' is deprecated: Mixed-type addition is deprecated. // Please use explicit type conversion. let zComp = Int.min + 1 let z = BigInt(zComp) expectTrue(z == zComp) expectTrue(zComp == z) expectFalse(zComp + 1 < z) expectTrue(z < zComp + 1) let w = BigInt(UInt.max) let wComp = UInt(extendingOrTruncating: w) expectTrue(w == wComp) expectTrue(wComp == w) expectTrue(wComp - (1 as UInt) < w) expectFalse(w < wComp - (1 as UInt)) // should be: // expectTrue(wComp - 1 < w) // expectTrue(w > wComp - 1) // but crashes at runtime } BigIntTests.test("Huge") { let x = BigInt(randomBits: 1_000_000) expectGT(x, x - 1) let y = -x expectGT(y, y - 1) } BigIntTests.test("Numeric").forEach(in: [ ("3GFWFN54YXNBS6K2ST8K9B89Q2AMRWCNYP4JAS5ZOPPZ1WU09MXXTIT27ZPVEG2Y", "9Y1QXS4XYYDSBMU4N3LW7R3R1WKK", "CIFJIVHV0K4MSX44QEX2US0MFFEAWJVQ8PJZ", "26HILZ7GZQN8MB4O17NSPO5XN1JI"), ("7PM82EHP7ZN3ZL7KOPB7B8KYDD1R7EEOYWB6M4SEION47EMS6SMBEA0FNR6U9VAM70HPY4WKXBM8DCF1QOR1LE38NJAVOPOZEBLIU1M05", "-202WEEIRRLRA9FULGA15RYROVW69ZPDHW0FMYSURBNWB93RNMSLRMIFUPDLP5YOO307XUNEFLU49FV12MI22MLCVZ5JH", "-3UNIZHA6PAL30Y", "1Y13W1HYB0QV2Z5RDV9Z7QXEGPLZ6SAA2906T3UKA46E6M4S6O9RMUF5ETYBR2QT15FJZP87JE0W06FA17RYOCZ3AYM3"), ("-ICT39SS0ONER9Z7EAPVXS3BNZDD6WJA791CV5LT8I4POLF6QYXBQGUQG0LVGPVLT0L5Z53BX6WVHWLCI5J9CHCROCKH3B381CCLZ4XAALLMD", "6T1XIVCPIPXODRK8312KVMCDPBMC7J4K0RWB7PM2V4VMBMODQ8STMYSLIXFN9ORRXCTERWS5U4BLUNA4H6NG8O01IM510NJ5STE", "-2P2RVZ11QF", "-3YSI67CCOD8OI1HFF7VF5AWEQ34WK6B8AAFV95U7C04GBXN0R6W5GM5OGOO22HY0KADIUBXSY13435TW4VLHCKLM76VS51W5Z9J"), ("-326JY57SJVC", "-8H98AQ1OY7CGAOOSG", "0", "-326JY57SJVC"), ("-XIYY0P3X9JIDF20ZQG2CN5D2Q5CD9WFDDXRLFZRDKZ8V4TSLE2EHRA31XL3YOHPYLE0I0ZAV2V9RF8AGPCYPVWEIYWWWZ3HVDR64M08VZTBL85PR66Z2F0W5AIDPXIAVLS9VVNLNA6I0PKM87YW4T98P0K", "-BUBZEC4NTOSCO0XHCTETN4ROPSXIJBTEFYMZ7O4Q1REOZO2SFU62KM3L8D45Z2K4NN3EC4BSRNEE", "2TX1KWYGAW9LAXUYRXZQENY5P3DSVXJJXK4Y9DWGNZHOWCL5QD5PLLZCE6D0G7VBNP9YGFC0Z9XIPCB", "-3LNPZ9JK5PUXRZ2Y1EJ4E3QRMAMPKZNI90ZFOBQJM5GZUJ84VMF8EILRGCHZGXJX4AXZF0Z00YA"), ("AZZBGH7AH3S7TVRHDJPJ2DR81H4FY5VJW2JH7O4U7CH0GG2DSDDOSTD06S4UM0HP1HAQ68B2LKKWD73UU0FV5M0H0D0NSXUJI7C2HW3P51H1JM5BHGXK98NNNSHMUB0674VKJ57GVVGY4", "1LYN8LRN3PY24V0YNHGCW47WUWPLKAE4685LP0J74NZYAIMIBZTAF71", "6TXVE5E9DXTPTHLEAG7HGFTT0B3XIXVM8IGVRONGSSH1UC0HUASRTZX8TVM2VOK9N9NATPWG09G7MDL6CE9LBKN", "WY37RSPBTEPQUA23AXB3B5AJRIUL76N3LXLP3KQWKFFSR7PR4E1JWH"), ("1000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000", "1000000000", "0"), ]) { strings in let x = BigInt(strings.0, radix: 36)! let y = BigInt(strings.1, radix: 36)! let q = BigInt(strings.2, radix: 36)! let r = BigInt(strings.3, radix: 36)! let (testQ, testR) = x.quotientAndRemainder(dividingBy: y) expectEqual(testQ, q) expectEqual(testR, r) expectEqual(x, y * q + r) } BigIntTests.test("Strings") { let x = BigInt("-3UNIZHA6PAL30Y", radix: 36)! expectEqual(x.binaryString, "-1000111001110110011101001110000001011001110110011011110011000010010010") expectEqual(x.decimalString, "-656993338084259999890") expectEqual(x.hexString, "-239D9D3816766F3092") expectEqual(x.compactString, "-3UNIZHA6PAL30Y") expectTrue(BigInt("12345") == 12345) expectTrue(BigInt("-12345") == -12345) expectTrue(BigInt("-3UNIZHA6PAL30Y", radix: 10) == nil) expectTrue(BigInt("---") == nil) expectTrue(BigInt(" 123") == nil) } BigIntTests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in // Test x == (x / y) * x + (x % y) let (x, y) = ( BigInt(randomBits: randomBitLength()), BigInt(randomBits: randomBitLength())) if !y.isZero { let (q, r) = x.quotientAndRemainder(dividingBy: y) expectEqual(q * y + r, x) expectEqual(q * y, x - r) } // Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1 let (x0, y0, x1, y1) = ( BigInt(randomBits: randomBitLength()), BigInt(randomBits: randomBitLength()), BigInt(randomBits: randomBitLength()), BigInt(randomBits: randomBitLength())) let r1 = (x0 + y0) * (x1 + y1) let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1)) expectEqual(r1, r2.0 + r2.1) } var BigInt8Tests = TestSuite("BigInt<UInt8>") BigInt8Tests.test("BinaryInteger interop") { let x: BigInt8 = 100 let xComp = UInt8(x) expectTrue(x == xComp) expectTrue(x < xComp + 1) expectFalse(xComp + 1 < x) let y: BigInt8 = -100 let yComp = Int8(y) expectTrue(y == yComp) expectTrue(y < yComp + (1 as Int8)) expectFalse(yComp + (1 as Int8) < y) let zComp = Int.min + 1 let z = BigInt8(zComp) expectTrue(z == zComp) expectTrue(zComp == z) expectFalse(zComp + 1 < z) expectTrue(z < zComp + 1) let w = BigInt8(UInt.max) let wComp = UInt(extendingOrTruncating: w) expectTrue(w == wComp) expectTrue(wComp == w) expectTrue(wComp - (1 as UInt) < w) expectFalse(w < wComp - (1 as UInt)) } BigInt8Tests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in // Test x == (x / y) * x + (x % y) let (x, y) = ( BigInt8(randomBits: randomBitLength()), BigInt8(randomBits: randomBitLength())) if !y.isZero { let (q, r) = x.quotientAndRemainder(dividingBy: y) expectEqual(q * y + r, x) expectEqual(q * y, x - r) } // Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1 let (x0, y0, x1, y1) = ( BigInt8(randomBits: randomBitLength()), BigInt8(randomBits: randomBitLength()), BigInt8(randomBits: randomBitLength()), BigInt8(randomBits: randomBitLength())) let r1 = (x0 + y0) * (x1 + y1) let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1)) expectEqual(r1, r2.0 + r2.1) } BigInt8Tests.test("Bitshift") { expectEqual(BigInt8(255) << 1, 510) expectTrue(BigInt(UInt32.max) << 16 == UInt(UInt32.max) << 16) var (x, y) = (1 as BigInt, 1 as UInt) for i in 0..<64 { // don't test 64-bit shift, UInt64 << 64 == 0 expectTrue(x << i == y << i) } (x, y) = (BigInt(UInt.max), UInt.max) for i in 0...64 { // test 64-bit shift, should both be zero expectTrue(x >> i == y >> i) } x = BigInt(-1) var z = -1 as Int for i in 0..<64 { expectTrue(x << i == z << i) } } BigInt8Tests.test("Bitwise").forEach(in: [ BigInt8(Int.max - 2), BigInt8(255), BigInt8(256), BigInt8(UInt32.max), ]) { value in for x in [value, -value] { expectTrue(x | 0 == x) expectTrue(x & 0 == 0) expectTrue(x & ~0 == x) expectTrue(x ^ 0 == x) expectTrue(x ^ ~0 == ~x) expectTrue(x == BigInt8(Int(extendingOrTruncating: x))) expectTrue(~x == BigInt8(~Int(extendingOrTruncating: x))) } } var BigIntBitTests = TestSuite("BigInt<Bit>") BigIntBitTests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in // Test x == (x / y) * x + (x % y) let (x, y) = ( BigIntBit(randomBits: randomBitLength() % 100), BigIntBit(randomBits: randomBitLength() % 100)) if !y.isZero { let (q, r) = x.quotientAndRemainder(dividingBy: y) expectEqual(q * y + r, x) expectEqual(q * y, x - r) } // Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1 let (x0, y0, x1, y1) = ( BigIntBit(randomBits: randomBitLength() % 100), BigIntBit(randomBits: randomBitLength() % 100), BigIntBit(randomBits: randomBitLength() % 100), BigIntBit(randomBits: randomBitLength() % 100)) let r1 = (x0 + y0) * (x1 + y1) let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1)) expectEqual(r1, r2.0 + r2.1) } BigIntBitTests.test("Conformances") { // Comparable let x = BigIntBit(Int.max) let y = x * x * x * x * x expectLT(y, y + 1) expectGT(y, y - 1) expectGT(y, 0) let z = -y expectLT(z, z + 1) expectGT(z, z - 1) expectLT(z, 0) expectEqual(-z, y) expectEqual(y + z, 0) // Hashable expectNotEqual(x.hashValue, y.hashValue) expectNotEqual(y.hashValue, z.hashValue) let set = Set([x, y, z]) expectTrue(set.contains(x)) expectTrue(set.contains(y)) expectTrue(set.contains(z)) expectFalse(set.contains(-x)) } runAllTests()
apache-2.0
6fc6c458389517f0e953a981d0a81784
28.28212
161
0.608
3.633761
false
false
false
false
Bunn/firefox-ios
Extensions/NotificationService/NotificationService.swift
1
13350
/* 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 Account import Shared import Storage import Sync import UserNotifications class NotificationService: UNNotificationServiceExtension { var display: SyncDataDisplay? var profile: ExtensionProfile? // This is run when an APNS notification with `mutable-content` is received. // If the app is backgrounded, then the alert notification is displayed. // If the app is foregrounded, then the notification.userInfo is passed straight to // AppDelegate.application(_:didReceiveRemoteNotification:completionHandler:) // Once the notification is tapped, then the same userInfo is passed to the same method in the AppDelegate. override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { let userInfo = request.content.userInfo guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else { return self.didFinish(PushMessage.accountVerified) } if self.profile == nil { self.profile = ExtensionProfile(localName: "profile") } guard let profile = self.profile else { self.didFinish(with: .noProfile) return } let queue = profile.queue let display = SyncDataDisplay(content: content, contentHandler: contentHandler, tabQueue: queue) self.display = display profile.syncDelegate = display let handler = FxAPushMessageHandler(with: profile) handler.handle(userInfo: userInfo).upon { res in self.didFinish(res.successValue, with: res.failureValue as? PushMessageError) } } func didFinish(_ what: PushMessage? = nil, with error: PushMessageError? = nil) { defer { // We cannot use tabqueue after the profile has shutdown; // however, we can't use weak references, because TabQueue isn't a class. // Rather than changing tabQueue, we manually nil it out here. self.display?.tabQueue = nil profile?._shutdown() } guard let display = self.display else { return } display.messageDelivered = false display.displayNotification(what, profile: profile, with: error) if !display.messageDelivered { display.displayUnknownMessageNotification(debugInfo: "Not delivered") } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. didFinish(with: .timeout) } } class SyncDataDisplay { var contentHandler: ((UNNotificationContent) -> Void) var notificationContent: UNMutableNotificationContent var sentTabs: [SentTab] var tabQueue: TabQueue? var messageDelivered: Bool = false init(content: UNMutableNotificationContent, contentHandler: @escaping (UNNotificationContent) -> Void, tabQueue: TabQueue) { self.contentHandler = contentHandler self.notificationContent = content self.sentTabs = [] self.tabQueue = tabQueue Sentry.shared.setup(sendUsageData: true) } func displayNotification(_ message: PushMessage? = nil, profile: ExtensionProfile?, with error: PushMessageError? = nil) { guard let message = message, error == nil else { return displayUnknownMessageNotification(debugInfo: "Error \(error?.description ?? "")") } switch message { case .commandReceived(let tab): displayNewSentTabNotification(tab: tab) case .accountVerified: displayAccountVerifiedNotification() case .deviceConnected(let deviceName): displayDeviceConnectedNotification(deviceName) case .deviceDisconnected(let deviceName): displayDeviceDisconnectedNotification(deviceName) case .thisDeviceDisconnected: displayThisDeviceDisconnectedNotification() case .collectionChanged(let collections): if collections.contains("clients") { displayOldSentTabNotification() } else { displayUnknownMessageNotification(debugInfo: "collection changed") } default: displayUnknownMessageNotification(debugInfo: "Unknown: \(message)") break } } } extension SyncDataDisplay { func displayDeviceConnectedNotification(_ deviceName: String) { presentNotification(title: Strings.FxAPush_DeviceConnected_title, body: Strings.FxAPush_DeviceConnected_body, bodyArg: deviceName) } func displayDeviceDisconnectedNotification(_ deviceName: String?) { if let deviceName = deviceName { presentNotification(title: Strings.FxAPush_DeviceDisconnected_title, body: Strings.FxAPush_DeviceDisconnected_body, bodyArg: deviceName) } else { // We should never see this branch presentNotification(title: Strings.FxAPush_DeviceDisconnected_title, body: Strings.FxAPush_DeviceDisconnected_UnknownDevice_body) } } func displayThisDeviceDisconnectedNotification() { presentNotification(title: Strings.FxAPush_DeviceDisconnected_ThisDevice_title, body: Strings.FxAPush_DeviceDisconnected_ThisDevice_body) } func displayAccountVerifiedNotification() { #if MOZ_CHANNEL_BETA presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: "DEBUG: Account Verified") return #endif presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: Strings.SentTab_NoTabArrivingNotification_body) } func displayUnknownMessageNotification(debugInfo: String) { #if MOZ_CHANNEL_BETA presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: "DEBUG: " + debugInfo) Sentry.shared.send(message: "SentTab error: \(debugInfo)") return #endif // if, by any change we haven't dealt with the message, then perhaps we // can recycle it as a sent tab message. if sentTabs.count > 0 { displayOldSentTabNotification() } else { presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: Strings.SentTab_NoTabArrivingNotification_body) } } } extension SyncDataDisplay { func displayNewSentTabNotification(tab: [String: String]) { if let urlString = tab["url"], let url = URL(string: urlString), url.isWebPage(), let title = tab["title"] { let tab = [ "title": title, "url": url.absoluteString, "displayURL": url.absoluteDisplayExternalString, "deviceName": nil ] as NSDictionary notificationContent.userInfo["sentTabs"] = [tab] as NSArray // Add tab to the queue. let item = ShareItem(url: urlString, title: title, favicon: nil) _ = tabQueue?.addToQueue(item).value // Force synchronous. presentNotification(title: Strings.SentTab_TabArrivingNotification_NoDevice_title, body: url.absoluteDisplayExternalString) } } } extension SyncDataDisplay { func displayOldSentTabNotification() { // We will need to be more precise about calling these SentTab alerts // once we are a) detecting different types of notifications and b) adding actions. // For now, we need to add them so we can handle zero-tab sent-tab-notifications. notificationContent.categoryIdentifier = "org.mozilla.ios.SentTab.placeholder" var userInfo = notificationContent.userInfo // Add the tabs we've found to userInfo, so that the AppDelegate // doesn't have to do it again. let serializedTabs = sentTabs.compactMap { t -> NSDictionary? in return [ "title": t.title, "url": t.url.absoluteString, "displayURL": t.url.absoluteDisplayExternalString, "deviceName": t.deviceName as Any, ] as NSDictionary } func present(_ tabs: [NSDictionary]) { if !tabs.isEmpty { userInfo["sentTabs"] = tabs as NSArray } notificationContent.userInfo = userInfo presentSentTabsNotification(tabs) } let center = UNUserNotificationCenter.current() center.getDeliveredNotifications { notifications in // Let's deal with sent-tab-notifications let sentTabNotifications = notifications.filter { $0.request.content.categoryIdentifier == self.notificationContent.categoryIdentifier } // We can delete zero tab sent-tab-notifications let emptyTabNotificationsIds = sentTabNotifications.filter { $0.request.content.userInfo["sentTabs"] == nil }.map { $0.request.identifier } center.removeDeliveredNotifications(withIdentifiers: emptyTabNotificationsIds) // The one we've just received (but not delivered) may not have any tabs in it either // e.g. if the previous one consumed two tabs. if serializedTabs.count == 0 { // In that case, we try and recycle an existing notification (one that has a tab in it). if let firstNonEmpty = sentTabNotifications.first(where: { $0.request.content.userInfo["sentTabs"] != nil }), let previouslyDeliveredTabs = firstNonEmpty.request.content.userInfo["sentTabs"] as? [NSDictionary] { center.removeDeliveredNotifications(withIdentifiers: [firstNonEmpty.request.identifier]) return present(previouslyDeliveredTabs) } } // We have tabs in this notification, or we couldn't recycle an existing one that does. present(serializedTabs) } } func presentSentTabsNotification(_ tabs: [NSDictionary]) { let title: String let body: String if tabs.count == 0 { title = Strings.SentTab_NoTabArrivingNotification_title #if MOZ_CHANNEL_BETA body = "DEBUG: Sent Tabs with no tab" Sentry.shared.send(message: "SentTab error: no tab") #else body = Strings.SentTab_NoTabArrivingNotification_body #endif } else { let deviceNames = Set(tabs.compactMap { $0["deviceName"] as? String }) if let deviceName = deviceNames.first, deviceNames.count == 1 { title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName) } else { title = Strings.SentTab_TabArrivingNotification_NoDevice_title } if tabs.count == 1 { // We give the fallback string as the url, // because we have only just introduced "displayURL" as a key. body = (tabs[0]["displayURL"] as? String) ?? (tabs[0]["url"] as! String) } else if deviceNames.count == 0 { body = Strings.SentTab_TabArrivingNotification_NoDevice_body } else { body = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_body, AppInfo.displayName) } } presentNotification(title: title, body: body) } func presentNotification(title: String, body: String, titleArg: String? = nil, bodyArg: String? = nil) { func stringWithOptionalArg(_ s: String, _ a: String?) -> String { if let a = a { return String(format: s, a) } return s } notificationContent.title = stringWithOptionalArg(title, titleArg) notificationContent.body = stringWithOptionalArg(body, bodyArg) // This is the only place we call the contentHandler. contentHandler(notificationContent) // This is the only place we change messageDelivered. We can check if contentHandler hasn't be called because of // our logic (rather than something funny with our environment, or iOS killing us). messageDelivered = true } } extension SyncDataDisplay: SyncDelegate { func displaySentTab(for url: URL, title: String, from deviceName: String?) { if url.isWebPage() { sentTabs.append(SentTab(url: url, title: title, deviceName: deviceName)) let item = ShareItem(url: url.absoluteString, title: title, favicon: nil) _ = tabQueue?.addToQueue(item).value // Force synchronous. } } } struct SentTab { let url: URL let title: String let deviceName: String? }
mpl-2.0
c80097b13cb5ab87379ea4223cf87e36
41.246835
142
0.639251
5.39612
false
false
false
false
li-wenxue/Weibo
新浪微博/新浪微博/Class/Tools/Extension/UIImage+Extensions.swift
1
1195
// // UIImage+Extensions.swift // 新浪微博 // // Created by win_学 on 16/9/13. // Copyright © 2016年 win_学. All rights reserved. // import Foundation extension UIImage { func wx_avatarImage(size: CGSize?, backgroundColor: UIColor = UIColor.white, lineColor: UIColor = UIColor.lightGray) -> UIImage? { var size = size if size == nil { size = self.size } let rect = CGRect(origin: CGPoint(), size: size!) // 1.获取绘图上下文 UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) // a.设置背景填充 backgroundColor.setFill() UIRectFill(rect) // 2.设置绘图区域轨迹 let path = UIBezierPath(ovalIn: rect) // b> 设置边线 // FIXME: 添加图片边框 //path.lineWidth = 2 //lineColor.setStroke() //path.stroke() // 3.裁剪绘图区域 path.addClip() // 4.绘图 draw(in: rect) // 5.获取结果 let result = UIGraphicsGetImageFromCurrentImageContext() // 6.关闭上下文 UIGraphicsEndImageContext() return result } }
mit
05d5956e4821613a9c415f3cd22ebdec
24.209302
134
0.559041
4.169231
false
false
false
false
lulee007/GankMeizi
GankMeizi/GanksViewController.swift
1
2647
// // GanksViewController.swift // GankMeizi // // Created by 卢小辉 on 16/5/27. // Copyright © 2016年 lulee007. All rights reserved. // import UIKit import RxSwift import PageMenu class GanksViewController: UIViewController { var pageMenu: CAPSPageMenu? // just wanna to prectice string map and filter let articleTypes = "福利 | Android | iOS | 休息视频 | 拓展资源 | 前端".componentsSeparatedByString("|") .map { (text: String) -> String in return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } .filter({!$0.isEmpty}) override func viewDidLoad() { super.viewDidLoad() setupControllers() } func setupControllers() { var controllers: [UIViewController] = [] for type in articleTypes{ controllers.append(ArticlesViewController.buildController(type)) } let y = UIApplication.sharedApplication().statusBarFrame.height + (self.navigationController?.navigationBar.frame.height)! let parent = self.parentViewController as! UITabBarController let parameters: [CAPSPageMenuOption] = [ .ScrollMenuBackgroundColor(UIColor.whiteColor()), .ViewBackgroundColor(UIColor.whiteColor()), .SelectedMenuItemLabelColor(ThemeUtil.colorWithHexString(ThemeUtil.ACCENT_COLOR)), .UnselectedMenuItemLabelColor(ThemeUtil.colorWithHexString(ThemeUtil.LIGHT_PRIMARY_COLOR)), .SelectionIndicatorColor(ThemeUtil.colorWithHexString(ThemeUtil.ACCENT_COLOR)), .BottomMenuHairlineColor(ThemeUtil.colorWithHexString(ThemeUtil.DIVIDER_COLOR)), .MenuItemFont(UIFont(name: "HelveticaNeue", size: 14.0)!), .MenuHeight(40.0), .MenuItemWidth(90.0), .CenterMenuItems(true) ] pageMenu = CAPSPageMenu(viewControllers: controllers, frame: CGRectMake(0, y, self.view.frame.width, self.view.frame.height - y - parent.tabBar.frame.size.height), pageMenuOptions: parameters) pageMenu?.scrollMenuBackgroundColor = UIColor.whiteColor() pageMenu?.bottomMenuHairlineColor = UIColor.blueColor() pageMenu?.selectedMenuItemLabelColor = ThemeUtil.colorWithHexString(ThemeUtil.ACCENT_COLOR) pageMenu?.selectionIndicatorColor = ThemeUtil.colorWithHexString("#0000aa") pageMenu?.bottomMenuHairlineColor = UIColor.brownColor() pageMenu?.viewBackgroundColor = UIColor.greenColor() self.view.addSubview((pageMenu?.view)!) } }
mit
d973daf1aa97260709368e73da37bb88
38.606061
200
0.671385
5.145669
false
false
false
false
bradhowes/SynthInC
Playgrounds/ScratchPad.playground/Contents.swift
1
3042
//: Playground - noun: a place where people can play import UIKit import AudioToolbox import CoreAudio import AVFoundation import SwiftMIDI var graph: AUGraph? = nil NewAUGraph(&graph) var desc = AudioComponentDescription(componentType: OSType(kAudioUnitType_Mixer), componentSubType: OSType(kAudioUnitSubType_MultiChannelMixer), componentManufacturer: OSType(kAudioUnitManufacturer_Apple), componentFlags: 0, componentFlagsMask: 0) var mixerNode: AUNode = 0 AUGraphAddNode(graph!, &desc, &mixerNode) desc = AudioComponentDescription(componentType: OSType(kAudioUnitType_Output), componentSubType: OSType(kAudioUnitSubType_RemoteIO), componentManufacturer: OSType(kAudioUnitManufacturer_Apple), componentFlags: 0, componentFlagsMask: 0) var outputNode: AUNode = 0 AUGraphAddNode(graph!, &desc, &outputNode) AUGraphOpen(graph!) var mixerUnit: AudioUnit? = nil AUGraphNodeInfo(graph!, mixerNode, nil, &mixerUnit) var busCount = UInt32(1); AudioUnitSetProperty(mixerUnit!, kAudioUnitProperty_ElementCount, kAudioUnitScope_Input, 0, &busCount, UInt32(MemoryLayout.size(ofValue: busCount))) var sampleRate: Float64 = 44100.0; AudioUnitSetProperty(mixerUnit!, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRate, UInt32(MemoryLayout.size(ofValue: sampleRate))) AUGraphConnectNodeInput(graph!, mixerNode, 0, outputNode, 0) var samplerNode: AUNode = 0 var samplerUnit: AudioUnit! desc = AudioComponentDescription( componentType: OSType(kAudioUnitType_MusicDevice), componentSubType: OSType(kAudioUnitSubType_Sampler), componentManufacturer: OSType(kAudioUnitManufacturer_Apple), componentFlags: 0, componentFlagsMask: 0) AUGraphAddNode(graph!, &desc, &samplerNode) AUGraphNodeInfo(graph!, samplerNode, nil, &samplerUnit) AudioUnitSetProperty(samplerUnit!, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRate, UInt32(MemoryLayout.size(ofValue: sampleRate))) let index = 0 AUGraphConnectNodeInput(graph!, samplerNode, 0, mixerNode, UInt32(index)) let bankMSB = UInt8(kAUSampler_DefaultMelodicBankMSB) let bankLSB = UInt8(kAUSampler_DefaultBankLSB) let patch = 1 let presetID = UInt8(patch) let soundFont = SoundFont.library["Fluid R3 GM"]! var data = AUSamplerInstrumentData(fileURL: Unmanaged.passUnretained(soundFont.fileURL as CFURL), instrumentType: UInt8(kInstrumentType_SF2Preset), bankMSB: bankMSB, bankLSB: bankLSB, presetID: presetID) AudioUnitSetProperty(samplerUnit, kAUSamplerProperty_LoadInstrument, kAudioUnitScope_Global, 0, &data, UInt32(MemoryLayout.size(ofValue: data)))
mit
6281947395bee55ba3dac4fe5d70d166
41.25
99
0.680145
4.798107
false
false
false
false
VirgilSecurity/virgil-sdk-keys-x
Source/KeychainStorage/KeychainStorage.swift
2
21861
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation #if os(macOS) || os(iOS) import LocalAuthentication #endif /// Declares error codes for KeychainStorage. See KeychainStorageError /// /// - utf8ConvertingError: Error while converting string to utf8 binary /// - emptyKeychainResponse: Keychain response is nil /// - wrongResponseType: Unexpected keychain response type /// - errorParsingKeychainResponse: Error while deserializing keychain response /// - invalidAppBundle: Bundle.main.bundleIdentifier is empty /// - keychainError: Keychain returned error /// - creatingAccessControlFailed: SecAccessControlCreateWithFlags returned error @objc(VSSKeychainStorageErrorCodes) public enum KeychainStorageErrorCodes: Int { case utf8ConvertingError = 1 case emptyKeychainResponse = 2 case wrongResponseType = 3 case errorParsingKeychainResponse = 4 case invalidAppBundle = 5 case keychainError = 6 case creatingAccessControlFailed = 7 } /// Class respresenting error returned from KeychainStorage @objc(VSSKeychainStorageError) public final class KeychainStorageError: NSObject, CustomNSError { /// Error domain @objc public static var errorDomain: String { return "VirgilSDK.KeyStorageErrorDomain" } /// Error code. See KeychainStorageErrorCodes @objc public var errorCode: Int { return self.errCode.rawValue } /// Error code. See KeychainStorageErrorCodes @objc public let errCode: KeychainStorageErrorCodes /// OSStatus returned from Keychain public let osStatus: OSStatus? /// OSStatus as NSNumber @objc public var osStatusNumber: NSNumber? { if let osStatus = self.osStatus { return NSNumber(integerLiteral: Int(osStatus)) } else { return nil } } internal init(errCode: KeychainStorageErrorCodes) { self.errCode = errCode self.osStatus = nil super.init() } internal init(osStatus: OSStatus?) { self.errCode = .keychainError self.osStatus = osStatus super.init() } } /// Class responsible for Keychain interactions. @objc(VSSKeychainStorage) open class KeychainStorage: NSObject { #if os(macOS) /// Comment for all macOS password entries created by this class. Used for filtering @objc public static let commentStringPrefix = "CREATED_BY_VIRGILSDK" /// Comment string /// /// - Returns: Comment string for macOS Keychain entries @objc public func commentString() -> String { return "\(KeychainStorage.commentStringPrefix).OWNER_APP=\(self.storageParams.appName)" } /// Created access for trusted application + current application /// /// - Parameter name: entry name /// - Returns: SecAccess /// - Throws: KeychainStorageError @objc public func createAccess(forName name: String, queryOptions: KeychainQueryOptions) throws -> SecAccess { // Make an exception list of trusted applications; that is, // applications that are allowed to access the item without // requiring user confirmation: var myselfT: SecTrustedApplication? var status = SecTrustedApplicationCreateFromPath(nil, &myselfT) guard status == errSecSuccess, let myself = myselfT else { throw KeychainStorageError(osStatus: status) } var trustedList = [SecTrustedApplication]() trustedList.append(myself) for application in queryOptions.trustedApplications { var appT: SecTrustedApplication? status = SecTrustedApplicationCreateFromPath(application, &appT) guard status == errSecSuccess, let app = appT else { throw KeychainStorageError(osStatus: status) } trustedList.append(app) } // Create an access object: var accessT: SecAccess? status = SecAccessCreate(name as CFString, trustedList as CFArray, &accessT) guard status == errSecSuccess, let access = accessT else { throw KeychainStorageError(osStatus: status) } return access } #endif #if os(macOS) || os(iOS) @objc public func createAccessControl() throws -> SecAccessControl { let flags: SecAccessControlCreateFlags #if os(macOS) if #available(OSX 10.13.4, *) { flags = [.biometryCurrentSet, .or, .devicePasscode] } else if #available(OSX 10.12.1, *) { flags = [.touchIDCurrentSet, .or, .devicePasscode] } else { flags = [.devicePasscode] } #elseif os(iOS) if #available(iOS 11.3, *) { flags = [.biometryCurrentSet, .or, .devicePasscode] } else { flags = [.touchIDCurrentSet, .or, .devicePasscode] } #endif guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, flags, nil) else { throw KeychainStorageError(errCode: KeychainStorageErrorCodes.creatingAccessControlFailed) } return access } #endif private func addBiometricParams(toQuery query: inout [String: Any], withQueryOptions queryOptions: KeychainQueryOptions) throws { #if os(macOS) || os(iOS) if queryOptions.biometricallyProtected { query.removeValue(forKey: kSecAttrAccessible as String) query[kSecAttrAccessControl as String] = try self.createAccessControl() query[kSecUseOperationPrompt as String] = queryOptions.biometricPromt query[kSecUseAuthenticationContext as String] = LAContext() } #endif } /// Private key identifier format @objc public static let privateKeyIdentifierFormat = ".%@.privatekey.%@\0" /// KeychainStorage parameters @objc public let storageParams: KeychainStorageParams /// Initializer /// /// - Parameter storageParams: KeychainStorage parameters @objc public init(storageParams: KeychainStorageParams) { self.storageParams = storageParams super.init() } /// Stores sensitive data to Keychain /// /// - Parameters: /// - data: Sensitive data /// - name: Alias for data /// - meta: Additional meta info /// - Returns: Stored entry /// - Throws: KeychainStorageError @objc open func store(data: Data, withName name: String, meta: [String: String]?, queryOptions: KeychainQueryOptions?) throws -> KeychainEntry { let queryOptions = queryOptions ?? KeychainQueryOptions() let tag = String(format: KeychainStorage.privateKeyIdentifierFormat, self.storageParams.appName, name) #if os(iOS) || os(tvOS) || os(watchOS) guard let tagData = tag.data(using: .utf8), let nameData = name.data(using: .utf8) else { throw KeychainStorageError(errCode: .utf8ConvertingError) } var query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecAttrApplicationLabel as String: nameData, kSecAttrApplicationTag as String: tagData, kSecAttrAccessible as String: queryOptions.accessibility as CFString, kSecAttrLabel as String: name, kSecAttrIsPermanent as String: true, kSecAttrCanEncrypt as String: true, kSecAttrCanDecrypt as String: false, kSecAttrCanDerive as String: false, kSecAttrCanSign as String: true, kSecAttrCanVerify as String: false, kSecAttrCanWrap as String: false, kSecAttrCanUnwrap as String: false, kSecAttrSynchronizable as String: false, kSecReturnData as String: true, kSecReturnAttributes as String: true ] // Access groups are not supported in simulator #if !targetEnvironment(simulator) if let accessGroup = queryOptions.accessGroup { query[kSecAttrAccessGroup as String] = accessGroup } #endif #elseif os(macOS) let access = try self.createAccess(forName: name, queryOptions: queryOptions) var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: name, kSecAttrService as String: tag, kSecAttrLabel as String: name, kSecAttrSynchronizable as String: false, kSecAttrAccess as String: access, kSecAttrComment as String: self.commentString(), kSecReturnData as String: true, kSecReturnAttributes as String: true ] #if DEBUG query[kSecAttrIsInvisible as String] = false #else query[kSecAttrIsInvisible as String] = true #endif #endif try self.addBiometricParams(toQuery: &query, withQueryOptions: queryOptions) let keyEntry = KeyEntry(name: name, value: data, meta: meta) let keyEntryData = NSKeyedArchiver.archivedData(withRootObject: keyEntry) query[kSecValueData as String] = keyEntryData var dataObject: AnyObject? let status = SecItemAdd(query as CFDictionary, &dataObject) let data = try KeychainStorage.validateKeychainResponse(dataObject: dataObject, status: status) return try KeychainStorage.parseKeychainEntry(from: data) } /// Updated entry in Keychain /// /// - Parameters: /// - name: Alias /// - data: New data /// - meta: New meta info /// - Throws: KeychainStorageError @objc open func updateEntry(withName name: String, data: Data, meta: [String: String]?, queryOptions: KeychainQueryOptions?) throws { let queryOptions = queryOptions ?? KeychainQueryOptions() let tag = String(format: KeychainStorage.privateKeyIdentifierFormat, self.storageParams.appName, name) #if os(iOS) || os(tvOS) || os(watchOS) guard let tagData = tag.data(using: .utf8), let nameData = name.data(using: .utf8) else { throw KeychainStorageError(errCode: .utf8ConvertingError) } var query = [String: Any]() query = [ kSecClass as String: kSecClassKey, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecAttrApplicationLabel as String: nameData, kSecAttrApplicationTag as String: tagData ] // Access groups are not supported in simulator #if !targetEnvironment(simulator) if let accessGroup = queryOptions.accessGroup { query[kSecAttrAccessGroup as String] = accessGroup } #endif #elseif os(macOS) var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: name, kSecAttrService as String: tag, kSecAttrComment as String: self.commentString() ] #endif try self.addBiometricParams(toQuery: &query, withQueryOptions: queryOptions) let keyEntry = KeyEntry(name: name, value: data, meta: meta) let keyEntryData = NSKeyedArchiver.archivedData(withRootObject: keyEntry) let keySpecificData: [String: Any] = [ kSecValueData as String: keyEntryData ] let status = SecItemUpdate(query as CFDictionary, keySpecificData as CFDictionary) guard status == errSecSuccess else { throw KeychainStorageError(osStatus: status) } } /// Retrieves entry from keychain /// /// - Parameter name: Alias /// - Returns: Retrieved entry /// - Throws: KeychainStorageError @objc open func retrieveEntry(withName name: String, queryOptions: KeychainQueryOptions?) throws -> KeychainEntry { let queryOptions = queryOptions ?? KeychainQueryOptions() let tag = String(format: KeychainStorage.privateKeyIdentifierFormat, self.storageParams.appName, name) #if os(iOS) || os(tvOS) || os(watchOS) guard let tagData = tag.data(using: .utf8), let nameData = name.data(using: .utf8) else { throw KeychainStorageError(errCode: .utf8ConvertingError) } var query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecAttrApplicationLabel as String: nameData, kSecAttrApplicationTag as String: tagData, kSecReturnData as String: true, kSecReturnAttributes as String: true ] #elseif os(macOS) var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: name, kSecAttrService as String: tag, kSecReturnData as String: true, kSecReturnAttributes as String: true, kSecAttrComment as String: self.commentString() ] #endif try self.addBiometricParams(toQuery: &query, withQueryOptions: queryOptions) var dataObject: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &dataObject) let data = try KeychainStorage.validateKeychainResponse(dataObject: dataObject, status: status) return try KeychainStorage.parseKeychainEntry(from: data) } /// Retrieves all entries in Keychain /// /// - Returns: Retrieved entries /// - Throws: KeychainStorageError @objc open func retrieveAllEntries(queryOptions: KeychainQueryOptions?) throws -> [KeychainEntry] { let queryOptions = queryOptions ?? KeychainQueryOptions() #if os(iOS) || os(tvOS) || os(watchOS) var query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecReturnData as String: true, kSecReturnAttributes as String: true, kSecMatchLimit as String: kSecMatchLimitAll ] #elseif os(macOS) var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecReturnData as String: true, kSecReturnAttributes as String: true, // Workaround: kSecMatchLimitAll doesn't work // Seems like UInt32.max / 2 is maximum allowed value, which should be enough for one application kSecMatchLimit as String: NSNumber(value: UInt32.max / 2), kSecAttrComment as String: self.commentString() ] #endif try self.addBiometricParams(toQuery: &query, withQueryOptions: queryOptions) var dataObject: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &dataObject) if status == errSecItemNotFound { return [] } let data = try KeychainStorage.validateKeychainResponse(dataObject: dataObject, status: status) guard let arr = data as? [AnyObject] else { throw KeychainStorageError(errCode: .wrongResponseType) } return arr.compactMap { try? KeychainStorage.parseKeychainEntry(from: $0) } } /// Deletes entry from Keychain /// /// - Parameter name: Alias /// - Throws: KeychainStorageError @objc open func deleteEntry(withName name: String, queryOptions: KeychainQueryOptions?) throws { let queryOptions = queryOptions ?? KeychainQueryOptions() let tag = String(format: KeychainStorage.privateKeyIdentifierFormat, self.storageParams.appName, name) #if os(iOS) || os(tvOS) || os(watchOS) guard let tagData = tag.data(using: .utf8), let nameData = name.data(using: .utf8) else { throw KeychainStorageError(errCode: .utf8ConvertingError) } var query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecAttrApplicationLabel as String: nameData, kSecAttrApplicationTag as String: tagData ] #elseif os(macOS) var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: name, kSecAttrService as String: tag, kSecAttrComment as String: self.commentString() ] #endif try self.addBiometricParams(toQuery: &query, withQueryOptions: queryOptions) let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess else { throw KeychainStorageError(osStatus: status) } } /// Deletes all entries from Keychain /// /// - Throws: KeychainStorageError @objc open func deleteAllEntries(queryOptions: KeychainQueryOptions? = nil) throws { let queryOptions = queryOptions ?? KeychainQueryOptions() #if os(iOS) || os(tvOS) || os(watchOS) var query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate ] #elseif os(macOS) var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, // Workaround: kSecMatchLimitAll doesn't work // Seems like UInt32.max / 2 is maximum allowed value, which should be enough for one application kSecMatchLimit as String: NSNumber(value: UInt32.max / 2), kSecAttrComment as String: self.commentString() ] #endif try self.addBiometricParams(toQuery: &query, withQueryOptions: queryOptions) let status = SecItemDelete(query as CFDictionary) if status == errSecItemNotFound { return } guard status == errSecSuccess else { throw KeychainStorageError(osStatus: status) } } /// Checks if entry exists in Keychain /// /// - Parameter name: Alias /// - Returns: true if entry exists, false otherwise /// - Throws: KeychainStorageError open func existsEntry(withName name: String, queryOptions: KeychainQueryOptions?) throws -> Bool { do { _ = try self.retrieveEntry(withName: name, queryOptions: queryOptions) return true } catch let error as KeychainStorageError { if error.errCode == .keychainError, let osStatus = error.osStatus, osStatus == errSecItemNotFound { return false } throw error } catch { throw error } } private static func validateKeychainResponse(dataObject: AnyObject?, status: OSStatus) throws -> AnyObject { guard status == errSecSuccess else { throw KeychainStorageError(osStatus: status) } guard let data = dataObject else { throw KeychainStorageError(errCode: .emptyKeychainResponse) } return data } private static func parseKeychainEntry(from data: AnyObject) throws -> KeychainEntry { guard let dict = data as? [String: Any] else { throw KeychainStorageError(errCode: .wrongResponseType) } guard let creationDate = dict[kSecAttrCreationDate as String] as? Date, let modificationDate = dict[kSecAttrModificationDate as String] as? Date, let rawData = dict[kSecValueData as String] as? Data, let storedKeyEntry = NSKeyedUnarchiver.unarchiveObject(with: rawData) as? KeyEntry else { throw KeychainStorageError(errCode: .errorParsingKeychainResponse) } return KeychainEntry(data: storedKeyEntry.value, name: storedKeyEntry.name, meta: storedKeyEntry.meta, creationDate: creationDate, modificationDate: modificationDate) } }
bsd-3-clause
1abb6c958ce77b45fd6210e8ef52ad90
35.865093
119
0.64288
5.429955
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Moog Ladder/AKMoogLadder.swift
1
5225
// // AKMoogLadder.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// Moog Ladder is an new digital implementation of the Moog ladder filter based /// on the work of Antti Huovilainen, described in the paper "Non-Linear Digital /// Implementation of the Moog Ladder Filter" (Proceedings of DaFX04, Univ of /// Napoli). This implementation is probably a more accurate digital /// representation of the original analogue filter. /// /// - Parameters: /// - input: Input node to process /// - cutoffFrequency: Filter cutoff frequency. /// - resonance: Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1. /// public class AKMoogLadder: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKMoogLadderAudioUnit? internal var token: AUParameterObserverToken? private var cutoffFrequencyParameter: AUParameter? private var resonanceParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Filter cutoff frequency. public var cutoffFrequency: Double = 1000 { willSet { if cutoffFrequency != newValue { if internalAU!.isSetUp() { cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.cutoffFrequency = Float(newValue) } } } } /// Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1. public var resonance: Double = 0.5 { willSet { if resonance != newValue { if internalAU!.isSetUp() { resonanceParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.resonance = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - Parameters: /// - input: Input node to process /// - cutoffFrequency: Filter cutoff frequency. /// - resonance: Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1. /// public init( _ input: AKNode, cutoffFrequency: Double = 1000, resonance: Double = 0.5) { self.cutoffFrequency = cutoffFrequency self.resonance = resonance var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = fourCC("mgld") description.componentManufacturer = fourCC("AuKt") description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKMoogLadderAudioUnit.self, asComponentDescription: description, name: "Local AKMoogLadder", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKMoogLadderAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter resonanceParameter = tree.valueForKey("resonance") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.cutoffFrequencyParameter!.address { self.cutoffFrequency = Double(value) } else if address == self.resonanceParameter!.address { self.resonance = Double(value) } } } internalAU?.cutoffFrequency = Float(cutoffFrequency) internalAU?.resonance = Float(resonance) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
2cf1e460b47b11c9b36d9d0c0c064a44
34.544218
182
0.628134
5.408903
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/LinkedBankAccountTableViewCell/LinkedBankAccountCellPresenter.swift
1
1961
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import RxCocoa import RxSwift public final class LinkedBankAccountCellPresenter { // MARK: - Public Properties public let account: LinkedBankAccount let badgeImageViewModel: Driver<BadgeImageViewModel> let title: Driver<LabelContent> let description: Driver<LabelContent> public let multiBadgeViewModel: Driver<MultiBadgeViewModel> // MARK: - Private Properties static let multiBadgeInsets: UIEdgeInsets = .init( top: 0, left: 72, bottom: 0, right: 0 ) private let badgeFactory = SingleAccountBadgeFactory() // MARK: - Init public init(account: LinkedBankAccount, action: AssetAction) { self.account = account multiBadgeViewModel = badgeFactory .badge(account: account, action: action) .map { .init( layoutMargins: LinkedBankAccountCellPresenter.multiBadgeInsets, height: 24.0, badges: $0 ) } .asDriver(onErrorJustReturn: .init()) title = .just( .init( text: account.label, font: .main(.semibold, 16.0), color: .titleText, alignment: .left, accessibility: .none ) ) description = .just( .init( text: LocalizationConstants.accountEndingIn + " \(account.accountNumber)", font: .main(.medium, 14.0), color: .descriptionText, alignment: .left, accessibility: .none ) ) badgeImageViewModel = .just(.default( image: .local(name: "icon-bank", bundle: .platformUIKit), cornerRadius: .round, accessibilityIdSuffix: "" )) } }
lgpl-3.0
eb3a902507de5b4923d9f9b46a1bc49c
27.823529
90
0.558673
5.240642
false
false
false
false
huonw/swift
test/attr/attr_nonobjc.swift
4
3799
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation @objc class LightSaber { init() { caloriesBurned = 5 } func defeatEnemy(_ b: Bool) -> Bool { // expected-note {{'defeatEnemy' previously declared here}} return !b } // Make sure we can overload a method with @nonobjc methods @nonobjc func defeatEnemy(_ i: Int) -> Bool { return (i > 0) } // This is not allowed, though func defeatEnemy(_ s: String) -> Bool { // expected-error {{method 'defeatEnemy' with Objective-C selector 'defeatEnemy:' conflicts with previous declaration with the same Objective-C selector}} return s != "" } @nonobjc subscript(index: Int) -> Int { return index } @nonobjc var caloriesBurned: Float } class BlueLightSaber : LightSaber { @nonobjc override func defeatEnemy(_ b: Bool) -> Bool { } } @objc class InchoateToad { init(x: Int) {} // expected-note {{previously declared}} @nonobjc init(x: Float) {} init(x: String) {} // expected-error {{conflicts with previous declaration with the same Objective-C selector}} } @nonobjc class NonObjCClassNotAllowed { } // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}} {{1-10=}} class NonObjCDeallocNotAllowed { @nonobjc deinit { // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}} {{3-12=}} } } @objc protocol ObjCProtocol { func protocolMethod() // expected-note {{}} @nonobjc func nonObjCProtocolMethodNotAllowed() // expected-error {{declaration is a member of an @objc protocol, and cannot be marked @nonobjc}} @nonobjc subscript(index: Int) -> Int { get } // expected-error {{declaration is a member of an @objc protocol, and cannot be marked @nonobjc}} var surfaceArea: Float { @nonobjc get } // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} var displacement: Float { get } } class SillyClass { @objc var description: String { @nonobjc get { return "" } } // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} } class ObjCAndNonObjCNotAllowed { @objc @nonobjc func redundantAttributes() { } // expected-error {{declaration is marked @objc, and cannot be marked @nonobjc}} } class DynamicAndNonObjCNotAllowed { @nonobjc dynamic func redundantAttributes() { } // expected-error {{a declaration cannot be both '@nonobjc' and 'dynamic'}} } class IBOutletAndNonObjCNotAllowed { @nonobjc @IBOutlet var leeloo : String? = "Hello world" // expected-error {{declaration is marked @IBOutlet, and cannot be marked @nonobjc}} } class NSManagedAndNonObjCNotAllowed { @nonobjc @NSManaged var rosie : NSObject // expected-error {{declaration is marked @NSManaged, and cannot be marked @nonobjc}} } @nonobjc func nonObjCTopLevelFuncNotAllowed() { } // expected-error {{only class members and extensions of classes can be declared @nonobjc}} {{1-10=}} @objc class NonObjCPropertyObjCProtocolNotAllowed : ObjCProtocol { // expected-error {{does not conform to protocol}} @nonobjc func protocolMethod() { } // expected-note {{candidate is explicitly '@nonobjc'}} func nonObjCProtocolMethodNotAllowed() { } subscript(index: Int) -> Int { return index } var displacement: Float { @nonobjc get { // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} return Float(self[10]) } } var surfaceArea: Float { get { return Float(100) } } } struct SomeStruct { } @nonobjc extension SomeStruct { } // expected-error{{only extensions of classes can be declared @nonobjc}} protocol SR4226_Protocol : class {} extension SR4226_Protocol { @nonobjc func function() {} // expected-error {{only class members and extensions of classes can be declared @nonobjc}} }
apache-2.0
874c70447945463b743649b686179056
32.619469
196
0.707291
4.14738
false
false
false
false
hechunyanchenshijin/DouYuZB
DYZB/DYZB/Classes/Home/Controller/HomeViewController.swift
1
3601
// // HomeViewController.swift // DYZB // // Created by 时锦 陈 on 2017/2/22. // Copyright © 2017年 Yun. All rights reserved. // import UIKit private let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 fileprivate lazy var pageTitleView : PageTitleView = { [weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() fileprivate lazy var pageContentView : PageContentView = {[weak self] in // 1. 确定我们内容的frame let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabbarH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH) // 2. 确定我们所有的子控制器 var childVCs = [UIViewController]() childVCs.append(RecommendViewController()) for _ in 0..<4 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVCs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVCs: childVCs, parentViewController: self) contentView.delegate = self return contentView }() // MARK:- 系统的回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置UI界面 setupUI() } } // MARK:- 设置UI界面 extension HomeViewController { fileprivate func setupUI() { // 0. 不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false // 1. 设置导航栏 setupNavigationBar() // 2. 添加TitleView view.addSubview(pageTitleView) // 3. 添加ContentView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.purple } private func setupNavigationBar() { // 1. 设置左侧的Item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") // 2. 设置右侧的Item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem] } } // MARK:- 遵守PageTitleViewDelegate协议 extension HomeViewController : PageTitleViewDelegate { func PageTitleViewD(titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } } // MARK:- 遵守PageContentViewDelegate协议 extension HomeViewController : PageContentViewDelegate { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
70475131afbb76e2b796a581932c70e5
28.551724
156
0.649358
5.056047
false
false
false
false
benjaminhallock/dojo-custom-camera
dojo-custom-camera/XMCCamera.swift
1
5516
// // XMCCamera.swift // dojo-custom-camera // // Created by David McGraw on 11/13/14. // Copyright (c) 2014 David McGraw. All rights reserved. // import UIKit import AVFoundation @objc protocol XMCCameraDelegate { func cameraSessionConfigurationDidComplete() func cameraSessionDidBegin() func cameraSessionDidStop() } class XMCCamera: NSObject { weak var delegate: XMCCameraDelegate? var session: AVCaptureSession! var sessionQueue: dispatch_queue_t! var stillImageOutput: AVCaptureStillImageOutput? init(sender: AnyObject) { super.init() self.delegate = sender as? XMCCameraDelegate self.setObservers() self.initializeSession() } deinit { self.removeObservers() } // MARK: Session func initializeSession() { self.session = AVCaptureSession() self.session.sessionPreset = AVCaptureSessionPresetPhoto self.sessionQueue = dispatch_queue_create("camera session", DISPATCH_QUEUE_SERIAL) dispatch_async(self.sessionQueue) { self.session.beginConfiguration() self.addVideoInput() self.addStillImageOutput() self.session.commitConfiguration() dispatch_async(dispatch_get_main_queue()) { NSLog("Session initialization did complete") self.delegate?.cameraSessionConfigurationDidComplete() } } } func startCamera() { dispatch_async(self.sessionQueue) { self.session.startRunning() } } func stopCamera() { dispatch_async(self.sessionQueue) { self.session.stopRunning() } } func captureStillImage(completed: (image: UIImage?) -> Void) { if let imageOutput = self.stillImageOutput { dispatch_async(self.sessionQueue, { () -> Void in var videoConnection: AVCaptureConnection? for connection in imageOutput.connections { let c = connection as! AVCaptureConnection for port in c.inputPorts { let p = port as! AVCaptureInputPort if p.mediaType == AVMediaTypeVideo { videoConnection = c; break } } if videoConnection != nil { break } } if videoConnection != nil { var error: NSError? imageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (imageSampleBuffer: CMSampleBufferRef!, error) -> Void in let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer) let image: UIImage? = UIImage(data: imageData!)! dispatch_async(dispatch_get_main_queue()) { completed(image: image) } }) } else { dispatch_async(dispatch_get_main_queue()) { completed(image: nil) } } }) } else { completed(image: nil) } } // MARK: Configuration func addVideoInput() { var error: NSError? let device: AVCaptureDevice = self.deviceWithMediaTypeWithPosition(AVMediaTypeVideo, position: AVCaptureDevicePosition.Back) let input = try! AVCaptureDeviceInput(device: device) if error == nil { if self.session.canAddInput(input) { self.session.addInput(input) } } } func addStillImageOutput() { stillImageOutput = AVCaptureStillImageOutput() stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] if self.session.canAddOutput(stillImageOutput) { session.addOutput(stillImageOutput) } } func deviceWithMediaTypeWithPosition(mediaType: NSString, position: AVCaptureDevicePosition) -> AVCaptureDevice { let devices: NSArray = AVCaptureDevice.devicesWithMediaType(mediaType as String) var captureDevice: AVCaptureDevice = devices.firstObject as! AVCaptureDevice for device in devices { let d = device as! AVCaptureDevice if d.position == position { captureDevice = d break; } } return captureDevice } // MARK: Observers func setObservers() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionDidStart:", name: AVCaptureSessionDidStartRunningNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionDidStop:", name: AVCaptureSessionDidStopRunningNotification, object: nil) } func removeObservers() { NSNotificationCenter.defaultCenter().removeObserver(self) } func sessionDidStart(notification: NSNotification) { dispatch_async(dispatch_get_main_queue()) { NSLog("Session did start") self.delegate?.cameraSessionDidBegin() } } func sessionDidStop(notification: NSNotification) { dispatch_async(dispatch_get_main_queue()) { NSLog("Session did stop") self.delegate?.cameraSessionDidStop() } } }
mit
fa4052d00c5ebb98198de3c650827df5
30.52
173
0.590645
5.788038
false
false
false
false
Jnosh/swift
test/attr/attr_availability.swift
16
51639
// RUN: %target-typecheck-verify-swift @available(*, unavailable) func unavailable_func() {} @available(*, unavailable, message: "message") func unavailable_func_with_message() {} @available(tvOS, unavailable) @available(watchOS, unavailable) @available(iOS, unavailable) @available(OSX, unavailable) func unavailable_multiple_platforms() {} @available // expected-error {{expected '(' in 'available' attribute}} func noArgs() {} @available(*) // expected-error {{expected ',' in 'available' attribute}} func noKind() {} @available(badPlatform, unavailable) // expected-warning {{unknown platform 'badPlatform' for attribute 'available'}} func unavailable_bad_platform() {} // Handle unknown platform. @available(HAL9000, unavailable) // expected-warning {{unknown platform 'HAL9000'}} func availabilityUnknownPlatform() {} // <rdar://problem/17669805> Availability can't appear on a typealias @available(*, unavailable, message: "oh no you don't") typealias int = Int // expected-note {{'int' has been explicitly marked unavailable here}} @available(*, unavailable, renamed: "Float") typealias float = Float // expected-note {{'float' has been explicitly marked unavailable here}} protocol MyNewerProtocol {} @available(*, unavailable, renamed: "MyNewerProtocol") protocol MyOlderProtocol {} // expected-note {{'MyOlderProtocol' has been explicitly marked unavailable here}} extension Int: MyOlderProtocol {} // expected-error {{'MyOlderProtocol' has been renamed to 'MyNewerProtocol'}} struct MyCollection<Element> { @available(*, unavailable, renamed: "Element") typealias T = Element // expected-note 2{{'T' has been explicitly marked unavailable here}} func foo(x: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{15-16=Element}} } extension MyCollection { func append(element: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{24-25=Element}} } @available(*, unavailable, renamed: "MyCollection") typealias YourCollection<Element> = MyCollection<Element> // expected-note {{'YourCollection' has been explicitly marked unavailable here}} var x : YourCollection<Int> // expected-error {{'YourCollection' has been renamed to 'MyCollection'}}{{9-23=MyCollection}} var x : int // expected-error {{'int' is unavailable: oh no you don't}} var y : float // expected-error {{'float' has been renamed to 'Float'}}{{9-14=Float}} // Encoded message @available(*, unavailable, message: "This message has a double quote \"") func unavailableWithDoubleQuoteInMessage() {} // expected-note {{'unavailableWithDoubleQuoteInMessage()' has been explicitly marked unavailable here}} func useWithEscapedMessage() { unavailableWithDoubleQuoteInMessage() // expected-error {{'unavailableWithDoubleQuoteInMessage()' is unavailable: This message has a double quote \"}} } // More complicated parsing. @available(OSX, message: "x", unavailable) let _: Int @available(OSX, introduced: 1, deprecated: 2.0, obsoleted: 3.0.0) let _: Int @available(OSX, introduced: 1.0.0, deprecated: 2.0, obsoleted: 3, unavailable, renamed: "x") let _: Int // Meaningless but accepted. @available(OSX, message: "x") let _: Int // Parse errors. @available() // expected-error{{expected platform name or '*' for 'available' attribute}} let _: Int @available(OSX,) // expected-error{{expected 'available' option such as 'unavailable', 'introduced', 'deprecated', 'obsoleted', 'message', or 'renamed'}} let _: Int @available(OSX, message) // expected-error{{expected ':' after 'message' in 'available' attribute}} let _: Int @available(OSX, message: ) // expected-error{{expected string literal in 'available' attribute}} let _: Int @available(OSX, message: x) // expected-error{{expected string literal in 'available' attribute}} let _: Int @available(OSX, unavailable:) // expected-error{{expected ')' in 'available' attribute}} expected-error{{expected declaration}} let _: Int @available(OSX, introduced) // expected-error{{expected ':' after 'introduced' in 'available' attribute}} let _: Int @available(OSX, introduced: ) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: x) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.x) // expected-error{{expected ')' in 'available' attribute}} expected-error {{expected declaration}} let _: Int @available(OSX, introduced: 1.0.x) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 0x1) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.0e4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: -1) // expected-error{{expected version number in 'available' attribute}} expected-error{{expected declaration}} let _: Int @available(OSX, introduced: 1.0.1e4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.0.0x4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(*, renamed: "bad name") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "_") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a+b") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(:b:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, deprecated, unavailable, message: "message") // expected-error{{'available' attribute cannot be both unconditionally 'unavailable' and 'deprecated'}} struct BadUnconditionalAvailability { }; @available(*, unavailable, message="oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{35-36=: }} typealias EqualFixIt1 = Int @available(*, unavailable, message = "oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{36-37=:}} typealias EqualFixIt2 = Int // Encoding in messages @available(*, deprecated, message: "Say \"Hi\"") func deprecated_func_with_message() {} // 'PANDA FACE' (U+1F43C) @available(*, deprecated, message: "Pandas \u{1F43C} are cute") struct DeprecatedTypeWithMessage { } func use_deprecated_with_message() { deprecated_func_with_message() // expected-warning{{'deprecated_func_with_message()' is deprecated: Say \"Hi\"}} var _: DeprecatedTypeWithMessage // expected-warning{{'DeprecatedTypeWithMessage' is deprecated: Pandas \u{1F43C} are cute}} } @available(*, deprecated, message: "message") func use_deprecated_func_with_message2() { deprecated_func_with_message() // no diagnostic } @available(*, deprecated, renamed: "blarg") func deprecated_func_with_renamed() {} @available(*, deprecated, message: "blarg is your friend", renamed: "blarg") func deprecated_func_with_message_renamed() {} @available(*, deprecated, renamed: "wobble") struct DeprecatedTypeWithRename { } func use_deprecated_with_renamed() { deprecated_func_with_renamed() // expected-warning{{'deprecated_func_with_renamed()' is deprecated: renamed to 'blarg'}} // expected-note@-1{{use 'blarg'}}{{3-31=blarg}} deprecated_func_with_message_renamed() //expected-warning{{'deprecated_func_with_message_renamed()' is deprecated: blarg is your friend}} // expected-note@-1{{use 'blarg'}}{{3-39=blarg}} var _: DeprecatedTypeWithRename // expected-warning{{'DeprecatedTypeWithRename' is deprecated: renamed to 'wobble'}} // expected-note@-1{{use 'wobble'}}{{10-34=wobble}} } // Short form of @available() @available(iOS 8.0, *) func functionWithShortFormIOSAvailable() {} @available(iOS 8, *) func functionWithShortFormIOSVersionNoPointAvailable() {} @available(iOS 8.0, OSX 10.10.3, *) func functionWithShortFormIOSOSXAvailable() {} @available(iOS 8.0 // expected-error {{must handle potential future platforms with '*'}} {{19-19=, *}} func shortFormMissingParen() { // expected-error {{expected ')' in 'available' attribute}} } @available(iOS 8.0, // expected-error {{expected platform name}} func shortFormMissingPlatform() { } @available(iOS 8.0, * func shortFormMissingParenAfterWildcard() { // expected-error {{expected ')' in 'available' attribute}} } @available(*) // expected-error {{expected ',' in 'available' attribute}} func onlyWildcardInAvailable() {} @available(iOS 8.0, *, OSX 10.10.3) func shortFormWithWildcardInMiddle() {} @available(iOS 8.0, OSX 10.10.3) // expected-error {{must handle potential future platforms with '*'}} {{32-32=, *}} func shortFormMissingWildcard() {} @availability(OSX, introduced: 10.10) // expected-error {{@availability has been renamed to @available}} {{2-14=available}} func someFuncUsingOldAttribute() { } // <rdar://problem/23853709> Compiler crash on call to unavailable "print" func TextOutputStreamTest(message: String, to: inout TextOutputStream) { print(message, &to) // expected-error {{'print' is unavailable: Please use the 'to' label for the target stream: 'print((...), to: &...)'}} } // expected-note@+1{{'T' has been explicitly marked unavailable here}} struct UnavailableGenericParam<@available(*, unavailable, message: "nope") T> { func f(t: T) { } // expected-error{{'T' is unavailable: nope}} } struct DummyType {} @available(*, unavailable, renamed: "&+") func +(x: DummyType, y: DummyType) {} // expected-note {{here}} @available(*, deprecated, renamed: "&-") func -(x: DummyType, y: DummyType) {} func testOperators(x: DummyType, y: DummyType) { x + y // expected-error {{'+' has been renamed to '&+'}} {{5-6=&+}} x - y // expected-warning {{'-' is deprecated: renamed to '&-'}} expected-note {{use '&-' instead}} {{5-6=&-}} } @available(*, unavailable, renamed: "DummyType.foo") func unavailableMember() {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.bar") func deprecatedMember() {} @available(*, unavailable, renamed: "DummyType.Inner.foo") func unavailableNestedMember() {} // expected-note {{here}} @available(*, unavailable, renamed: "DummyType.Foo") struct UnavailableType {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.Bar") typealias DeprecatedType = Int func testGlobalToMembers() { unavailableMember() // expected-error {{'unavailableMember()' has been renamed to 'DummyType.foo'}} {{3-20=DummyType.foo}} deprecatedMember() // expected-warning {{'deprecatedMember()' is deprecated: renamed to 'DummyType.bar'}} expected-note {{use 'DummyType.bar' instead}} {{3-19=DummyType.bar}} unavailableNestedMember() // expected-error {{'unavailableNestedMember()' has been renamed to 'DummyType.Inner.foo'}} {{3-26=DummyType.Inner.foo}} let x: UnavailableType? = nil // expected-error {{'UnavailableType' has been renamed to 'DummyType.Foo'}} {{10-25=DummyType.Foo}} _ = x let y: DeprecatedType? = nil // expected-warning {{'DeprecatedType' is deprecated: renamed to 'DummyType.Bar'}} expected-note {{use 'DummyType.Bar' instead}} {{10-24=DummyType.Bar}} _ = y } @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgNames(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "moreShinyLabeledArguments(example:)") func deprecatedArgNames(b: Int) {} @available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)") func unavailableMemberArgNames(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)") func deprecatedMemberArgNames(b: Int) {} @available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)", message: "ha") func unavailableMemberArgNamesMsg(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)", message: "ha") func deprecatedMemberArgNamesMsg(b: Int) {} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableNoArgs() {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableSame(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)") func unavailableVeryLongArgNames(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)") func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.init(other:)") func unavailableInit(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "Foo.Bar.init(other:)") func unavailableNestedInit(a: Int) {} // expected-note 2 {{here}} func testArgNames() { unavailableArgNames(a: 0) // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-22=shinyLabeledArguments}} {{23-24=example}} deprecatedArgNames(b: 1) // expected-warning {{'deprecatedArgNames(b:)' is deprecated: renamed to 'moreShinyLabeledArguments(example:)'}} expected-note {{use 'moreShinyLabeledArguments(example:)' instead}} {{3-21=moreShinyLabeledArguments}} {{22-23=example}} unavailableMemberArgNames(a: 0) // expected-error {{'unavailableMemberArgNames(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)'}} {{3-28=DummyType.shinyLabeledArguments}} {{29-30=example}} deprecatedMemberArgNames(b: 1) // expected-warning {{'deprecatedMemberArgNames(b:)' is deprecated: replaced by 'DummyType.moreShinyLabeledArguments(example:)'}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-27=DummyType.moreShinyLabeledArguments}} {{28-29=example}} unavailableMemberArgNamesMsg(a: 0) // expected-error {{'unavailableMemberArgNamesMsg(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)': ha}} {{3-31=DummyType.shinyLabeledArguments}} {{32-33=example}} deprecatedMemberArgNamesMsg(b: 1) // expected-warning {{'deprecatedMemberArgNamesMsg(b:)' is deprecated: ha}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-30=DummyType.moreShinyLabeledArguments}} {{31-32=example}} unavailableNoArgs() // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}} unavailableSame(a: 0) // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-18=shinyLabeledArguments}} unavailableUnnamed(0) // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-21=shinyLabeledArguments}} {{22-22=example: }} unavailableUnnamedSame(0) // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-25=shinyLabeledArguments}} unavailableNewlyUnnamed(a: 0) // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-26=shinyLabeledArguments}} {{27-30=}} unavailableVeryLongArgNames(a: 0) // expected-error {{'unavailableVeryLongArgNames(a:)' has been renamed to 'shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)'}} {{3-30=shinyLabeledArguments}} {{31-32=veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ}} unavailableMultiSame(a: 0, b: 1) // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-23=shinyLabeledArguments}} unavailableMultiUnnamed(0, 1) // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{3-26=shinyLabeledArguments}} {{27-27=example: }} {{30-30=another: }} unavailableMultiUnnamedSame(0, 1) // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-30=shinyLabeledArguments}} unavailableMultiNewlyUnnamed(a: 0, b: 1) // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-31=shinyLabeledArguments}} {{32-35=}} {{38-41=}} unavailableInit(a: 0) // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{3-18=Int}} {{19-20=other}} let fn = unavailableInit // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{12-27=Int.init}} fn(1) unavailableNestedInit(a: 0) // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{3-24=Foo.Bar}} {{25-26=other}} let fn2 = unavailableNestedInit // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{13-34=Foo.Bar.init}} fn2(1) } @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableTooFew(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableTooFewUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableTooManyUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableNoArgsTooMany() {} // expected-note {{here}} func testRenameArgMismatch() { unavailableTooFew(a: 0) // expected-error{{'unavailableTooFew(a:)' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}} unavailableTooFewUnnamed(0) // expected-error{{'unavailableTooFewUnnamed' has been renamed to 'shinyLabeledArguments()'}} {{3-27=shinyLabeledArguments}} unavailableTooMany(a: 0) // expected-error{{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-21=shinyLabeledArguments}} unavailableTooManyUnnamed(0) // expected-error{{'unavailableTooManyUnnamed' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-28=shinyLabeledArguments}} unavailableNoArgsTooMany() // expected-error{{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-27=shinyLabeledArguments}} } @available(*, unavailable, renamed: "Int.foo(self:)") func unavailableInstance(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") func unavailableInstanceUnlabeled(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:other:)") func unavailableInstanceFirst(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(other:self:)") func unavailableInstanceSecond(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(_:self:c:)") func unavailableInstanceSecondOfThree(a: Int, b: Int, c: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)", message: "blah") func unavailableInstanceMessage(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "Int.foo(self:)") func deprecatedInstance(a: Int) {} @available(*, deprecated, renamed: "Int.foo(self:)", message: "blah") func deprecatedInstanceMessage(a: Int) {} @available(*, unavailable, renamed: "Foo.Bar.foo(self:)") func unavailableNestedInstance(a: Int) {} // expected-note {{here}} func testRenameInstance() { unavailableInstance(a: 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=0.foo}} {{23-27=}} unavailableInstanceUnlabeled(0) // expected-error{{'unavailableInstanceUnlabeled' has been replaced by instance method 'Int.foo()'}} {{3-31=0.foo}} {{32-33=}} unavailableInstanceFirst(a: 0, b: 1) // expected-error{{'unavailableInstanceFirst(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-27=0.foo}} {{28-34=}} {{34-35=other}} unavailableInstanceSecond(a: 0, b: 1) // expected-error{{'unavailableInstanceSecond(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-28=1.foo}} {{29-30=other}} {{33-39=}} unavailableInstanceSecondOfThree(a: 0, b: 1, c: 2) // expected-error{{'unavailableInstanceSecondOfThree(a:b:c:)' has been replaced by instance method 'Int.foo(_:c:)'}} {{3-35=1.foo}} {{36-39=}} {{42-48=}} unavailableInstance(a: 0 + 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=(0 + 0).foo}} {{23-31=}} unavailableInstanceMessage(a: 0) // expected-error{{'unavailableInstanceMessage(a:)' has been replaced by instance method 'Int.foo()': blah}} {{3-29=0.foo}} {{30-34=}} deprecatedInstance(a: 0) // expected-warning{{'deprecatedInstance(a:)' is deprecated: replaced by instance method 'Int.foo()'}} expected-note{{use 'Int.foo()' instead}} {{3-21=0.foo}} {{22-26=}} deprecatedInstanceMessage(a: 0) // expected-warning{{'deprecatedInstanceMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.foo()' instead}} {{3-28=0.foo}} {{29-33=}} unavailableNestedInstance(a: 0) // expected-error{{'unavailableNestedInstance(a:)' has been replaced by instance method 'Foo.Bar.foo()'}} {{3-28=0.foo}} {{29-33=}} } @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceTooFew(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceTooFewUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)") func unavailableInstanceTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)") func unavailableInstanceTooManyUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceNoArgsTooMany() {} // expected-note {{here}} func testRenameInstanceArgMismatch() { unavailableInstanceTooFew(a: 0, b: 1) // expected-error{{'unavailableInstanceTooFew(a:b:)' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} unavailableInstanceTooFewUnnamed(0, 1) // expected-error{{'unavailableInstanceTooFewUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} unavailableInstanceTooMany(a: 0) // expected-error{{'unavailableInstanceTooMany(a:)' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}} unavailableInstanceTooManyUnnamed(0) // expected-error{{'unavailableInstanceTooManyUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}} unavailableInstanceNoArgsTooMany() // expected-error{{'unavailableInstanceNoArgsTooMany()' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} } @available(*, unavailable, renamed: "getter:Int.prop(self:)") func unavailableInstanceProperty(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "getter:Int.prop(self:)") func unavailableInstancePropertyUnlabeled(_ a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "getter:Int.prop()") func unavailableClassProperty() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:global()") func unavailableGlobalProperty() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:Int.prop(self:)", message: "blah") func unavailableInstancePropertyMessage(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:Int.prop()", message: "blah") func unavailableClassPropertyMessage() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:global()", message: "blah") func unavailableGlobalPropertyMessage() {} // expected-note {{here}} @available(*, deprecated, renamed: "getter:Int.prop(self:)") func deprecatedInstanceProperty(a: Int) {} @available(*, deprecated, renamed: "getter:Int.prop()") func deprecatedClassProperty() {} @available(*, deprecated, renamed: "getter:global()") func deprecatedGlobalProperty() {} @available(*, deprecated, renamed: "getter:Int.prop(self:)", message: "blah") func deprecatedInstancePropertyMessage(a: Int) {} @available(*, deprecated, renamed: "getter:Int.prop()", message: "blah") func deprecatedClassPropertyMessage() {} @available(*, deprecated, renamed: "getter:global()", message: "blah") func deprecatedGlobalPropertyMessage() {} func testRenameGetters() { unavailableInstanceProperty(a: 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=1.prop}} {{30-36=}} unavailableInstancePropertyUnlabeled(1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=1.prop}} {{39-42=}} unavailableInstanceProperty(a: 1 + 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=(1 + 1).prop}} {{30-40=}} unavailableInstancePropertyUnlabeled(1 + 1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=(1 + 1).prop}} {{39-46=}} unavailableClassProperty() // expected-error{{'unavailableClassProperty()' has been replaced by property 'Int.prop'}} {{3-27=Int.prop}} {{27-29=}} unavailableGlobalProperty() // expected-error{{'unavailableGlobalProperty()' has been replaced by 'global'}} {{3-28=global}} {{28-30=}} unavailableInstancePropertyMessage(a: 1) // expected-error{{'unavailableInstancePropertyMessage(a:)' has been replaced by property 'Int.prop': blah}} {{3-37=1.prop}} {{37-43=}} unavailableClassPropertyMessage() // expected-error{{'unavailableClassPropertyMessage()' has been replaced by property 'Int.prop': blah}} {{3-34=Int.prop}} {{34-36=}} unavailableGlobalPropertyMessage() // expected-error{{'unavailableGlobalPropertyMessage()' has been replaced by 'global': blah}} {{3-35=global}} {{35-37=}} deprecatedInstanceProperty(a: 1) // expected-warning {{'deprecatedInstanceProperty(a:)' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-29=1.prop}} {{29-35=}} deprecatedClassProperty() // expected-warning {{'deprecatedClassProperty()' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-26=Int.prop}} {{26-28=}} deprecatedGlobalProperty() // expected-warning {{'deprecatedGlobalProperty()' is deprecated: replaced by 'global'}} expected-note{{use 'global' instead}} {{3-27=global}} {{27-29=}} deprecatedInstancePropertyMessage(a: 1) // expected-warning {{'deprecatedInstancePropertyMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-36=1.prop}} {{36-42=}} deprecatedClassPropertyMessage() // expected-warning {{'deprecatedClassPropertyMessage()' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-33=Int.prop}} {{33-35=}} deprecatedGlobalPropertyMessage() // expected-warning {{'deprecatedGlobalPropertyMessage()' is deprecated: blah}} expected-note{{use 'global' instead}} {{3-34=global}} {{34-36=}} } @available(*, unavailable, renamed: "setter:Int.prop(self:_:)") func unavailableSetInstanceProperty(a: Int, b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(_:self:)") func unavailableSetInstancePropertyReverse(a: Int, b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(self:newValue:)") func unavailableSetInstancePropertyUnlabeled(_ a: Int, _ b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(newValue:self:)") func unavailableSetInstancePropertyUnlabeledReverse(_ a: Int, _ b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(x:)") func unavailableSetClassProperty(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "setter:global(_:)") func unavailableSetGlobalProperty(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "setter:Int.prop(self:_:)") func unavailableSetInstancePropertyInout(a: inout Int, b: Int) {} // expected-note {{here}} func testRenameSetters() { unavailableSetInstanceProperty(a: 1, b: 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=1.prop}} {{33-43= = }} {{44-45=}} unavailableSetInstancePropertyUnlabeled(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=1.prop}} {{42-46= = }} {{47-48=}} unavailableSetInstancePropertyReverse(a: 1, b: 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=2.prop}} {{40-44= = }} {{45-52=}} unavailableSetInstancePropertyUnlabeledReverse(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=2.prop}} {{49-50= = }} {{51-55=}} unavailableSetInstanceProperty(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=(1 + 1).prop}} {{33-47= = }} {{52-53=}} unavailableSetInstancePropertyUnlabeled(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=(1 + 1).prop}} {{42-50= = }} {{55-56=}} unavailableSetInstancePropertyReverse(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=(2 + 2).prop}} {{40-44= = }} {{49-60=}} unavailableSetInstancePropertyUnlabeledReverse(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=(2 + 2).prop}} {{49-50= = }} {{55-63=}} unavailableSetClassProperty(a: 1) // expected-error{{'unavailableSetClassProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=Int.prop}} {{30-34= = }} {{35-36=}} unavailableSetGlobalProperty(1) // expected-error{{'unavailableSetGlobalProperty' has been replaced by 'global'}} {{3-31=global}} {{31-32= = }} {{33-34=}} var x = 0 unavailableSetInstancePropertyInout(a: &x, b: 2) // expected-error{{'unavailableSetInstancePropertyInout(a:b:)' has been replaced by property 'Int.prop'}} {{3-38=x.prop}} {{38-49= = }} {{50-51=}} } @available(*, unavailable, renamed: "Int.foo(self:execute:)") func trailingClosure(_ value: Int, fn: () -> Void) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:bar:execute:)") func trailingClosureArg(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(bar:self:execute:)") func trailingClosureArg2(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}} func testInstanceTrailingClosure() { // FIXME: regression in fixit due to noescape-by-default trailingClosure(0) {} // expected-error {{'trailingClosure(_:fn:)' has been replaced by instance method 'Int.foo(execute:)'}} // FIXME: {{3-18=0.foo}} {{19-20=}} trailingClosureArg(0, 1) {} // expected-error {{'trailingClosureArg(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-21=0.foo}} {{22-25=}} {{25-25=bar: }} trailingClosureArg2(0, 1) {} // expected-error {{'trailingClosureArg2(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-22=1.foo}} {{23-23=bar: }} {{24-27=}} } @available(*, unavailable, renamed: "+") func add(_ value: Int, _ other: Int) {} // expected-note {{here}} infix operator *** @available(*, unavailable, renamed: "add") func ***(value: (), other: ()) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:_:)") func ***(value: Int, other: Int) {} // expected-note {{here}} prefix operator *** @available(*, unavailable, renamed: "add") prefix func ***(value: Int?) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") prefix func ***(value: Int) {} // expected-note {{here}} postfix operator *** @available(*, unavailable, renamed: "add") postfix func ***(value: Int?) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") postfix func ***(value: Int) {} // expected-note {{here}} func testOperators() { add(0, 1) // expected-error {{'add' has been renamed to '+'}} {{none}} () *** () // expected-error {{'***' has been renamed to 'add'}} {{none}} 0 *** 1 // expected-error {{'***' has been replaced by instance method 'Int.foo(_:)'}} {{none}} ***nil // expected-error {{'***' has been renamed to 'add'}} {{none}} ***0 // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}} nil*** // expected-error {{'***' has been renamed to 'add'}} {{none}} 0*** // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}} } extension Int { @available(*, unavailable, renamed: "init(other:)") @discardableResult static func factory(other: Int) -> Int { return other } // expected-note 2 {{here}} @available(*, unavailable, renamed: "Int.init(other:)") @discardableResult static func factory2(other: Int) -> Int { return other } // expected-note 2 {{here}} static func testFactoryMethods() { factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{none}} factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{5-13=Int}} } } func testFactoryMethods() { Int.factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{6-14=}} Int.factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{3-15=Int}} } class Base { @available(*, unavailable) func bad() {} // expected-note {{here}} @available(*, unavailable, message: "it was smelly") func smelly() {} // expected-note {{here}} @available(*, unavailable, renamed: "new") func old() {} // expected-note {{here}} @available(*, unavailable, renamed: "new", message: "it was smelly") func oldAndSmelly() {} // expected-note {{here}} @available(*, unavailable) var badProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, message: "it was smelly") var smellyProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, renamed: "new") var oldProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, renamed: "new", message: "it was smelly") var oldAndSmellyProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, renamed: "init") func nowAnInitializer() {} // expected-note {{here}} @available(*, unavailable, renamed: "init()") func nowAnInitializer2() {} // expected-note {{here}} @available(*, unavailable, renamed: "foo") init(nowAFunction: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "foo(_:)") init(nowAFunction2: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgNames(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgRenamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableNoArgs() {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableSame(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)") func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "init(shinyNewName:)") init(unavailableArgNames: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(a:)") init(_ unavailableUnnamed: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(_:)") init(unavailableNewlyUnnamed: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(a:b:)") init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(_:_:)") init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:)") func unavailableTooFew(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)") func unavailableTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:)") func unavailableNoArgsTooMany() {} // expected-note {{here}} @available(*, unavailable, renamed: "Base.shinyLabeledArguments()") func unavailableHasType() {} // expected-note {{here}} } class Sub : Base { override func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}} override func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}} override func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{17-20=new}} override func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{17-29=new}} override var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}} override var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}} override var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{16-23=new}} override var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{16-32=new}} override func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}} override func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}} override init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}} override init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}} override func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-36=shinyLabeledArguments}} {{37-37=example }} override func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-38=shinyLabeledArguments}} {{39-40=example}} override func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{17-34=shinyLabeledArguments}} override func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{17-32=shinyLabeledArguments}} override func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-35=shinyLabeledArguments}} {{36-37=example}} override func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-39=shinyLabeledArguments}} override func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-40=shinyLabeledArguments}} {{41-41=_ }} override func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{17-37=shinyLabeledArguments}} override func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{17-40=shinyLabeledArguments}} {{41-42=example}} {{51-52=another}} override func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-44=shinyLabeledArguments}} override func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-45=shinyLabeledArguments}} {{46-46=_ }} {{54-54=_ }} override init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{17-17=shinyNewName }} override init(_ unavailableUnnamed: Int) {} // expected-error {{'init' has been renamed to 'init(a:)'}} {{17-18=a}} override init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{17-17=_ }} override init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init' has been renamed to 'init(a:b:)'}} {{17-18=a}} {{49-51=}} override init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{17-45=_}} {{54-54=_ }} override func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} override func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}} override func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} override func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}} } // U: Unnamed, L: Labeled @available(*, unavailable, renamed: "after(fn:)") func closure_U_L(_ x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(fn:)") func closure_L_L(x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(_:)") func closure_L_U(x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_UU_LL(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_LU_LL(x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_LL_LL(x: Int, y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_UU_LL_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_UU_LU(_ x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_LU_LU(x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_LL_LU(x: Int, y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_UU_LU_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} func testTrailingClosure() { closure_U_L { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_U_L() { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_U_L({ 0 }) // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-15=fn: }} {{none}} closure_L_L { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_L_L() { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_L_L(x: { 0 }) // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-16=fn}} {{none}} closure_L_U { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}} closure_L_U() { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}} closure_L_U(x: { 0 }) // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{15-18=}} {{none}} closure_UU_LL(0) { 0 } // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_UU_LL(0, { 0 }) // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{20-20=fn: }} {{none}} closure_LU_LL(x: 0) { 0 } // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LU_LL(x: 0, { 0 }) // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-23=fn: }} {{none}} closure_LL_LL(x: 1) { 1 } // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LL(x: 1, y: { 0 }) // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-24=fn}} {{none}} closure_UU_LL_ne(1) { 1 } // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} closure_UU_LL_ne(1, { 0 }) // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{23-23=fn: }} {{none}} closure_UU_LU(0) { 0 } // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_UU_LU(0, { 0 }) // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_LU_LU(x: 0) { 0 } // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LU_LU(x: 0, { 0 }) // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LU(x: 1) { 1 } // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LU(x: 1, y: { 0 }) // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{23-26=}} {{none}} closure_UU_LU_ne(1) { 1 } // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} closure_UU_LU_ne(1, { 0 }) // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} } @available(*, unavailable, renamed: "after(x:)") func defaultUnnamed(_ a: Int = 1) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(x:y:)") func defaultBeforeRequired(a: Int = 1, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "after(x:y:z:)") func defaultPlusTrailingClosure(a: Int = 1, b: Int = 2, c: () -> Void) {} // expected-note 3 {{here}} func testDefaults() { defaultUnnamed() // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{none}} defaultUnnamed(1) // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{18-18=x: }} {{none}} defaultBeforeRequired(b: 5) // expected-error {{'defaultBeforeRequired(a:b:)' has been renamed to 'after(x:y:)'}} {{3-24=after}} {{25-26=y}} {{none}} defaultPlusTrailingClosure {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{none}} defaultPlusTrailingClosure(c: {}) // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=z}} {{none}} defaultPlusTrailingClosure(a: 1) {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=x}} {{none}} } @available(*, unavailable, renamed: "after(x:y:)") func variadic1(a: Int ..., b: Int = 0) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(x:y:)") func variadic2(a: Int, _ b: Int ...) {} // expected-note {{here}} @available(*, unavailable, renamed: "after(x:_:y:z:)") func variadic3(_ a: Int, b: Int ..., c: String = "", d: String) {} // expected-note 2 {{here}} func testVariadic() { variadic1(a: 1, 2) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{none}} variadic1(a: 1, 2, b: 3) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{22-23=y}} {{none}} variadic2(a: 1, 2, 3) // expected-error {{'variadic2(a:_:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{19-19=y: }} {{none}} variadic3(1, b: 2, 3, d: "test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-19=}} {{25-26=z}} {{none}} variadic3(1, d:"test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-17=z}} {{none}} }
apache-2.0
fdba713afcb108bd97d0b33b8b661534
64.782166
303
0.693294
3.854807
false
false
false
false
taka0125/AddressBookSync
Pod/Classes/Sync/AddressBookRecordStatus.swift
1
2080
// // AddressBookRecordStatus.swift // AddressBookSync // // Created by Takahiro Ooishi // Copyright (c) 2015 Takahiro Ooishi. All rights reserved. // Released under the MIT license. // import Foundation import RealmSwift final class AddressBookRecordStatus: Object { dynamic var recordId = "" dynamic var hashCode = "" dynamic var deleted = false dynamic var verifiedAt: Double = 0.0 dynamic var updatedAt: Double = 0.0 dynamic var syncedAt: Double = 0.0 override static func primaryKey() -> String? { return "recordId" } override static func indexedProperties() -> [String] { return ["deleted"] } func isChanged(record: AddressBookRecord) -> Bool { guard let hashCode = record.hashCode() else { return false } return self.hashCode != hashCode } class func find(recordId: String) -> AddressBookRecordStatus? { return ABSRealm.instance().objectForPrimaryKey(self, key: recordId) } class func needSyncRecordIds() -> [String] { let objects = ABSRealm.instance().objects(self) return objects.filter("updatedAt >= syncedAt and deleted == false").map { $0.recordId } } class func fetchAllDeletedRecordIds() -> [String] { let objects = ABSRealm.instance().objects(self) return objects.filter("deleted == true").map { $0.recordId } } class func markAsDelete(timestamp: NSTimeInterval) { let realm = ABSRealm.instance() let results = realm.objects(self).filter("verifiedAt < %lf", timestamp) results.setValue(true, forKeyPath: "deleted") results.setValue(timestamp, forKeyPath: "updatedAt") } class func markAsSynced(recordIds: [String], timestamp: NSTimeInterval) { let realm = ABSRealm.instance() let results = realm.objects(self).filter("recordId IN %@", recordIds) results.setValue(timestamp, forKeyPath: "syncedAt") } class func destoryAllDeletedRecords(recordIds: [String]) { let realm = ABSRealm.instance() let results = realm.objects(self).filter("deleted == true and recordId IN %@", recordIds) realm.delete(results) } }
mit
390da9a11df875b9e57f08cf27cbebd3
29.588235
93
0.695673
4.236253
false
false
false
false
boolkybear/ChromaProjectApp
ChromaProjectApp/ChromaProjectApp/ChromaDocument.swift
1
9939
// // ChromaDocument.swift // ChromaProjectApp // // Created by Boolky Bear on 28/12/14. // Copyright (c) 2014 ByBDesigns. All rights reserved. // import UIKit private enum DocumentKey: String { case OrderKey = "order" case ThumbnailKey = "thumbnail" case NameKey = "name" case CaptionKey = "caption" case BackgroundKey = "background" } private enum DocumentLayerKey: String { case ImageKey = "image" case TransformKey = "transform" case ChromaKey = "chroma" case IdentifierKey = "identifier" } typealias DocumentFileWrapper = NSFileWrapper typealias DocumentLayerFileWrapper = NSFileWrapper extension NSFileWrapper { func fileWrapperForKey(key: String) -> NSFileWrapper? { return self.fileWrappers[key] as? NSFileWrapper } func removeFileWrapperForKey(key: String) -> Bool { var childExists = false if let childWrapper = self.fileWrapperForKey(key) { self.removeFileWrapper(childWrapper) childExists = true } return childExists } } extension DocumentFileWrapper { func order() -> [String]? { var order: [String]? = nil if let orderData = self.fileWrapperForKey(DocumentKey.OrderKey.rawValue)?.regularFileContents { order = NSKeyedUnarchiver.unarchiveObjectWithData(orderData) as? [String] } return order } private func imageForKey(documentKey: DocumentKey) -> UIImage? { var image: UIImage? = nil if let imageData = self.fileWrapperForKey(documentKey.rawValue)?.regularFileContents { image = UIImage(data: imageData) } return image } func thumbnail() -> UIImage? { return self.imageForKey(.ThumbnailKey) } func background() -> UIImage? { return self.imageForKey(.BackgroundKey) } private func stringForKey(documentKey: DocumentKey, encoding: UInt) -> String? { var string: String? = nil if let stringData = self.fileWrapperForKey(documentKey.rawValue)?.regularFileContents { if let str = NSString(data: stringData, encoding: encoding) { string = String(str) } } return string } func name() -> String? { return self.stringForKey(.NameKey, encoding: NSUTF8StringEncoding) } func caption() -> String? { return self.stringForKey(.CaptionKey, encoding: NSUTF8StringEncoding) } func layerWrapper(identifier: String) -> DocumentLayerFileWrapper? { return self.fileWrapperForKey(identifier) } private func setStringForKey(string: String?, documentKey: DocumentKey, encoding: UInt) -> String? { var dev: String? = nil self.removeFileWrapperForKey(documentKey.rawValue) if let string = string { let stringWrapper = NSFileWrapper(regularFileWithContents: string.dataUsingEncoding(encoding, allowLossyConversion: false) ?? NSData()) stringWrapper.preferredFilename = documentKey.rawValue dev = self.addFileWrapper(stringWrapper) } return dev } func setName(newName: String?) -> String? { return self.setStringForKey(newName, documentKey: .NameKey, encoding: NSUTF8StringEncoding) } func setCaption(newCaption: String?) -> String? { return self.setStringForKey(newCaption, documentKey: .CaptionKey, encoding: NSUTF8StringEncoding) } } extension DocumentLayerFileWrapper { func image() -> UIImage? { var image: UIImage? = nil if let imageData = self.fileWrapperForKey(DocumentLayerKey.ImageKey.rawValue)?.regularFileContents { image = UIImage(data: imageData) } return image } func transform() -> CGAffineTransform { var transform: CGAffineTransform = CGAffineTransformIdentity if let transformData = self.fileWrapperForKey(DocumentLayerKey.TransformKey.rawValue)?.regularFileContents { if let transformString = NSString(data: transformData, encoding: NSUTF8StringEncoding) { transform = CGAffineTransformFromString(transformString) } } return transform } func chroma() -> UIColor? { var chroma: UIColor? = nil if let chromaData = self.fileWrapperForKey(DocumentLayerKey.ChromaKey.rawValue)?.regularFileContents { if let chromaDict: [ String : CGFloat ] = NSKeyedUnarchiver.unarchiveObjectWithData(chromaData) as? [ String : CGFloat ] { chroma = UIColor(red: chromaDict["r"] ?? 0.0, green: chromaDict["g"] ?? 0.0, blue: chromaDict["b"] ?? 0.0, alpha: chromaDict["a"] ?? 1.0) } } return chroma } } class ChromaDocumentLayer { var image: UIImage? var transform: CGAffineTransform var chroma: UIColor? var identifier: String init() { self.image = nil self.transform = CGAffineTransformIdentity self.chroma = nil self.identifier = NSUUID().UUIDString } } class ChromaDocument: UIDocument { // private let orderKey = "order" // private let imageKey = "image" // private let captionKey = "caption" private var layers: [ChromaDocumentLayer] = [ChromaDocumentLayer]() var thumbnail: UIImage? = nil var name: String? = nil var background: UIImage? = nil var caption: String? = nil var fileWrapper: NSFileWrapper? = nil var count: Int { return self.layers.count } subscript(index: Int) -> ChromaDocumentLayer { let layer = self.layers[index] return layer } override func loadFromContents(contents: AnyObject, ofType typeName: String, error outError: NSErrorPointer) -> Bool { self.fileWrapper = contents as? DocumentFileWrapper self.thumbnail = self.fileWrapper?.thumbnail() self.name = self.fileWrapper?.name() self.background = self.fileWrapper?.background() self.caption = self.fileWrapper?.caption() self.layers.removeAll() if let orderArray = self.fileWrapper?.order() { for layerIdentifier in orderArray { let layer = ChromaDocumentLayer() layer.identifier = layerIdentifier if let layerWrapper = self.fileWrapper?.layerWrapper(layer.identifier) { if let image = layerWrapper.image() { layer.image = image } layer.transform = layerWrapper.transform() if let chroma = layerWrapper.chroma() { layer.chroma = chroma } } self.layers.append(layer) } } return true } override func contentsForType(typeName: String, error outError: NSErrorPointer) -> AnyObject? { if self.fileWrapper == nil { self.fileWrapper = NSFileWrapper(directoryWithFileWrappers: [NSObject : AnyObject]()) } return self.fileWrapper } func removeLayerAtIndex(index: Int) { let layer = self.layers.removeAtIndex(index) let layerWrapper = self.fileWrapper?.fileWrapperForKey(layer.identifier) if let layerWrapper = layerWrapper { self.fileWrapper?.removeFileWrapper(layerWrapper) } self.recreateOrderWrapper() } func recreateOrderWrapper() { let orderWrapper = self.fileWrapper?.fileWrapperForKey(DocumentKey.OrderKey.rawValue) if let orderWrapper = orderWrapper { self.fileWrapper?.removeFileWrapper(orderWrapper) } if(self.layers.count > 0) { let identifierArray = self.layers.map() { layer in layer.identifier } var error: NSError? = nil let orderData = NSKeyedArchiver.archivedDataWithRootObject(identifierArray) let newOrderWrapper = NSFileWrapper(regularFileWithContents: orderData) newOrderWrapper.preferredFilename = DocumentKey.OrderKey.rawValue self.fileWrapper?.addFileWrapper(newOrderWrapper) } } class func validExtensions() -> [String] { var extensions = [String]() if let infoDict = NSBundle.mainBundle().infoDictionary { if let types = infoDict["CFBundleDocumentTypes"] as? [AnyObject] { for typeDict in types { if let contentTypes = typeDict["LSItemContentTypes"] as? [AnyObject] { for contentType in contentTypes { let pathExtension = contentType.pathExtension if contains(extensions, pathExtension) == false { extensions.append(pathExtension) } } } } } } return extensions } } // Setters extension ChromaDocument { typealias FileWrapperErrorHandler = (String?) -> Void func defaultErrorHandler(newKey: String?) { if let key = newKey { if let newWrapper = self.fileWrapper?.fileWrapperForKey(key) { self.fileWrapper?.removeFileWrapper(newWrapper) } } } func setRegularFileWithData(data: NSData?, preferredFilename: String, errorHandler: FileWrapperErrorHandler?) { if let dataWrapper = self.fileWrapper?.fileWrapperForKey(preferredFilename) { self.fileWrapper?.removeFileWrapper(dataWrapper) } if let data = data { let dataKey = self.fileWrapper?.addRegularFileWithContents(data, preferredFilename: DocumentKey.CaptionKey.rawValue) if dataKey == nil || dataKey! != preferredFilename { if let handler = errorHandler { handler(dataKey) } } } } func setCaption(newCaption: String?) { self.fileWrapper?.setCaption(newCaption) self.caption = newCaption ?? "" self.saveToURL(self.fileURL, forSaveOperation: .ForOverwriting) { success in if !success { println("Could not overwrite file!") } } } func addNewLayer() { } func setBackground(background: UIImage?) { var data: NSData? = nil if let backgroundImage = background { data = UIImageJPEGRepresentation(backgroundImage, 1.0) } self.setRegularFileWithData(data, preferredFilename: DocumentKey.BackgroundKey.rawValue) { [unowned self] string in self.defaultErrorHandler(string) } } func setThumbnail(thumbnail: UIImage?) { var data: NSData? = nil if let thumbnailImage = thumbnail { data = UIImageJPEGRepresentation(thumbnailImage, 1.0) } self.setRegularFileWithData(data, preferredFilename: DocumentKey.ThumbnailKey.rawValue) { [unowned self] string in self.defaultErrorHandler(string) } } func setName(newName: String?) { self.fileWrapper?.setName(newName) self.name = newName ?? "Untitled" self.saveToURL(self.fileURL, forSaveOperation: .ForOverwriting) { success in if !success { println("Could not overwrite file!") } } } }
mit
042eaec43845cdff9c888f07d1102971
21.903226
141
0.709629
3.80513
false
false
false
false
davidjhodge/main-repository
What's Poppin?/What's Poppin?/SettingsTVC.swift
1
2679
// // SettingsTVC.swift // What's Poppin? // // Created by David Hodge on 2/2/15. // Copyright (c) 2015 Genesis Apps, LLC. All rights reserved. // import UIKit class SettingsTVC: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
apache-2.0
6f4c8ec15fd70b58b8f18f9af60fb2d9
33.346154
157
0.685704
5.412121
false
false
false
false
maitruonghcmus/QuickChat
QuickChat/Model/Conversation.swift
1
4839
// MIT License // Copyright (c) 2017 Haik Aslanyan // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit import Firebase class Conversation { //MARK: Properties let user: User var lastMessage: Message var locked : Bool //MARK: Methods class func showConversations(completion: @escaping ([Conversation]) -> Swift.Void) { if let currentUserID = FIRAuth.auth()?.currentUser?.uid { var conversations = [Conversation]() FIRDatabase.database().reference().child("users").child(currentUserID).child("conversations").observe(.childAdded, with: { (snapshot) in if snapshot.exists() { let fromID = snapshot.key let values = snapshot.value as! [String: String] let location = values["location"]! let locked = values["locked"] != nil && values["locked"] == "1" ? true : false User.info(forUserID: fromID, completion: { (user) in let emptyMessage = Message.init(type: .text, content: "loading", owner: .sender, timestamp: 0, isRead: true) let conversation = Conversation.init(user: user, lastMessage: emptyMessage, locked: locked) conversations.append(conversation) conversation.lastMessage.downloadLastMessage(forLocation: location, completion: { (_) in completion(conversations) }) }) } }) } } //MARK: Inits init(user: User, lastMessage: Message, locked: Bool) { self.user = user self.lastMessage = lastMessage self.locked = locked } //MARK: Delete //MARK: Methods class func delete(conv:Conversation, completion: @escaping (Bool) -> Swift.Void) { if let currentUserID = FIRAuth.auth()?.currentUser?.uid { FIRDatabase.database().reference().child("users").child(currentUserID).child("conversations").child(conv.user.id).removeValue(completionBlock: { (error, ref) in if error == nil { completion(true) } else { completion(false) } }) } else { completion(false) } } //MARK: Lock class func checkLocked(uid: String, completion: @escaping (Bool) -> Swift.Void) { if FIRAuth.auth()?.currentUser?.uid != nil { FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("conversations").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in if let data = snapshot.value as? [String: String] { let locked = data["locked"] != nil && data["locked"] == "1" ? true : false completion(locked) } else { completion(false) } }) } else { completion(false) } } class func setLocked(uid: String, locked: Bool, completion: @escaping (Bool) -> Swift.Void) { if FIRAuth.auth()?.currentUser?.uid != nil { let values = ["locked": locked ? "1" : "0"] FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("conversations").child(uid).updateChildValues(values, withCompletionBlock: { (errr, _) in if errr == nil { completion(true) } else { completion(false) } }) } else { completion(false) } } }
mit
9b207fa64d205358442eebb35d02b5bd
40.715517
200
0.577805
4.843844
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Sandbox/LeaveRolloverOnScreen_Swift/LeaveRolloverOnScreen_Swift/ChartView.swift
1
1995
import UIKit import SciChart class CustomRollover : SCIRolloverModifier { override func onPanGesture(_ gesture: UIPanGestureRecognizer!, at view: UIView!) -> Bool { if (gesture.state != .ended) { return super.onPanGesture(gesture, at: view) } return true ; } } class ChartView: SCIChartSurface { let rollover = CustomRollover() override init(frame: CGRect) { super.init(frame: frame) completeConfiguration() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) completeConfiguration() } fileprivate func completeConfiguration() { let dataSeries = SCIXyDataSeries(xType: .float, yType: .float) for i in 0...10 { let yValue = Int(arc4random_uniform(10)) dataSeries.appendX(SCIGeneric(i), y: SCIGeneric(yValue)) } let rSeries = SCIFastLineRenderableSeries() rSeries.strokeStyle = SCISolidPenStyle(colorCode: 0xFF279B27, withThickness: 1.0) rSeries.dataSeries = dataSeries SCIUpdateSuspender.usingWithSuspendable(self) { self.xAxes.add(SCINumericAxis()) self.yAxes.add(SCINumericAxis()) self.renderableSeries.add(rSeries) self.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomExtentsModifier(), self.rollover]) } let button = UIButton(frame: CGRect(x: 100, y: 5, width: 200, height: 50)) button.setTitle("Add/Remove Rollover", for: .normal) button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) self.addSubview(button) } @objc func buttonAction(sender: UIButton!) { rollover.isEnabled = !rollover.isEnabled if (rollover.isEnabled) { self.chartModifiers.add(rollover) } else { self.chartModifiers.remove(rollover) } } }
mit
12f0e1fbfd212dc8023632b6e5db1775
32.25
143
0.626065
4.60739
false
false
false
false
ryanbaldwin/RealmSwiftFHIR
firekit/firekitTests/classes/CascadeDeletableTests.swift
3
2045
// // RealmExtensionTests.swift // FireKit // // Created by Ryan Baldwin on 2017-08-09. // Copyright © 2017 Bunnyhug. All rights fall under Apache 2 // import XCTest import Foundation import FireKit import RealmSwift class CascadeDeletableTests: XCTestCase, RealmPersistenceTesting { var realm: Realm! override func setUp() { realm = makeRealm() } func testCanDeleteUnmanagedResource() { let patient = Patient() patient.cascadeDelete() } func testCanDeleteManagedResource() { let patient = Patient() try! realm.write { realm.add(patient) } XCTAssertNotNil(realm.objects(Patient.self).first) try! realm.write { patient.cascadeDelete() } XCTAssertNil(realm.objects(Patient.self).first) } func testCanDeleteChildRelationship() { let patient = Patient() patient.animal = PatientAnimal() try! realm.write { realm.add(patient) } XCTAssertNotNil(realm.objects(Patient.self).first) XCTAssertNotNil(realm.objects(PatientAnimal.self).first) try! realm.write { patient.cascadeDelete() } XCTAssertNil(realm.objects(Patient.self).first) XCTAssertNil(realm.objects(PatientAnimal.self).first) } func testCanDeleteChildLists() { let patient = Patient() let name = HumanName() name.family.append(RealmString(val: "Baldwin")) name.given.append(RealmString(val: "Ryan")) patient.name.append(name) try! realm.write { realm.add(patient) } XCTAssertNotNil(realm.objects(Patient.self).first) XCTAssertNotNil(realm.objects(HumanName.self).first) XCTAssertEqual(realm.objects(RealmString.self).count, 2) try! realm.write { patient.cascadeDelete() } XCTAssertEqual(realm.objects(RealmString.self).count, 0) XCTAssertNil(realm.objects(HumanName.self).first) XCTAssertNil(realm.objects(Patient.self).first) } }
apache-2.0
eda674ad44f37b2f84b7dd421365559d
29.969697
66
0.64726
4.472648
false
true
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Model/RespModel/SLVRecommendKeyword.swift
1
4105
// // SLVRecommendKeyword.swift // selluv-ios // // Created by 조백근 on 2017. 1. 25.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import Foundation import ObjectMapper import RealmSwift class SLVRecommendKeyword { /* kind String 추천 검색어 유형 category: 카테고리 brand: 브랜드 model: 모델명 tag: 태그 keywords Array[Object] 검색어 목록 */ var rCategories:[RecommendCategory] = [] var rBrands: [RecommendBrand] = [] var rModels: [RecommendModel] = [] var rTags: [RecommendTag] = [] func parseForBinding(data: AnyObject?) { if let data = data { _ = (data as! [AnyObject]).map() { let pack = $0 as! [String: AnyObject] let kind = pack["kind"] as! String if kind == "category" { let keys = pack["keywords"] as! [AnyObject] for i in keys { let item = i as! [String: String] let name = item["name"] let cate = RecommendCategory() cate.name = name self.rCategories.append(cate) } } else if kind == "brand" { let keys = pack["keywords"] as! [AnyObject] for i in keys { let item = i as! [String: String] let ko = item["korean"] let en = item["english"] let brand = RecommendBrand() brand.korean = ko brand.english = en self.rBrands.append(brand) } } else if kind == "model" { let keys = pack["keywords"] as! [AnyObject] for i in keys { let item = i as! [String: String] let name = item["model"] let model = RecommendModel() model.model = name self.rModels.append(model) } } else if kind == "tag" { let keys = pack["keywords"] as! [AnyObject] for i in keys { let item = i as! [String: AnyObject] let tags = item["tags"] as? [String] if let tags = tags { if tags.count > 0 { for j in tags { if j != "" { let tagObject = RecommendTag() tagObject.tags = j self.rTags.append(tagObject) } } } } } } } } } } class RecommendCategory: Mappable { var name:String? required convenience init?(map: Map) { self.init() } func mapping(map: Map) { name <- map["name"] } } class RecommendBrand: Mappable { var english:String? var korean:String? required convenience init?(map: Map) { self.init() } func mapping(map: Map) { english <- map["english"] korean <- map["korean"] } } class RecommendModel: Mappable { var model:String? required convenience init?(map: Map) { self.init() } func mapping(map: Map) { model <- map["model"] } } class RecommendTag: Mappable { var tags:String? required convenience init?(map: Map) { self.init() } func mapping(map: Map) { tags <- map["tags"] } }
mit
f54d1e10d77dea2218dbf87054730df1
28.985185
70
0.39501
5.104666
false
false
false
false
Hxucaa/ReactiveArray
Example/Tests/ReactiveArraySpec.swift
1
38541
// // ReactiveArraySpec.swift // ReactiveArraySpec // // Created by Guido Marucci Blas on 6/29/15. // Copyright (c) 2015 Wolox. All rights reserved. // import Quick import Nimble import ReactiveArray import ReactiveCocoa import Result private func waitForOperation<T>( fromProducer producer: SignalProducer<Operation<T>, NoError>, when: () -> (), onInitiate: [T] -> () = { fail("Invalid operation type: .Initiate(\($0))") }, onAppend: T -> () = { fail("Invalid operation type: .Append(\($0))") }, onAppendContentsOf: [T] -> () = { fail("Invalid operation type: .AppendContentsOf(\($0))") }, onInsert: (T, Int) -> () = { fail("Invalid operation type: .Insert(\($0), \($1))") }, onReplace: (T, Int) -> () = { fail("Invalid operation type: .Replace(\($0), \($1))") }, onDelete: Int -> () = { fail("Invalid operation type: .Delete(\($0))") }, onReplaceAll: [T] -> () = { fail("Invalid operation type: .ReplaceAll(\($0))") }, onRemoveAll: Bool -> () = { fail("Invalid operation type: .RemoveAll(\($0))") } ) { waitUntil { done in producer.startWithNext { operation in switch operation { case let .Initiate(values): onInitiate(values) case let .Append(value): onAppend(value) case let .AppendContentsOf(values): onAppendContentsOf(values) case let .Insert(value, index): onInsert(value, index) case let .Replace(value, index): onReplace(value, index) case let .RemoveElement(index): onDelete(index) case let .ReplaceAll(values): onReplaceAll(values) case let .RemoveAll(keepCapacity): onRemoveAll(keepCapacity) } done() } when() } } private func waitForOperation<T>( fromSignal signal: Signal<Operation<T>, NoError>, when: () -> (), onInitiate: [T] -> () = { fail("Invalid operation type: .Initiate(\($0))") }, onAppend: T -> () = { fail("Invalid operation type: .Append(\($0))") }, onAppendContentsOf: [T] -> () = { fail("Invalid operation type: .AppendContentsOf(\($0))") }, onInsert: (T, Int) -> () = { fail("Invalid operation type: .Insert(\($0), \($1))") }, onReplace: (T, Int) -> () = { fail("Invalid operation type: .Replace(\($0), \($1))") }, onDelete: Int -> () = { fail("Invalid operation type: .Delete(\($0))") }, onReplaceAll: [T] -> () = { fail("Invalid operation type: .ReplaceAll(\($0))") }, onRemoveAll: Bool -> () = { fail("Invalid operation type: .RemoveAll(\($0))") } ) { let producer = SignalProducer<Operation<T>, NoError> { (observer, disposable) in signal.observe(observer) } waitForOperation(fromProducer: producer, when: when, onInitiate: onInitiate, onAppend: onAppend, onAppendContentsOf: onAppendContentsOf, onInsert: onInsert, onReplace: onReplace, onDelete: onDelete, onReplaceAll: onReplaceAll, onRemoveAll: onRemoveAll) } private func waitForOperation<T>( fromArray array: ReactiveArray<T>, when: () -> (), onInitiate: [T] -> () = { fail("Invalid operation type: .Initiate(\($0))") }, onAppend: T -> () = { fail("Invalid operation type: .Append(\($0))") }, onAppendContentsOf: [T] -> () = { fail("Invalid operation type: .AppendContentsOf(\($0))") }, onInsert: (T, Int) -> () = { fail("Invalid operation type: .Insert(\($0), \($1))") }, onReplace: (T, Int) -> () = { fail("Invalid operation type: .Replace(\($0), \($1))") }, onDelete: Int -> () = { fail("Invalid operation type: .Delete(\($0))") }, onReplaceAll: [T] -> () = { fail("Invalid operation type: .ReplaceAll(\($0))") }, onRemoveAll: Bool -> () = { fail("Invalid operation type: .RemoveAll(\($0))") } ) { waitForOperation(fromSignal: array.signal, when: when, onInitiate: onInitiate, onAppend: onAppend, onAppendContentsOf: onAppendContentsOf, onInsert: onInsert, onReplace: onReplace, onDelete: onDelete, onReplaceAll: onReplaceAll, onRemoveAll: onRemoveAll) } class ReactiveArraySpec: QuickSpec { override func spec() { var originalData: [Int]! var reactiveArray: ReactiveArray<Int>! beforeEach { originalData = [1,2,3,4] reactiveArray = ReactiveArray(elements: originalData) } describe("#append") { it("appends the given element at the end of the array") { reactiveArray.append(5) expect(reactiveArray[reactiveArray.count - 1]).to(equal(5)) } it("increments the amount of elements in the array by one") { let countBeforeAppend = reactiveArray.count reactiveArray.append(5) expect(reactiveArray.count).to(equal(countBeforeAppend + 1)) } it("signals an append operation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray.append(5) }, onAppend: { value in expect(value).to(equal(5)) } ) } } describe("#appendContentsOf") { var originalCount: Int! let additionalArray = [5,6,7,8] beforeEach { originalCount = reactiveArray.count } it("should appendContentsOf the array with an additional array of elements") { reactiveArray.appendContentsOf(additionalArray) var newArray = reactiveArray.array newArray.removeRange(0...(originalCount - 1)) expect(newArray).to(equal(additionalArray)) } it("should increment the number of elements in the array by the number of new elements") { reactiveArray.appendContentsOf(additionalArray) expect(reactiveArray.count).to(equal(originalCount + additionalArray.count)) } it("should signal an `appendContentsOf` operation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray.appendContentsOf(additionalArray) }, onAppendContentsOf: { values in originalData.appendContentsOf(additionalArray) expect(values).to(equal(additionalArray)) } ) } } describe("#insert") { let element = 10 let index = 1 it("should insert the new element at given index") { reactiveArray.insert(element, atIndex: index) expect(reactiveArray[index]).to(equal(element)) originalData.insert(element, atIndex: index) expect(reactiveArray.array).to(equal(originalData)) } it("should signal an `Insert` operation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray.insert(element, atIndex: index) }, onInsert: { (value, i) in expect(value).to(equal(element)) expect(i).to(equal(index)) } ) } } describe("#replace") { context("when there is a value at the given position") { it("replaces the old value with the new one") { reactiveArray.replace(5, atIndex: 1) expect(reactiveArray[1]).to(equal(5)) } it("signals an `.Replace` operation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray.replace(5, atIndex: 1) }, onReplace: { (value, index) in expect(value).to(equal(5)) expect(index).to(equal(1)) } ) } it("should return the original element at the given index") { let index = 2 let originalElement = reactiveArray.array[index] let replacedElement = reactiveArray.replace(9, atIndex: index) expect(replacedElement).to(equal(originalElement)) } } // TODO: Fix this case because this raises an exception that cannot // be caught // context("when the index is out of bounds") { // // it("raises an exception") { // expect { // array.replace(5, atIndex: array.count + 10) // }.to(raiseException(named: "NSInternalInconsistencyException")) // } // // } } describe("#removeAtIndex") { it("removes the element at the given position") { reactiveArray.removeAtIndex(1) expect(reactiveArray.array).to(equal([1,3,4])) } it("signals a delete operation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray.removeAtIndex(1) }, onDelete: { index in expect(index).to(equal(1)) } ) } it("should return the element that is being removed") { let index = 1 let originalElement = reactiveArray.array[index] let removedElement = reactiveArray.removeAtIndex(index) expect(removedElement).to(equal(originalElement)) } } describe("#replaceAll") { let data = [1,3,5,7,9] it("should replace the element with a new array of data") { reactiveArray.replaceAll(data) expect(reactiveArray.array).to(equal(data)) } it("should signal a `ReplaceAll` opearation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray.replaceAll(data) }, onReplaceAll: { values in expect(values).to(equal(data)) expect(values).toNot(equal(originalData)) } ) } } describe("#removeAll") { let removeOp = { (keepCapacity: Bool) in waitUntil { done in let countBeforeOperation = reactiveArray.count reactiveArray.observableCount.producer .take(2) .collect() .startWithNext { counts in expect(counts).to(equal([countBeforeOperation, 0])) done() } reactiveArray.removeAll(keepCapacity) } } context("when `keepCapacity` is set to `true`") { it("should remove all elements in the array") { removeOp(true) } it("should signal a `RemoveAll` operation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray.removeAll(true) }, onRemoveAll: { keepCapacity in expect(keepCapacity).to(equal(true)) } ) } } context("when `keepCapacity` is set to `false`") { it("should remove all elements in the array") { removeOp(false) } it("should signal a `RemoveAll` operation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray.removeAll(false) }, onRemoveAll: { keepCapacity in expect(keepCapacity).to(equal(false)) } ) } } } describe("#[]") { it("returns the element at the given position") { expect(reactiveArray[2]).to(equal(3)) } } describe("#[]=") { context("when there is a value at the given position") { it("replaces the old value with the new one") { reactiveArray[1] = 5 expect(reactiveArray[1]).to(equal(5)) } it("signals an `.Replace` operation") { waitForOperation( fromArray: reactiveArray, when: { reactiveArray[1] = 5 }, onReplace: { (value, index) in expect(value).to(equal(5)) expect(index).to(equal(1)) } ) } } } describe("#mirror") { var mirror: ReactiveArray<Int>! let newElements = [1,2,3,4,5] beforeEach { mirror = reactiveArray.mirror { $0 + 10 } } it("returns a new reactive array that maps the values of the original array") { expect(mirror.array).to(equal(originalData.map { $0 + 10 })) } context("when an `.Append` is executed on the original array") { it("signals a mapped `Append` operation") { waitForOperation( fromArray: mirror, when: { reactiveArray.append(5) }, onAppend: { value in expect(value).to(equal(15)) } ) } } context("when an `.AppendContentsOf` is executed on the original array") { it("should signal a mapped `appendContentsOf` operation") { let mappedNewElements = newElements.map { $0 + 10 } waitForOperation( fromArray: mirror, when: { reactiveArray.appendContentsOf(newElements) }, onAppendContentsOf: { values in expect(values).to(equal(mappedNewElements)) } ) } } context("when an `.Insert` is executed on the original array") { it("should signal a mapped `Insert` operation") { let newElement = 2 let index = 4 waitForOperation( fromArray: mirror, when: { reactiveArray.insert(newElement, atIndex: index) }, onInsert: { value, i in expect(value).to(equal(newElement + 10)) expect(i).to(equal(index)) } ) } } context("when a `.Replace` is executed on the original array") { it("signals a mapped `.Replace` operation") { waitForOperation( fromArray: mirror, when: { reactiveArray[1] = 5 }, onReplace: { (value, index) in expect(value).to(equal(15)) expect(index).to(equal(1)) } ) } } context("when a `.RemoveAtIndex` is executed on the original array") { it("signals a mapped `RemoveAtIndex` operation") { waitForOperation( fromArray: mirror, when: { reactiveArray.removeAtIndex(1) }, onDelete: { index in expect(index).to(equal(1)) } ) } } context("when a `.ReplaceAll` is executed on the original array") { it("should signal a mapped `ReplaceAll` operation") { let mappedNewElements = newElements.map { $0 + 10 } waitForOperation( fromArray: mirror, when: { reactiveArray.replaceAll(newElements) }, onReplaceAll: { values in expect(values).to(equal(mappedNewElements)) } ) } } context("when a `.RemoveAll` is executed on the original array") { it("should signal a mapped `RemoveAll` operation") { let keep = true waitForOperation( fromArray: mirror, when: { reactiveArray.removeAll(keep) }, onRemoveAll: { keepCapacity in expect(keepCapacity).to(equal(keep)) } ) } } } describe("#producer") { var a: ReactiveArray<Int>! let orignalDataArray = [3,5,76,3,6,4,6] beforeEach { a = ReactiveArray(elements: orignalDataArray) } context("when the array has elements") { it("signals an `.Initiate` operation for each stored element") { waitUntil { done in a.producer .startWithNext { operation in let result = operation == Operation.Initiate(values: orignalDataArray) expect(result).to(beTrue()) done() } } } } context("when an `.Append` operation is executed in the original array") { it("forwards the operation") { waitForOperation( fromProducer: a.producer.skip(1), when: { a.append(5) }, onAppend: { value in expect(value).to(equal(5)) } ) } } context("when an `.AppendContentsOf` operation is executed in the original array") { it("forwards the operation") { let newElements = [1,2,3,4,5] waitForOperation( fromProducer: a.producer.skip(1), // skip the `Initiate` operations happened when the array is initialized. when: { a.appendContentsOf(newElements) }, onAppendContentsOf: { values in expect(values).to(equal(newElements)) } ) } } context("when an `.Insert` operation is executed in the original array") { it("forwards the operation") { let newElement = 2 let index = 4 waitForOperation( fromProducer: a.producer.skip(1), // skip the `Initiate` operations happened when the array is initialized. when: { a.insert(newElement, atIndex: index) }, onInsert: { value, i in expect(value).to(equal(newElement)) expect(i).to(equal(index)) } ) } } context("when an `.Replace` operation is executed in the original array") { it("forwards the operation") { waitForOperation( fromProducer: a.producer.skip(1), // Skips the operation triggered due to the array not being empty when: { a.replace(5, atIndex: 0) }, onReplace: { (value, index) in expect(value).to(equal(5)) expect(index).to(equal(0)) } ) } } context("when a `.RemoveAtIndex` operation is executed in the original array") { it("forwards the operation") { waitForOperation( fromProducer: a.producer.skip(1), // Skips the operation triggered due to the array not being empty when: { a.removeAtIndex(0) }, onDelete: { index in expect(index).to(equal(0)) } ) } } context("when a `.ReplaceAll` operation is executed in the original array") { it("forwards the operation") { let newElements = [1,2,3,4,5] waitForOperation( fromProducer: a.producer.skip(1), when: { a.replaceAll(newElements) }, onReplaceAll: { values in expect(values).to(equal(newElements)) } ) } } context("when a `.RemoveAll` operation is exeucte in the original array") { it("forwards the operation") { let keep = true waitForOperation( fromProducer: a.producer.skip(1), when: { a.removeAll(keep) }, onRemoveAll: { keepCapacity in expect(keepCapacity).to(equal(keep)) } ) } } } describe("#signal") { context("when an `.Append` operation is executed") { it("signals the operations") { waitForOperation( fromSignal: reactiveArray.signal, when: { reactiveArray.append(5) }, onAppend: { value in expect(value).to(equal(5)) } ) } } context("when an `.AppendContentsOf` operation is executed") { let newElements = [1,2,3,4,5,6,7,8] it("should signal the operations") { waitForOperation( fromSignal: reactiveArray.signal, when: { reactiveArray.appendContentsOf(newElements) }, onAppendContentsOf: { values in expect(values).to(equal(newElements)) } ) } } context("when an `.Insert` opeartion is exeucted") { it("should signal the operation") { let newElement = 5 let index = 2 waitForOperation( fromSignal: reactiveArray.signal, when: { reactiveArray.insert(newElement, atIndex: index) }, onInsert: { value, i in expect(value).to(equal(newElement)) expect(i).to(equal(index)) } ) } } context("when an `.Replace` operation is executed") { it("signals the operations") { waitForOperation( fromSignal: reactiveArray.signal, when: { reactiveArray.replace(5, atIndex: 1) }, onReplace: { (value, index) in expect(value).to(equal(5)) expect(index).to(equal(1)) } ) } } context("when a `.RemoveAtIndex` operation is executed") { it("signals the operations") { waitForOperation( fromSignal: reactiveArray.signal, when: { reactiveArray.removeAtIndex(1) }, onDelete: { index in expect(index).to(equal(1)) } ) } } context("when a `.ReplaceAll` operation is executed in the original array") { it("forwards the operation") { let newElements = [1,2,3,4,5] waitForOperation( fromSignal: reactiveArray.signal, when: { reactiveArray.replaceAll(newElements) }, onReplaceAll: { values in expect(values).to(equal(newElements)) } ) } } context("when a `.RemoveAll` operation is exeucte in the original array") { it("forwards the operation") { let keep = true waitForOperation( fromSignal: reactiveArray.signal, when: { reactiveArray.removeAll(keep) }, onRemoveAll: { keepCapacity in expect(keepCapacity).to(equal(keep)) } ) } } } describe("observableCount") { var countBeforeOperation: Int! var producer: SignalProducer<Int, NoError>! let newElements = [1,2,3,4,5,6,7,8] beforeEach { countBeforeOperation = reactiveArray.count producer = reactiveArray.observableCount.producer } it("returns the initial amount of elements in the array") { producer.startWithNext { count in expect(count).to(equal(countBeforeOperation)) } } context("when an `.Append` operation is executed") { it("updates the count") { waitUntil { done in producer .skip(1) .startWithNext { count in expect(count).to(equal(countBeforeOperation + 1)) done() } reactiveArray.append(656) } } } context("when an `.AppendContentsOf` operation is executed") { it("should update the count by the number of new elements") { waitUntil { done in producer .take(2) .collect() .startWithNext { counts in expect(counts[0]).to(equal(countBeforeOperation)) expect(counts[1]).to(equal(countBeforeOperation + newElements.count)) done() } reactiveArray.appendContentsOf(newElements) } } } context("when an `.Insert` operation is executed") { it("should update the count by an increment of 1") { waitUntil { done in producer .take(2) .collect() .startWithNext { counts in expect(counts[0]).to(equal(countBeforeOperation)) expect(counts[1]).to(equal(countBeforeOperation + 1)) done() } reactiveArray.insert(5, atIndex: 2) } } } context("when an `.Replace` operation is executed") { it("does not update the count") { waitUntil { done in producer .take(2) .collect() .startWithNext { counts in expect(counts[0]).to(equal(countBeforeOperation)) expect(counts[1]).to(equal(countBeforeOperation)) done() } reactiveArray.replace(657, atIndex: 1) reactiveArray.append(656) } } } context("when a `.RemoveAtIndex` operation is executed") { it("updates the count") { waitUntil { done in producer .skip(1) .startWithNext { count in expect(count).to(equal(countBeforeOperation - 1)) done() } reactiveArray.removeAtIndex(1) } } } context("when a `.ReplaceAll` operation is executed") { it("updates the count") { waitUntil { done in producer .take(2) .collect() .startWithNext { counts in expect(counts[0]).to(equal(countBeforeOperation)) expect(counts[1]).to(equal(newElements.count)) done() } reactiveArray.replaceAll(newElements) } } } context("when a `RemoveAll` operation is executed") { it("updates the count") { waitUntil { done in producer .take(2) .collect() .startWithNext { counts in expect(counts[0]).to(equal(countBeforeOperation)) expect(counts[1]).to(equal(0)) done() } reactiveArray.removeAll(true) } } } } describe("isEmpty") { context("when the array is empty") { it("returns true") { expect(ReactiveArray<Int>().isEmpty).to(beTrue()) } } context("when the array is not empty") { it("returns false") { expect(reactiveArray.isEmpty).to(beFalse()) } } } describe("count") { it("returns the amount of elements in the array") { expect(reactiveArray.count).to(equal(originalData.count)) } } describe("startIndex") { context("when the array is not empty") { it("returns the index of the first element") { expect(reactiveArray.startIndex).to(equal(0)) } } context("when the array is empty") { beforeEach { reactiveArray = ReactiveArray<Int>() } it("returns the index of the first element") { expect(reactiveArray.startIndex).to(equal(0)) } } } describe("endIndex") { context("when the array is not empty") { it("returns the index of the last element plus one") { expect(reactiveArray.endIndex).to(equal(reactiveArray.count)) } } context("when the array is empty") { beforeEach { reactiveArray = ReactiveArray<Int>() } it("returns zero") { expect(reactiveArray.startIndex).to(equal(0)) } } } describe("first") { it("returns the first element in the array") { expect(reactiveArray.first).to(equal(originalData[0])) } context("when the array is empty") { it("should return nil") { reactiveArray = ReactiveArray() expect(reactiveArray.first).to(beNil()) } } } describe("last") { it("returns the last element in the array") { expect(reactiveArray.last).to(equal(4)) } context("when the array is empty") { it("should return nil") { reactiveArray = ReactiveArray() expect(reactiveArray.last).to(beNil()) } } } } }
mit
327734397f9c1f00052be4ac9602351a
34.985994
258
0.385148
6.601747
false
false
false
false
yoichitgy/Swinject
Sources/Container.Arguments.swift
2
27085
// // Copyright © 2019 Swinject Contributors. All rights reserved. // // // NOTICE: // // Container.Arguments.swift is generated from Container.Arguments.erb by ERB. // Do NOT modify Container.Arguments.swift directly. // Instead, modify Container.Arguments.erb and run `script/gencode` at the project root directory to generate the code. // import Foundation // MARK: - Registeration with Arguments extension Container { /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 1 argument to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 2 arguments to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1, Arg2>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1, Arg2) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 3 arguments to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1, Arg2, Arg3>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1, Arg2, Arg3) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 4 arguments to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1, Arg2, Arg3, Arg4>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 5 arguments to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 6 arguments to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 7 arguments to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 8 arguments to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the ``Container`` needs to instantiate the instance. /// It takes a ``Resolver`` instance and 9 arguments to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining. @discardableResult public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } } // MARK: - Resolver with Arguments extension Container { /// Retrieves the instance with the specified service type and 1 argument to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - argument: 1 argument to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and 1 argument is found in the ``Container``. public func resolve<Service, Arg1>( _ serviceType: Service.Type, argument: Arg1 ) -> Service? { return resolve(serviceType, name: nil, argument: argument) } /// Retrieves the instance with the specified service type, 1 argument to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - argument: 1 argument to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// 1 argument and name is found in the ``Container``. public func resolve<Service, Arg1>( _: Service.Type, name: String?, argument: Arg1 ) -> Service? { typealias FactoryType = ((Resolver, Arg1)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, argument)) } } /// Retrieves the instance with the specified service type and list of 2 arguments to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - arguments: List of 2 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and list of 2 arguments is found in the ``Container``. public func resolve<Service, Arg1, Arg2>( _ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2 ) -> Service? { return resolve(serviceType, name: nil, arguments: arg1, arg2) } /// Retrieves the instance with the specified service type, list of 2 arguments to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - arguments: List of 2 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// list of 2 arguments and name is found in the ``Container``. public func resolve<Service, Arg1, Arg2>( _: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2 ) -> Service? { typealias FactoryType = ((Resolver, Arg1, Arg2)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, arg1, arg2)) } } /// Retrieves the instance with the specified service type and list of 3 arguments to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - arguments: List of 3 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and list of 3 arguments is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3>( _ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3 ) -> Service? { return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3) } /// Retrieves the instance with the specified service type, list of 3 arguments to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - arguments: List of 3 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// list of 3 arguments and name is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3>( _: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3 ) -> Service? { typealias FactoryType = ((Resolver, Arg1, Arg2, Arg3)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, arg1, arg2, arg3)) } } /// Retrieves the instance with the specified service type and list of 4 arguments to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - arguments: List of 4 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and list of 4 arguments is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4>( _ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4 ) -> Service? { return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4) } /// Retrieves the instance with the specified service type, list of 4 arguments to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - arguments: List of 4 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// list of 4 arguments and name is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4>( _: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4 ) -> Service? { typealias FactoryType = ((Resolver, Arg1, Arg2, Arg3, Arg4)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, arg1, arg2, arg3, arg4)) } } /// Retrieves the instance with the specified service type and list of 5 arguments to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - arguments: List of 5 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and list of 5 arguments is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5>( _ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5 ) -> Service? { return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5) } /// Retrieves the instance with the specified service type, list of 5 arguments to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - arguments: List of 5 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// list of 5 arguments and name is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5>( _: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5 ) -> Service? { typealias FactoryType = ((Resolver, Arg1, Arg2, Arg3, Arg4, Arg5)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, arg1, arg2, arg3, arg4, arg5)) } } /// Retrieves the instance with the specified service type and list of 6 arguments to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - arguments: List of 6 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and list of 6 arguments is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>( _ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6 ) -> Service? { return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5, arg6) } /// Retrieves the instance with the specified service type, list of 6 arguments to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - arguments: List of 6 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// list of 6 arguments and name is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>( _: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6 ) -> Service? { typealias FactoryType = ((Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, arg1, arg2, arg3, arg4, arg5, arg6)) } } /// Retrieves the instance with the specified service type and list of 7 arguments to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - arguments: List of 7 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and list of 7 arguments is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>( _ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7 ) -> Service? { return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7) } /// Retrieves the instance with the specified service type, list of 7 arguments to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - arguments: List of 7 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// list of 7 arguments and name is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>( _: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7 ) -> Service? { typealias FactoryType = ((Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, arg1, arg2, arg3, arg4, arg5, arg6, arg7)) } } /// Retrieves the instance with the specified service type and list of 8 arguments to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - arguments: List of 8 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and list of 8 arguments is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>( _ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7, _ arg8: Arg8 ) -> Service? { return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) } /// Retrieves the instance with the specified service type, list of 8 arguments to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - arguments: List of 8 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// list of 8 arguments and name is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>( _: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7, _ arg8: Arg8 ) -> Service? { typealias FactoryType = ((Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)) } } /// Retrieves the instance with the specified service type and list of 9 arguments to the factory closure. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - arguments: List of 9 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// and list of 9 arguments is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>( _ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7, _ arg8: Arg8, _ arg9: Arg9 ) -> Service? { return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) } /// Retrieves the instance with the specified service type, list of 9 arguments to the factory closure and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// - arguments: List of 9 arguments to pass to the factory closure. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type, /// list of 9 arguments and name is found in the ``Container``. public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>( _: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7, _ arg8: Arg8, _ arg9: Arg9 ) -> Service? { typealias FactoryType = ((Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9)) -> Any return _resolve(name: name) { (factory: FactoryType) in factory((self, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)) } } }
mit
c4b3172695dee8fcfb237832a44bb8c2
52.420118
140
0.629412
4.227251
false
false
false
false
Eonil/SQLite3
Sources/HighLevel/Schema.Definitions.swift
2
919
// // Schema.Definitions.swift // EonilSQLite3 // // Created by Hoon H. on 11/2/14. // // import Foundation public extension Schema { // public let tables:[Schema.Table] public struct Table { public let name:String public let key:[String] ///< Primary key column names. public let columns:[Column] } public struct Column { public let name:String public let nullable:Bool public let type:TypeCode public let unique:Bool ///< Has unique key constraint. This must be true if this column is set to a PK. public let index:Ordering? ///< Index sorting order. This must be non-nil value if this column is set as a PK. public enum TypeCode : String { case None = "" case Integer = "INTEGER" case Float = "FLOAT" case Text = "TEXT" case Blob = "BLOB" } public enum Ordering : String { case Ascending = "ASC" case Descending = "DESC" } } }
mit
ce111d135f5382d547ffed81364fab3f
19.886364
114
0.651795
3.013115
false
false
false
false
d7laungani/DLLocalNotifications
DLLocalNotifications/DLLocalNotifications.swift
1
14012
// // DLLocalNotifications.swift // DLLocalNotifications // // Created by Devesh Laungani on 12/14/16. // Copyright © 2016 Devesh Laungani. All rights reserved. // import Foundation import UserNotifications let MAX_ALLOWED_NOTIFICATIONS = 64 @available(iOS 10.0, *) public class DLNotificationScheduler { // Apple allows you to only schedule 64 notifications at a time static let maximumScheduledNotifications = 60 public init () {} public func cancelAlllNotifications () { UNUserNotificationCenter.current().removeAllPendingNotificationRequests() DLQueue.queue.clear() saveQueue() } // Returns all notifications in the notifications queue. public func notificationsQueue() -> [DLNotification] { return DLQueue.queue.notificationsQueue() } // Cancel the notification if scheduled or queued public func cancelNotification (notification: DLNotification) { let identifier = (notification.localNotificationRequest != nil) ? notification.localNotificationRequest?.identifier : notification.identifier cancelNotificationWithIdentifier(identifier: identifier!) notification.scheduled = false } // Cancel the notification if scheduled or queued public func cancelNotification (identifier : String) { cancelNotificationWithIdentifier(identifier: identifier) } private func cancelNotificationWithIdentifier (identifier: String) { UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier]) let queue = DLQueue.queue.notificationsQueue() var i = 0 for noti in queue { if identifier == noti.identifier { DLQueue.queue.removeAtIndex(i) break } i += 1 } } public func getScheduledNotifications(handler:@escaping (_ request:[UNNotificationRequest]?)-> Void) { UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (requests) in handler(requests) }) } public func getScheduledNotification(with identifier: String, handler:@escaping (_ request:UNNotificationRequest?)-> Void) { var foundNotification:UNNotificationRequest? = nil UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (requests) in for request in requests { if let request1 = request.trigger as? UNTimeIntervalNotificationTrigger { if (request.identifier == identifier) { print("Timer interval notificaiton: \(request1.nextTriggerDate().debugDescription)") handler(request) } break } if let request2 = request.trigger as? UNCalendarNotificationTrigger { if (request.identifier == identifier) { handler(request) if(request2.repeats) { print(request) print("Calendar notification: \(request2.nextTriggerDate().debugDescription) and repeats") } else { print("Calendar notification: \(request2.nextTriggerDate().debugDescription) does not repeat") } break } } if let request3 = request.trigger as? UNLocationNotificationTrigger { print("Location notification: \(request3.region.debugDescription)") } } }) } public func printAllNotifications () { print("printing all notifications") UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (requests) in print(requests.count) for request in requests { if let request1 = request.trigger as? UNTimeIntervalNotificationTrigger { print("Timer interval notificaiton: \(request1.nextTriggerDate().debugDescription)") } if let request2 = request.trigger as? UNCalendarNotificationTrigger { if(request2.repeats) { print(request) print("Calendar notification: \(request2.nextTriggerDate().debugDescription) and repeats") } else { print("Calendar notification: \(request2.nextTriggerDate().debugDescription) does not repeat") } } if let request3 = request.trigger as? UNLocationNotificationTrigger { print("Location notification: \(request3.region.debugDescription)") } } }) } private func convertToNotificationDateComponent (notification: DLNotification, repeatInterval: RepeatingInterval ) -> DateComponents { print(notification.fromDateComponents != nil) let dateFromDateComponents = Calendar.current.date(from: notification.fromDateComponents!) var newComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second ], from: dateFromDateComponents!) if repeatInterval != .none { switch repeatInterval { case .minute: newComponents = Calendar.current.dateComponents([ .second], from: dateFromDateComponents!) case .hourly: newComponents = Calendar.current.dateComponents([ .minute], from: dateFromDateComponents!) case .daily: newComponents = Calendar.current.dateComponents([.hour, .minute], from: dateFromDateComponents!) case .weekly: newComponents = Calendar.current.dateComponents([.hour, .minute, .weekday], from: dateFromDateComponents!) case .monthly: newComponents = Calendar.current.dateComponents([.hour, .minute, .day], from: dateFromDateComponents!) case .yearly: newComponents = Calendar.current.dateComponents([.hour, .minute, .day, .month], from: dateFromDateComponents!) default: break } } print(newComponents.debugDescription) return newComponents } fileprivate func queueNotification (notification: DLNotification) -> String? { if notification.scheduled { return nil } else { DLQueue.queue.push(notification) } return notification.identifier } public func scheduleNotification ( notification: DLNotification) { queueNotification(notification: notification) } public func scheduleAllNotifications () { let queue = DLQueue.queue.notificationsQueue() var count = 0 for _ in queue { if count < min(DLNotificationScheduler.maximumScheduledNotifications, MAX_ALLOWED_NOTIFICATIONS) { let popped = DLQueue.queue.pop() scheduleNotificationInternal(notification: popped) count += 1 } else { break } } } // Refactored for backwards compatability fileprivate func scheduleNotificationInternal ( notification: DLNotification) -> String? { if notification.scheduled { return nil } else { var trigger: UNNotificationTrigger? if (notification.region != nil) { trigger = UNLocationNotificationTrigger(region: notification.region!, repeats: false) } else { if let repeatInterval = notification.repeatInterval as? RepeatingInterval , let dateComponents = notification.fromDateComponents as? DateComponents { // If RepeatingInterval Notification trigger = UNCalendarNotificationTrigger(dateMatching: convertToNotificationDateComponent(notification: notification, repeatInterval: notification.repeatInterval), repeats: notification.repeats) } // If Date based notification else if let fireDate = notification.fireDate{ //trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: fireDate.timeIntervalSince(Date()), repeats: notification.repeats) if (notification.repeatInterval == .none) { trigger = UNCalendarNotificationTrigger(dateMatching: Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second ], from: fireDate) , repeats: notification.repeats) } } /* if (notification.repeatInterval == .minute) { trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: (TimeInterval(60)), repeats: notification.repeats) } if (notification.repeatInterval == .hourly) { trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: (TimeInterval(3600)), repeats: false) } */ } let content = UNMutableNotificationContent() content.title = notification.alertTitle! content.body = notification.alertBody! content.sound = notification.soundName == "" ? UNNotificationSound.default : UNNotificationSound.init(named: UNNotificationSoundName(rawValue: notification.soundName)) if (notification.soundName == "1") { content.sound = nil} if !(notification.attachments == nil) { content.attachments = notification.attachments! } if !(notification.launchImageName == nil) { content.launchImageName = notification.launchImageName! } if !(notification.category == nil) { content.categoryIdentifier = notification.category! } notification.localNotificationRequest = UNNotificationRequest(identifier: notification.identifier!, content: content, trigger: trigger!) let center = UNUserNotificationCenter.current() center.add(notification.localNotificationRequest!, withCompletionHandler: {(error) in if error != nil { print(error.debugDescription) } }) notification.scheduled = true } return notification.identifier } ///Persists the notifications queue to the disk ///> Call this method whenever you need to save changes done to the queue and/or before terminating the app. public func saveQueue() -> Bool { return DLQueue.queue.save() } ///- returns: Count of scheduled notifications by iOS. func scheduledCount(completion: @escaping (Int) -> Void) { UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (localNotifications) in completion(localNotifications.count) }) } // You have to manually keep in mind ios 64 notification limit public func repeatsFromToDate (identifier: String, alertTitle: String, alertBody: String, fromDate: Date, toDate: Date, interval: Double, repeats: RepeatingInterval, category: String = "åa", sound: String = " ") { // Create multiple Notifications let intervalDifference = Int( toDate.timeIntervalSince(fromDate) / interval ) var nextDate = fromDate for i in 0..<intervalDifference + 1 { // Next notification Date let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second ], from: nextDate) let identifier = identifier + String(i + 1) var notification = DLNotification(identifier: identifier, alertTitle: alertTitle, alertBody: alertBody, fromDateComponents: dateComponents, repeatInterval: repeats) notification.category = category notification.soundName = sound print("Dates from notifications : " + notification.fromDateComponents!.debugDescription) self.queueNotification(notification: notification) nextDate = nextDate.addingTimeInterval(interval) } } public func scheduleCategories(categories: [DLCategory]) { var notificationCategories = Set<UNNotificationCategory>() for category in categories { guard let categoryInstance = category.categoryInstance else { continue } notificationCategories.insert(categoryInstance) } UNUserNotificationCenter.current().setNotificationCategories(notificationCategories) } } // Repeating Interval Times public enum RepeatingInterval: String { case none, minute, hourly, daily, weekly, monthly, yearly } extension Date { func removeSeconds() -> Date { let calendar = Calendar.current let components = (calendar as NSCalendar).components([.year, .month, .day, .hour, .minute], from: self) return calendar.date(from: components)! } }
mit
ad5a463efaad00af592d127103516cd9
38.464789
217
0.589864
6.333635
false
false
false
false
jairoeli/Habit
Zero/Sources/Utils/DeallocationChecker.swift
1
1764
// // DeallocationChecker.swift // Zero // // Created by Jairo Eli de Leon on 7/7/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // import UIKit // Source: https://github.com/fastred/DeallocationChecker extension UIViewController { /// This method asserts whether a view controller gets deallocated after it disappeared /// due to one of these reasons: /// - it was removed from its parent, or /// - it (or one of its parents) was dismissed. /// /// **You should call this method only from UIViewController.viewDidDisappear(_:).** /// - Parameter delay: Delay after which the check if a /// view controller got deallocated is performed public func dch_checkDeallocation(afterDelay delay: TimeInterval = 2.0) { #if DEBUG let rootParentViewController = dch_rootParentViewController // We don't check `isBeingDismissed` simply on this view controller because it's common // to wrap a view controller in another view controller (e.g. a stock UINavigationController) // and present the wrapping view controller instead. if isMovingFromParentViewController || rootParentViewController.isBeingDismissed { let viewControllerType = type(of: self) let disappearanceSource: String = isMovingFromParentViewController ? "removed from its parent" : "dismissed" DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { [weak self] in assert(self == nil, "\(viewControllerType) not deallocated after being \(disappearanceSource)") }) } #endif } private var dch_rootParentViewController: UIViewController { var root = self while let parent = root.parent { root = parent } return root } }
mit
932d9f631dc78bf25ad2242a6ad9b32d
34.24
116
0.694098
4.698667
false
false
false
false
SwiftKidz/Slip
Tests/Whilst/WhilstTests.swift
1
2165
/* MIT License Copyright (c) 2016 SwiftKidz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest import Slip class WhilstTests: XCTestCase { func testFunctionality() { let expectationRun = self.expectation(description: name ?? "Test") var count: Int = 0 Whilst<Int>(test: { return count < 5 }, run: { (opHandler) in count += 1 opHandler.finish(count) }).onFinish { (state, result) in XCTAssertNotNil(result.value) XCTAssert(result.value! == [1, 2, 3, 4, 5]) expectationRun.fulfill() }.start() waitForExpectations(timeout: TestConfig.timeout, handler: nil) let expectationNotRun = self.expectation(description: name ?? "Test") Whilst<Int>(test: { return count < 5 }, run: { (opHandler) in count += 1 opHandler.finish(count) }).onFinish { (state, result) in XCTAssertNotNil(result.value) XCTAssertTrue(result.value!.isEmpty) expectationNotRun.fulfill() }.start() waitForExpectations(timeout: TestConfig.timeout, handler: nil) } }
mit
f4783ed2e8f2340525308fd4fc7b719d
35.083333
79
0.686374
4.645923
false
true
false
false
drichardson/SwiftyUUID
SwiftyUUID/UUID.swift
1
1637
// // UUID.swift // SwiftyUUID // // Created by Doug Richardson on 8/7/15. // // /// An array of UUID bytes. When returned from functions you can assume it is a valid /// 16 byte UUID. If creating your own, ensure it is 16 bytes long. public typealias UUIDBytes = [UInt8] /** Wrapper for UUIDBytes, providing immutability and support for extensions. */ public struct UUID { let bytes : UUIDBytes /// Create a randomly generated, version 4 UUID. public init() { bytes = Version4UUID() } /** Wrap UUIDBytes. :params: bytes The UUID bytes to use. Must be 16 bytes long. */ public init(bytes : UUIDBytes) { assert(bytes.count == 16) self.bytes = bytes } } extension UUID { /** Get a string representation of the UUID of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is a lowercase hex digit. - returns: A string representation of the UUID. */ public func CanonicalString() -> String { let args : [CVarArg] = [ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15] ] return String(format: "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", arguments: args) } } extension UUID : Equatable { } /// Compare two UUIDs for equality. Two UUIDs are equal if their underlying bytes are equal. public func ==(lhs: UUID, rhs: UUID) -> Bool { return lhs.bytes == rhs.bytes }
unlicense
47e7fd34b86c0a706b359c219a5896c6
25.836066
118
0.600489
3.678652
false
false
false
false
IBM-Swift/Kitura-net
Sources/KituraNet/ClientResponse.swift
1
8141
/* * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import LoggerAPI // MARK: ClientResponse /** This class describes the response sent by the remote server to an HTTP request sent using the `ClientRequest` class. Data or Strings can be read in, and URLs can be parsed. ### Usage Example: ### ````swift //The `ClientResponse` object that describes the response that was received from the remote server is used in a callback. public typealias Callback = (ClientResponse?) -> Void ```` */ public class ClientResponse { /** HTTP Status code ### Usage Example: ### ````swift var httpStatusCode = .unknown ... } ```` */ public private(set) var httpStatusCode: HTTPStatusCode = .unknown /** HTTP Method of the incoming message. ### Usage Example: ### ````swift self.method = method ... } ```` */ @available(*, deprecated, message: "This method never worked on Client Responses and was inherited incorrectly from a super class") public var method: String { return httpParser.method } /** Major version of HTTP of the response ### Usage Example: ### ````swift print(String(describing: request.httpVersionMajor)) ```` */ public var httpVersionMajor: UInt16? { return httpParser.httpVersionMajor } /** Minor version of HTTP of the response ### Usage Example: ### ````swift print(String(describing: request.httpVersionMinor)) ```` */ public var httpVersionMinor: UInt16? { return httpParser.httpVersionMinor } /** The set of HTTP headers received with the response ### Usage Example: ### ````swift let protocols = request.headers["Upgrade"] ```` */ public var headers: HeadersContainer { return httpParser.headers } // Private /// Default buffer size used for creating a BufferList private static let bufferSize = 2000 /// The http_parser Swift wrapper private var httpParser: HTTPParser /// State of response parsing private var parserStatus = HTTPParserStatus() private var buffer = Data(capacity: bufferSize) /// Parse the message /// /// - Parameter buffer: An NSData object contaning the data to be parsed /// - Parameter from: From where in the buffer to start parsing func parse (_ buffer: NSData, from: Int) -> HTTPParserStatus { let length = buffer.length - from guard length > 0 else { /* Handle unexpected EOF. Usually just close the connection. */ parserStatus.error = .unexpectedEOF return parserStatus } // If we were reset because of keep alive if parserStatus.state == .reset { reset() } let bytes = buffer.bytes.assumingMemoryBound(to: Int8.self) + from let (numberParsed, _) = httpParser.execute(bytes, length: length) if numberParsed == length { // Tell parser we reached the end _ = httpParser.execute(bytes, length: 0) } if httpParser.completed { parsingCompleted() } else if numberParsed != length { /* Handle error. Usually just close the connection. */ parserStatus.error = .parsedLessThanRead } parserStatus.bytesLeft = length - numberParsed return parserStatus } /** Read a chunk of the body of the response. - Parameter into: An NSMutableData to hold the data in the response. - Throws: if an error occurs while reading the body. - Returns: the number of bytes read. ### Usage Example: ### ````swift let readData = try self.read(into: data) ```` */ public func read(into data: inout Data) throws -> Int { let count = httpParser.bodyChunk.fill(data: &data) return count } /** Read the whole body of the response. - Parameter into: An NSMutableData to hold the data in the response. - Throws: if an error occurs while reading the data. - Returns: the number of bytes read. ### Usage Example: ### ````swift let length = try request.readAllData(into: &body) ```` */ @discardableResult public func readAllData(into data: inout Data) throws -> Int { var length = try read(into: &data) var bytesRead = length while length > 0 { length = try read(into: &data) bytesRead += length } return bytesRead } /** Read a chunk of the body and return it as a String. - Throws: if an error occurs while reading the data. - Returns: an Optional string. ### Usage Example: ### ````swift let body = try request.readString() ```` */ public func readString() throws -> String? { buffer.count = 0 let length = try read(into: &buffer) if length > 0 { return String(data: buffer, encoding: .utf8) } else { return nil } } /// Extra handling performed when a message is completely parsed func parsingCompleted() { parserStatus.keepAlive = httpParser.isKeepAlive() parserStatus.state = .messageComplete httpStatusCode = httpParser.statusCode } /// Signal that reading is being reset func prepareToReset() { parserStatus.state = .reset } /// When we're ready, really reset everything private func reset() { parserStatus.reset() httpParser.reset() } /// Initializes a `ClientResponse` instance init(skipBody: Bool = false) { httpParser = HTTPParser(isRequest: false, skipBody: skipBody) } /** The HTTP Status code, as an Int, sent in the response by the remote server. ### Usage Example: ### ````swift statusCode = HTTPStatusCode(rawValue: status) ?? .unknown ```` */ public internal(set) var status = -1 { didSet { statusCode = HTTPStatusCode(rawValue: status) ?? .unknown } } /** The HTTP Status code, as an `HTTPStatusCode`, sent in the response by the remote server. ### Usage Example: ### ````swift response.statusCode = .badRequest ```` */ public internal(set) var statusCode: HTTPStatusCode = HTTPStatusCode.unknown /// BufferList instance for storing the response var responseBuffers = BufferList() /// Location in buffer to start parsing private var startParsingFrom = 0 /// Parse the contents of the responseBuffers func parse() -> HTTPParserStatus { let buffer = NSMutableData() responseBuffers.rewind() _ = responseBuffers.fill(data: buffer) // There can be multiple responses in the responseBuffers, if a Continue response // was received from the server. Each call to this function parses a single // response, starting from the prior parse call, if any, left off. when this // happens, the http_parser needs to be reset between invocations. prepareToReset() let parseStatus = parse(buffer, from: startParsingFrom) startParsingFrom = buffer.length - parseStatus.bytesLeft return parseStatus } }
apache-2.0
b567f3596249ec4b39efe9f76889d376
28.075
172
0.60312
5.006765
false
false
false
false
vitoflorko-swiftdev/VariableDataTable
VariableDataTable/VDTable.swift
1
7822
// // VDTable.swift // VariableDataTable // // Created by Vojtech Florko on 01/08/2017. // Copyright © 2017 Vojtech Florko. All rights reserved. // import UIKit public class VDTable: UIView { override public func awakeFromNib() { super.awakeFromNib() } public func assembleHorizontalTable(headCells: [HeadCell], dataCells: [DataCell], textAlignment: NSTextAlignment = .left) { for view in self.subviews { view.removeFromSuperview() } let widthOfOneItem = self.frame.width / (CGFloat(headCells.count)) var totalWidth: CGFloat = 0.0 var widths: [CGFloat] = [] let heightOfOneRow = ((self.frame.height) / CGFloat(dataCells.count + 1)) let headView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: heightOfOneRow)) headView.backgroundColor = UIColor.white for i in 0..<headCells.count { var newItemWidth = widthOfOneItem if headCells[i].dimension > 0 { newItemWidth = headCells[i].dimension } newItemWidth = CGFloat(ceil(Double(newItemWidth))) let headName = UILabel(frame: CGRect(x: totalWidth , y: 0, width: newItemWidth, height: heightOfOneRow)) headName.numberOfLines = 4 totalWidth += newItemWidth widths.append(newItemWidth) headName.font = UIFont(name: headCells[i].fontStyle, size: headCells[i].fontSize) headName.textColor = headCells[i].fontColor headName.text = headCells[i].textValue headName.textAlignment = textAlignment headName.backgroundColor = headCells[i].bgColor headView.addSubview(headName) } let headSectionLine = UIView(frame: CGRect(x: 0, y: headView.frame.height - 1, width: headView.frame.width, height: 1)) headSectionLine.backgroundColor = UIColor.darkGray headView.addSubview(headSectionLine) self.addSubview(headView) for i in 0..<dataCells.count { let dataView = UIView(frame: CGRect(x: 0, y: heightOfOneRow * CGFloat(i) + headView.frame.height, width: self.frame.width, height: heightOfOneRow)) dataView.backgroundColor = dataCells[i].bgColor var xPosition: CGFloat = 0.0 for j in 0..<widths.count { widths[j] = CGFloat(ceil(Double(widths[j]))) let dataElement = UILabel(frame: CGRect(x: xPosition , y: 0, width: widths[j], height: heightOfOneRow)) xPosition += widths[j] dataElement.numberOfLines = 2 dataElement.font = UIFont(name: dataCells[i].fontStyle, size: dataCells[i].fontSize) dataElement.textColor = dataCells[i].fontColor dataElement.textAlignment = textAlignment if j < dataCells[i].textValues.count { dataElement.text = dataCells[i].textValues[j] } dataView.addSubview(dataElement) } self.addSubview(dataView) } } public func assembleVerticalTable(headCells: [HeadCell], dataCells: [DataCell], textAlignment: NSTextAlignment = .left) { for view in self.subviews { view.removeFromSuperview() } let heightOfOneItem = self.frame.height / (CGFloat(headCells.count)) var totalHeight: CGFloat = 0.0 var heights: [CGFloat] = [] var yPositions: [CGFloat] = [] let widthOfOneRow = ((self.frame.width) / CGFloat(dataCells.count + 1)) let headView = UIView(frame: CGRect(x: 0, y: 0, width: widthOfOneRow, height: self.frame.height)) headView.backgroundColor = UIColor.white for i in 0..<headCells.count { var newItemHeight = heightOfOneItem if headCells[i].dimension >= 0 { newItemHeight = headCells[i].dimension } newItemHeight = CGFloat(ceil(Double(newItemHeight))) let headName = UILabel(frame: CGRect(x: 0, y: totalHeight, width: headView.frame.width, height: newItemHeight)) headName.numberOfLines = headCells[i].textValue.count / 2 yPositions.append(totalHeight) totalHeight += newItemHeight heights.append(headName.frame.height) headName.font = UIFont(name: headCells[i].fontStyle, size: headCells[i].fontSize) headName.textColor = headCells[i].fontColor headName.text = headCells[i].textValue headName.textAlignment = textAlignment headName.backgroundColor = headCells[i].bgColor headView.addSubview(headName) } self.addSubview(headView) let headSectionLine = UIView(frame: CGRect(x: headView.frame.width - 1, y: 0, width: 1, height: self.frame.height)) headSectionLine.backgroundColor = UIColor.darkGray headView.addSubview(headSectionLine) for i in 0..<dataCells.count { let dataView = UIView(frame: CGRect(x: widthOfOneRow * CGFloat(i) + widthOfOneRow, y: 0, width: widthOfOneRow, height: self.frame.height)) dataView.backgroundColor = dataCells[i].bgColor var yPosition: CGFloat = 0.0 for j in 0..<heights.count { heights[j] = CGFloat(ceil(Double(heights[j]))) let dataElement = UILabel(frame: CGRect(x: 0, y: yPositions[j], width: widthOfOneRow, height: heights[j])) yPosition += heights[j] dataElement.numberOfLines = 4 dataElement.font = UIFont(name: dataCells[i].fontStyle, size: dataCells[i].fontSize) dataElement.textColor = dataCells[i].fontColor if j < dataCells[i].textValues.count { dataElement.text = dataCells[i].textValues[j] dataElement.textAlignment = textAlignment dataElement.numberOfLines = dataElement.text!.count / 2 } dataElement.backgroundColor = dataCells[i].bgColor dataView.addSubview(dataElement) } self.addSubview(dataView) } } } public class HeadCell { var textValue: String var dimension: CGFloat var fontStyle: String var fontColor: UIColor var fontSize: CGFloat var bgColor: UIColor public init(textValue: String, dimension: CGFloat = -1, fontStyle: String = "Helvetica", fontColor: UIColor = UIColor.black, fontSize: CGFloat = 12, bgColor: UIColor = UIColor.white) { self.textValue = textValue self.dimension = dimension self.fontStyle = fontStyle self.fontColor = fontColor self.fontSize = fontSize self.bgColor = bgColor } } public class DataCell { var textValues: [String] var fontStyle: String var fontColor: UIColor var fontSize: CGFloat var bgColor: UIColor public init(textValues: [String], fontStyle: String = "Helvetica", fontColor: UIColor = UIColor.black, fontSize: CGFloat = 12, bgColor: UIColor = UIColor.white) { self.textValues = textValues self.fontStyle = fontStyle self.fontColor = fontColor self.fontSize = fontSize self.bgColor = bgColor } }
mit
a99bd284f2398d544888af785ecce878
35.71831
186
0.578571
4.997444
false
false
false
false
PjGeeroms/IOSRecipeDB
YummlyProject/Models/Recipe.swift
1
2430
// // Recipe.swift // YummlyProject // // Created by Pieter-Jan Geeroms on 06/12/2016. // Copyright © 2016 Pieter-Jan Geeroms. All rights reserved. // import Foundation import UIKit import SwiftyJSON final class Recipe: ResponseObjectSerializable, ResponseCollectionSerializable { let id: String let slug: String let name: String let portions: String let ingredients: [String] let instructions: [String] let imageString: String var image: UIImage? let body: String let author: Author // init(id: String, name: String, portions: String, ingredients: [String], instructions: [String], image: String, body: String, slug: String, author: Author ) { // self.id = id // self.name = name // self.slug = slug // self.portions = portions // self.ingredients = ingredients // self.instructions = instructions // self.image = image // self.body = body // self.author = author // } required init?(response: HTTPURLResponse, representation: Any) { guard let representation = representation as? [String: Any], let id = representation["_id"] as? String, let slug = representation["slug"] as? String, let body = representation["body"] as? String, let imageString = representation["image"] as? String, let portions = representation["portions"] as? String, let name = representation["title"] as? String, let ingredients = representation["ingredients"] as? [String], let instructions = representation["instructions"] as? [String], let author = representation["author"] as? [String: Any] else { return nil } self.id = id self.name = name self.slug = slug self.portions = portions self.ingredients = ingredients self.instructions = instructions self.imageString = imageString self.body = body self.author = Author(response: response, representation: author)! } } extension String { func capitalizingFirstLetter() -> String { let first = String(characters.prefix(1)).capitalized let other = String(characters.dropFirst()) return first + other } mutating func capitalizeFirstLetter() { self = self.capitalizingFirstLetter() } }
mit
d9526290821de79b43a877488ac15eb6
30.545455
163
0.616715
4.662188
false
false
false
false
Majki92/SwiftEmu
SwiftBoy/IMemoryBankController.swift
2
3997
// // IMemoryBankController.swift // SwiftBoy // // Created by Michal Majczak on 08.10.2015. // Copyright © 2015 Michal Majczak. All rights reserved. // import Foundation // This protocol defines API for any MBC that is used in SwiftBoy protocol IMemoryBankController { func write(address: UInt16, value: UInt8) func read(address: UInt16) -> UInt8 func getDMAData(address: UInt16, size: UInt16) -> [UInt8] func reset() func saveRAM() func loadRAM() } extension IMemoryBankController { func reset() {} func saveRAM() {} func loadRAM() {} } // Cartridge types: // 0x00 - Raw ROM cartridge // 0x01 - MBC1 // 0x02 - MBC1 + RAM // 0x03 - MBC1 + RAM + Battery // 0x05 - MBC2 // 0x06 - MBC2 + RAM + Battery // 0x08 - ROM + RAM // 0x09 - ROM + RAM + Battery // 0x0B - MMM01 // 0x0C - MMM01 + RAM // 0x0D - MMM01 + RAM + Battery // 0x0F - MBC3 + RTC + Battery // 0x10 - MBC3 + RAM + RTC + Battery // 0x11 - MBC3 // 0x12 - MBC3 + RAM // 0x13 - MBC3 + RAM + Battery // 0x19 - MBC5 // 0x1A - MBC5 + RAM // 0x1B - MBC5 + RAM + Battery // 0x1C - MBC5 + Rumble // 0x1D - MBC5 + RAM + Rumble // 0x1E - MBC5 + RAM + Battery + Rumble // 0x20 - MBC6 + RAM + Battery // 0x22 - MBC7 + RAM + Battery + Accelerometer // 0xFC - Pocket Camera // 0xFD - BANDAI TAMA5 // 0xFE - HuC3 // 0xFF - HuC1 + RAM + Battery // Function for loading rom images. It returns propper MBC controller populated with rom data func loadRomMBC(_ name: URL) -> IMemoryBankController? { let romPath = name; guard let romData = try? Data(contentsOf: romPath) else { LogE("Failed to load " + name.absoluteString + ".gb rom!") exit(-1) } var rom = [UInt8](repeating: 0, count: romData.count) (romData as NSData).getBytes(&rom, length: romData.count) LogI("Rom " + name.absoluteString + ".gb load success.") LogD("Rom type: 0x" + String(format:"%02X", rom[0x0147])) switch rom[0x0147] { case 0: return RawRom(rom: rom) case 0x01...0x03: return MBC1(rom: rom) case 0x0F...0x13: return MBC3(rom: rom) case 0x19...0x1E: return MBC5(rom: rom) default: LogE("Failed to load proper MBC!") return nil } } // Function for calculating rom bank count based on rom header data func getROMBankCount(_ romSizeRegiserVal: UInt8 ) -> Int { if romSizeRegiserVal > 0x08 { LogE("Too big rom size, possibly broken rom image.") return -1 } return Int(2 << romSizeRegiserVal) } // Function for calculating ram bank count based on rom header data func getRAMBankCount(_ ramSizeRegiserVal: UInt8 ) -> Int { var count = -1 switch ramSizeRegiserVal { case 0x00: count = 0 case 0x01: count = 1 case 0x02: count = 1 case 0x03: count = 4 case 0x04: count = 16 case 0x05: count = 8 default: LogE("Too big ram size, possibly broken rom image.") } return count } // Function for calculating rom total size based on rom header data func getROMTotalSize(_ romSizeRegiserVal: UInt8 ) -> Int { if romSizeRegiserVal > 0x08 { LogE("Too big rom size, possibly broken rom image.") return -1 } return getROMBankCount(romSizeRegiserVal) * 16 * 1024 } // Function for calculating brom total size based on rom header data func getRAMTotalSize(_ ramSizeRegiserVal: UInt8 ) -> Int { var count = Int(0) switch ramSizeRegiserVal { case 0x00: count = 0 case 0x01: count = 2 case 0x02: count = 8 case 0x03: count = 32 case 0x04: count = 128 case 0x05: count = 64 default: LogE("Too big ram size, possibly broken rom image.") return -1 } return count*1024 } // Function for extracting cartridge name based on rom header data func getCartridgeName(_ nameData: [UInt8]) -> String { var name = String() for byte in nameData { if byte == 0 { break; } name.append(Character(UnicodeScalar(byte))) } return name }
gpl-2.0
92f2ed56bec6183b5adac6eff4a4f860
26.75
93
0.630881
3.313433
false
false
false
false
Mindera/Alicerce
Sources/Persistence/CoreData/NSManagedObjectContext+CoreDataStack.swift
1
3049
import CoreData #if canImport(AlicerceLogging) import AlicerceLogging #endif // MARK: - performThrowing public extension NSManagedObjectContext { typealias ContextClosure<T> = () throws -> T typealias ContextCompletionClosure<T> = (T?, Error?) -> Void func performThrowing<T>(_ closure: @escaping ContextClosure<T>, completion: @escaping ContextCompletionClosure<T>) { perform { do { let value = try closure() completion(value, nil) } catch { completion(nil, error) } } } func performThrowingAndWait<T>(_ closure: @escaping ContextClosure<T>) throws -> T { // swiftlint:disable:next implicitly_unwrapped_optional var value: T! var error: Error? performAndWait { do { value = try closure() } catch let closureError { error = closureError } } if let error = error { throw error } return value } } // MARK: - persistChanges public extension NSManagedObjectContext { func persistChanges(_ description: String, saveParent: Bool = true, waitForParent: Bool = false) throws { guard hasChanges else { return } do { try save() } catch let error { Log.internalLogger.error("💥 Failed to save context \(self) (\(description)) with error: \(error)! " + "Rolling back all changes...") rollback() throw error } guard saveParent, let parent = parent else { return } var parentError: Error? let parentSave = { guard parent.hasChanges else { return } do { try parent.save() } catch let error { Log.internalLogger.error("💥 Failed to save parent context \(parent) (\(description)) with " + "error: \(error)! Rolling back changes in parent...") parent.rollback() parentError = error } } waitForParent ? parent.performAndWait(parentSave) : parent.perform(parentSave) if let parentError = parentError { throw parentError } } } // MARK: - Parent Coordinator & Store type public extension NSManagedObjectContext { var topLevelPersistentStoreCoordinator: NSPersistentStoreCoordinator? { switch (persistentStoreCoordinator, parent) { case (let persistentStoreCoordinator?, _): return persistentStoreCoordinator case (_, let parent?): return parent.topLevelPersistentStoreCoordinator default: return nil } } var isSQLiteStoreBased: Bool { switch topLevelPersistentStoreCoordinator?.firstStoreType { case .sqlite?: return true default: return false } } }
mit
b4ab3ec4c76efb7f05d5f518de9c5087
24.358333
120
0.554716
5.512681
false
false
false
false
kejinlu/SwiftyText
SwiftyTextDemo/ListViewController.swift
1
3003
// // ListViewController.swift // SwiftyText // // Created by Luke on 1/5/16. // Copyright © 2016 geeklu.com. All rights reserved. // import Foundation import SwiftyText class ListViewController: UITableViewController, SwiftyLabelDelegate { var attributedTexts = [NSAttributedString]() override func viewDidLoad() { //self.tableView.allowsSelection = false self.tableView.contentInset = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0) var i = 0 while i < 75 { let a = NSMutableAttributedString(string: "Writing Swift code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next project — or addition into your current app — because Swift code works side-by-side with Objective-C.") let link = SwiftyTextLink() link.attributes = [NSForegroundColorAttributeName:UIColor(red: 0, green: 122/255.0, blue: 1.0, alpha: 1.0),NSUnderlineStyleAttributeName:NSUnderlineStyle.StyleSingle.rawValue] link.URL = NSURL(string: "https://developer.apple.com/swift/") a.setLink(link, range: NSMakeRange(8, 5)) let imageAttachment = SwiftyTextAttachment() imageAttachment.image = UIImage(named: "swift") imageAttachment.padding = 10.0 imageAttachment.imageSize = CGSizeMake(40, 40) imageAttachment.attachmentTextVerticalAlignment = .Center a.insertAttachment(imageAttachment, atIndex: a.length - 9) self.attributedTexts.append(a) i += 1 } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.attributedTexts.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let CellIdentifier = "SwiftyTextCell" let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as! SwiftyLabelCell let attributedText = self.attributedTexts[indexPath.row] cell.swiftyLabel.drawsTextAsynchronously = true cell.swiftyLabel.attributedText = attributedText return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("row selected") } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let attributedText = self.attributedTexts[indexPath.row] let size = attributedText.proposedSizeWithConstrainedSize(CGSize(width: self.tableView.bounds.width, height: CGFloat.max), exclusionPaths: nil, lineBreakMode: nil, maximumNumberOfLines: nil) return size.height } override func scrollViewWillBeginDragging(scrollView: UIScrollView) { } }
mit
2248f849f6c8c0aa3af9d18c0d5dc44c
43.761194
297
0.691461
5.107325
false
false
false
false
rosberry/TableViewTools
Example/Example-iOS/Example-iOS/Classes/ExampleTableViewCell.swift
1
1478
// // ExampleTableViewCell.swift // Example-iOS // // Created by Dmitry Frishbuter on 26/12/2016. // Copyright © 2016 Rosberry. All rights reserved. // import UIKit class ExampleTableViewCell: UITableViewCell { let titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont.boldSystemFont(ofSize: 14) titleLabel.numberOfLines = 0 return titleLabel }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() titleLabel.sizeToFit() if let text = titleLabel.text { let width = contentView.bounds.width - 32 titleLabel.frame = CGRect(x: 16, y: (contentView.bounds.height - titleLabel.bounds.height) / 2, width: width, height: text.heightWithConstrainedWidth(width: width, font: titleLabel.font)) } } override func sizeThatFits(_ size: CGSize) -> CGSize { setNeedsLayout() layoutIfNeeded() return CGSize(width: size.width, height: titleLabel.bounds.height + 16) } }
mit
21e080d1d11cd45ebe1c9177b1eeb5a3
30.425532
115
0.597833
5.058219
false
false
false
false
programersun/HiChongSwift
HiChongSwift/ZXYImageBrowser/ZXY_ImageBrowserVC.swift
1
18581
// // ZXY_ImageBrowserVC.swift // ZXYImageBrowser // // Created by ZXYStart on 15/1/23. // Copyright (c) 2015年 宇周. All rights reserved. // import UIKit @objc protocol ZXY_ImageBrowserVCDelegate : class { /** sheet点击代理时间 :param: sheetView 所创建的sheetView 实例 :param: index 非负表示用户点击按钮 ,-1表示点击取消 :returns: 返回空 */ func longPressClickActionSheetAt(indexPath : Int) /** sheet点击代理时间 :param: sheetView 所创建的sheetView 实例 :param: index 非负表示用户点击按钮 ,-1表示点击取消 :returns: 返回空 */ optional func longPressClickActionSheetAtImage(indexPath : Int , withImage: UIImage) } class ZXY_ImageBrowserVC: UIViewController { private let tagForAdd = 1300 weak var delegate : ZXY_ImageBrowserVCDelegate? private let edgeWidth = 15.0 private var _currentIndex : Int = 0 private var _currentScroll : UIScrollView! private var _itemCellINUse : NSMutableSet? private var _itemCellINDeuse : NSMutableSet? private var _isOriChange : Bool = false private var _selectIndex : Int? = 0 private var _titleView : UIView = UIView() private var _titleLbl : UILabel = UILabel() private var _titleBtn : UIButton = UIButton() private var _isTitleHide : Bool = false private var _currentImageForGive : UIImage? private var actionSheet : ZXY_SheetView? private var actionCancel : String? private var actionList : [String]? var photoItems : [ZXY_ImageItem]! override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.None) //self.startInitScrollView() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.prefersStatusBarHidden() self.setNeedsStatusBarAppearanceUpdate() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.startInitScrollView() } override func loadView() { self.view = UIView() self.view.frame = UIScreen.mainScreen().bounds self.view.backgroundColor = UIColor.blackColor() } func setLongPressActionInfo(cancelBtn: String?,andMessage messages : String...) { actionList = messages actionCancel = cancelBtn } func setSelectIndex(selectIndex : Int?) { self._selectIndex = selectIndex _currentIndex = selectIndex! for var i = 0 ;i < photoItems.count ; i++ { var tempItem = photoItems[i] tempItem.itemIndex = i tempItem.isFistShow = i == _selectIndex } if(self.isViewLoaded()) { var frame: CGRect = self.view.bounds if(_currentScroll == nil) { self.startInitScrollView() } _currentScroll.contentOffset = CGPointMake(frame.size.width * CGFloat(_selectIndex!), 0.0) self.showPhotos() } } func presentShow() { var window : UIWindow = UIApplication.sharedApplication().keyWindow! self.view.alpha = 0 window.addSubview(self.view) window.rootViewController?.addChildViewController(self) UIView.animateWithDuration(0.2, animations: { () -> Void in self.view.alpha = 1 }) { [weak self](isDown) -> Void in if(self?._selectIndex == 0) { self?.showPhotos() } } } private func startInitScrollView() -> Void { var frame: CGRect = self.view.bounds //self.view.setTranslatesAutoresizingMaskIntoConstraints(false) frame.origin.x -= CGFloat(edgeWidth) frame.size.width += CGFloat(2 * edgeWidth) if(_currentScroll == nil) { _currentScroll = UIScrollView(frame: frame) self.view.addSubview(_currentScroll) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: _currentScroll, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 15.0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: _currentScroll, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -15.0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: _currentScroll, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: _currentScroll, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)) _titleView.frame = CGRectMake(0, 0, frame.size.width, 70) _titleView.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.7) _titleLbl.frame = CGRectMake(frame.size.width/2 - 60, 30, 100, 20) _titleLbl.textAlignment = NSTextAlignment.Center _titleLbl.font = UIFont.systemFontOfSize(15) _titleBtn.frame = CGRectMake(5, 25, 50, 30) _titleBtn.setTitle("返回", forState: UIControlState.Normal) _titleBtn.setTitleColor(UIColor(red: 3/255.0, green: 144/255.0, blue: 252/255.0, alpha: 1), forState: UIControlState.Normal) _titleBtn.titleLabel?.font = UIFont.systemFontOfSize(15) _titleBtn.addTarget(self, action: Selector("hideBrowser"), forControlEvents: UIControlEvents.TouchUpInside) _titleView.addSubview(_titleLbl) _titleView.addSubview(_titleBtn) self.view.addSubview(_titleView) } else { _titleView.frame = CGRectMake(0, _titleView.frame.origin.y, frame.size.width, 70) _titleLbl.frame = CGRectMake(frame.size.width/2 - 60, 30, 100, 20) _currentScroll.frame = frame } _currentScroll.delegate = self _currentScroll.pagingEnabled = true _currentScroll.backgroundColor = UIColor.clearColor() _currentScroll.showsHorizontalScrollIndicator = false _currentScroll.showsVerticalScrollIndicator = true var contentWidth : CGFloat = frame.size.width * CGFloat(photoItems.count) _currentScroll.contentSize = CGSizeMake(contentWidth, frame.height) _currentScroll.contentOffset = CGPointMake(frame.size.width * CGFloat(_currentIndex), 0.0) _titleLbl.text = "\(_currentIndex + 1) / \(photoItems.count) " _currentScroll.setTranslatesAutoresizingMaskIntoConstraints(false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setPhotos(photos : [ZXY_ImageItem]) { self.photoItems = photos if(self.photoItems.count > 1) { _itemCellINDeuse = NSMutableSet() _itemCellINUse = NSMutableSet() } for var i = 0 ;i < photoItems.count ;i++ { var photo : ZXY_ImageItem = photoItems[i] photo.itemIndex = i photo.isFistShow = i == _selectIndex } if(_currentScroll != nil) { _currentScroll.removeFromSuperview() _currentScroll = nil // var frame: CGRect = self.view.bounds // //self.view.setTranslatesAutoresizingMaskIntoConstraints(false) // frame.origin.x -= CGFloat(edgeWidth) // frame.size.width += CGFloat(2 * edgeWidth) // var contentWidth : CGFloat = frame.size.width * CGFloat(photoItems.count) // _currentScroll.contentSize = CGSizeMake(contentWidth, frame.height) // _currentScroll.contentOffset = CGPointMake(frame.size.width * CGFloat(_currentIndex), 0.0) // _titleLbl.text = "\(_currentIndex + 1) / \(photoItems.count) " // _currentScroll.setTranslatesAutoresizingMaskIntoConstraints(false) } } private func getTagFromIndex(index : Int) -> Int { return index + tagForAdd } private func getIndexFromTag(tag : Int) ->Int { return tag - tagForAdd } private func showPhotos() { if(photoItems.count == 1) { self.showItemAtIndex(0) return } var currentBounds = _currentScroll.bounds var begainIndex = Int(floorf(Float((CGRectGetMinX(currentBounds) + CGFloat(2 * edgeWidth)) / CGRectGetWidth(currentBounds)))) var endIndex = Int(floorf(Float((CGRectGetMaxX(currentBounds) - CGFloat(2 * edgeWidth) - 1.0) / CGRectGetWidth(currentBounds)))) if(begainIndex < 0) { begainIndex = 0 } if(begainIndex >= photoItems.count) { begainIndex = photoItems.count - 1 } if (endIndex < 0) { endIndex = 0 } if(endIndex >= photoItems.count) { endIndex = photoItems.count - 1 } for var i = 0 ;i < _itemCellINUse?.count ; i++ { var tempItemV : ZXY_ImageItemView = _itemCellINUse?.allObjects[i] as! ZXY_ImageItemView var index = self.getIndexFromTag(tempItemV.tag) if(index < begainIndex || index > endIndex) { tempItemV.removeFromSuperview() _itemCellINUse?.removeObject(tempItemV) } } _itemCellINUse?.minusSet(_itemCellINDeuse! as Set<NSObject>) if(_itemCellINDeuse?.count > 2) { _itemCellINDeuse?.removeObject(_itemCellINDeuse!.anyObject()!) } for var j = begainIndex ; j <= endIndex ; j++ { if(!isViewShowing(j)) { self.showItemAtIndex(j) } } } func removeShowView() { var currentBounds = _currentScroll.bounds var begainIndex = Int(floorf(Float((CGRectGetMinX(currentBounds) + CGFloat(2 * edgeWidth)) / CGRectGetWidth(currentBounds)))) var endIndex = Int(floorf(Float((CGRectGetMaxX(currentBounds) - CGFloat(2 * edgeWidth) - 1.0) / CGRectGetWidth(currentBounds)))) if(begainIndex < 0) { begainIndex = 0 } if(begainIndex >= photoItems.count) { begainIndex = photoItems.count - 1 } if (endIndex < 0) { endIndex = 0 } if(endIndex >= photoItems.count) { endIndex = photoItems.count - 1 } for var i = 0 ;i < _itemCellINUse?.count ; i++ { var tempItemV : ZXY_ImageItemView = _itemCellINUse?.allObjects[i] as! ZXY_ImageItemView var index = self.getIndexFromTag(tempItemV.tag) if(index < begainIndex || index > endIndex) { tempItemV.removeFromSuperview() _itemCellINUse?.removeObject(tempItemV) } } _itemCellINUse?.minusSet(_itemCellINDeuse! as Set<NSObject>) if(_itemCellINDeuse?.count > 2) { _itemCellINDeuse?.removeObject(_itemCellINDeuse!.anyObject()!) } for var j = begainIndex ; j <= endIndex ; j++ { for var i = 0 ;i < _itemCellINUse?.count ; i++ { var tempItemV : ZXY_ImageItemView = _itemCellINUse?.allObjects[i] as! ZXY_ImageItemView var indexs = self.getIndexFromTag(tempItemV.tag) if(indexs == j) { //tempItemV.setZoomScale(1, animated: true) tempItemV.removeFromSuperview() _itemCellINUse?.removeObject(tempItemV) } } } } private func getItemViewFromDeuser() -> ZXY_ImageItemView? { var tempItemView: ZXY_ImageItemView? = _itemCellINDeuse?.anyObject() as? ZXY_ImageItemView if(tempItemView != nil) { _itemCellINDeuse?.removeObject(tempItemView!) } return tempItemView } private func isViewShowing(index : Int) -> Bool { for var i = 0 ;i < _itemCellINUse?.count ; i++ { var tempItemV : ZXY_ImageItemView = _itemCellINUse?.allObjects[i] as! ZXY_ImageItemView var indexs = self.getIndexFromTag(tempItemV.tag) if(indexs == index) { //tempItemV.setZoomScale(1, animated: true) return true } } return false } private func showItemAtIndex(index: Int) { var tempImageView = self.getItemViewFromDeuser() if(tempImageView == nil) { var frame : CGRect = _currentScroll.bounds tempImageView = ZXY_ImageItemView(frame: CGRectMake(CGFloat(index) * frame.size.width + CGFloat(edgeWidth), 0, frame.size.width - CGFloat(2 * edgeWidth), frame.size.height)) } else { var frame : CGRect = _currentScroll.bounds tempImageView?.frame = CGRectMake(CGFloat(index) * frame.size.width + CGFloat(edgeWidth), 0, frame.size.width - CGFloat(2 * edgeWidth), frame.size.height) } tempImageView?.delegateOfItem = self //tempImageView?.setTranslatesAutoresizingMaskIntoConstraints(false) //_titleLbl.text = "\(_currentIndex + 1) / \(photoItems.count) " //tempImageView?.setZoomScale(1, animated: true) if(photoItems.count == 1) { for temp in _currentScroll.subviews { var currentTemp : UIView? = temp as? UIView currentTemp?.removeFromSuperview() } } tempImageView?.setCurrentItem(photoItems[index]) tempImageView?.tag = self.getTagFromIndex(index) _currentScroll.addSubview(tempImageView!) _itemCellINUse?.addObject(tempImageView!) } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { //println("width is \(UIScreen.mainScreen().bounds.size.width) height is \(UIScreen.mainScreen().bounds.size.height)") _isOriChange = true self.view.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height) self.removeShowView() self.startInitScrollView() self.showItemAtIndex(_currentIndex) _isOriChange = false } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { actionSheet?.hideSheet(self.view) actionSheet?.delegate = nil if(actionSheet != nil) { actionSheet = nil } _isOriChange = true self.view.frame = CGRectMake(0, 0, size.width, size.height) self.removeShowView() self.startInitScrollView() self.showItemAtIndex(_currentIndex) _isOriChange = false } override func prefersStatusBarHidden() -> Bool { return true } } extension ZXY_ImageBrowserVC : UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { if(_isOriChange) { return } self.showPhotos() } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { var currentIndexs = scrollView.contentOffset.x / scrollView.frame.size.width _titleLbl.text = "\(Int(currentIndexs) + 1) / \(photoItems.count) " _currentIndex = Int(currentIndexs) } } // MARK: 单击事件 extension ZXY_ImageBrowserVC : ZXY_ImageItemViewDelegate , ZXY_SheetViewDelegate { func longPressItemAtIndexPath(indexPath: Int, giveYouImage: UIImage) { if(self.delegate == nil) { return } if((self.view) != nil) { if(actionList != nil ) { actionSheet = ZXY_SheetView(zxyTitle: nil, cancelBtn: actionCancel, andMessage: actionList!) actionSheet?.delegate = self actionSheet?.showSheet(self.view) _currentImageForGive = giveYouImage } } } func clickItemAtIndex(sheetView: ZXY_SheetView, index: Int) { if(self.delegate != nil) { if((self.delegate?.longPressClickActionSheetAtImage?(index, withImage: _currentImageForGive!)) != nil) { //println("实现了") } self.delegate?.longPressClickActionSheetAt(index) } } func clickItemAtIndexPath(indexPath: Int) { UIView.animateWithDuration(0.2, animations: { [weak self] () -> Void in if( self?._isTitleHide == true ) { self?._isTitleHide = false var frames = self?._titleView.frame as CGRect! self?._titleView.frame = CGRectMake(0, 0 , frames.size.width , frames.size.height) self?._titleView.alpha = 1 } else { var frames = self?._titleView.frame as CGRect! self?._isTitleHide = true self?._titleView.frame = CGRectMake(0, 0 - frames.size.height, frames.size.width , frames.size.height) self?._titleView.alpha = 0 return } }) } func hideBrowser() { UIView.animateWithDuration(0.2, animations: { () -> Void in self.view.alpha = 0 }) { [weak self ](isDown) -> Void in //self?._itemCellINDeuse = nil //self?._itemCellINUse = nil self?.view.removeFromSuperview() self?.removeFromParentViewController() } } }
apache-2.0
c9fe9813f51454ca13aa4ca254f4eeb2
34.169847
241
0.58587
4.952701
false
false
false
false
sonnygauran/trailer
Trailer/PreferencesWindow.swift
1
39155
import Foundation final class PreferencesWindow : NSWindow, NSWindowDelegate, NSTableViewDelegate, NSTableViewDataSource, NSTabViewDelegate { // Preferences window @IBOutlet weak var refreshButton: NSButton! @IBOutlet weak var activityDisplay: NSProgressIndicator! @IBOutlet weak var projectsTable: NSTableView! @IBOutlet weak var versionNumber: NSTextField! @IBOutlet weak var launchAtStartup: NSButton! @IBOutlet weak var refreshDurationLabel: NSTextField! @IBOutlet weak var refreshDurationStepper: NSStepper! @IBOutlet weak var hideUncommentedPrs: NSButton! @IBOutlet weak var repoFilter: NSTextField! @IBOutlet weak var showAllComments: NSButton! @IBOutlet weak var sortingOrder: NSButton! @IBOutlet weak var sortModeSelect: NSPopUpButton! @IBOutlet weak var showCreationDates: NSButton! @IBOutlet weak var dontKeepPrsMergedByMe: NSButton! @IBOutlet weak var hideAvatars: NSButton! @IBOutlet weak var dontConfirmRemoveAllMerged: NSButton! @IBOutlet weak var dontConfirmRemoveAllClosed: NSButton! @IBOutlet weak var displayRepositoryNames: NSButton! @IBOutlet weak var includeRepositoriesInFiltering: NSButton! @IBOutlet weak var groupByRepo: NSButton! @IBOutlet weak var markUnmergeableOnUserSectionsOnly: NSButton! @IBOutlet weak var repoCheckLabel: NSTextField! @IBOutlet weak var repoCheckStepper: NSStepper! @IBOutlet weak var countOnlyListedItems: NSButton! @IBOutlet weak var prMergedPolicy: NSPopUpButton! @IBOutlet weak var prClosedPolicy: NSPopUpButton! @IBOutlet weak var checkForUpdatesAutomatically: NSButton! @IBOutlet weak var checkForUpdatesLabel: NSTextField! @IBOutlet weak var checkForUpdatesSelector: NSStepper! @IBOutlet weak var openPrAtFirstUnreadComment: NSButton! @IBOutlet weak var logActivityToConsole: NSButton! @IBOutlet weak var commentAuthorBlacklist: NSTokenField! // Statuses @IBOutlet weak var showStatusItems: NSButton! @IBOutlet weak var makeStatusItemsSelectable: NSButton! @IBOutlet weak var statusItemRescanLabel: NSTextField! @IBOutlet weak var statusItemRefreshCounter: NSStepper! @IBOutlet weak var statusItemsRefreshNote: NSTextField! @IBOutlet weak var notifyOnStatusUpdates: NSButton! @IBOutlet weak var notifyOnStatusUpdatesForAllPrs: NSButton! @IBOutlet weak var statusTermMenu: NSPopUpButton! @IBOutlet weak var statusTermsField: NSTokenField! // Comments @IBOutlet weak var disableAllCommentNotifications: NSButton! @IBOutlet weak var autoParticipateOnTeamMentions: NSButton! @IBOutlet weak var autoParticipateWhenMentioned: NSButton! // Display @IBOutlet weak var useVibrancy: NSButton! @IBOutlet weak var includeLabelsInFiltering: NSButton! @IBOutlet weak var includeTitlesInFiltering: NSButton! @IBOutlet weak var includeStatusesInFiltering: NSButton! @IBOutlet weak var grayOutWhenRefreshing: NSButton! @IBOutlet weak var assignedPrHandlingPolicy: NSPopUpButton! @IBOutlet weak var includeServersInFiltering: NSButton! @IBOutlet weak var includeUsersInFiltering: NSButton! // Labels @IBOutlet weak var labelRescanLabel: NSTextField! @IBOutlet weak var labelRefreshNote: NSTextField! @IBOutlet weak var labelRefreshCounter: NSStepper! @IBOutlet weak var showLabels: NSButton! // Servers @IBOutlet weak var serverList: NSTableView! @IBOutlet weak var apiServerName: NSTextField! @IBOutlet weak var apiServerApiPath: NSTextField! @IBOutlet weak var apiServerWebPath: NSTextField! @IBOutlet weak var apiServerAuthToken: NSTextField! @IBOutlet weak var apiServerSelectedBox: NSBox! @IBOutlet weak var apiServerTestButton: NSButton! @IBOutlet weak var apiServerDeleteButton: NSButton! @IBOutlet weak var apiServerReportError: NSButton! // Misc @IBOutlet weak var repeatLastExportAutomatically: NSButton! @IBOutlet weak var lastExportReport: NSTextField! @IBOutlet weak var dumpApiResponsesToConsole: NSButton! // Keyboard @IBOutlet weak var hotkeyEnable: NSButton! @IBOutlet weak var hotkeyCommandModifier: NSButton! @IBOutlet weak var hotkeyOptionModifier: NSButton! @IBOutlet weak var hotkeyShiftModifier: NSButton! @IBOutlet weak var hotkeyLetter: NSPopUpButton! @IBOutlet weak var hotKeyHelp: NSTextField! @IBOutlet weak var hotKeyContainer: NSBox! @IBOutlet weak var hotkeyControlModifier: NSButton! // Repos @IBOutlet weak var allPrsSetting: NSPopUpButton! @IBOutlet weak var allIssuesSetting: NSPopUpButton! @IBOutlet weak var allNewPrsSetting: NSPopUpButton! @IBOutlet weak var allNewIssuesSetting: NSPopUpButton! // Tabs @IBOutlet weak var tabs: NSTabView! override init(contentRect: NSRect, styleMask aStyle: Int, backing bufferingType: NSBackingStoreType, `defer` flag: Bool) { super.init(contentRect: contentRect, styleMask: aStyle, backing: bufferingType, `defer`: flag) } override func awakeFromNib() { super.awakeFromNib() delegate = self updateAllItemSettingButtons() allNewPrsSetting.addItemsWithTitles(RepoDisplayPolicy.labels) allNewIssuesSetting.addItemsWithTitles(RepoDisplayPolicy.labels) reloadSettings() versionNumber.stringValue = versionString() let selectedIndex = min(tabs.numberOfTabViewItems-1, Settings.lastPreferencesTabSelectedOSX) tabs.selectTabViewItem(tabs.tabViewItemAtIndex(selectedIndex)) let n = NSNotificationCenter.defaultCenter() n.addObserver(serverList, selector: Selector("reloadData"), name: API_USAGE_UPDATE, object: nil) n.addObserver(self, selector: Selector("updateImportExportSettings"), name: SETTINGS_EXPORTED, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(serverList) NSNotificationCenter.defaultCenter().removeObserver(self) } private func updateAllItemSettingButtons() { allPrsSetting.removeAllItems() allIssuesSetting.removeAllItems() let rowCount = projectsTable.selectedRowIndexes.count if rowCount > 1 { allPrsSetting.addItemWithTitle("Set selected PRs...") allIssuesSetting.addItemWithTitle("Set selected issues...") } else { allPrsSetting.addItemWithTitle("Set all PRs...") allIssuesSetting.addItemWithTitle("Set all issues...") } allPrsSetting.addItemsWithTitles(RepoDisplayPolicy.labels) allIssuesSetting.addItemsWithTitles(RepoDisplayPolicy.labels) } func reloadSettings() { serverList.selectRowIndexes(NSIndexSet(index: 0), byExtendingSelection: false) fillServerApiFormFromSelectedServer() api.updateLimitsFromServer() updateStatusTermPreferenceControls() commentAuthorBlacklist.objectValue = Settings.commentAuthorBlacklist setupSortMethodMenu() sortModeSelect.selectItemAtIndex(Settings.sortMethod) prMergedPolicy.selectItemAtIndex(Settings.mergeHandlingPolicy) prClosedPolicy.selectItemAtIndex(Settings.closeHandlingPolicy) launchAtStartup.integerValue = StartupLaunch.isAppLoginItem() ? 1 : 0 dontConfirmRemoveAllClosed.integerValue = Settings.dontAskBeforeWipingClosed ? 1 : 0 displayRepositoryNames.integerValue = Settings.showReposInName ? 1 : 0 includeRepositoriesInFiltering.integerValue = Settings.includeReposInFilter ? 1 : 0 includeLabelsInFiltering.integerValue = Settings.includeLabelsInFilter ? 1 : 0 includeTitlesInFiltering.integerValue = Settings.includeTitlesInFilter ? 1 : 0 includeUsersInFiltering.integerValue = Settings.includeUsersInFilter ? 1 : 0 includeServersInFiltering.integerValue = Settings.includeServersInFilter ? 1 : 0 includeStatusesInFiltering.integerValue = Settings.includeStatusesInFilter ? 1 : 0 dontConfirmRemoveAllMerged.integerValue = Settings.dontAskBeforeWipingMerged ? 1 : 0 hideUncommentedPrs.integerValue = Settings.hideUncommentedItems ? 1 : 0 autoParticipateWhenMentioned.integerValue = Settings.autoParticipateInMentions ? 1 : 0 autoParticipateOnTeamMentions.integerValue = Settings.autoParticipateOnTeamMentions ? 1 : 0 hideAvatars.integerValue = Settings.hideAvatars ? 1 : 0 dontKeepPrsMergedByMe.integerValue = Settings.dontKeepPrsMergedByMe ? 1 : 0 grayOutWhenRefreshing.integerValue = Settings.grayOutWhenRefreshing ? 1 : 0 notifyOnStatusUpdates.integerValue = Settings.notifyOnStatusUpdates ? 1 : 0 notifyOnStatusUpdatesForAllPrs.integerValue = Settings.notifyOnStatusUpdatesForAllPrs ? 1 : 0 disableAllCommentNotifications.integerValue = Settings.disableAllCommentNotifications ? 1 : 0 showAllComments.integerValue = Settings.showCommentsEverywhere ? 1 : 0 sortingOrder.integerValue = Settings.sortDescending ? 1 : 0 showCreationDates.integerValue = Settings.showCreatedInsteadOfUpdated ? 1 : 0 groupByRepo.integerValue = Settings.groupByRepo ? 1 : 0 assignedPrHandlingPolicy.selectItemAtIndex(Settings.assignedPrHandlingPolicy) showStatusItems.integerValue = Settings.showStatusItems ? 1 : 0 makeStatusItemsSelectable.integerValue = Settings.makeStatusItemsSelectable ? 1 : 0 markUnmergeableOnUserSectionsOnly.integerValue = Settings.markUnmergeableOnUserSectionsOnly ? 1 : 0 countOnlyListedItems.integerValue = Settings.countOnlyListedItems ? 0 : 1 openPrAtFirstUnreadComment.integerValue = Settings.openPrAtFirstUnreadComment ? 1 : 0 logActivityToConsole.integerValue = Settings.logActivityToConsole ? 1 : 0 dumpApiResponsesToConsole.integerValue = Settings.dumpAPIResponsesInConsole ? 1 : 0 showLabels.integerValue = Settings.showLabels ? 1 : 0 useVibrancy.integerValue = Settings.useVibrancy ? 1 : 0 allNewPrsSetting.selectItemAtIndex(Settings.displayPolicyForNewPrs) allNewIssuesSetting.selectItemAtIndex(Settings.displayPolicyForNewIssues) hotkeyEnable.integerValue = Settings.hotkeyEnable ? 1 : 0 hotkeyControlModifier.integerValue = Settings.hotkeyControlModifier ? 1 : 0 hotkeyCommandModifier.integerValue = Settings.hotkeyCommandModifier ? 1 : 0 hotkeyOptionModifier.integerValue = Settings.hotkeyOptionModifier ? 1 : 0 hotkeyShiftModifier.integerValue = Settings.hotkeyShiftModifier ? 1 : 0 enableHotkeySegments() hotkeyLetter.addItemsWithTitles(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]) hotkeyLetter.selectItemWithTitle(Settings.hotkeyLetter) refreshUpdatePreferences() updateStatusItemsOptions() updateLabelOptions() hotkeyEnable.enabled = true repoCheckStepper.floatValue = Settings.newRepoCheckPeriod newRepoCheckChanged(nil) refreshDurationStepper.floatValue = min(Settings.refreshPeriod, 3600) refreshDurationChanged(nil) updateImportExportSettings() updateActivity() } func updateActivity() { if app.isRefreshing { refreshButton.enabled = false projectsTable.enabled = false allPrsSetting.enabled = false allIssuesSetting.enabled = false activityDisplay.startAnimation(nil) } else { refreshButton.enabled = ApiServer.someServersHaveAuthTokensInMoc(mainObjectContext) projectsTable.enabled = true allPrsSetting.enabled = true allIssuesSetting.enabled = true activityDisplay.stopAnimation(nil) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func showLabelsSelected(sender: NSButton) { Settings.showLabels = (sender.integerValue==1) app.deferredUpdateTimer.push() updateLabelOptions() api.resetAllLabelChecks() if Settings.showLabels { ApiServer.resetSyncOfEverything() } } @IBAction func dontConfirmRemoveAllMergedSelected(sender: NSButton) { Settings.dontAskBeforeWipingMerged = (sender.integerValue==1) } @IBAction func markUnmergeableOnUserSectionsOnlySelected(sender: NSButton) { Settings.markUnmergeableOnUserSectionsOnly = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func displayRepositoryNameSelected(sender: NSButton) { Settings.showReposInName = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func useVibrancySelected(sender: NSButton) { Settings.useVibrancy = (sender.integerValue==1) app.prMenu.updateVibrancy() app.issuesMenu.updateVibrancy() } @IBAction func logActivityToConsoleSelected(sender: NSButton) { Settings.logActivityToConsole = (sender.integerValue==1) logActivityToConsole.integerValue = Settings.logActivityToConsole ? 1 : 0 if Settings.logActivityToConsole { let alert = NSAlert() alert.messageText = "Warning" #if DEBUG alert.informativeText = "Sorry, logging is always active in development versions" #else alert.informativeText = "Logging is a feature meant for error reporting, having it constantly enabled will cause this app to be less responsive, use more power, and constitute a security risk" #endif alert.addButtonWithTitle("OK") alert.beginSheetModalForWindow(self, completionHandler: nil) } } @IBAction func dumpApiResponsesToConsoleSelected(sender: NSButton) { Settings.dumpAPIResponsesInConsole = (sender.integerValue==1) if Settings.dumpAPIResponsesInConsole { let alert = NSAlert() alert.messageText = "Warning" alert.informativeText = "This is a feature meant for error reporting, having it constantly enabled will cause this app to be less responsive, use more power, and constitute a security risk" alert.addButtonWithTitle("OK") alert.beginSheetModalForWindow(self, completionHandler: nil) } } @IBAction func includeServersInFilteringSelected(sender: NSButton) { Settings.includeServersInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeUsersInFilteringSelected(sender: NSButton) { Settings.includeUsersInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeLabelsInFilteringSelected(sender: NSButton) { Settings.includeLabelsInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeStatusesInFilteringSelected(sender: NSButton) { Settings.includeStatusesInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeTitlesInFilteringSelected(sender: NSButton) { Settings.includeTitlesInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeRepositoriesInfilterSelected(sender: NSButton) { Settings.includeReposInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func dontConfirmRemoveAllClosedSelected(sender: NSButton) { Settings.dontAskBeforeWipingClosed = (sender.integerValue==1) } @IBAction func autoParticipateOnMentionSelected(sender: NSButton) { Settings.autoParticipateInMentions = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func autoParticipateOnTeamMentionSelected(sender: NSButton) { Settings.autoParticipateOnTeamMentions = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func dontKeepMyPrsSelected(sender: NSButton) { Settings.dontKeepPrsMergedByMe = (sender.integerValue==1) } @IBAction func grayOutWhenRefreshingSelected(sender: NSButton) { Settings.grayOutWhenRefreshing = (sender.integerValue==1) } @IBAction func disableAllCommentNotificationsSelected(sender: NSButton) { Settings.disableAllCommentNotifications = (sender.integerValue==1) } @IBAction func notifyOnStatusUpdatesSelected(sender: NSButton) { Settings.notifyOnStatusUpdates = (sender.integerValue==1) } @IBAction func notifyOnStatusUpdatesOnAllPrsSelected(sender: NSButton) { Settings.notifyOnStatusUpdatesForAllPrs = (sender.integerValue==1) } @IBAction func hideAvatarsSelected(sender: NSButton) { Settings.hideAvatars = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } private func affectedReposFromSelection() -> [Repo] { let selectedRows = projectsTable.selectedRowIndexes var affectedRepos = [Repo]() if selectedRows.count > 1 { for row in selectedRows { if !tableView(projectsTable, isGroupRow: row) { affectedRepos.append(repoForRow(row)) } } } else { affectedRepos = Repo.reposForFilter(repoFilter.stringValue) } return affectedRepos } @IBAction func allPrsPolicySelected(sender: NSPopUpButton) { let index = sender.indexOfSelectedItem - 1 if index < 0 { return } for r in affectedReposFromSelection() { r.displayPolicyForPrs = index if index != RepoDisplayPolicy.Hide.rawValue { r.resetSyncState() } } projectsTable.reloadData() sender.selectItemAtIndex(0) updateDisplayIssuesSetting() } @IBAction func allIssuesPolicySelected(sender: NSPopUpButton) { let index = sender.indexOfSelectedItem - 1 if index < 0 { return } for r in affectedReposFromSelection() { r.displayPolicyForIssues = index if index != RepoDisplayPolicy.Hide.rawValue { r.resetSyncState() } } projectsTable.reloadData() sender.selectItemAtIndex(0) updateDisplayIssuesSetting() } private func updateDisplayIssuesSetting() { DataManager.postProcessAllItems() app.preferencesDirty = true app.deferredUpdateTimer.push() DataManager.saveDB() Settings.possibleExport(nil) } @IBAction func allNewPrsPolicySelected(sender: NSPopUpButton) { Settings.displayPolicyForNewPrs = sender.indexOfSelectedItem } @IBAction func allNewIssuesPolicySelected(sender: NSPopUpButton) { Settings.displayPolicyForNewIssues = sender.indexOfSelectedItem } @IBAction func hideUncommentedRequestsSelected(sender: NSButton) { Settings.hideUncommentedItems = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func showAllCommentsSelected(sender: NSButton) { Settings.showCommentsEverywhere = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func sortOrderSelected(sender: NSButton) { Settings.sortDescending = (sender.integerValue==1) setupSortMethodMenu() DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func countOnlyListedItemsSelected(sender: NSButton) { Settings.countOnlyListedItems = (sender.integerValue==0) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func openPrAtFirstUnreadCommentSelected(sender: NSButton) { Settings.openPrAtFirstUnreadComment = (sender.integerValue==1) } @IBAction func sortMethodChanged(sender: AnyObject) { Settings.sortMethod = sortModeSelect.indexOfSelectedItem DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func showStatusItemsSelected(sender: NSButton) { Settings.showStatusItems = (sender.integerValue==1) app.deferredUpdateTimer.push() updateStatusItemsOptions() api.resetAllStatusChecks() if Settings.showStatusItems { ApiServer.resetSyncOfEverything() } } private func setupSortMethodMenu() { let m = NSMenu(title: "Sorting") if Settings.sortDescending { m.addItemWithTitle("Youngest First", action: Selector("sortMethodChanged:"), keyEquivalent: "") m.addItemWithTitle("Most Recently Active", action: Selector("sortMethodChanged:"), keyEquivalent: "") m.addItemWithTitle("Reverse Alphabetically", action: Selector("sortMethodChanged:"), keyEquivalent: "") } else { m.addItemWithTitle("Oldest First", action: Selector("sortMethodChanged:"), keyEquivalent: "") m.addItemWithTitle("Inactive For Longest", action: Selector("sortMethodChanged:"), keyEquivalent: "") m.addItemWithTitle("Alphabetically", action: Selector("sortMethodChanged:"), keyEquivalent: "") } sortModeSelect.menu = m sortModeSelect.selectItemAtIndex(Settings.sortMethod) } private func updateStatusItemsOptions() { let enable = Settings.showStatusItems makeStatusItemsSelectable.enabled = enable notifyOnStatusUpdates.enabled = enable notifyOnStatusUpdatesForAllPrs.enabled = enable statusTermMenu.enabled = enable statusTermsField.enabled = enable statusItemRefreshCounter.enabled = enable statusItemRescanLabel.alphaValue = enable ? 1.0 : 0.5 statusItemsRefreshNote.alphaValue = enable ? 1.0 : 0.5 let count = Settings.statusItemRefreshInterval statusItemRefreshCounter.integerValue = count statusItemRescanLabel.stringValue = count>1 ? "...and re-scan once every \(count) refreshes" : "...and re-scan on every refresh" } private func updateLabelOptions() { let enable = Settings.showLabels labelRefreshCounter.enabled = enable labelRescanLabel.alphaValue = enable ? 1.0 : 0.5 labelRefreshNote.alphaValue = enable ? 1.0 : 0.5 let count = Settings.labelRefreshInterval labelRefreshCounter.integerValue = count labelRescanLabel.stringValue = count>1 ? "...and re-scan once every \(count) refreshes" : "...and re-scan on every refresh" } @IBAction func labelRefreshCounterChanged(sender: NSStepper) { Settings.labelRefreshInterval = labelRefreshCounter.integerValue updateLabelOptions() } @IBAction func statusItemRefreshCountChanged(sender: NSStepper) { Settings.statusItemRefreshInterval = statusItemRefreshCounter.integerValue updateStatusItemsOptions() } @IBAction func makeStatusItemsSelectableSelected(sender: NSButton) { Settings.makeStatusItemsSelectable = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func showCreationSelected(sender: NSButton) { Settings.showCreatedInsteadOfUpdated = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func groupbyRepoSelected(sender: NSButton) { Settings.groupByRepo = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func assignedPrHandlingPolicySelected(sender: NSPopUpButton) { Settings.assignedPrHandlingPolicy = sender.indexOfSelectedItem; DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func checkForUpdatesAutomaticallySelected(sender: NSButton) { Settings.checkForUpdatesAutomatically = (sender.integerValue==1) refreshUpdatePreferences() } private func refreshUpdatePreferences() { let setting = Settings.checkForUpdatesAutomatically let interval = Settings.checkForUpdatesInterval checkForUpdatesLabel.hidden = !setting checkForUpdatesSelector.hidden = !setting checkForUpdatesSelector.integerValue = interval checkForUpdatesAutomatically.integerValue = setting ? 1 : 0 checkForUpdatesLabel.stringValue = interval<2 ? "Check every hour" : "Check every \(interval) hours" } @IBAction func checkForUpdatesIntervalChanged(sender: NSStepper) { Settings.checkForUpdatesInterval = sender.integerValue refreshUpdatePreferences() } @IBAction func launchAtStartSelected(sender: NSButton) { StartupLaunch.setLaunchOnLogin(sender.integerValue==1) } @IBAction func refreshReposSelected(sender: NSButton?) { app.prepareForRefresh() let tempContext = DataManager.tempContext() api.fetchRepositoriesToMoc(tempContext) { if ApiServer.shouldReportRefreshFailureInMoc(tempContext) { var errorServers = [String]() for apiServer in ApiServer.allApiServersInMoc(tempContext) { if apiServer.goodToGo && !apiServer.syncIsGood { errorServers.append(apiServer.label ?? "NoServerName") } } let serverNames = errorServers.joinWithSeparator(", ") let alert = NSAlert() alert.messageText = "Error" alert.informativeText = "Could not refresh repository list from \(serverNames), please ensure that the tokens you are using are valid" alert.addButtonWithTitle("OK") alert.runModal() } else { do { try tempContext.save() } catch _ { } } app.completeRefresh() } } private func selectedServer() -> ApiServer? { let selected = serverList.selectedRow if selected >= 0 { return ApiServer.allApiServersInMoc(mainObjectContext)[selected] } return nil } @IBAction func deleteSelectedServerSelected(sender: NSButton) { if let selectedServer = selectedServer(), index = indexOfObject(ApiServer.allApiServersInMoc(mainObjectContext), value: selectedServer) { mainObjectContext.deleteObject(selectedServer) serverList.reloadData() serverList.selectRowIndexes(NSIndexSet(index: min(index, serverList.numberOfRows-1)), byExtendingSelection: false) fillServerApiFormFromSelectedServer() app.deferredUpdateTimer.push() DataManager.saveDB() } } @IBAction func apiServerReportErrorSelected(sender: NSButton) { if let apiServer = selectedServer() { apiServer.reportRefreshFailures = (sender.integerValue != 0) storeApiFormToSelectedServer() } } func updateImportExportSettings() { repeatLastExportAutomatically.integerValue = Settings.autoRepeatSettingsExport ? 1 : 0 if let lastExportDate = Settings.lastExportDate, fileName = Settings.lastExportUrl?.absoluteString, unescapedName = fileName.stringByRemovingPercentEncoding { let time = itemDateFormatter.stringFromDate(lastExportDate) lastExportReport.stringValue = "Last exported \(time) to \(unescapedName)" } else { lastExportReport.stringValue = "" } } @IBAction func repeatLastExportSelected(sender: AnyObject) { Settings.autoRepeatSettingsExport = (repeatLastExportAutomatically.integerValue==1) } @IBAction func exportCurrentSettingsSelected(sender: NSButton) { let s = NSSavePanel() s.title = "Export Current Settings..." s.prompt = "Export" s.nameFieldLabel = "Settings File" s.message = "Export Current Settings..." s.extensionHidden = false s.nameFieldStringValue = "Trailer Settings" s.allowedFileTypes = ["trailerSettings"] s.beginSheetModalForWindow(self, completionHandler: { response in if response == NSFileHandlingPanelOKButton, let url = s.URL { Settings.writeToURL(url) DLog("Exported settings to %@", url.absoluteString) } }) } @IBAction func importSettingsSelected(sender: NSButton) { let o = NSOpenPanel() o.title = "Import Settings From File..." o.prompt = "Import" o.nameFieldLabel = "Settings File" o.message = "Import Settings From File..." o.extensionHidden = false o.allowedFileTypes = ["trailerSettings"] o.beginSheetModalForWindow(self, completionHandler: { response in if response == NSFileHandlingPanelOKButton, let url = o.URL { atNextEvent { app.tryLoadSettings(url, skipConfirm: Settings.dontConfirmSettingsImport) } } }) } private func colorButton(button: NSButton, withColor: NSColor) { let title = button.attributedTitle.mutableCopy() as! NSMutableAttributedString title.addAttribute(NSForegroundColorAttributeName, value: withColor, range: NSMakeRange(0, title.length)) button.attributedTitle = title } private func enableHotkeySegments() { if Settings.hotkeyEnable { colorButton(hotkeyCommandModifier, withColor: Settings.hotkeyCommandModifier ? NSColor.controlTextColor() : NSColor.disabledControlTextColor()) colorButton(hotkeyControlModifier, withColor: Settings.hotkeyControlModifier ? NSColor.controlTextColor() : NSColor.disabledControlTextColor()) colorButton(hotkeyOptionModifier, withColor: Settings.hotkeyOptionModifier ? NSColor.controlTextColor() : NSColor.disabledControlTextColor()) colorButton(hotkeyShiftModifier, withColor: Settings.hotkeyShiftModifier ? NSColor.controlTextColor() : NSColor.disabledControlTextColor()) } hotKeyContainer.hidden = !Settings.hotkeyEnable hotKeyHelp.hidden = Settings.hotkeyEnable } @IBAction func enableHotkeySelected(sender: NSButton) { Settings.hotkeyEnable = hotkeyEnable.integerValue != 0 Settings.hotkeyLetter = hotkeyLetter.titleOfSelectedItem ?? "T" Settings.hotkeyControlModifier = hotkeyControlModifier.integerValue != 0 Settings.hotkeyCommandModifier = hotkeyCommandModifier.integerValue != 0 Settings.hotkeyOptionModifier = hotkeyOptionModifier.integerValue != 0 Settings.hotkeyShiftModifier = hotkeyShiftModifier.integerValue != 0 enableHotkeySegments() app.addHotKeySupport() } private func reportNeedFrontEnd() { let alert = NSAlert() alert.messageText = "Please provide a full URL for the web front end of this server first" alert.addButtonWithTitle("OK") alert.runModal() } @IBAction func createTokenSelected(sender: NSButton) { if apiServerWebPath.stringValue.isEmpty { reportNeedFrontEnd() } else { let address = apiServerWebPath.stringValue + "/settings/tokens/new" NSWorkspace.sharedWorkspace().openURL(NSURL(string: address)!) } } @IBAction func viewExistingTokensSelected(sender: NSButton) { if apiServerWebPath.stringValue.isEmpty { reportNeedFrontEnd() } else { let address = apiServerWebPath.stringValue + "/settings/applications" NSWorkspace.sharedWorkspace().openURL(NSURL(string: address)!) } } @IBAction func viewWatchlistSelected(sender: NSButton) { if apiServerWebPath.stringValue.isEmpty { reportNeedFrontEnd() } else { let address = apiServerWebPath.stringValue + "/watching" NSWorkspace.sharedWorkspace().openURL(NSURL(string: address)!) } } @IBAction func prMergePolicySelected(sender: NSPopUpButton) { Settings.mergeHandlingPolicy = sender.indexOfSelectedItem } @IBAction func prClosePolicySelected(sender: NSPopUpButton) { Settings.closeHandlingPolicy = sender.indexOfSelectedItem } private func updateStatusTermPreferenceControls() { let mode = Settings.statusFilteringMode statusTermMenu.selectItemAtIndex(mode) if mode != 0 { statusTermsField.enabled = true statusTermsField.alphaValue = 1.0 } else { statusTermsField.enabled = false statusTermsField.alphaValue = 0.8 } statusTermsField.objectValue = Settings.statusFilteringTerms } @IBAction func statusFilterMenuChanged(sender: NSPopUpButton) { Settings.statusFilteringMode = sender.indexOfSelectedItem Settings.statusFilteringTerms = statusTermsField.objectValue as! [String] updateStatusTermPreferenceControls() app.deferredUpdateTimer.push() } @IBAction func testApiServerSelected(sender: NSButton) { sender.enabled = false let apiServer = selectedServer()! api.testApiToServer(apiServer) { error in let alert = NSAlert() if error != nil { alert.messageText = "The test failed for " + (apiServer.apiPath ?? "NoApiPath") alert.informativeText = error!.localizedDescription } else { alert.messageText = "This API server seems OK!" } alert.addButtonWithTitle("OK") alert.runModal() sender.enabled = true } } @IBAction func apiRestoreDefaultsSelected(sender: NSButton) { if let apiServer = selectedServer() { apiServer.resetToGithub() fillServerApiFormFromSelectedServer() storeApiFormToSelectedServer() } } private func fillServerApiFormFromSelectedServer() { if let apiServer = selectedServer() { apiServerName.stringValue = apiServer.label ?? "" apiServerWebPath.stringValue = apiServer.webPath ?? "" apiServerApiPath.stringValue = apiServer.apiPath ?? "" apiServerAuthToken.stringValue = apiServer.authToken ?? "" apiServerSelectedBox.title = apiServer.label ?? "New Server" apiServerTestButton.enabled = !(apiServer.authToken ?? "").isEmpty apiServerDeleteButton.enabled = (ApiServer.countApiServersInMoc(mainObjectContext) > 1) apiServerReportError.integerValue = apiServer.reportRefreshFailures.boolValue ? 1 : 0 } } private func storeApiFormToSelectedServer() { if let apiServer = selectedServer() { apiServer.label = apiServerName.stringValue apiServer.apiPath = apiServerApiPath.stringValue apiServer.webPath = apiServerWebPath.stringValue apiServer.authToken = apiServerAuthToken.stringValue apiServerTestButton.enabled = !(apiServer.authToken ?? "").isEmpty serverList.reloadData() } } @IBAction func addNewApiServerSelected(sender: NSButton) { let a = ApiServer.insertNewServerInMoc(mainObjectContext) a.label = "New API Server" serverList.reloadData() if let index = indexOfObject(ApiServer.allApiServersInMoc(mainObjectContext), value: a) { serverList.selectRowIndexes(NSIndexSet(index: index), byExtendingSelection: false) fillServerApiFormFromSelectedServer() } } @IBAction func refreshDurationChanged(sender: NSStepper?) { Settings.refreshPeriod = refreshDurationStepper.floatValue refreshDurationLabel.stringValue = "Refresh items every \(refreshDurationStepper.integerValue) seconds" } @IBAction func newRepoCheckChanged(sender: NSStepper?) { Settings.newRepoCheckPeriod = repoCheckStepper.floatValue repoCheckLabel.stringValue = "Refresh repos & teams every \(repoCheckStepper.integerValue) hours" } func windowWillClose(notification: NSNotification) { if ApiServer.someServersHaveAuthTokensInMoc(mainObjectContext) && app.preferencesDirty { app.startRefresh() } else { if app.refreshTimer == nil && Settings.refreshPeriod > 0.0 { app.startRefreshIfItIsDue() } } app.setUpdateCheckParameters() app.closedPreferencesWindow() } override func controlTextDidChange(n: NSNotification?) { if let obj: AnyObject = n?.object { if obj===apiServerName { if let apiServer = selectedServer() { apiServer.label = apiServerName.stringValue storeApiFormToSelectedServer() } } else if obj===apiServerApiPath { if let apiServer = selectedServer() { apiServer.apiPath = apiServerApiPath.stringValue storeApiFormToSelectedServer() apiServer.clearAllRelatedInfo() app.reset() } } else if obj===apiServerWebPath { if let apiServer = selectedServer() { apiServer.webPath = apiServerWebPath.stringValue storeApiFormToSelectedServer() } } else if obj===apiServerAuthToken { if let apiServer = selectedServer() { apiServer.authToken = apiServerAuthToken.stringValue storeApiFormToSelectedServer() apiServer.clearAllRelatedInfo() app.reset() } } else if obj===repoFilter { projectsTable.reloadData() } else if obj===statusTermsField { let existingTokens = Settings.statusFilteringTerms let newTokens = statusTermsField.objectValue as! [String] if existingTokens != newTokens { Settings.statusFilteringTerms = newTokens app.deferredUpdateTimer.push() } } else if obj===commentAuthorBlacklist { let existingTokens = Settings.commentAuthorBlacklist let newTokens = commentAuthorBlacklist.objectValue as! [String] if existingTokens != newTokens { Settings.commentAuthorBlacklist = newTokens } } } } ///////////// Tabs func tabView(tabView: NSTabView, willSelectTabViewItem tabViewItem: NSTabViewItem?) { if let item = tabViewItem { let newIndex = tabView.indexOfTabViewItem(item) if newIndex == 1 { if (app.lastRepoCheck.isEqualToDate(never()) || Repo.countVisibleReposInMoc(mainObjectContext) == 0) && ApiServer.someServersHaveAuthTokensInMoc(mainObjectContext) { refreshReposSelected(nil) } } Settings.lastPreferencesTabSelectedOSX = newIndex } } ///////////// Repo table func tableViewSelectionDidChange(notification: NSNotification) { if self.serverList === notification.object { fillServerApiFormFromSelectedServer() } else if self.projectsTable === notification.object { updateAllItemSettingButtons() } } private func repoForRow(row: Int) -> Repo { let parentCount = Repo.countParentRepos(repoFilter.stringValue) var r = row if r > parentCount { r-- } let filteredRepos = Repo.reposForFilter(repoFilter.stringValue) return filteredRepos[r-1] } func tableView(tv: NSTableView, shouldSelectRow row: Int) -> Bool { return !tableView(tv, isGroupRow:row) } func tableView(tv: NSTableView, willDisplayCell c: AnyObject, forTableColumn tableColumn: NSTableColumn?, row: Int) { let cell = c as! NSCell if tv === projectsTable { if tableColumn?.identifier == "repos" { if tableView(tv, isGroupRow:row) { cell.title = row==0 ? "Parent Repositories" : "Forked Repositories" cell.enabled = false } else { cell.enabled = true let r = repoForRow(row) let repoName = r.fullName ?? "NoRepoName" let title = (r.inaccessible?.boolValue ?? false) ? repoName + " (inaccessible)" : repoName let textColor = (row == tv.selectedRow) ? NSColor.selectedControlTextColor() : (r.shouldSync() ? NSColor.textColor() : NSColor.textColor().colorWithAlphaComponent(0.4)) cell.attributedStringValue = NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: textColor]) } } else { if let menuCell = cell as? NSPopUpButtonCell { menuCell.removeAllItems() if tableView(tv, isGroupRow:row) { menuCell.selectItemAtIndex(-1) menuCell.enabled = false menuCell.arrowPosition = NSPopUpArrowPosition.NoArrow } else { let r = repoForRow(row) menuCell.enabled = true menuCell.arrowPosition = NSPopUpArrowPosition.ArrowAtBottom var count = 0 let fontSize = NSFont.systemFontSizeForControlSize(NSControlSize.SmallControlSize) for policy in RepoDisplayPolicy.policies { let m = NSMenuItem() m.attributedTitle = NSAttributedString(string: policy.name(), attributes: [ NSFontAttributeName: count==0 ? NSFont.systemFontOfSize(fontSize) : NSFont.boldSystemFontOfSize(fontSize), NSForegroundColorAttributeName: policy.color(), ]) menuCell.menu?.addItem(m) count++ } let selectedIndex = tableColumn?.identifier == "prs" ? (r.displayPolicyForPrs?.integerValue ?? 0) : (r.displayPolicyForIssues?.integerValue ?? 0) menuCell.selectItemAtIndex(selectedIndex) } } } } else { let allServers = ApiServer.allApiServersInMoc(mainObjectContext) let apiServer = allServers[row] if tableColumn?.identifier == "server" { cell.title = apiServer.label ?? "NoApiServer" let tc = c as! NSTextFieldCell if apiServer.lastSyncSucceeded?.boolValue ?? false { tc.textColor = NSColor.textColor() } else { tc.textColor = NSColor.redColor() } } else { // api usage let c = cell as! NSLevelIndicatorCell c.minValue = 0 let rl = apiServer.requestsLimit?.doubleValue ?? 0.0 c.maxValue = rl c.warningValue = rl*0.5 c.criticalValue = rl*0.8 c.doubleValue = rl - (apiServer.requestsRemaining?.doubleValue ?? 0) } } } func tableView(tableView: NSTableView, isGroupRow row: Int) -> Bool { if tableView === projectsTable { return (row == 0 || row == Repo.countParentRepos(repoFilter.stringValue) + 1) } else { return false } } func numberOfRowsInTableView(tableView: NSTableView) -> Int { if tableView === projectsTable { return Repo.reposForFilter(repoFilter.stringValue).count + 2 } else { return ApiServer.countApiServersInMoc(mainObjectContext) } } func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { return nil } func tableView(tv: NSTableView, setObjectValue object: AnyObject?, forTableColumn tableColumn: NSTableColumn?, row: Int) { if tv === projectsTable { if !tableView(tv, isGroupRow: row) { let r = repoForRow(row) if let index = object?.integerValue { if tableColumn?.identifier == "prs" { r.displayPolicyForPrs = index } else if tableColumn?.identifier == "issues" { r.displayPolicyForIssues = index } if index != RepoDisplayPolicy.Hide.rawValue { r.resetSyncState() } updateDisplayIssuesSetting() } } } } }
mit
834388f2d0cd1db253c854cd81478030
36.008507
196
0.768816
4.326041
false
false
false
false
skyfe79/TIL
about.iOS/about.Swift/15.Deinitialization.playground/Contents.swift
1
1861
/*: # Deinitialization * 컴퓨터의 자원이 유한하기 때문에 이 모든 것이 필요한 것이다. */ import UIKit /*: ## How Deinitialization Works */ do { class SomeClass { deinit { // perform the deinitialization } } } /*: ## Deinitializers in Action */ do { class Bank { static var coinsInBank = 10_000 static func vendCoins(numberOfCoinsRequested: Int) -> Int { let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank) coinsInBank -= numberOfCoinsToVend return numberOfCoinsToVend } static func receiveCoins(coins: Int) { coinsInBank += coins } } class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.vendCoins(coins) } func winCoins(coins: Int) { coinsInPurse += Bank.vendCoins(coins) } deinit { Bank.receiveCoins(coinsInPurse) } } var playerOne: Player? = Player(coins: 100) print("A new player has joined the game with \(playerOne!.coinsInPurse) coins") // Prints "A new player has joined the game with 100 coins" print("There are now \(Bank.coinsInBank) coins left in the bank") // Prints "There are now 9900 coins left in the bank" playerOne!.winCoins(2_000) print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins") // Prints "PlayerOne won 2000 coins & now has 2100 coins" print("The bank now only has \(Bank.coinsInBank) coins left") // Prints "The bank now only has 7900 coins left" playerOne = nil print("PlayerOne has left the game") // Prints "PlayerOne has left the game" print("The bank now has \(Bank.coinsInBank) coins") // Prints "The bank now has 10000 coins" }
mit
54262aee29d125149710f5484cddb1e4
27.3125
83
0.611264
4.060538
false
false
false
false
martinschilliger/SwissGrid
Pods/Alamofire/Source/Timeline.swift
2
6908
// // Timeline.swift // // Copyright (c) 2014-2017 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 /// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. public struct Timeline { /// The time the request was initialized. public let requestStartTime: CFAbsoluteTime /// The time the first bytes were received from or sent to the server. public let initialResponseTime: CFAbsoluteTime /// The time when the request was completed. public let requestCompletedTime: CFAbsoluteTime /// The time when the response serialization was completed. public let serializationCompletedTime: CFAbsoluteTime /// The time interval in seconds from the time the request started to the initial response from the server. public let latency: TimeInterval /// The time interval in seconds from the time the request started to the time the request completed. public let requestDuration: TimeInterval /// The time interval in seconds from the time the request completed to the time response serialization completed. public let serializationDuration: TimeInterval /// The time interval in seconds from the time the request started to the time response serialization completed. public let totalDuration: TimeInterval /// Creates a new `Timeline` instance with the specified request times. /// /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. /// Defaults to `0.0`. /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults /// to `0.0`. /// /// - returns: The new `Timeline` instance. public init( requestStartTime: CFAbsoluteTime = 0.0, initialResponseTime: CFAbsoluteTime = 0.0, requestCompletedTime: CFAbsoluteTime = 0.0, serializationCompletedTime: CFAbsoluteTime = 0.0) { self.requestStartTime = requestStartTime self.initialResponseTime = initialResponseTime self.requestCompletedTime = requestCompletedTime self.serializationCompletedTime = serializationCompletedTime latency = initialResponseTime - requestStartTime requestDuration = requestCompletedTime - requestStartTime serializationDuration = serializationCompletedTime - requestCompletedTime totalDuration = serializationCompletedTime - requestStartTime } } // MARK: - CustomStringConvertible extension Timeline: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the latency, the request /// duration and the total duration. public var description: String { let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs", ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } } // MARK: - CustomDebugStringConvertible extension Timeline: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes the request start time, the /// initial response time, the request completed time, the serialization completed time, the latency, the request /// duration and the total duration. public var debugDescription: String { let requestStartTime = String(format: "%.3f", self.requestStartTime) let initialResponseTime = String(format: "%.3f", self.initialResponseTime) let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Request Start Time\": " + requestStartTime, "\"Initial Response Time\": " + initialResponseTime, "\"Request Completed Time\": " + requestCompletedTime, "\"Serialization Completed Time\": " + serializationCompletedTime, "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs", ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } }
mit
54b94dba1370379d315eaa4ffc445e01
50.17037
118
0.690359
5.261234
false
false
false
false
kenohori/azul4d
azul4d/Math.swift
1
3143
// azul4d // Copyright © 2016 Ken Arroyo Ohori // // 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 Metal import MetalKit func matrix4x4_perspective(fieldOfView: Float, aspectRatio: Float, nearZ: Float, farZ: Float) -> matrix_float4x4 { let ys: Float = 1.0 / tanf(fieldOfView*0.5) let xs: Float = ys / aspectRatio let zs: Float = farZ / (nearZ-farZ) return matrix_from_columns(vector4(xs, 0.0, 0.0, 0.0), vector4(0.0, ys, 0.0, 0.0), vector4(0.0, 0.0, zs, -1.0), vector4(0.0, 0.0, zs*nearZ, 0.0)) } func matrix4x4_look_at(eye: float3, centre: float3, up: float3) -> matrix_float4x4 { let z = vector_normalize(eye-centre) let x = vector_normalize(vector_cross(up, z)) let y = vector_cross(z, x) let t = vector3(-vector_dot(x, eye), -vector_dot(y, eye), -vector_dot(z, eye)) return matrix_from_columns(vector4(x.x, y.x, z.x, 0.0), vector4(x.y, y.y, z.y, 0.0), vector4(x.z, y.z, z.z, 0.0), vector4(t.x, t.y, t.z, 1.0)) } func matrix4x4_rotation(angle: Float, axis: float3) -> matrix_float4x4 { let normalisedAxis = vector_normalize(axis) if normalisedAxis.x.isNaN || normalisedAxis.y.isNaN || normalisedAxis.z.isNaN { return matrix_identity_float4x4 } let ct = cosf(angle) let st = sinf(angle) let ci = 1 - ct let x = normalisedAxis.x let y = normalisedAxis.y let z = normalisedAxis.z return matrix_from_columns(vector4(ct + x * x * ci, y * x * ci + z * st, z * x * ci - y * st, 0), vector4(x * y * ci - z * st, ct + y * y * ci, z * y * ci + x * st, 0), vector4(x * z * ci + y * st, y * z * ci - x * st, ct + z * z * ci, 0), vector4(0.0, 0.0, 0.0, 1.0)) } func matrix4x4_translation(shift: float3) -> matrix_float4x4 { return matrix_from_columns(vector4(1.0, 0.0, 0.0, 0.0), vector4(0.0, 1.0, 0.0, 0.0), vector4(0.0, 0.0, 1.0, 0.0), vector4(shift.x, shift.y, shift.z, 1.0)) } func matrix_upper_left_3x3(matrix: matrix_float4x4) -> matrix_float3x3 { return matrix_from_columns(vector3(matrix.columns.0.x, matrix.columns.0.y, matrix.columns.0.z), vector3(matrix.columns.1.x, matrix.columns.1.y, matrix.columns.1.z), vector3(matrix.columns.2.x, matrix.columns.2.y, matrix.columns.2.z)) }
gpl-3.0
5f640040fc1c9ba3ca1f1659a66ff0d7
44.536232
114
0.586887
3.09252
false
false
false
false
chen392356785/DouyuLive
DouyuLive/DouyuLive/Classes/Main/View/PageTitleView.swift
1
6282
// // PageTitleView.swift // DouyuLive // // Created by chenxiaolei on 2016/9/29. // Copyright © 2016年 chenxiaolei. All rights reserved. // import UIKit protocol PageTitleViewDelegate: class { func pageTitleView(titleView: PageTitleView, selectedIndex: Int) } private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) class PageTitleView: UIView { //MARK:- 定义属性 private var currentIndex : Int = 0 private var titles: [String] weak var delegate: PageTitleViewDelegate? // MARK:- 懒加载属性 private lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false; scrollView.scrollsToTop = false; scrollView.bounces = false; return scrollView; }() private lazy var scrollLine: UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() private lazy var titleLabels : [UILabel] = [UILabel]() //MARK:- 自定义构造函数 init(frame: CGRect, titles: [String]) { self.titles = titles; super.init(frame: frame); // 设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:- 设置UI界面 private func setupUI() { // 1.添加UIScrollView addSubview(scrollView) scrollView.frame = bounds; // 2.添加titles对应的Label上 setupTitleLables() // 3.设置底线和滚动的滑块 setupBottomMenuAndScrollLine() } private func setupTitleLables() { // 0.确定label的一些frame的值 let LabelW: CGFloat = frame.width / CGFloat(titles.count) let LabelH: CGFloat = frame.height - kScrollLineH let LabelY: CGFloat = 0 for (index, title) in titles.enumerated() { // 1. 创建UILabel let label = UILabel() // 2.设置Lable的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center // 3.设置label的frame let LabelX: CGFloat = LabelW * CGFloat(index) label.frame = CGRect(x: LabelX, y: LabelY, width: LabelW, height: LabelH) // 4.将lable添加到scrollView中 scrollView.addSubview(label) titleLabels.append(label) // 5.给Label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } private func setupBottomMenuAndScrollLine() { // 1.添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) // 2.添加scrollLine // 2.1.获取第一个Label guard let firstLabel = titleLabels.first else { return} firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } //MARK:-监听label的点击 @objc private func titleLabelClick(tapGes : UITapGestureRecognizer) { // 1.获取当前Label guard let currentLabel = tapGes.view as? UILabel else { return } if currentLabel.tag == currentIndex {return} // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) // 4.保存最新Label的下标识 currentIndex = currentLabel.tag // 5.滚动条位置发生改变 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollLineX } // 6.通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } //MARK:- 对外界暴露的方法 func setTitleWithProgress(progress : CGFloat, sourceIndex: Int, targetIndex: Int) { // 1.取出sourceIndex/targetIndex let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 2.处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 3.处理颜色渐变(复杂) // 3.1取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 3.2变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex } }
mit
6500c049f63f6e1e04744f619bbeb014
31.889503
174
0.601881
4.724603
false
false
false
false
CanyFrog/HCComponent
HCSource/UIView+Extension.swift
1
914
// // UIView+Extension.swift // HCComponents // // Created by huangcong on 2017/4/26. // Copyright © 2017年 Person Inc. All rights reserved. // import Foundation extension UIView { public var viewController: UIViewController? { var view = self repeat { let nextResponder = view.next if nextResponder?.isKind(of: UIViewController.self) == true { return nextResponder as? UIViewController } else { view = view.superview! } } while (view.superview != nil && view.next != nil) return nil } public func removeAllSubviews() { _ = subviews.map { $0.removeFromSuperview() } } public class func autolayoutInit() -> Self { let view = self.init() view.translatesAutoresizingMaskIntoConstraints = false return view } }
mit
ff730ccc9c4b1bd71c744b8590b2bd50
24.305556
73
0.572997
4.871658
false
false
false
false
sharath-cliqz/browser-ios
Storage/SQL/Cliqz/BrowserDBExtension.swift
2
3732
// // BrowserDBExtension.swift // Client // // Created by Sahakyan on 6/1/16. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation import Deferred import Shared public let NotificationDatabaseWasCreated = "NotificationDatabaseWasCreated" let TableHiddenTopSites = "hidden_top_sites" extension BrowserDB { func extendTables() { createHiddenTopSitesTable() extendBookmarksTable() } fileprivate func createHiddenTopSitesTable() { let hiddenTopSitesTableCreate = "CREATE TABLE IF NOT EXISTS \(TableHiddenTopSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT UNIQUE " + ")" self.run([hiddenTopSitesTableCreate]) } fileprivate func extendBookmarksTable() { let columnName = "bookmarked_date" guard !isColumnExist(TableBookmarksLocal, columnName: columnName) else { return } self.alterTableWithExtraColumn(TableBookmarksLocal, columnName: columnName) self.migrateOldBookmarks() } fileprivate func alterTableWithExtraColumn(_ tableName: String, columnName: String) -> Success { return self.run([ ("ALTER TABLE \(tableName) ADD COLUMN \(columnName) INTEGER NOT NULL DEFAULT 0", nil) ]) } fileprivate func isColumnExist(_ tableName: String, columnName: String) -> Bool { let tableInfoSQL = "PRAGMA table_info(\(tableName))" let result = self.runQuery(tableInfoSQL, args: nil, factory: BrowserDB.columnNameFactory).value if let columnNames = result.successValue { for tableColumnName in columnNames { if tableColumnName == columnName { return true } } } return false } fileprivate class func columnNameFactory(_ row: SDRow) -> String { let columnName = row["name"] as! String return columnName } fileprivate func migrateOldBookmarks() { if isColumnExist(TableVisits, columnName: "favorite") { let fetchFavoritesSQL = "SELECT \(TableVisits).id, \(TableVisits).date, \(TableHistory).url, \(TableHistory).title " + "FROM \(TableHistory) " + "INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " + "WHERE \(TableVisits).favorite = 1 " let results = self.runQuery(fetchFavoritesSQL, args: nil, factory: SQLiteHistory.historyVisitsFactory).value if let favs = results.successValue { for f in favs { if !isURLBookmarked(f?.url) { let newGUID = Bytes.generateGUID() let args: Args = [ newGUID as AnyObject?, BookmarkNodeType.bookmark.rawValue as AnyObject?, f?.url as AnyObject?, f?.title as AnyObject?, BookmarkRoots.MobileFolderGUID as AnyObject?, BookmarksFolderTitleMobile as AnyObject?, NSNumber(value: (f?.latestVisit?.date)! / 1000), SyncStatus.new.rawValue as AnyObject?, NSNumber(value: (f?.latestVisit?.date)! / 1000), f?.url as AnyObject? ] let insertSQL = "INSERT INTO \(TableBookmarksLocal) " + "(guid, type, bmkUri, title, parentid, parentName, local_modified, sync_status, bookmarked_date, faviconID) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT iconID FROM \(ViewIconForURL) WHERE url = ?))" self.run(insertSQL, withArgs: args) } } } } } fileprivate func idFactory(_ row: SDRow) -> Int { return row[0] as! Int } fileprivate func isURLBookmarked(_ url: String?) -> Bool { guard let u = url else { return false } let urlArgs: Args = [ u as Optional<AnyObject> ] let isBookmarkedURLSQL = "SELECT id FROM \(TableBookmarksLocal) WHERE bmkUri = ?" guard let v = self.runQuery(isBookmarkedURLSQL, args: urlArgs, factory: idFactory).value.successValue, v.asArray().count > 0 else { return false } return true } }
mpl-2.0
bb4f1133abc4feeac91d184cede92fe9
29.834711
121
0.677298
3.923239
false
false
false
false
TerryCK/GogoroBatteryMap
GogoroMap/Myplayground.playground/Sources/BatteryStationPointAnnotation.swift
1
1470
// // BatteryStationPointAnnotation.swift // GogoroMap // // Created by 陳 冠禎 on 23/02/2019. // Copyright © 2019 陳 冠禎. All rights reserved. // import UIKit import MapKit public protocol BatteryStationPointAnnotationProtocol: Hashable { func merge(newStations: [Self], oldStations: [Self]) -> [Self] } public extension BatteryStationPointAnnotationProtocol where Self: MKPointAnnotation { func merge(newStations: [Self], oldStations: [Self]) -> [Self] { return Array(Set<Self>(oldStations).intersection(newStations).union(newStations)) } } public final class BatteryStationPointAnnotation: MKPointAnnotation, BatteryStationPointAnnotationProtocol { public let image: UIImage, placemark: MKPlacemark, address: String, isOpening: Bool public var checkinCounter: Int? = nil, checkinDay: String? = nil public init(station: ResponseStationProtocol) { let name = station.name.localized() ?? "" let location = CLLocationCoordinate2D(latitude: station.latitude, longitude: station.longitude) placemark = MKPlacemark(coordinate: location, addressDictionary: [name: ""]) image = station.annotationImage address = station.address.localized() ?? "" isOpening = station.isOpening super.init() title = name subtitle = "\("Open hours:") \(station.availableTime ?? "")" coordinate = location } }
mit
646244561d67b6b53e2b968a409c3d80
32.883721
108
0.678106
4.442073
false
false
false
false
gouyz/GYZBaking
baking/Pods/Cosmos/Cosmos/CosmosView.swift
4
11149
import UIKit /** A star rating view that can be used to show customer rating for the products. On can select stars by tapping on them when updateOnTouch settings is true. An optional text can be supplied that is shown on the right side. Example: cosmosView.rating = 4 cosmosView.text = "(123)" Shows: ★★★★☆ (132) */ @IBDesignable open class CosmosView: UIView { /** The currently shown number of stars, usually between 1 and 5. If the value is decimal the stars will be shown according to the Fill Mode setting. */ @IBInspectable open var rating: Double = CosmosDefaultSettings.rating { didSet { if oldValue != rating { update() } } } /// Currently shown text. Set it to nil to display just the stars without text. @IBInspectable open var text: String? { didSet { if oldValue != text { update() } } } /// Star rating settings. open var settings = CosmosSettings() { didSet { update() } } /// Stores calculated size of the view. It is used as intrinsic content size. private var viewSize = CGSize() /// Draws the stars when the view comes out of storyboard with default settings open override func awakeFromNib() { super.awakeFromNib() update() } /** Initializes and returns a newly allocated cosmos view object. */ convenience public init() { self.init(frame: CGRect()) } /** Initializes and returns a newly allocated cosmos view object with the specified frame rectangle. - parameter frame: The frame rectangle for the view. */ override public init(frame: CGRect) { super.init(frame: frame) update() self.frame.size = intrinsicContentSize improvePerformance() } /// Initializes and returns a newly allocated cosmos view object. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) improvePerformance() } /// Change view settings for faster drawing private func improvePerformance() { /// Cache the view into a bitmap instead of redrawing the stars each time layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale isOpaque = true } /** Updates the stars and optional text based on current values of `rating` and `text` properties. */ open func update() { // Create star layers // ------------ var layers = CosmosLayers.createStarLayers( rating, settings: settings, isRightToLeft: RightToLeft.isRightToLeft(self) ) // Create text layer // ------------ if let text = text { let textLayer = createTextLayer(text, layers: layers) layers = addTextLayer(textLayer: textLayer, layers: layers) } layer.sublayers = layers // Update size // ------------ updateSize(layers) // Update accesibility // ------------ updateAccessibility() } /** Creates the text layer for the given text string. - parameter text: Text string for the text layer. - parameter layers: Arrays of layers containing the stars. - returns: The newly created text layer. */ private func createTextLayer(_ text: String, layers: [CALayer]) -> CALayer { let textLayer = CosmosLayerHelper.createTextLayer(text, font: settings.textFont, color: settings.textColor) let starsSize = CosmosSize.calculateSizeToFitLayers(layers) if RightToLeft.isRightToLeft(self) { CosmosText.position(textLayer, starsSize: CGSize(width: 0, height: starsSize.height), textMargin: 0) } else { CosmosText.position(textLayer, starsSize: starsSize, textMargin: settings.textMargin) } layer.addSublayer(textLayer) return textLayer } /** Adds text layer to the array of layers - parameter textLayer: A text layer. - parameter layers: An array where the text layer will be added. - returns: An array of layer with the text layer. */ private func addTextLayer(textLayer: CALayer, layers: [CALayer]) -> [CALayer] { var allLayers = layers // Position stars after the text for right-to-left languages if RightToLeft.isRightToLeft(self) { for starLayer in layers { starLayer.position.x += textLayer.bounds.width + CGFloat(settings.textMargin); } allLayers.insert(textLayer, at: 0) } else { allLayers.append(textLayer) } return allLayers } /** Updates the size to fit all the layers containing stars and text. - parameter layers: Array of layers containing stars and the text. */ private func updateSize(_ layers: [CALayer]) { viewSize = CosmosSize.calculateSizeToFitLayers(layers) invalidateIntrinsicContentSize() } /// Returns the content size to fit all the star and text layers. override open var intrinsicContentSize:CGSize { return viewSize } // MARK: - Accessibility private func updateAccessibility() { CosmosAccessibility.update(self, rating: rating, text: text, settings: settings) } /// Called by the system in accessibility voice-over mode when the value is incremented by the user. open override func accessibilityIncrement() { super.accessibilityIncrement() rating += CosmosAccessibility.accessibilityIncrement(rating, settings: settings) didTouchCosmos?(rating) didFinishTouchingCosmos?(rating) } /// Called by the system in accessibility voice-over mode when the value is decremented by the user. open override func accessibilityDecrement() { super.accessibilityDecrement() rating -= CosmosAccessibility.accessibilityDecrement(rating, settings: settings) didTouchCosmos?(rating) didFinishTouchingCosmos?(rating) } // MARK: - Touch recognition /// Closure will be called when user touches the cosmos view. The touch rating argument is passed to the closure. open var didTouchCosmos: ((Double)->())? /// Closure will be called when the user lifts finger from the cosmos view. The touch rating argument is passed to the closure. open var didFinishTouchingCosmos: ((Double)->())? /// Overriding the function to detect the first touch gesture. open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard let location = touchLocationFromBeginningOfRating(touches) else { return } onDidTouch(location) } /// Overriding the function to detect touch move. open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) guard let location = touchLocationFromBeginningOfRating(touches) else { return } onDidTouch(location) } /// Returns the distance of the touch relative to the left edge of the first star func touchLocationFromBeginningOfRating(_ touches: Set<UITouch>) -> CGFloat? { guard let touch = touches.first else { return nil } var location = touch.location(in: self).x // In right-to-left languages, the first star will be on the right if RightToLeft.isRightToLeft(self) { location = bounds.width - location } return location } /// Detecting event when the user lifts their finger. open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) didFinishTouchingCosmos?(rating) } /** Called when the view is touched. - parameter locationX: The horizontal location of the touch relative to the width of the stars. - parameter starsWidth: The width of the stars excluding the text. */ func onDidTouch(_ locationX: CGFloat) { let calculatedTouchRating = CosmosTouch.touchRating(locationX, settings: settings) if settings.updateOnTouch { rating = calculatedTouchRating } if calculatedTouchRating == previousRatingForDidTouchCallback { // Do not call didTouchCosmos if rating has not changed return } didTouchCosmos?(calculatedTouchRating) previousRatingForDidTouchCallback = calculatedTouchRating } private var previousRatingForDidTouchCallback: Double = -123.192 /// Increase the hitsize of the view if it's less than 44px for easier touching. override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let oprimizedBounds = CosmosTouchTarget.optimize(bounds) return oprimizedBounds.contains(point) } // MARK: - Properties inspectable from the storyboard @IBInspectable var totalStars: Int = CosmosDefaultSettings.totalStars { didSet { settings.totalStars = totalStars } } @IBInspectable var starSize: Double = CosmosDefaultSettings.starSize { didSet { settings.starSize = starSize } } @IBInspectable var filledColor: UIColor = CosmosDefaultSettings.filledColor { didSet { settings.filledColor = filledColor } } @IBInspectable var emptyColor: UIColor = CosmosDefaultSettings.emptyColor { didSet { settings.emptyColor = emptyColor } } @IBInspectable var emptyBorderColor: UIColor = CosmosDefaultSettings.emptyBorderColor { didSet { settings.emptyBorderColor = emptyBorderColor } } @IBInspectable var emptyBorderWidth: Double = CosmosDefaultSettings.emptyBorderWidth { didSet { settings.emptyBorderWidth = emptyBorderWidth } } @IBInspectable var filledBorderColor: UIColor = CosmosDefaultSettings.filledBorderColor { didSet { settings.filledBorderColor = filledBorderColor } } @IBInspectable var filledBorderWidth: Double = CosmosDefaultSettings.filledBorderWidth { didSet { settings.filledBorderWidth = filledBorderWidth } } @IBInspectable var starMargin: Double = CosmosDefaultSettings.starMargin { didSet { settings.starMargin = starMargin } } @IBInspectable var fillMode: Int = CosmosDefaultSettings.fillMode.rawValue { didSet { settings.fillMode = StarFillMode(rawValue: fillMode) ?? CosmosDefaultSettings.fillMode } } @IBInspectable var textSize: Double = CosmosDefaultSettings.textSize { didSet { settings.textFont = settings.textFont.withSize(CGFloat(textSize)) } } @IBInspectable var textMargin: Double = CosmosDefaultSettings.textMargin { didSet { settings.textMargin = textMargin } } @IBInspectable var textColor: UIColor = CosmosDefaultSettings.textColor { didSet { settings.textColor = textColor } } @IBInspectable var updateOnTouch: Bool = CosmosDefaultSettings.updateOnTouch { didSet { settings.updateOnTouch = updateOnTouch } } @IBInspectable var minTouchRating: Double = CosmosDefaultSettings.minTouchRating { didSet { settings.minTouchRating = minTouchRating } } /// Draw the stars in interface buidler open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() update() } }
mit
7e8bd0e36db4626750e0f5c3ac59f0a7
26.8475
219
0.686686
4.944075
false
false
false
false
calebd/swift
validation-test/Reflection/inherits_ObjCClasses.swift
1
6556
// RUN: %empty-directory(%t) // RUN: %clang %target-cc-options -isysroot %sdk -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o // RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ -lswiftSwiftReflectionTest %t/ObjCClasses.o %s -o %t/inherits_ObjCClasses // RUN: %target-run %target-swift-reflection-test %t/inherits_ObjCClasses | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test import simd import ObjCClasses import SwiftReflectionTest //// FirstClass -- base class, has one word-sized ivar // Variant A: 16 byte alignment class FirstClassA : FirstClass { var xx: int4 = [1,2,3,4] } let firstClassA = FirstClassA() reflect(object: firstClassA) // CHECK-64: Type reference: // CHECK-64: (class inherits_ObjCClasses.FirstClassA) // CHECK-64: Type info: // CHECK-64: (class_instance size=32 alignment=16 stride=32 num_extra_inhabitants=0 // CHECK-64: (field name=xx offset=16 // CHECK-64: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_ObjCClasses.FirstClassA) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=32 alignment=16 stride=32 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=xx offset=16 // CHECK-32-NEXT: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0))) // Variant B: word size alignment class FirstClassB : FirstClass { var zz: Int = 0 } let firstClassB = FirstClassB() reflect(object: firstClassB) // CHECK-64: Type reference: // CHECK-64: (class inherits_ObjCClasses.FirstClassB) // CHECK-64: Type info: // CHECK-64: (class_instance size=24 alignment=8 stride=24 num_extra_inhabitants=0 // CHECK-64: (field name=zz offset=16 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_ObjCClasses.FirstClassB) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=zz offset=12 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))) //// SecondClass -- base class, has two word-sized ivars // Variant A: 16 byte alignment class SecondClassA : SecondClass { var xx: int4 = [1,2,3,4] } let secondClassA = SecondClassA() reflect(object: secondClassA) // CHECK-64: Type reference: // CHECK-64: (class inherits_ObjCClasses.SecondClassA) // CHECK-64: Type info: // CHECK-64: (class_instance size=48 alignment=16 stride=48 num_extra_inhabitants=0 // CHECK-64: (field name=xx offset=32 // CHECK-64: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_ObjCClasses.SecondClassA) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=32 alignment=16 stride=32 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=xx offset=16 // CHECK-32-NEXT: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0))) // Variant B: word size alignment class SecondClassB : SecondClass { var zz: Int = 0 } let secondClassB = SecondClassB() reflect(object: secondClassB) // CHECK-64: Type reference: // CHECK-64: (class inherits_ObjCClasses.SecondClassB) // CHECK-64: Type info: // CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 // CHECK-64: (field name=zz offset=24 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_ObjCClasses.SecondClassB) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=zz offset=12 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))) //// ThirdClass -- base class, has three word-sized ivars // Variant A: 16 byte alignment class ThirdClassA : ThirdClass { var xx: int4 = [1,2,3,4] } let thirdClassA = ThirdClassA() reflect(object: thirdClassA) // CHECK-64: Type reference: // CHECK-64: (class inherits_ObjCClasses.ThirdClassA) // CHECK-64: Type info: // CHECK-64: (class_instance size=48 alignment=16 stride=48 num_extra_inhabitants=0 // CHECK-64: (field name=xx offset=32 // CHECK-64: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_ObjCClasses.ThirdClassA) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=32 alignment=16 stride=32 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=xx offset=16 // CHECK-32-NEXT: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0))) // Variant B: word size alignment class ThirdClassB : ThirdClass { var zz: Int = 0 } let thirdClassB = ThirdClassB() reflect(object: thirdClassB) // CHECK-64: Type reference: // CHECK-64: (class inherits_ObjCClasses.ThirdClassB) // CHECK-64: Type info: // CHECK-64: (class_instance size=40 alignment=8 stride=40 num_extra_inhabitants=0 // CHECK-64: (field name=zz offset=32 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_ObjCClasses.ThirdClassB) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=zz offset=16 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))) doneReflecting()
apache-2.0
e22b66ca5627b2cf425624545c751609
35.021978
147
0.710647
3.182524
false
false
false
false
Aufree/ESTMusicIndicator
Classes/ESTMusicIndicatorContentView.swift
1
7594
// // ESTMusicIndicatorContentView.swift // ESTMusicIndicator // // Created by Aufree on 12/6/15. // Copyright © 2015 The EST Group. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class ESTMusicIndicatorContentView: UIView { private let kBarCount = 3 private let kBarWidth:CGFloat = 3.0 private let kBarIdleHeight:CGFloat = 3.0 private let kHorizontalBarSpacing:CGFloat = 2.0 // Measured on iPad 2 (non-Retina) private let kRetinaHorizontalBarSpacing:CGFloat = 1.5 // Measured on iPhone 5s (Retina) private let kBarMinPeakHeight:CGFloat = 6.0 private let kBarMaxPeakHeight:CGFloat = 12.0 private let kMinBaseOscillationPeriod = CFTimeInterval(0.6) private let kMaxBaseOscillationPeriod = CFTimeInterval(0.8) private let kOscillationAnimationKey:String = "oscillation" private let kDecayDuration = CFTimeInterval(0.3) private let kDecayAnimationKey:String = "decay" var barLayers = [CALayer]() var hasInstalledConstraints: Bool = false override init(frame: CGRect) { super.init(frame: frame) translatesAutoresizingMaskIntoConstraints = false prepareBarLayers() tintColorDidChange() setNeedsUpdateConstraints() } convenience init() { self.init(frame:CGRect.zero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func prepareBarLayers() { var xOffset:CGFloat = 0.0 for i in 1...kBarCount { let newLayer = createBarLayerWithXOffset(xOffset, layerIndex: i) barLayers.append(newLayer) layer.addSublayer(newLayer) xOffset = newLayer.frame.maxX + horizontalBarSpacing() } } private func createBarLayerWithXOffset(_ xOffset: CGFloat, layerIndex: Int) -> CALayer { let layer: CALayer = CALayer() layer.anchorPoint = CGPoint(x: 0.0, y: 1.0) // At the bottom-left corner layer.position = CGPoint(x: xOffset, y: kBarMaxPeakHeight) // In superview's coordinate layer.bounds = CGRect(x: 0.0, y: 0.0, width: kBarWidth, height: (CGFloat(layerIndex) * kBarMaxPeakHeight/CGFloat(kBarCount))) // In its own coordinate } return layer } private func horizontalBarSpacing() -> CGFloat { if UIScreen.main.scale == 2.0 { return kRetinaHorizontalBarSpacing } else { return kHorizontalBarSpacing } } override func tintColorDidChange() { for layer in barLayers{ layer.backgroundColor = tintColor.cgColor } } override var intrinsicContentSize : CGSize { var unionFrame:CGRect = CGRect.zero for layer in barLayers { unionFrame = unionFrame.union(layer.frame) } return unionFrame.size; } override func updateConstraints() { if !hasInstalledConstraints { let size = intrinsicContentSize addConstraint(NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: size.width)); addConstraint(NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: size.height)); hasInstalledConstraints = true } super.updateConstraints() } func startOscillation() { let basePeriod = kMinBaseOscillationPeriod + (drand48() * (kMaxBaseOscillationPeriod - kMinBaseOscillationPeriod)) for layer in barLayers { startOscillatingBarLayer(layer, basePeriod: basePeriod) } } func stopOscillation() { for layer in barLayers { layer.removeAnimation(forKey: kOscillationAnimationKey) } } func isOscillating() -> Bool { if let _ = barLayers.first?.animation(forKey: kOscillationAnimationKey) { return true } else { return false } } func startDecay() { for layer in barLayers { startDecayingBarLayer(layer) } } func stopDecay() { for layer in barLayers { layer.removeAnimation(forKey: kDecayAnimationKey) } } private func startOscillatingBarLayer(_ layer: CALayer, basePeriod: CFTimeInterval) { // arc4random_uniform() will return a uniformly distributed random number **less** upper_bound. let peakHeight: CGFloat = kBarMinPeakHeight + CGFloat(arc4random_uniform(UInt32(kBarMaxPeakHeight - kBarMinPeakHeight + 1))) var fromBouns = layer.bounds; fromBouns.size.height = kBarIdleHeight; var toBounds: CGRect = layer.bounds toBounds.size.height = peakHeight let animation: CABasicAnimation = CABasicAnimation(keyPath: "bounds") animation.fromValue = NSValue(cgRect:fromBouns) animation.toValue = NSValue(cgRect:toBounds) animation.repeatCount = Float.infinity // Forever animation.autoreverses = true animation.duration = TimeInterval((CGFloat(basePeriod) / 2) * (kBarMaxPeakHeight / peakHeight)) animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseIn) layer.add(animation, forKey: kOscillationAnimationKey) } private func startDecayingBarLayer(_ layer: CALayer) { let animation: CABasicAnimation = CABasicAnimation(keyPath: "bounds") if let presentation = layer.presentation() { animation.fromValue = NSValue(cgRect:CALayer(layer: presentation).bounds) } animation.toValue = NSValue(cgRect:layer.bounds) animation.duration = kDecayDuration animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut) layer.add(animation, forKey: kDecayAnimationKey) } }
mit
48081a9c4de50a3306399449807b2c3d
37.739796
160
0.623601
5.092555
false
false
false
false
couchbits/iOSToolbox
Sources/Extensions/UIKit/UISwipeGestureRecognizerExtensions.swift
1
1305
// // UISwipeGestureRecognizerExtensions.swift // iOSToolbox // // Created by Dominik Gauggel on 12.03.19. // import Foundation import UIKit private var SwipeBlockHandlerKey: UInt8 = 0 extension UISwipeGestureRecognizer { public convenience init(swipe: ((UISwipeGestureRecognizer) -> Void)? = nil) { self.init() initializeHandler(swipe) } public var swipe: ((UISwipeGestureRecognizer) -> Void)? { get { return blockHandler?.blockHandler } set { initializeHandler(newValue) } } internal var blockHandler: GenericBlockHandler<UISwipeGestureRecognizer>? { get { return getAssociated(associativeKey: &SwipeBlockHandlerKey) } set { setAssociated(value: newValue, associativeKey: &SwipeBlockHandlerKey) } } internal func initializeHandler(_ handler: ((UISwipeGestureRecognizer) -> Void)?) { if let handler = blockHandler { removeTarget(handler, action: GenericBlockHandlerAction) } if let handler = handler { blockHandler = GenericBlockHandler(object: self, blockHandler: handler) if let blockHandler = blockHandler { addTarget(blockHandler, action: GenericBlockHandlerAction) } } } }
mit
9f7c7227982b36289aea2236e642fb2e
28
87
0.650575
5.178571
false
false
false
false
ngageoint/mage-ios
Mage/Extensions/KeyboardHelper.swift
1
1864
extension KeyboardHelper { enum Animation { case keyboardWillShow case keyboardWillHide case keyboardDidShow } typealias HandleBlock = (_ animation: Animation, _ keyboardFrame: CGRect, _ duration: TimeInterval) -> Void } final class KeyboardHelper { private let handleBlock: HandleBlock init(handleBlock: @escaping HandleBlock) { self.handleBlock = handleBlock setupNotification() } deinit { NotificationCenter.default.removeObserver(self) } private func setupNotification() { _ = NotificationCenter.default .addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] notification in self?.handle(animation: .keyboardWillShow, notification: notification) } _ = NotificationCenter.default .addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] notification in self?.handle(animation: .keyboardWillHide, notification: notification) } _ = NotificationCenter.default .addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { [weak self] notification in self?.handle(animation: .keyboardDidShow, notification: notification) } } private func handle(animation: Animation, notification: Notification) { guard let userInfo = notification.userInfo, let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return } handleBlock(animation, keyboardFrame, duration) } }
apache-2.0
df6a3ed34b9c5db70e8e8aa586708fc7
37.833333
132
0.659335
5.880126
false
false
false
false
timelessg/TLStoryCamera
TLStoryCameraFramework/TLStoryCameraFramework/Class/Views/TLStoryBottomImagePickerView.swift
1
8837
// // TLStoryBottomImagePickerView.swift // TLStoryCamera // // Created by GarryGuo on 2017/6/1. // Copyright © 2017年 GarryGuo. All rights reserved. // import UIKit import Photos protocol TLStoryBottomImagePickerViewDelegate: NSObjectProtocol { func photoLibraryPickerDidSelectVideo(url:URL) func photoLibraryPickerDidSelectPhoto(image:UIImage) } class TLStoryBottomImagePickerView: UIView { public weak var delegate:TLStoryBottomImagePickerViewDelegate? fileprivate var collectionView:UICollectionView? fileprivate var hintLabel:UILabel = { let label = UILabel.init() label.font = UIFont.systemFont(ofSize: 12) label.textColor = UIColor.init(colorHex: 0xffffff, alpha: 0.6) label.textAlignment = .center label.numberOfLines = 0 return label }() fileprivate var authorizationBtn:TLButton = { let btn = TLButton.init(type: UIButtonType.custom) btn.setTitle("允许访问照片", for: .normal) btn.setTitleColor(UIColor.init(colorHex: 0x4797e1, alpha: 1), for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 15) btn.isHidden = true return btn }() fileprivate var imgs = [PHAsset]() override init(frame: CGRect) { super.init(frame: frame) let collectionHeight = self.height - 23 let layout = UICollectionViewFlowLayout.init() layout.itemSize = CGSize.init(width: 80, height: collectionHeight) layout.minimumLineSpacing = 5 layout.scrollDirection = .horizontal collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 23, width: self.width, height: collectionHeight), collectionViewLayout: layout) collectionView!.backgroundColor = UIColor.clear collectionView!.delegate = self collectionView!.dataSource = self; collectionView!.showsHorizontalScrollIndicator = false collectionView!.register(TLPhotoLibraryPickerCell.self, forCellWithReuseIdentifier: "cell") self.addSubview(collectionView!) self.addSubview(hintLabel) self.addSubview(authorizationBtn) authorizationBtn.addTarget(self, action: #selector(requestAlbumAuthorization), for: .touchUpInside) authorizationBtn.sizeToFit() authorizationBtn.center = CGPoint.init(x: self.width / 2, y: self.height - authorizationBtn.height / 2 - 30) } public func loadPhotos() { if !TLAuthorizedManager.checkAuthorization(with: .album) { self.hintLabel.text = "要将最新的照片和视频加入故事,请允许\n访问照片" self.hintLabel.font = UIFont.systemFont(ofSize: 15) self.hintLabel.sizeToFit() self.hintLabel.center = CGPoint.init(x: self.width / 2, y: 20 + self.hintLabel.height / 2) self.authorizationBtn.isHidden = false }else { self.imgs.removeAll() let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: false)] let results = PHAsset.fetchAssets(with: options) let dayLate = NSDate().timeIntervalSince1970 - 24 * 60 * 60 var count = 0 while count < results.count { let r = results[count] if r.creationDate?.timeIntervalSince1970 ?? 0 > dayLate { self.imgs.append(r) } count += 1 } if self.imgs.count > 0 { self.hintLabel.text = "过去24小时" self.hintLabel.font = UIFont.systemFont(ofSize: 12) self.hintLabel.sizeToFit() self.hintLabel.center = CGPoint.init(x: self.width / 2, y: 23 / 2) }else { self.hintLabel.text = "过去24小时内没有照片" self.hintLabel.font = UIFont.systemFont(ofSize: 12) self.hintLabel.sizeToFit() self.hintLabel.center = CGPoint.init(x: self.width / 2, y: self.height / 2) } self.authorizationBtn.isHidden = true self.collectionView?.reloadData() } } @objc fileprivate func requestAlbumAuthorization() { TLAuthorizedManager.requestAuthorization(with: .album) { (type, success) in self.loadPhotos() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TLStoryBottomImagePickerView: UICollectionViewDelegate, UICollectionViewDataSource { internal func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imgs.count } internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TLPhotoLibraryPickerCell cell.set(asset: self.imgs[indexPath.row]) return cell } internal func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let asset = self.imgs[indexPath.row] print(asset.mediaType) if asset.mediaType == .video { PHImageManager.default().requestAVAsset(forVideo: asset, options: nil) { (ass, mix, map) in guard let url = (ass as? AVURLAsset)?.url else { return } DispatchQueue.main.async { self.delegate?.photoLibraryPickerDidSelectVideo(url: url) } } } if asset.mediaType == .image { let imgSize = CGSize.init(width: asset.pixelWidth, height: asset.pixelHeight) let scale = imgSize.width / imgSize.height; let targetSize = TLStoryConfiguration.outputPhotoSize let newWidth = max(min(imgSize.width, targetSize.width), targetSize.width); let newHeight = max(min(imgSize.height, targetSize.height), targetSize.height); let newSize = scale > 1 ? CGSize.init(width: newWidth, height: newWidth / scale) : CGSize.init(width: newHeight * scale, height: newHeight) let option = PHImageRequestOptions.init(); option.isSynchronous = true option.isNetworkAccessAllowed = true PHImageManager.default().requestImage(for: asset, targetSize: newSize, contentMode: .aspectFill, options: option, resultHandler: { (image, info) in guard let img = image else { return } DispatchQueue.main.async { self.delegate?.photoLibraryPickerDidSelectPhoto(image: img) } }) } } } class TLPhotoLibraryPickerCell: UICollectionViewCell { fileprivate lazy var thumImgview:UIImageView = { let imgView = UIImageView.init() imgView.contentMode = .scaleAspectFill imgView.clipsToBounds = true return imgView }() fileprivate lazy var durationLabel:UILabel = { let label = UILabel.init() label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: 12) return label }() public var asset:PHAsset? override init(frame: CGRect) { super.init(frame: frame) self.contentView.addSubview(thumImgview) thumImgview.frame = self.bounds self.contentView.addSubview(durationLabel) } public func set(asset:PHAsset) { self.asset = asset PHCachingImageManager.default().requestImage(for: asset, targetSize: self.size, contentMode: PHImageContentMode.aspectFill, options: nil) { (image, nfo) in self.thumImgview.image = image } let time = Int(asset.duration) let h = time / 3600 let min = Int((time - h * 3600) / 60) let s = Int((time - h * 3600) % 60) let hourStr = h <= 0 ? "" : h < 10 ? "0\(h):" : "\(h):" let minStr = min <= 0 ? "0:" : min < 10 ? "0\(min):" : "\(min):" let sStr = s <= 0 ? "" : s < 10 ? "0\(s)" : "\(s)" durationLabel.isHidden = asset.mediaType != .video || time == 0 durationLabel.text = hourStr + minStr + sStr durationLabel.sizeToFit() durationLabel.center = CGPoint.init(x: self.width - durationLabel.width / 2 - 5, y: self.height - durationLabel.height / 2 - 5) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
2c893cf5e16063b1135dfc94baece923
38.781818
163
0.610832
4.822039
false
false
false
false
DannyVancura/SwifTrix
SwifTrix/User Interface/FormFill/STFormField.swift
1
6150
// // STForm.swift // SwifTrix // // The MIT License (MIT) // // Copyright © 2015 Daniel Vancura // // 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 /** An STFormField represents the data for a cell inside the STFormFillController. It contains the label that will be presented to the user and should describe shortly what the user is supposed to enter (e.g. "Your E-Mail", "First name", ...). Further it specifies, whether or not the value is required to be entered to proceed, what data type is expected (E-Mail format, Date, ...) and optionally, you can provide additional requirements that check, whether the input provided by the user is valid. In the case that you want to provide your own view (for example to select a certain value from a UITableView), you can also pass a custom function to the form field that will be called once the user taps on the text field. In this case, the displayed text field will not be editable via keyboard. */ public class STFormField: NSObject { public var label: String public var isRequired: Bool public var dataType: STFormFillDataType public var additionalRequirements: [(valueCheck: String -> Bool, errorText: String)?] public var customFormFieldAction: ((inout STFormField) -> ())? public var value: String? { didSet { self.delegate?.formField(self, valueDidChange: self.value) } } var delegate: STFormFieldDelegate? /** All requirements - those predefined by using a certain data type and also the additional requirements */ var allRequirements: [(valueCheck: String -> Bool, errorText: String)?] { get { var all = dataType.requirements all.appendContentsOf(additionalRequirements) return all } } /** Returns whether the form fields value fulfills all requirements */ public func isValueValid() -> Bool { guard let value = self.value else { return false } for requirement in self.allRequirements { if let requirement = requirement { if !requirement.valueCheck(value) { return false } } } return true } /** Creates a form field with the specified values. - parameter label: User-visible label that shortly (i.e. in one or two short words) describes what the user is supposed to enter - parameter isRequired: Specifies whether this field has to be filled to proceed or whether it is optional - parameter dataType: A data type for the input data - parameter additionalFormatters: One or more formatters that verify the input. If the text entered by the user is invalid for one of these formatters, the corresponding `errorText` is displayed as a warning. - parameter customFormFieldAction: If you provide this argument, the form field's text field will not be selected on user interaction but `customFormFieldAction` will be called with the form field you create. You can provide this method to present a new view (for example with a date picker) and set the value of the form field in this view. */ public convenience init(label: String, isRequired:Bool, dataType: STFormFillDataType, additionalRequirements: [(valueCheck: String -> Bool, errorText: String)?], customFormFieldAction: ((inout STFormField) -> ())) { self.init(label: label, isRequired: isRequired, dataType: dataType, additionalRequirements: additionalRequirements) self.customFormFieldAction = customFormFieldAction } /** Creates a form field with the specified values. - parameter label: User-visible label that shortly (i.e. in one or two short words) describes what the user is supposed to enter - parameter isRequired: Specifies whether this field has to be filled to proceed or whether it is optional - parameter dataType: A data type for the input data - parameter additionalFormatters: One or more formatters that verify the input. If the text entered by the user is invalid for one of these formatters, the corresponding `errorText` is displayed as a warning. */ public init(label: String, isRequired:Bool, dataType: STFormFillDataType, additionalRequirements: [(valueCheck: String -> Bool, errorText: String)?]) { self.label = label self.isRequired = isRequired self.dataType = dataType self.additionalRequirements = additionalRequirements } /** Creates a form field with the specified values. - parameter label: User-visible label that shortly (i.e. in one or two short words) describes what the user is supposed to enter - parameter isRequired: Specifies whether this field has to be filled to proceed or whether it is optional - parameter dataType: A data type for the input data */ public convenience init(label: String, isRequired:Bool, dataType: STFormFillDataType) { self.init(label: label, isRequired: isRequired, dataType: dataType, additionalRequirements: []) } }
mit
d90b4c94ca18b5469743c807346820db
53.910714
793
0.713612
4.970897
false
false
false
false
johnno1962d/swift
test/ClangModules/blocks_parse.swift
1
1780
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify %s // REQUIRES: objc_interop import blocks import Foundation var someNSString : NSString func useString(_ s: String) {} dispatch_async(dispatch_get_current_queue()) { } someNSString.enumerateLines {(s:String?) in } someNSString.enumerateLines {s in } someNSString.enumerateLines({ useString($0) }) dispatch_async(dispatch_get_current_queue(), /*not a block=*/()) // expected-error{{cannot convert value of type '()' to expected argument type 'dispatch_block_t' (aka '@convention(block) () -> ()')}} func testNoEscape(f: @noescape @convention(block) () -> Void, nsStr: NSString, fStr: @noescape (String!) -> Void) { dispatch_async(dispatch_get_current_queue(), f) // expected-error{{invalid conversion from non-escaping function of type '@noescape @convention(block) () -> Void' to potentially escaping function type 'dispatch_block_t' (aka '@convention(block) () -> ()')}} dispatch_sync(dispatch_get_current_queue(), f) // okay: dispatch_sync is noescape // rdar://problem/19818617 nsStr.enumerateLines(fStr) // okay due to @noescape _ = nsStr.enumerateLines as Int // expected-error{{cannot convert value of type '(@noescape (String!) -> Void) -> Void' to type 'Int' in coercion}} } func checkTypeImpl<T>(_ a: inout T, _: T.Type) {} do { var block = blockWithoutNullability() checkTypeImpl(&block, ImplicitlyUnwrappedOptional<dispatch_block_t>.self) } do { var block = blockWithNonnull() checkTypeImpl(&block, dispatch_block_t.self) } do { var block = blockWithNullUnspecified() checkTypeImpl(&block, ImplicitlyUnwrappedOptional<dispatch_block_t>.self) } do { var block = blockWithNullable() checkTypeImpl(&block, Optional<dispatch_block_t>.self) }
apache-2.0
4fea5cd23b239e69f7f24e8ef47e004f
38.555556
259
0.710674
3.755274
false
false
false
false
superbderrick/SummerSlider
useCases/withCocoaPod/SummerSlider/HorizontalViewController.swift
1
3202
// // HorizontalViewController.swift // SummerSlider // // Created by Kang Jinyeoung on 24/09/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import SummerSlider class HorizontalViewController: UIViewController { var testSlider1:SummerSlider! var testSlider2:SummerSlider! var testSlider3:SummerSlider! @IBOutlet weak var testSlider4: SummerSlider! @IBOutlet weak var testSlider5: SummerSlider! @IBOutlet weak var testSlider6: SummerSlider! let testRect1 = CGRect(x:30 ,y:70 , width:300 , height:30) let testRect2 = CGRect(x:30 ,y:120 , width:300 , height:30) let testRect3 = CGRect(x:30 ,y:170 , width:300 , height:30) override func viewDidLoad() { super.viewDidLoad() var marksArray1 = Array<Float>() marksArray1 = [0,10,20,30,40,50,60,70,80,90,100] testSlider1 = SummerSlider(frame: testRect1) testSlider1.selectedBarColor = UIColor.blue testSlider1.unselectedBarColor = UIColor.red testSlider1.markColor = UIColor.yellow testSlider1.markWidth = 2.0 testSlider1.markPositions = marksArray1 var marksArray2 = Array<Float>() marksArray2 = [10.0,15.0,23.0,67.0,71.0] testSlider2 = SummerSlider(frame: testRect2) testSlider2.selectedBarColor = UIColor(red:138/255.0 ,green:255/255.0 ,blue:0/255 ,alpha:1.0) testSlider2.unselectedBarColor = UIColor(red:108/255.0 ,green:200/255.0 ,blue:0/255.0 ,alpha:1.0) testSlider2.markColor = UIColor.red testSlider2.markWidth = 1.0 testSlider2.markPositions = marksArray2 testSlider3 = SummerSlider(frame: testRect3) var marksArray3 = Array<Float>() marksArray3 = [20.0,15.0,23.0,67.0, 90.0] testSlider3 = SummerSlider(frame: testRect3) testSlider3.selectedBarColor = UIColor.blue testSlider3.unselectedBarColor = UIColor(red:20/255.0 ,green:40/255.0 ,blue:0/255.0 ,alpha:1.0) testSlider3.markColor = UIColor.gray testSlider3.markWidth = 10.0 testSlider3.markPositions = marksArray3 self.view.addSubview(testSlider1) self.view.addSubview(testSlider2) self.view.addSubview(testSlider3) var marksArray4 = Array<Float>() marksArray4 = [0.0,25.0,90.0] testSlider4.selectedBarColor = UIColor.purple testSlider4.unselectedBarColor = UIColor.brown testSlider4.markColor = UIColor.gray testSlider4.markWidth = 3.0 testSlider4.markPositions = marksArray4 var marksArray5 = Array<Float>() marksArray5 = [10.0,20.0,30.0 , 80,90.0] testSlider5.selectedBarColor = UIColor.cyan testSlider5.unselectedBarColor = UIColor.red testSlider5.markColor = UIColor.green testSlider5.markWidth = 1.0 testSlider5.markPositions = marksArray5 var marksArray6 = Array<Float>() marksArray6 = [0,12,23,34,45,56,77,99] testSlider6.selectedBarColor = UIColor.white testSlider6.unselectedBarColor = UIColor.black testSlider6.markColor = UIColor.orange testSlider6.markWidth = 6.0 testSlider6.markPositions = marksArray6 } }
mit
8ebdae1428d32eb24f3eff92aaa57c8f
32.34375
103
0.679788
3.937269
false
true
false
false
swiftsanyue/TestKitchen
TestKitchen/TestKitchen/classes/common(公共类)/Const.swift
1
10738
// // Const.swift // TestKitchen // // Created by gaokunpeng on 16/8/16. // Copyright © 2016年 apple. All rights reserved. // import UIKit //定义一些常量和接口 //屏幕的宽度和高度 let KScreenW = UIScreen.mainScreen().bounds.size.width let KScreenH = UIScreen.mainScreen().bounds.size.height //首页推荐点击事件的类型 //接口 //大部分是Post请求 public let kHostUrl = "http://api.izhangchu.com/?appVersion=4.5&sysVersion=9.3.2&devModel=iPhone" //一、食谱 //1、推荐 //首页推荐参数 //methodName=SceneHome&token=&user_id=&version=4.5 //1)广告 //广告详情 //methodName=CourseSeriesView&series_id=22&token=&user_id=&version=4.32 //广告分享 //methodName=AppShare&shareID=&shareModule=course&token=&user_id=&version=4.32 //评论 //methodName=CommentList&page=1&relate_id=22&size=10&token=&type=2&user_id=&version=4.32 //methodName=CommentList&page=2&relate_id=22&size=10&token=&type=2&user_id=&version=4.32 //评论发送 //content=%E5%AD%A6%E4%B9%A0%E4%BA%86&methodName=CommentInsert&parent_id=0&relate_id=23&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32 //content="学习了" //2)基本类型 //新手入门 //食材搭配 //material_ids=45%2C47&methodName=SearchMix&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //material_ids=45%2C47&methodName=SearchMix&page=2&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //场景菜谱 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=SceneList&page=1&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=SceneList&page=2&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //点击进详情 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=AppShare&shareID=105&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=SceneInfo&scene_id=105&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //再点击列表进详情 //做法 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesView&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //食材 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesMaterial&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //相关常识 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesCommensense&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //相宜相克 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesSuitable&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //评论数 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //发布 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //收藏 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //ids=14528&methodName=UserUpdatelikes&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //评论 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=CommentList&page=1&relate_id=14528&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //发送评论 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //content=%E5%AD%A6%E4%B9%A0%E4%B8%80%E4%B8%8B&methodName=CommentInsert&parent_id=0&relate_id=14528&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //content=@"学习一下" //dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //上传照片 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=ShequTopic&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //activity_id=&content=%E5%BE%88%E5%A5%BD%E5%90%83&image=1457877114055_8928429596.jpg&methodName=ShequPostadd&token=8ABD36C80D1639D9E81130766BE642B7&topics=%5B%7B%22topic_id%22%3A%226%22%2C%22topic_name%22%3A%22%E4%B8%80%E4%BA%BA%E9%A3%9F%22%2C%22locx%22%3A%22160%22%2C%22locy%22%3A%22160%22%2C%22width%22%3A%22320%22%7D%5D&user_id=1386387&version=4.32&video= //content = @“很好吃” //猜你喜欢 //methodName=UserLikes&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //口味有变 //methodName=LbsProvince&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //baidu_city=%E6%B7%B1%E5%9C%B3%E5%B8%82&baidu_province=%E5%B9%BF%E4%B8%9C%E7%9C%81&effect=312&like=230&methodName=UserDraw&province=3&taste=316&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //点击一个标签进入搜索列表 //cat_id=252&methodName=CategorySearch&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //搜索 //keyword=%E6%97%A9%E9%A4%90&methodName=SearchDishes&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //keyword=早餐 //日食记 //methodName=AppShare&shareID=&shareModule=course&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=CourseSeriesView&series_id=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=CommentList&page=1&relate_id=18&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32 //台湾食记 //methodName=AppShare&shareID=&shareModule=course&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=CourseSeriesView&series_id=12&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=CommentList&page=1&relate_id=12&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32 //3)今日食谱推荐 //进列表 //methodName=AppShare&shareID=51&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=SceneInfo&scene_id=51&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //相关场景 //methodName=SceneInfo&scene_id=112&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //4)春季养生肝为先 //methodName=AppShare&shareID=127&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=SceneInfo&scene_id=127&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //5)场景菜谱 //methodName=SceneList&page=1&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=SceneInfo&scene_id=134&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //6)推荐达人 //methodName=TalentRecommend&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //关注 //ids=1249795&methodName=UpdateFollow&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //取消关注 //ids=1249795&methodName=UpdateFollow&token=8ABD36C80D1639D9E81130766BE642B7&type=0&user_id=1386387&version=4.32 //达人详情页 // //7)精选作品 //is_marrow=1&methodName=ShequList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //作品详情 //methodName=CommentList&page=1&relate_id=35282&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=3&user_id=1386387&version=4.32 //methodName=AppShare&shareID=35282&shareModule=shequ&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=ShequPostview&post_id=35282&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //8)美食专题 //methodName=TopicList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //专题详情 //methodName=TopicView&version=1.0&user_id=1386387&topic_id=175&_time=1457878578&_signature=0ba3640c73c17441b675a7dd968a66e8 //http://h5.izhangchu.com/topic_view/index.html?&topic_id=134&user_id=1386387&token=8ABD36C80D1639D9E81130766BE642B7&app_exitpage= //2、食材 //methodName=MaterialSubtype&token=&user_id=&version=4.32 //详情 //material_id=62&methodName=MaterialView&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //相关菜例 //material_id=62&methodName=MaterialDishes&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //选购要诀 //营养功效 //实用百科 //material_id=62&methodName=MaterialDishes&page=2&size=6&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //3、分类 //methodName=CategoryIndex&token=&user_id=&version=4.32 //进列表 //cat_id=316&methodName=CategorySearch&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //4、搜索 //热门搜索 //methodName=SearchHot&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //二、社区 //推荐 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=ShequRecommend&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.33 //最新 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //last_id=0&methodName=ShequList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //关注 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=ShequFollow&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //三、商城 //四、食课 //methodName=CourseIndex&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //五、我的 //注册 //获取验证码 //device_id=021fc7f7528&methodName=UserLogin&mobile=13716422377&token=&user_id=&version=4.32 //code=173907&device_id=021fc7f7528&methodName=UserAuth&mobile=13716422377&token=&user_id=&version=4.32 // //GET : http://182.92.228.160:80/zhangchu/onlinezhangchu/users/1386387 //注册 //methodName=UserPwd&nickname=sh%E6%8E%8C%E5%8E%A8&password=9745b090734f44cdd7b2ef1d88c26b1f&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //sh掌厨 05513867720
mit
0034dbde66b3f3135d73b8c8e33f038c
34.645614
359
0.799685
2.380272
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/ReferenceShowing.swift
1
6651
import Foundation protocol ReferenceShowing: ArticleScrolling { var webView: WKWebView { get } var articleURL: URL { get } // var articleURL: URL? { get } } extension ReferenceShowing where Self: ViewController & WMFReferencePageViewAppearanceDelegate & UIPageViewControllerDelegate & ReferenceViewControllerDelegate { // MARK: - Actions /// Show references that were tapped in the article /// For now, we're keeping WMFReference to bridge with Objective-C but it should be merged with Reference in the future func showReferences(_ scriptMessageReferences: [WMFLegacyReference], selectedIndex: Int, animated: Bool) { guard selectedIndex < scriptMessageReferences.count else { showGenericError() return } let referencesBoundingClientRect = getBoundingClientRect(for: scriptMessageReferences) let referenceRectInScrollCoordinates = webView.scrollView.convert(referencesBoundingClientRect, from: webView) if traitCollection.verticalSizeClass == .compact || self.traitCollection.horizontalSizeClass == .compact { showReferencesPanel(with: scriptMessageReferences, referencesBoundingClientRect: referencesBoundingClientRect, referenceRectInScrollCoordinates: referenceRectInScrollCoordinates, selectedIndex: selectedIndex, animated: animated) } else { if !isBoundingClientRectVisible(referencesBoundingClientRect) { let center = referenceRectInScrollCoordinates.center scroll(to: center, centered: true, animated: true) { [weak self] (_) in self?.showReferencesPopover(with: scriptMessageReferences[selectedIndex], referenceRectInScrollCoordinates: referenceRectInScrollCoordinates, animated: animated) } } else { showReferencesPopover(with: scriptMessageReferences[selectedIndex], referenceRectInScrollCoordinates: referenceRectInScrollCoordinates, animated: animated) } } } /// Show references that were tapped in the article as a panel func showReferencesPanel(with references: [WMFLegacyReference], referencesBoundingClientRect: CGRect, referenceRectInScrollCoordinates: CGRect, selectedIndex: Int, animated: Bool) { let vc = WMFReferencePageViewController.wmf_viewControllerFromReferencePanelsStoryboard() vc.delegate = self vc.pageViewController.delegate = self vc.appearanceDelegate = self vc.apply(theme: theme) vc.modalPresentationStyle = .overFullScreen vc.modalTransitionStyle = .crossDissolve vc.lastClickedReferencesIndex = selectedIndex vc.lastClickedReferencesGroup = references vc.articleURL = articleURL present(vc, animated: false) { // should be false even if animated is true self.adjustScrollForReferencePageViewController(referencesBoundingClientRect, referenceRectInScrollCoordinates: referenceRectInScrollCoordinates, viewController: vc, animated: animated) } } /// Show references that were tapped in the article as a popover func showReferencesPopover(with reference: WMFLegacyReference, referenceRectInScrollCoordinates: CGRect, animated: Bool) { let width = min(min(view.frame.size.width, view.frame.size.height) - 20, 355) guard let popoverVC = WMFReferencePopoverMessageViewController.wmf_initialViewControllerFromClassStoryboard() else { showGenericError() return } popoverVC.articleURL = articleURL (popoverVC as Themeable).apply(theme: theme) popoverVC.modalPresentationStyle = .popover popoverVC.reference = reference popoverVC.width = width popoverVC.view.backgroundColor = theme.colors.paperBackground let presenter = popoverVC.popoverPresentationController presenter?.passthroughViews = [webView] presenter?.delegate = popoverVC presenter?.permittedArrowDirections = [.up, .down] presenter?.backgroundColor = theme.colors.paperBackground presenter?.sourceView = view presenter?.sourceRect = view.convert(referenceRectInScrollCoordinates, from: webView.scrollView) present(popoverVC, animated: animated) { // Reminder: The textView's scrollEnabled needs to remain "NO" until after the popover is // presented. (When scrollEnabled is NO the popover can better determine the textView's // full content height.) See the third reference "[3]" on "enwiki > Pythagoras". popoverVC.scrollEnabled = true } } } private extension ReferenceShowing where Self: ViewController { // MARK: - Utilities func getBoundingClientRect(for references: [WMFLegacyReference]) -> CGRect { guard var rect = references.first?.rect else { return .zero } for reference in references { rect = rect.union(reference.rect) } rect = rect.offsetBy(dx: 0, dy: 1) rect = rect.insetBy(dx: -1, dy: -3) return rect } func adjustScrollForReferencePageViewController(_ referencesBoundingClientRect: CGRect, referenceRectInScrollCoordinates: CGRect, viewController: WMFReferencePageViewController, animated: Bool) { let deltaY = webView.scrollView.contentOffset.y < 0 ? 0 - webView.scrollView.contentOffset.y : 0 let referenceRectInWindowCoordinates = webView.scrollView.convert(referenceRectInScrollCoordinates, to: nil).offsetBy(dx: 0, dy: deltaY) guard !referenceRectInWindowCoordinates.isEmpty, let firstPanel = viewController.firstPanelView() else { return } let panelRectInWindowCoordinates = firstPanel.convert(firstPanel.bounds, to: nil) guard !isBoundingClientRectVisible(referencesBoundingClientRect) || referenceRectInWindowCoordinates.intersects(panelRectInWindowCoordinates) else { viewController.backgroundView.clearRect = referenceRectInWindowCoordinates return } let oldY = webView.scrollView.contentOffset.y let scrollPoint = referenceRectInScrollCoordinates.offsetBy(dx: 0, dy: 0.5 * panelRectInWindowCoordinates.height).center scroll(to: scrollPoint, centered: true, animated: animated) { [weak self] (_) in guard let newY = self?.webView.scrollView.contentOffset.y else { return } let delta = newY - oldY viewController.backgroundView.clearRect = referenceRectInWindowCoordinates.offsetBy(dx: 0, dy: 0 - delta) } } }
mit
1972ef36d785da45c65ca8d432d08f6b
53.073171
240
0.709517
5.834211
false
false
false
false
kevintavog/Radish
src/Radish/Controllers/SearchWindowController.swift
1
3108
// // import AppKit import Async import RangicCore class SearchWindowController : NSWindowController, NSWindowDelegate { var viewSearchResults = false @IBOutlet weak var hostText: NSTextField! @IBOutlet weak var searchText: NSTextField! @IBOutlet weak var statusImage: NSImageView! @IBOutlet weak var statusLabel: NSTextField! @IBOutlet weak var workingIndicator: NSProgressIndicator! override func windowDidLoad() { self.window?.delegate = self } override func awakeFromNib() { hostText.stringValue = Preferences.findAPhotoHost statusImage.isHidden = true statusLabel.stringValue = "" workingIndicator.isHidden = true searchText.stringValue = Preferences.lastSearchText if Preferences.findAPhotoHost.count > 0 { window?.makeFirstResponder(searchText) } } func windowWillClose(_ notification: Notification) { NSApplication.shared.stopModal() } @IBAction func cancel(_ sender: AnyObject) { close() } @IBAction func view(_ sender: AnyObject) { statusImage.isHidden = true statusLabel.stringValue = "" workingIndicator.startAnimation(sender) workingIndicator.isHidden = false Preferences.lastSearchText = searchText.stringValue let hostValue = self.hostText.stringValue let searchValue = self.searchText.stringValue // Run search (clear status text, start working indicator) // When it completes (end working indicator) // If it succeeds, set flag and close // If it fails, set status message and stay open Async.background { FindAPhotoResults.search( hostValue, text: searchValue, first: 1, count: 1, completion: { (result: FindAPhotoResults) -> () in Async.main { self.workingIndicator.isHidden = true self.workingIndicator.stopAnimation(sender) self.statusImage.isHidden = false if result.hasError { self.statusImage.image = NSImage(named: "FailedCheck") self.statusLabel.stringValue = "FAILED: \(result.errorMessage!)" } else { Preferences.findAPhotoHost = hostValue self.statusImage.image = NSImage(named: "SucceededCheck") if result.totalMatches! == 0 { self.statusLabel.stringValue = "Succeeded - but there are no matches" } else { self.statusLabel.stringValue = "Succeeded with a total of \(result.totalMatches!) matches" self.viewSearchResults = true self.close() } } } }) } } }
mit
4009308a5bc4c6f426050cc22f5a773f
32.419355
122
0.555985
5.809346
false
false
false
false
richterd/BirthdayGroupReminder
BirthdayGroupReminder/BGRAdressBook.swift
1
2276
// // BGRAdressBook.swift // BirthdayGroupReminder // // Created by Daniel Richter on 16.07.14. // Copyright (c) 2014 Daniel Richter. All rights reserved. // import UIKit class BGRAdressBook: NSObject { var delegate = UIApplication.shared.delegate as! AppDelegate func usersSortedByBirthday(_ selectedGroups : [ABRecordID]) -> [RHPerson]{ let addressBook = delegate.addressBook var users : [RHPerson] = [] for groupID : ABRecordID in selectedGroups{ let group : RHGroup = addressBook.group(forABRecordID: groupID) let friends = group.members as! [RHPerson] for user in friends{ if ((user.birthday) != nil){ users.append(user) } } } //Sort by birthday users.sort(){ let leftDate : Date = $0.birthday let rightDate : Date = $1.birthday let left = (Calendar.current as NSCalendar).components([.day, .month, .year], from: leftDate) let right = (Calendar.current as NSCalendar).components([.day, .month, .year], from: rightDate) let current = (Calendar.current as NSCalendar).components([.day, .month, .year], from: Date()) //Its save to unwrap the information here let lday = left.day! var lmonth = left.month! let rday = right.day! var rmonth = right.month! //Shift dates depending on current date if(lmonth < current.month!){ lmonth += 12 } else if(lmonth == current.month){ if(lday < current.day!){ lmonth += 12 } } if(rmonth < current.month!){ rmonth += 12 } else if(rmonth == current.month){ if(rday < current.day!){ rmonth += 12 } } //Now sort them var diff = lmonth - rmonth if(diff == 0){diff = lday - rday} if(diff < 0){ return true }else{ return false } } return users } }
gpl-2.0
3f30f842b23bdd01b7ab726d97223f00
31.056338
107
0.494728
4.654397
false
false
false
false
EBGToo/SBFrames
Tests/PositionTest.swift
1
7189
// // PositionTest.swift // SBFrames // // Created by Ed Gamble on 6/15/16. // Copyright © 2016 Edward B. Gamble Jr. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import XCTest import SBUnits @testable import SBFrames class PositionTest: XCTestCase { let accuracy = Quaternion.epsilon override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func checkValues (_ p: Position, frame: Frame, unit: SBUnits.Unit<Length>, x: Double, y: Double, z: Double) { XCTAssert(p.has (frame: frame)) XCTAssertEqual(p.x.value, x, accuracy: accuracy) XCTAssertEqual(p.y.value, y, accuracy: accuracy) XCTAssertEqual(p.z.value, z, accuracy: accuracy) XCTAssertTrue(p.x.unit === unit) XCTAssertTrue(p.y.unit === unit) XCTAssertTrue(p.z.unit === unit) XCTAssertTrue(p.unit === unit) XCTAssertEqual(p.unit, unit) } func testInit() { let f1 = Frame.root let p1 = Position (frame:f1) checkValues (p1, frame: f1, unit: meter, x: 0.0, y: 0.0, z: 0.0) let px = Position (frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) checkValues (px, frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) let py = Position (frame: f1, unit: meter, x: 0.0, y: 1.0, z: 0.0) checkValues (py, frame: f1, unit: meter, x: 0.0, y: 1.0, z: 0.0) let pz = Position (frame: f1, unit: meter, x: 0.0, y: 0.0, z: 1.0) checkValues (pz, frame: f1, unit: meter, x: 0.0, y: 0.0, z: 1.0) } func testInvert () { let f1 = Frame.root let px = Position (frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) checkValues (px, frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) let pxi = px.inverse checkValues (pxi, frame: f1, unit: meter, x: -1.0, y: 0.0, z: 0.0) let pxl = Position (frame: f1, unit: meter, x: 1.0, y: 1.0, z: 1.0).inverse checkValues (pxl, frame: f1, unit: meter, x: -1.0, y: -1.0, z: -1.0) } func testTranslate () { let f1 = Frame.root let px = Position (frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) checkValues (px, frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) let pxt1 = px.translate(Position (frame: f1, unit: meter, x: 0.0, y: 1.0, z: 0.0)) checkValues (pxt1, frame: f1, unit: meter, x: 1.0, y: 1.0, z: 0.0) let pxt2 = px.translate(pxt1.inverse) checkValues (pxt2, frame: f1, unit: meter, x: 0.0, y: -1.0, z: 0.0) } func testTranslateUnits () { let f1 = Frame.root let px = Position (frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) checkValues (px, frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) let pxt1 = px.translate(Position (frame: f1, unit: millimeter, x: -1000.0, y: 0.0, z: 0.0)) checkValues (pxt1, frame: f1, unit: meter, x: 0.0, y: 0.0, z: 0.0) } func testRotate () { let f1 = Frame.root let px = Position (frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) checkValues (px, frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) // let r1 = Orientation (frame: f1, angle: Quantity<Angle>(value: Double.pi / 2, unit: radian), axis: .z) let pxr1 = px.rotate(r1) checkValues(pxr1, frame: f1, unit: meter, x: 0.0, y: 1.0, z: 0.0) // let r2 = Orientation (frame: f1, angle: Quantity<Angle>(value: 2 * Double.pi, unit: radian), axis: .z) let pxr2 = px.rotate(r2) checkValues(pxr2, frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) // Rotate around: z, x, and y by pi/2 -> back to self let rz = Orientation (frame: f1, angle: Quantity<Angle>(value: Double.pi / 2, unit: radian), axis: .z) let rx = Orientation (frame: f1, angle: Quantity<Angle>(value: Double.pi / 2, unit: radian), axis: .x) let ry = Orientation (frame: f1, angle: Quantity<Angle>(value: Double.pi / 2, unit: radian), axis: .y) let pxrxyz = px.rotate(rz).rotate(rx).rotate(ry) checkValues(pxrxyz, frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) } func testDistance () { let f1 = Frame.root let px = Position (frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) checkValues (px, frame: f1, unit: meter, x: 1.0, y: 0.0, z: 0.0) XCTAssertEqual(px.distance.value, 1.0) let pxt1 = px.translate(Position (frame: f1, unit: meter, x: 0.0, y: 1.0, z: 0.0)) checkValues (pxt1, frame: f1, unit: meter, x: 1.0, y: 1.0, z: 0.0) XCTAssertEqual(pxt1.distance.value, sqrt (2.0)) XCTAssertEqual(pxt1.distanceBetween(px).value, 1.0) XCTAssertEqual(px.distanceBetween(pxt1).value, 1.0) } func testDirection () { let f1 = Frame.root let px = Position (frame: f1, unit: meter, x: 2.0, y: 0.0, z: 0.0) checkValues (px, frame: f1, unit: meter, x: 2.0, y: 0.0, z: 0.0) let dx = px.direction XCTAssertNotNil (dx) XCTAssertEqual(dx!.x, 1.0, accuracy: accuracy) XCTAssertEqual(dx!.y, 0.0, accuracy: accuracy) XCTAssertEqual(dx!.z, 0.0, accuracy: accuracy) let pxy = Position (frame: f1, unit: meter, x: 2.0, y: 2.0, z: 0.0) checkValues (pxy, frame: f1, unit: meter, x: 2.0, y: 2.0, z: 0.0) let dxy = pxy.direction XCTAssertNotNil (dxy) XCTAssertEqual(dxy!.x, 1 / sqrt (2.0), accuracy: accuracy) XCTAssertEqual(dxy!.y, 1 / sqrt (2.0), accuracy: accuracy) XCTAssertEqual(dxy!.z, 0.0, accuracy: accuracy) let p0 = Position (frame: f1, unit: meter, x: 0.0, y: 0.0, z: 0.0) checkValues (p0, frame: f1, unit: meter, x: 0.0, y: 0.0, z: 0.0) let d0 = p0.direction XCTAssertNil (d0) } func testScale () { let f1 = Frame.root let px = Position (frame: f1, unit: meter, x: 1000.0, y: 0.0, z: 0.0) checkValues (px, frame: f1, unit: meter, x: 1000.0, y: 0.0, z: 0.0) let py = Position (frame: f1, unit: kilometer, x: 1.0, y: 0.0, z: 0.0) checkValues (py, frame: f1, unit: kilometer, x: 1.0, y: 0.0, z: 0.0) XCTAssertEqual(px, py.scale(for: meter)) } func testRIA () { } func testRAH () { } func testTransformedTo () { } func testTransformto () { } func testTransformBy () { } func testMutable () { let p1 = Position (frame: Frame.root, unit: meter, x: 1.0, y: 0.0, z: 0.0) var p2 = p1 checkValues (p1, frame: Frame.root, unit: meter, x: 1.0, y: 0.0, z: 0.0) checkValues (p2, frame: Frame.root, unit: meter, x: 1.0, y: 0.0, z: 0.0) let off1 = Position (frame: Frame.root, unit: meter, x: -2.0, y: 0.0, z: 0.0) // Translate p2; ensure p1 is unchanged. p2.translated(off1) checkValues (p1, frame: Frame.root, unit: meter, x: 1.0, y: 0.0, z: 0.0) checkValues (p2, frame: Frame.root, unit: meter, x: -1.0, y: 0.0, z: 0.0) } func testPerformanceExample() { self.measure { } } }
mit
00b3a3c8f38e8f9e4cc673c647a5a890
30.388646
111
0.559544
2.795799
false
true
false
false
EstebanVallejo/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/String+Additions.swift
2
1021
// // String+Additions.swift // MercadoPagoSDK // // Created by Matias Gualino on 29/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation extension String { var localized: String { var bundle : NSBundle? = MercadoPago.getBundle() if bundle == nil { bundle = NSBundle.mainBundle() } return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "") } static public func isNullOrEmpty(value: String?) -> Bool { return value == nil || value!.isEmpty } static public func isDigitsOnly(a: String) -> Bool { if let n = a.toInt() { return true } else { return false } } subscript (i: Int) -> String { if count(self) > i { return String(Array(self)[i]) } return "" } public func indexAt(theInt:Int)->String.Index { return advance(self.startIndex, theInt) } }
mit
5bef3aa90d9d6b5bb90e9638b0f93d98
20.291667
89
0.556317
4.084
false
false
false
false
walkingsmarts/ReactiveCocoa
ReactiveCocoa/UIKit/UIControl.swift
4
4302
import ReactiveSwift import UIKit import enum Result.NoError extension Reactive where Base: UIControl { /// The current associated action of `self`, with its registered event mask /// and its disposable. internal var associatedAction: Atomic<(action: CocoaAction<Base>, controlEvents: UIControlEvents, disposable: Disposable)?> { return associatedValue { _ in Atomic(nil) } } /// Set the associated action of `self` to `action`, and register it for the /// control events specified by `controlEvents`. /// /// - parameters: /// - action: The action to be associated. /// - controlEvents: The control event mask. /// - disposable: An outside disposable that will be bound to the scope of /// the given `action`. internal func setAction(_ action: CocoaAction<Base>?, for controlEvents: UIControlEvents, disposable: Disposable? = nil) { associatedAction.modify { associatedAction in associatedAction?.disposable.dispose() if let action = action { base.addTarget(action, action: CocoaAction<Base>.selector, for: controlEvents) let compositeDisposable = CompositeDisposable() compositeDisposable += isEnabled <~ action.isEnabled compositeDisposable += { [weak base = self.base] in base?.removeTarget(action, action: CocoaAction<Base>.selector, for: controlEvents) } compositeDisposable += disposable associatedAction = (action, controlEvents, ScopedDisposable(compositeDisposable)) } else { associatedAction = nil } } } /// Create a signal which sends a `value` event for each of the specified /// control events. /// /// - note: If you mean to observe the **value** of `self` with regard to a particular /// control event, `mapControlEvents(_:_:)` should be used instead. /// /// - parameters: /// - controlEvents: The control event mask. /// /// - returns: A signal that sends the control each time the control event occurs. public func controlEvents(_ controlEvents: UIControlEvents) -> Signal<Base, NoError> { return mapControlEvents(controlEvents, { $0 }) } /// Create a signal which sends a `value` event for each of the specified /// control events. /// /// - important: You should use `mapControlEvents` in general unless the state of /// the control — e.g. `text`, `state` — is not concerned. In other /// words, you should avoid using `map` on a control event signal to /// extract the state from the control. /// /// - note: For observations that could potentially manipulate the first responder /// status of `base`, `mapControlEvents(_:_:)` is made aware of the potential /// recursion induced by UIKit and would collect the values for the control /// events accordingly using the given transform. /// /// - parameters: /// - controlEvents: The control event mask. /// - transform: A transform to reduce `Base`. /// /// - returns: A signal that sends the reduced value from the control each time the /// control event occurs. public func mapControlEvents<Value>(_ controlEvents: UIControlEvents, _ transform: @escaping (Base) -> Value) -> Signal<Value, NoError> { return Signal { observer in let receiver = CocoaTarget(observer) { transform($0 as! Base) } base.addTarget(receiver, action: #selector(receiver.invoke), for: controlEvents) let disposable = lifetime.ended.observeCompleted(observer.sendCompleted) return AnyDisposable { [weak base = self.base] in disposable?.dispose() base?.removeTarget(receiver, action: #selector(receiver.invoke), for: controlEvents) } } } @available(*, unavailable, renamed: "controlEvents(_:)") public func trigger(for controlEvents: UIControlEvents) -> Signal<(), NoError> { fatalError() } /// Sets whether the control is enabled. public var isEnabled: BindingTarget<Bool> { return makeBindingTarget { $0.isEnabled = $1 } } /// Sets whether the control is selected. public var isSelected: BindingTarget<Bool> { return makeBindingTarget { $0.isSelected = $1 } } /// Sets whether the control is highlighted. public var isHighlighted: BindingTarget<Bool> { return makeBindingTarget { $0.isHighlighted = $1 } } }
mit
202c7d8d9ae9e2f388b6d94f1b821ae1
37.375
138
0.683574
4.259663
false
false
false
false
seaburg/PHDiff
Example/Example/RandomDemoColors.swift
2
1562
// // RandomDemoColors.swift // Example // // Created by Andre Alves on 10/16/16. // Copyright © 2016 Andre Alves. All rights reserved. // import Foundation struct RandomDemoColors { private let colors: [DemoColor] = [ DemoColor(name: "Red", r: 255, g: 0, b: 0), DemoColor(name: "Green", r: 0, g: 255, b: 0), DemoColor(name: "Blue", r: 0, g: 0, b: 255), DemoColor(name: "Yellow", r: 255, g: 255, b: 0), DemoColor(name: "Purple", r: 137, g: 104, b: 205), DemoColor(name: "Orange", r: 255, g: 165, b: 0), DemoColor(name: "Pink", r: 255, g: 52, b: 179), DemoColor(name: "Light Gray", r: 211, g: 211, b: 211), DemoColor(name: "Gold", r: 255, g: 215, b: 0), DemoColor(name: "Firebrick", r: 205, g: 38, b: 38), DemoColor(name: "Olive", r: 196, g: 255, b: 62) ] func randomColors() -> [DemoColor] { return Array(colors.shuffle()[0..<randomNumber(colors.count/2..<colors.count)]) } private func randomNumber(_ range: Range<Int>) -> Int { let min = range.lowerBound let max = range.upperBound return Int(arc4random_uniform(UInt32(max - min))) + min } } extension Array { fileprivate func shuffle() -> [Element] { var original = self var result: [Element] = [] while original.count > 0 { let upperBound = UInt32(original.count - 1) let r = Int(arc4random_uniform(upperBound)) result.append(original.remove(at: r)) } return result } }
mit
1df46bba883953f0081b2941d2ef6b42
31.520833
87
0.563741
3.378788
false
false
false
false
GuanshanLiu/Animation-Timing
Animation Timing/MainTableViewController.swift
1
2036
// // MainTableViewController.swift // Animation Timing // // Created by Guanshan Liu on 21/1/15. // Copyright (c) 2015 Guanshan Liu. All rights reserved. // import UIKit class MainTableViewController: UITableViewController { typealias Demo = (name: String, controller: () -> UIViewController ) let demos: [Demo] = [ ("Basic Transform", { BasicTransformsViewController() }), ("Model & Presentation Layers", { ModelOrPresentationViewController() }), ("Alert", { AlertSampleViewController() } ), ("Timing Function", { TimingFunctionViewController() } ), ("Timing Curves", { FunctionCurvesViewController() } ), ("beginTime", { BeginTimeViewController() } ), ("timeOffset", { TimeOffsetViewController() } ), ("speed & timeOffset", { SpeedTimeOffsetViewController() } ) ] override func viewDidLoad() { super.viewDidLoad() title = "Animation Timing" tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return demos.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell // Configure the cell... cell.textLabel?.text = demos[indexPath.row].name return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = demos[indexPath.row].controller() vc.title = demos[indexPath.row].name navigationController?.pushViewController(vc, animated: true) tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
450d9becff30170442b8ef55fcc04051
32.933333
125
0.680255
5.233933
false
false
false
false
Ashok28/Kingfisher
Sources/Networking/ImagePrefetcher.swift
7
20048
// // ImagePrefetcher.swift // Kingfisher // // Created by Claire Knight <[email protected]> on 24/02/2016 // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Progress update block of prefetcher when initialized with a list of resources. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while /// downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void) /// Progress update block of prefetcher when initialized with a list of resources. /// /// - `skippedSources`: An array of sources that are already cached before the prefetching starting. /// - `failedSources`: An array of sources that fail to be fetched. /// - `completedResources`: An array of sources that are fetched and cached successfully. public typealias PrefetcherSourceProgressBlock = ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void) /// Completion block of prefetcher when initialized with a list of sources. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while /// downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void) /// Completion block of prefetcher when initialized with a list of sources. /// /// - `skippedSources`: An array of sources that are already cached before the prefetching starting. /// - `failedSources`: An array of sources that fail to be fetched. /// - `completedSources`: An array of sources that are fetched and cached successfully. public typealias PrefetcherSourceCompletionHandler = ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void) /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them. /// This is useful when you know a list of image resources and want to download them before showing. It also works with /// some Cocoa prefetching mechanism like table view or collection view `prefetchDataSource`, to start image downloading /// and caching before they display on screen. public class ImagePrefetcher: CustomStringConvertible { public var description: String { return "\(Unmanaged.passUnretained(self).toOpaque())" } /// The maximum concurrent downloads to use when prefetching images. Default is 5. public var maxConcurrentDownloads = 5 private let prefetchSources: [Source] private let optionsInfo: KingfisherParsedOptionsInfo private var progressBlock: PrefetcherProgressBlock? private var completionHandler: PrefetcherCompletionHandler? private var progressSourceBlock: PrefetcherSourceProgressBlock? private var completionSourceHandler: PrefetcherSourceCompletionHandler? private var tasks = [String: DownloadTask.WrappedTask]() private var pendingSources: ArraySlice<Source> private var skippedSources = [Source]() private var completedSources = [Source]() private var failedSources = [Source]() private var stopped = false // A manager used for prefetching. We will use the helper methods in manager. private let manager: KingfisherManager private let pretchQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.pretchQueue") private static let requestingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.requestingQueue") private var finished: Bool { let totalFinished: Int = failedSources.count + skippedSources.count + completedSources.count return totalFinished == prefetchSources.count && tasks.isEmpty } /// Creates an image prefetcher with an array of URLs. /// /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process. /// The images which are already cached will be skipped without downloading again. /// /// - Parameters: /// - urls: The URLs which should be prefetched. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init( urls: [URL], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { let resources: [Resource] = urls.map { $0 } self.init( resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /// Creates an image prefetcher with an array of URLs. /// /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process. /// The images which are already cached will be skipped without downloading again. /// /// - Parameters: /// - urls: The URLs which should be prefetched. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init( urls: [URL], options: KingfisherOptionsInfo? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { let resources: [Resource] = urls.map { $0 } self.init( resources: resources, options: options, progressBlock: nil, completionHandler: completionHandler) } /// Creates an image prefetcher with an array of resources. /// /// - Parameters: /// - resources: The resources which should be prefetched. See `Resource` type for more. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init( resources: [Resource], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { self.init(sources: resources.map { $0.convertToSource() }, options: options) self.progressBlock = progressBlock self.completionHandler = completionHandler } /// Creates an image prefetcher with an array of resources. /// /// - Parameters: /// - resources: The resources which should be prefetched. See `Resource` type for more. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init( resources: [Resource], options: KingfisherOptionsInfo? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { self.init(sources: resources.map { $0.convertToSource() }, options: options) self.completionHandler = completionHandler } /// Creates an image prefetcher with an array of sources. /// /// - Parameters: /// - sources: The sources which should be prefetched. See `Source` type for more. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called every time an source fetching successes, fails, is skipped. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init(sources: [Source], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherSourceProgressBlock? = nil, completionHandler: PrefetcherSourceCompletionHandler? = nil) { self.init(sources: sources, options: options) self.progressSourceBlock = progressBlock self.completionSourceHandler = completionHandler } /// Creates an image prefetcher with an array of sources. /// /// - Parameters: /// - sources: The sources which should be prefetched. See `Source` type for more. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init(sources: [Source], options: KingfisherOptionsInfo? = nil, completionHandler: PrefetcherSourceCompletionHandler? = nil) { self.init(sources: sources, options: options) self.completionSourceHandler = completionHandler } init(sources: [Source], options: KingfisherOptionsInfo?) { var options = KingfisherParsedOptionsInfo(options) prefetchSources = sources pendingSources = ArraySlice(sources) // We want all callbacks from our prefetch queue, so we should ignore the callback queue in options. // Add our own callback dispatch queue to make sure all internal callbacks are // coming back in our expected queue. options.callbackQueue = .dispatch(pretchQueue) optionsInfo = options let cache = optionsInfo.targetCache ?? .default let downloader = optionsInfo.downloader ?? .default manager = KingfisherManager(downloader: downloader, cache: cache) } /// Starts to download the resources and cache them. This can be useful for background downloading /// of assets that are required for later use in an app. This code will not try and update any UI /// with the results of the process. public func start() { pretchQueue.async { guard !self.stopped else { assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.") self.handleComplete() return } guard self.maxConcurrentDownloads > 0 else { assertionFailure("There should be concurrent downloads value should be at least 1.") self.handleComplete() return } // Empty case. guard self.prefetchSources.count > 0 else { self.handleComplete() return } let initialConcurrentDownloads = min(self.prefetchSources.count, self.maxConcurrentDownloads) for _ in 0 ..< initialConcurrentDownloads { if let resource = self.pendingSources.popFirst() { self.startPrefetching(resource) } } } } /// Stops current downloading progress, and cancel any future prefetching activity that might be occuring. public func stop() { pretchQueue.async { if self.finished { return } self.stopped = true self.tasks.values.forEach { $0.cancel() } } } private func downloadAndCache(_ source: Source) { let downloadTaskCompletionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void) = { result in self.tasks.removeValue(forKey: source.cacheKey) do { let _ = try result.get() self.completedSources.append(source) } catch { self.failedSources.append(source) } self.reportProgress() if self.stopped { if self.tasks.isEmpty { self.failedSources.append(contentsOf: self.pendingSources) self.handleComplete() } } else { self.reportCompletionOrStartNext() } } var downloadTask: DownloadTask.WrappedTask? ImagePrefetcher.requestingQueue.sync { let context = RetrievingContext( options: optionsInfo, originalSource: source ) downloadTask = manager.loadAndCacheImage( source: source, context: context, completionHandler: downloadTaskCompletionHandler) } if let downloadTask = downloadTask { tasks[source.cacheKey] = downloadTask } } private func append(cached source: Source) { skippedSources.append(source) reportProgress() reportCompletionOrStartNext() } private func startPrefetching(_ source: Source) { if optionsInfo.forceRefresh { downloadAndCache(source) return } let cacheType = manager.cache.imageCachedType( forKey: source.cacheKey, processorIdentifier: optionsInfo.processor.identifier) switch cacheType { case .memory: append(cached: source) case .disk: if optionsInfo.alsoPrefetchToMemory { let context = RetrievingContext(options: optionsInfo, originalSource: source) _ = manager.retrieveImageFromCache( source: source, context: context) { _ in self.append(cached: source) } } else { append(cached: source) } case .none: downloadAndCache(source) } } private func reportProgress() { if progressBlock == nil && progressSourceBlock == nil { return } let skipped = self.skippedSources let failed = self.failedSources let completed = self.completedSources CallbackQueue.mainCurrentOrAsync.execute { self.progressSourceBlock?(skipped, failed, completed) self.progressBlock?( skipped.compactMap { $0.asResource }, failed.compactMap { $0.asResource }, completed.compactMap { $0.asResource } ) } } private func reportCompletionOrStartNext() { if let resource = self.pendingSources.popFirst() { // Loose call stack for huge ammount of sources. pretchQueue.async { self.startPrefetching(resource) } } else { guard allFinished else { return } self.handleComplete() } } var allFinished: Bool { return skippedSources.count + failedSources.count + completedSources.count == prefetchSources.count } private func handleComplete() { if completionHandler == nil && completionSourceHandler == nil { return } // The completion handler should be called on the main thread CallbackQueue.mainCurrentOrAsync.execute { self.completionSourceHandler?(self.skippedSources, self.failedSources, self.completedSources) self.completionHandler?( self.skippedSources.compactMap { $0.asResource }, self.failedSources.compactMap { $0.asResource }, self.completedSources.compactMap { $0.asResource } ) self.completionHandler = nil self.progressBlock = nil } } }
mit
598f94945d4237768175fc54432d4d31
44.357466
120
0.668246
5.386351
false
false
false
false
Yurssoft/QuickFile
Pods/CodableFirebase/CodableFirebase/FirestoreDecoder.swift
1
2415
// // FirestoreDecoder.swift // Slap // // Created by Oleksii on 21/10/2017. // Copyright © 2017 Slap. All rights reserved. // import Foundation public protocol FirestoreDecodable: Decodable {} public protocol FirestoreEncodable: Encodable {} public typealias DocumentReferenceType = FirestoreDecodable & FirestoreEncodable public typealias FieldValueType = FirestoreEncodable public protocol GeoPointType: FirestoreDecodable, FirestoreEncodable { var latitude: Double { get } var longitude: Double { get } init(latitude: Double, longitude: Double) } open class FirestoreDecoder { public init() {} open var userInfo: [CodingUserInfoKey : Any] = [:] open func decode<T : Decodable>(_ type: T.Type, from container: [String: Any]) throws -> T { let options = _FirebaseDecoder._Options( dateDecodingStrategy: nil, dataDecodingStrategy: nil, skipFirestoreTypes: true, userInfo: userInfo ) let decoder = _FirebaseDecoder(referencing: container, options: options) guard let value = try decoder.unbox(container, as: T.self) else { throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: [], debugDescription: "The given dictionary was invalid")) } return value } } enum GeoPointKeys: CodingKey { case latitude, longitude } extension GeoPointType { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: GeoPointKeys.self) let latitude = try container.decode(Double.self, forKey: .latitude) let longitude = try container.decode(Double.self, forKey: .longitude) self.init(latitude: latitude, longitude: longitude) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: GeoPointKeys.self) try container.encode(latitude, forKey: .latitude) try container.encode(longitude, forKey: .longitude) } } enum DocumentReferenceError: Error { case typeIsNotSupported case typeIsNotNSObject } extension FirestoreDecodable { public init(from decoder: Decoder) throws { throw DocumentReferenceError.typeIsNotSupported } } extension FirestoreEncodable { public func encode(to encoder: Encoder) throws { throw DocumentReferenceError.typeIsNotSupported } }
mit
f3d0b9c7fb2e0922d26a31e051480282
29.948718
146
0.69594
4.714844
false
false
false
false
Jaspion/Kilza
spec/res/swift/hash/A.swift
1
1935
// // A.swift // // Created on <%= Time.now.strftime("%Y-%m-%d") %> // Copyright (c) <%= Time.now.strftime("%Y") %>. All rights reserved. // Generated by Kilza https://github.com/Jaspion/Kilza // import Foundation public class A: NSObject, NSCoding { // Original names public class func model(obj: AnyObject) -> A? { var instance: A? if (obj is String) { instance = A.init(str: obj as! String) } else if (obj is Dictionary<String, AnyObject>) { instance = A.init(dict: obj as! Dictionary) } return instance } public convenience init?(str: String) { if let data = str.dataUsingEncoding(NSUTF8StringEncoding) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) self.init(dict: object as! Dictionary) } catch _ as NSError { self.init(dict: Dictionary()) } } else { self.init(dict: Dictionary()) } } public init?(dict: Dictionary<String, AnyObject>) { super.init() } public func dictionaryRepresentation() -> Dictionary<String, AnyObject> { let mutableDict: Dictionary = [String: AnyObject]() return NSDictionary.init(dictionary: mutableDict) as! Dictionary<String, AnyObject> } public func objectOrNil(forKey key: String, fromDictionary dict: Dictionary<String, AnyObject>) -> AnyObject? { if let object: AnyObject = dict[key] { if !(object is NSNull) { return object } } return nil } required public init(coder aDecoder: NSCoder) { } public func encodeWithCoder(aCoder: NSCoder) { } override public var description: String { get { return "\(dictionaryRepresentation())" } } }
mit
ac71e85527ebd55a4dc83849889aed70
27.455882
134
0.583463
4.479167
false
false
false
false
rwbutler/TypographyKit
TypographyKit/Classes/UITextViewAdditions.swift
1
5330
// // UITextViewAdditions.swift // Pods-TypographyKit_Example // // Created by Ross Butler on 9/7/17. // import Foundation import UIKit extension UITextView { public var letterCase: LetterCase { get { // swiftlint:disable:next force_cast return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.letterCase) as! LetterCase } set { objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.letterCase, newValue, .OBJC_ASSOCIATION_RETAIN) if !isAttributed() { self.text = self.text?.letterCase(newValue) } } } @objc public var fontTextStyle: UIFont.TextStyle { get { // swiftlint:disable:next force_cast return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.fontTextStyle) as! UIFont.TextStyle } set { objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.fontTextStyle, newValue, .OBJC_ASSOCIATION_RETAIN) if let typography = Typography(for: newValue) { self.typography = typography } } } @objc public var fontTextStyleName: String { get { return fontTextStyle.rawValue } set { fontTextStyle = UIFont.TextStyle(rawValue: newValue) } } public var typography: Typography { get { // swiftlint:disable:next force_cast return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.typography) as! Typography } set { objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.typography, newValue, .OBJC_ASSOCIATION_RETAIN) addObserver() guard !isAttributed() else { return } if let newFont = newValue.font(UIApplication.shared.preferredContentSizeCategory) { self.font = newFont } if let textColor = newValue.textColor { self.textColor = textColor } if let letterCase = newValue.letterCase { self.letterCase = letterCase } } } public func attributedText(_ text: NSAttributedString?, style: UIFont.TextStyle, letterCase: LetterCase? = nil, textColor: UIColor? = nil, replacingDefaultTextColor: Bool = false) { // Update text. if let text = text { self.attributedText = text } // Update text color. if let textColor = textColor { self.textColor = textColor } guard var typography = Typography(for: style), let attrString = text else { return } // Apply overriding parameters. typography.textColor = textColor ?? typography.textColor typography.letterCase = letterCase ?? typography.letterCase self.fontTextStyle = style self.typography = typography let mutableString = NSMutableAttributedString(attributedString: attrString) let textRange = NSRange(location: 0, length: attrString.string.count) mutableString.enumerateAttributes(in: textRange, options: [], using: { value, range, _ in update(attributedString: mutableString, with: value, in: range, and: typography) }) self.attributedText = mutableString if replacingDefaultTextColor { let defaultColor = defaultTextColor(in: mutableString) let replacementString = replaceTextColor(defaultColor, with: typography.textColor, in: mutableString) self.attributedText = replacementString } } // MARK: Functions public func text(_ text: String?, style: UIFont.TextStyle, letterCase: LetterCase? = nil, textColor: UIColor? = nil) { if let text = text { self.text = text } if var typography = Typography(for: style) { // Only override letterCase and textColor if explicitly specified if let textColor = textColor { typography.textColor = textColor } if let letterCase = letterCase { typography.letterCase = letterCase } self.typography = typography } } } extension UITextView: TypographyKitElement { func isAttributed() -> Bool { guard let attributedText = attributedText else { return false } return isAttributed(attributedText) } func contentSizeCategoryDidChange(_ notification: NSNotification) { if let newValue = notification.userInfo?[UIContentSizeCategory.newValueUserInfoKey] as? UIContentSizeCategory { if isAttributed(attributedText) { self.attributedText(attributedText, style: fontTextStyle) } else { self.font = self.typography.font(newValue) } self.setNeedsLayout() } } }
mit
4f9a92024082131b8e7363d0263b4fc7
34.533333
120
0.577486
5.915649
false
false
false
false
nthegedus/ReviewTime
ReviewTime/ViewControllers/HomeViewController.swift
1
6918
// // HomeViewController.swift // ReviewTime // // Created by Nathan Hegedus on 18/06/15. // Copyright (c) 2015 Nathan Hegedus. All rights reserved. // import UIKit import TwitterKit class HomeViewController: UIViewController { var timer: NSTimer? @IBOutlet weak var lastUpdateLabel: UILabel! @IBOutlet weak var iosTypeLabel: UILabel! @IBOutlet weak var iosDaysLabel: UILabel! @IBOutlet weak var iosDescriptionLabel: UILabel! @IBOutlet weak var macTypeLabel: UILabel! @IBOutlet weak var macDaysLabel: UILabel! @IBOutlet weak var macDescriptionLabel: UILabel! @IBOutlet weak var errorButton: UIButton! @IBOutlet weak var iosButton: NHButton! @IBOutlet weak var macButton: NHButton! @IBOutlet weak var extraInfoLabel: UILabel! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! var loginTwitterButton:TWTRLogInButton? var reviewTimeResult: ReviewTime? { didSet { self.iosDaysLabel.hidden = false self.iosDaysLabel.text = NSLocalizedString("\(reviewTimeResult!.iosAverageTime) days", comment: "Average Days") self.iosDescriptionLabel.text = NSLocalizedString("Based on \(reviewTimeResult!.iosTotalTweets) reviews in the last 14 days", comment: "Description reviews iOS") self.macDaysLabel.hidden = false self.macDaysLabel.text = NSLocalizedString("\(reviewTimeResult!.macAverageTime) days", comment: "Average Days") self.macDescriptionLabel.text = NSLocalizedString("Based on \(reviewTimeResult!.macTotalTweets) reviews in the last 30 days", comment: "Description reviews Mac") self.lastUpdateLabel.text = NSLocalizedString("last updated: \(reviewTimeResult!.lastUpdate)", comment: "Last update Label") self.activityIndicatorView.stopAnimating() self.fadeInLabels() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.fetchData() self.logAnalytics() } override func awakeFromNib() { super.awakeFromNib() NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetMac", name: "Mac", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetIOS", name: "iOS", object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.timer?.invalidate() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Private Methods private func logAnalytics() { let tracker = GAI.sharedInstance().defaultTracker tracker.set("HomeViewController", value: "Load_Home") let builder = GAIDictionaryBuilder.createScreenView() tracker.send(builder.build() as [NSObject : AnyObject]) } internal func fetchData() { self.activityIndicatorView.startAnimating() ReviewTimeWS.fetchReviewTimeData { (reviewTime, error) -> Void in if error == nil { self.reviewTimeResult = reviewTime self.timer = NSTimer.scheduledTimerWithTimeInterval(30*60, target: self, selector: "fetchData", userInfo: nil, repeats: false) }else{ self.activityIndicatorView.stopAnimating() UIView.animateWithDuration(0.5, animations: { () -> Void in self.errorButton.alpha = 1.0 }) } } } private func fadeInLabels() { UIView.animateWithDuration(0.5, animations: { () -> Void in self.iosDaysLabel.alpha = 1.0 self.iosTypeLabel.alpha = 1.0 self.iosDescriptionLabel.alpha = 1.0 self.macDaysLabel.alpha = 1.0 self.macTypeLabel.alpha = 1.0 self.macDescriptionLabel.alpha = 1.0 self.lastUpdateLabel.alpha = 1.0 }) } private func validateTwitterLogin(completion: ((NSError?) -> Void)?) { if Twitter.sharedInstance().session() == nil { Twitter.sharedInstance().logInWithCompletion { (session, error) -> Void in completion!(error) } }else{ completion!(nil) } } private func tweetReviewTimeWithHashtag(hashtag: String) { let composer = TWTRComposer() composer.setText(hashtag) composer.showFromViewController(self, completion: { (result) -> Void in if (result == TWTRComposerResult.Done) { let tracker = GAI.sharedInstance().defaultTracker tracker.set("Tweeted", value: "Tweeted_\(hashtag)") log.debug("Tweeted") } }) } // MARK: - IBActions @IBAction func tryAgain(sender: AnyObject) { UIView.animateWithDuration(0.5, animations: { () -> Void in self.errorButton.alpha = 0.0 }) { (finished) -> Void in self.fetchData() } } @IBAction func tweetIOS() { let tracker = GAI.sharedInstance().defaultTracker tracker.set("Start Twitter for iOS hashtag", value: "Tweet_iOS") self.validateTwitterLogin { (error) -> Void in if error == nil { self.tweetReviewTimeWithHashtag(ReviewTime.Hashtag.ios) } } } @IBAction func tweetMac( ) { let tracker = GAI.sharedInstance().defaultTracker tracker.set("Start Twitter for Mac hashtag", value: "Tweet_Mac") self.validateTwitterLogin { (error) -> Void in if error == nil { self.tweetReviewTimeWithHashtag(ReviewTime.Hashtag.mac) } } } @IBAction func openInfo(sender: AnyObject) { let title = NSLocalizedString("Where does this data come from?", comment: "Title alert about") let message = NSLocalizedString("This is not official Apple data. It is based only on anecdotal data gathered from people posting their latest review times on Twitter and App.net using the #macreviewtime or #iosreviewtime hash tags.", comment: "Message alert about") let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let action = UIAlertAction(title: "ok", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } }
mit
6fd2ef0f75f79afe2c9233176fa5afa4
33.763819
274
0.613183
5.105535
false
false
false
false